For the LiveKit Agent Python SDK, does the RunCont...
# ask-ai
f
For the LiveKit Agent Python SDK, does the RunContext attribute get sent as part of the context to the LLM with every LLM request?
t
Thanks for reaching out, Amitrajit. 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 better! Could you please share a bit more about how you're using the RunContext attribute in the LiveKit Agent Python SDK? For instance, are you curious about how it behaves during certain API calls, or are you interested in its overall role in LLM interactions? Your details will really help me assist you effectively.
f
I want to know if it gets sent as context to the LLM whenever the LLM API is called during the conversation
t
Thank you for your question! The
RunContext
attribute in the LiveKit Agent Python SDK isn’t directly sent as input context to the LLM during API calls, but it still plays an important role behind the scenes: •
RunContext
gives you access to shared session data (through
context.userdata
) and the current
AgentSession
. • The actual information sent to the LLM is handled by the
ChatContext
, which includes things like conversation history, system instructions, and any function call responses you’ve explicitly added. • If you want to include data from
RunContext
in the LLM input, you’ll need to explicitly add it to the
ChatContext
during function execution or by customizing the agent pipeline. So, to sum it up, while
RunContext
itself isn’t sent directly to the LLM, the data it manages can definitely influence the LLM input when you integrate it into the
ChatContext
. I hope this helps clarify things! Feel free to ask if you have more questions. Sources: livekit-agents/livekit/agents/voice/agent.py | Agents v0.x migration guide - Python | LiveKit Docs | rpc/rpc_agent.py | Pipeline nodes and hooks | LiveKit Docs
f
How can I use RunContext while initializing a new workflow after transferring to it?
t
I'm glad you're interested in using
RunContext
to initialize a new workflow after transferring to it! Let me guide you through the steps to make this process smooth and effective: 1. Define a
UserData
Dataclass:
This is where you’ll create a dataclass to hold shared state across agents, like session context or any workflow-specific information. Here’s a simple example to get you started:
Copy code
@dataclass
class UserData:
    customer_name: Optional[str] = None
    order: Optional[list[str]] = None
2. Type the `RunContext`: To keep things type-safe, use
RunContext[UserData]
when creating the context for your function tools:
RunContext_T = RunContext[UserData]
3. Use
RunContext
in Transfer Functions:
Within a
@function_tool
, accept
context: RunContext_T
so you can preserve the state during the transfer. Here’s an example that shows how to do this:
Copy code
@function_tool()
async def to_reservation(self, context: RunContext_T) -> tuple[Agent, str]:
    userdata = context.userdata
    userdata.prev_agent = self
    next_agent = userdata.agents["reservation"]
    return next_agent, "Transferring to reservation."
4. Initialize Workflow in `on_enter`: When the new agent becomes active, its
on_enter()
method is called. You can use
self.session.userdata
to retrieve the previous state and set up the workflow accordingly. Here’s how you might do that:
Copy code
async def on_enter(self) -> None:
    userdata: UserData = self.session.userdata
    if userdata.prev_agent:
        # Copy chat history from previous agent
        chat_ctx = self.chat_ctx.copy()
        items_copy = userdata.prev_agent.chat_ctx.truncate(max_items=6).items
        chat_ctx.items.extend(items_copy)
        await self.update_chat_ctx(chat_ctx)
By following these steps, you’ll ensure that your new workflow inherits the shared session state seamlessly, allowing conversations to continue naturally. If you have any questions or need further clarification, feel free to ask—I’m here to help! Sources: examples/warm-transfer/README.md | telephony/survey_caller/survey_calling_agent.py | Workflows | LiveKit Docs
f
What if I want to take elements of it and make it a part of the initial system instructions provided at the time of initialization of the new workflow?
t
I'm glad you're exploring how to include elements of
RunContext
in the initial system instructions during the setup of a new workflow. Let's walk through the steps together: 1. Define a
UserData
Class:
Start by creating a dataclass to hold shared state, like user-specific info or workflow metadata. Here's a simple example:
Copy code
@dataclass
class UserData:
    user_name: str = ""
    custom_instructions: str = ""
2. Initialize
UserData
in the Entrypoint:
You can use the
JobContext
to grab metadata and fill your
UserData
object. For instance:
Copy code
async def entrypoint(ctx: JobContext):
    await ctx.connect()

    user_name = ctx.job.metadata.get("user_name", "there")

    userdata = UserData(
        user_name=user_name,
        custom_instructions=f"You are assisting {user_name}. Be warm and professional."
    )

    session = AgentSession(
        userdata=userdata,
        llm=openai.LLM(),
        stt=deepgram.STT(),
        tts=elevenlabs.TTS(),
        vad=silero.VAD.load()
    )

    await session.start(room=ctx.room, agent=MyAgent())
3. Customize Instructions in `on_enter`: Within the
on_enter
method, you can dynamically update the system instructions by accessing
self.session.userdata
. Here's how:
Copy code
async def on_enter(self):
    userdata = self.session.userdata
    chat_ctx = self.chat_ctx.copy()

    chat_ctx.add_message(
        role="system",
        content=f"User name: {userdata.user_name}. {userdata.custom_instructions}"
    )

    await self.update_chat_ctx(chat_ctx)
    self.session.generate_reply()
Just a quick note:
RunContext
itself isn't available during initialization. So, using
UserData
is a great way to pass along relevant context and personalize your workflow instructions. If you have any questions or want to dive deeper, feel free to ask—I'm here to help! Sources: Tool definition and use | LiveKit Docs | avatars/hedra/dynamically_created_avatar/agent.py | livekit-agents/livekit/agents/job.py
f
What about session.userdata? Is that available at the time of initialization?
t
Absolutely!
session.userdata
is available right from the start when you initialize the LiveKit Agent Python SDK. It’s passed into the
AgentSession
constructor and saved as a class property, so you can access it as soon as your session is created. Feel free to use
session.userdata
to store and retrieve any shared state or custom data not only during initialization but throughout the entire session. If you have any questions about how to make the most of it, I’m here to help! Sources: examples/voice_agents/realtime_joke_teller.py | docs/index.yaml
f
What is the best way to include context at the start of a session? Is it by adding it as a system message directly in the chat context using the on_enter() function while starting a new workflow
t
I'm glad you asked! The best way to include context right at the start of a session is by adding it as a system message within the chat context using the
on_enter()
function. This method is highly recommended because it helps the LLM understand the necessary context before it starts generating responses. Here’s a friendly guide on how you can do it: 1. Use
on_enter()
for System Messages:
Begin by adding a system message that clearly defines the agent's role and includes any relevant user or session data. For example:
Copy code
chat_ctx.add_message(
    role="system",
    content=f"You are the {agent_name}. {userdata.summarize()}"
)
await self.update_chat_ctx(chat_ctx)
2. Leverage
UserData
for Context:
It’s helpful to use a
UserData
dataclass to keep track of session-level state, like user details or previous agent context, and then access it within
on_enter()
. 3. Preserve Chat History: When moving between workflows, try copying the chat history from the previous agent to keep the conversation smooth and continuous. For instance:
Copy code
items_copy = userdata.prev_agent.chat_ctx.truncate(max_items=6).items
chat_ctx.items.extend(items_copy)
4. Optimize Performance: To keep things running quickly, avoid making network calls inside
on_enter()
. Instead, preload any static data or use metadata passed during session initialization. By following these steps, you’ll create a seamless and context-rich experience for your users while keeping your session handling efficient. If you have any questions or need further help, I’m here for you! Sources: Pipeline nodes and hooks | LiveKit Docs | flows/simple_flow.py | External data and RAG | LiveKit Docs