Hi! I'm implementing LangGraph, following the docu...
# ask-ai
p
Hi! I'm implementing LangGraph, following the documentation here: https://docs.livekit.io/agents/models/llm/plugins/langchain/ But what should I put in my session.start 'agent' ?
t
Thanks for reaching out, Alessandro. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
I'd love to help you with implementing LangGraph! Could you please share a bit more about what you're working on? Are you running into any errors, or is there a specific feature you'd like some guidance with? I'm here to support you every step of the way.
p
I'm implementing LangGraph, following the documentation here: https://docs.livekit.io/agents/models/llm/plugins/langchain/ But what should I put in my session.start 'agent' ? (edited)
t
Let's walk through how to set up the
agent
in
session.start
when you're working with LangGraph. You'll want to create an instance of the
Agent
class, making sure to set the
llm
parameter to a
langchain.LLMAdapter
that wraps your compiled LangGraph workflow. Here's a friendly example to guide you:
Copy code
async def entrypoint(ctx: JobContext):
    graph = create_graph()  # returns a compiled StateGraph

    agent = Agent(
        instructions="",
        llm=langchain.LLMAdapter(graph),
    )

    session = AgentSession(
        vad=silero.VAD.load(),
        stt=deepgram.STT(model="nova-3", language="multi"),
        tts=deepgram.TTS(),
        turn_detection=MultilingualModel(),
    )

    await session.start(
        agent=agent,
        room=ctx.room,
        room_input_options=RoomInputOptions(),
    )
In this setup, the LangGraph workflow is first compiled using
.compile()
before it’s wrapped by
LLMAdapter
. Then, the
Agent
instance is passed to
session.start
along with the room context. If anything feels unclear or if you’d like me to explain any part in more detail, please don’t hesitate to ask—I’m here to help! Sources: livekit-plugins/livekit-plugins-bey/livekit/plugins/bey/avatar.py | LangChain integration guide | LiveKit Docs
p
is this graph correctly compiled? def create_graph() -> StateGraph: openai_llm = init_chat_model(model="azure_openai:gpt-5-nano") def chatbot_node(state: State): return {"messages": [openai_llm.invoke(state["messages"])]} builder = StateGraph(State) builder.add_node("chatbot", chatbot_node) builder.add_edge(START, "chatbot") return builder.compile()
t
Thanks for sharing your graph! It looks mostly spot on, but let’s double-check a few important details together: 1. State Definition: Please make sure your
State
class is defined as a
TypedDict
and that the
messages
field is annotated with
add_messages
from
langgraph.graph.message
. This step is key to enabling the stateful message accumulation you want. 2. LLM Initialization: When you use the
init_chat_model
function, double-check that the model name
"azure_openai:gpt-5-nano"
is valid and supported in your environment. 3. Graph Compilation: Your call to
builder.compile()
is exactly right and necessary. Just be sure the graph compiles locally before you hand it over to
LLMAdapter
. To help you out, here’s an example of a complete implementation that you can refer to:
Copy code
from typing import Annotated, TypedDict
from langchain_core.messages import BaseMessage
from langgraph.graph import StateGraph, START
from langgraph.graph.message import add_messages
from langchain.chat_models import init_chat_model

class State(TypedDict):
    messages: Annotated[list[BaseMessage], add_messages]

def create_graph():
    llm = init_chat_model(model="azure_openai:gpt-5-nano")

    def chatbot_node(state: State):
        return {"messages": [llm.invoke(state["messages"])]}

    builder = StateGraph(State)
    builder.add_node("chatbot", chatbot_node)
    builder.add_edge(START, "chatbot")
    return builder.compile()
If anything feels unclear or if you run into any bumps along the way, please don’t hesitate to reach out. I’m here to help! Sources: examples/voice_agents/README.md | LangChain integration guide | LiveKit Docs
p
inside the session, how can check if the graph returns something? session = AgentSession( vad=silero.VAD.load(), stt=deepgram.STT(model="nova-3", language="multi"), tts=deepgram.TTS(), turn_detection=MultilingualModel(), ) await session.start( agent=agent, room=ctx.room, room_input_options=RoomInputOptions(), )
t
To help you check if the LangGraph workflow returns something during your session, you can keep an eye on specific events or take a look directly at the chat context. Here’s how you can do it: • Monitor Events: ◦ conversation_item_added: This event happens whenever a new message is added to the chat. If the item's
role
is
"assistant"
and it includes
text_content
, it means the LangGraph workflow has produced a response.
Copy code
conversation_events = []
session.on("conversation_item_added", conversation_events.append)

for event in conversation_events:
    if event.item.role == "assistant" and event.item.text_content:
        print("LangGraph returned:", event.item.text_content)
◦ function_tools_executed: This event triggers when a tool runs. You can check the tool's output like this:
Copy code
def on_tool_executed(event):
    for call in event.function_calls:
        print(f"Tool called: {call.name}, Args: {call.arguments}")

session.on("function_tools_executed", on_tool_executed)
• Inspect Chat Context: The
chat_ctx
object keeps track of the conversation history. You can access it after your interaction with:
Copy code
chat_items = session.agent.chat_ctx.items
for item in chat_items:
    if item.type == "message" and item.role == "assistant":
        print("Assistant response:", item.text_content)
    elif item.type == "function_call_output":
        print("Tool result:", item.output)
If anything isn’t clear or you’d like me to walk you through this step-by-step, please don’t hesitate to ask—I’m here to help! Sources: livekit-agents/livekit/agents/voice/agent_session.py | Testing and evaluation | LiveKit Docs
p
okay, where should i put the code you suggested? Here's my code class State(TypedDict): messages: Annotated[list[BaseMessage], add_messages] # Define your LangGraph workflow def create_workflow() -> StateGraph: llm_model = init_chat_model(model="azure_openai:gpt-5-nano") def node_1(state: dict): response = [llm_model.invoke(state["messages"])] return {"messages": response} workflow = StateGraph(State) # Add nodes to workflow workflow.add_edge(START, "node1") workflow.add_node("node1", node_1) return workflow.compile() async def entrypoint(ctx: JobContext): graph=create_workflow() agent = Agent( instructions="", # Instructions are handled by the LangGraph llm=langchain.LLMAdapter(graph) ) # Using Azure OpenAI session = AgentSession( stt = openai.STT.with_azure( language="it", model="gpt-4o-mini-transcribe", ), tts=openai.TTS.with_azure( model="gpt-4o-mini-tts", voice="coral", ), vad=silero.VAD.load(), turn_detection=MultilingualModel(), ) await session.start( room=ctx.room, agent = agent, room_input_options=RoomInputOptions( noise_cancellation=noise_cancellation.BVC(), ), ) await session.generate_reply( instructions="Greet the user and offer your assistance." ) if name == "__main__": agents.cli.run_app(agents.WorkerOptions(entrypoint_fnc=entrypoint))
t
I'm happy to help you integrate the code for monitoring events or inspecting the chat context directly into your
entrypoint
function. Here's a friendly guide on how you can modify your code: 1. Monitor Events: You can add event listeners for
conversation_item_added
and
function_tools_executed
before starting the session. Here's an example:
Copy code
async def entrypoint(ctx: JobContext):
    graph = create_workflow()

    agent = Agent(
        instructions="",    # Instructions are handled by the LangGraph
        llm=langchain.LLMAdapter(graph)
    )

    session = AgentSession(
        stt=openai.STT.with_azure(
            language="it",
            model="gpt-4o-mini-transcribe",
        ),
        tts=openai.TTS.with_azure(
            model="gpt-4o-mini-tts",
            voice="coral",
        ),
        vad=silero.VAD.load(),
        turn_detection=MultilingualModel(),
    )

    # Add event listeners
    conversation_events = []
    session.on("conversation_item_added", conversation_events.append)

    def on_tool_executed(event):
        for call in event.function_calls:
            print(f"Tool called: {call.name}, Args: {call.arguments}")

    session.on("function_tools_executed", on_tool_executed)

    await session.start(
        room=ctx.room,
        agent=agent,
        room_input_options=RoomInputOptions(
            noise_cancellation=noise_cancellation.BVC(),
        ),
    )

    await session.generate_reply(
        instructions="Greet the user and offer your assistance."
    )

    # Check outputs after session interaction
    for event in conversation_events:
        if event.item.role == "assistant" and event.item.text_content:
            print("LangGraph returned:", event.item.text_content)
2. Inspect Chat Context: After your session interaction, you might want to take a look at the chat context directly. Here's how you can do it:
Copy code
# Inspect chat context
    chat_items = session.agent.chat_ctx.items
    for item in chat_items:
        if item.type == "message" and item.role == "assistant":
            print("Assistant response:", item.text_content)
        elif item.type == "function_call_output":
            print("Tool result:", item.output)
If anything is unclear or if you’d like me to walk you through any part of this, please don’t hesitate to ask. I’m here to support you!