I want to capture necessary information from user'...
# ask-ai
c
I want to capture necessary information from user's inputs during the conversation with my agent and pass this to chat context instead of relying on the llms's intelligence to remember these. How can I implement this using a dataclass?
t
Thanks for reaching out, Subham. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
Let's walk through how you can capture user inputs and pass them to the chat context using a dataclass. I'll guide you step-by-step: 1. Define a Dataclass: First, create a Python dataclass to organize the data you want to capture, like user inputs or session-specific details. Don't forget to include
JobContext
for room and participant info.
Copy code
from dataclasses import dataclass, field
from typing import Optional
from livekit.agents import JobContext

@dataclass
class UserData:
    ctx: JobContext
    user_name: Optional[str] = None
    age: Optional[int] = None
    conversation_history: list[dict] = field(default_factory=list)
2. Initialize UserData: Next, in your
entrypoint
function, create an instance of this dataclass and pass it to
AgentSession
.
Copy code
async def entrypoint(ctx: JobContext):
    await ctx.connect()
    userdata = UserData(ctx=ctx)
    session = AgentSession[UserData](userdata=userdata, llm=openai.LLM(), stt=deepgram.STT(), tts=elevenlabs.TTS())
    await session.start(room=ctx.room, agent=MyAgent())
3. Access and Update UserData: Within your agent or tools, you can use the
userdata
object to capture inputs and update the chat context as needed.
Copy code
class MyAgent(Agent):
    async def on_enter(self):
        userdata = self.session.userdata
        userdata.user_name = "Alice"
        userdata.age = 30
        userdata.conversation_history.append({"role": "system", "content": f"User {userdata.user_name} joined."})
4. Integrate with Chat Context: Finally, use the stored data to personalize replies or add messages to the chat context.
await self.session.say(f"Hello {userdata.user_name}, I see you're {userdata.age} years old!", allow_interruptions=True)
This way, you keep user data well-structured and persistent throughout the session, which really helps create dynamic and personalized interactions. If you have any questions or want to explore this further, feel free to ask—I'm here to help! Sources: basics/context_variables.py | Workflows | LiveKit Docs
c
can I instead update chat context for this?
t
Absolutely, you can update the chat context directly without relying on a dataclass. Using the
update_chat_ctx()
method provided by the agent is a great way to keep everything in sync, especially during realtime sessions. Here’s a simple way to do it: 1. Create or Modify Chat Context: Start by preparing a new or updated
ChatContext
object with the changes you want. 2. Update the Context: Then, apply those changes using the
update_chat_ctx()
method.
await agent.update_chat_ctx(new_chat_ctx, exclude_invalid_function_calls=True)
For instance, if you want to modify a user message before the LLM processes it, you can override the
on_user_turn_completed()
method like this:
Copy code
async def on_user_turn_completed(self, turn_ctx: llm.ChatContext, new_message: llm.ChatMessage):
    # Edit the user message
    new_message.content[0].text = "Edited user message."

    # Update the chat context
    await self.update_chat_ctx(turn_ctx)
This way, you’re ensuring the chat context updates happen smoothly and safely, which helps avoid any issues that might come from directly changing
chat_ctx.messages
. I hope this helps clarify things for you! Sources: plugins/google/src/beta/realtime/realtime_api.ts | Agent Session & Client Integration | livekit/livekit_composite | DeepWiki | Agents v0.x migration guide - Node.js | LiveKit Docs | Agents v0.x migration guide - Python | LiveKit Docs | livekit-agents/livekit/agents/voice/agent.py
c
can I make the agent update it in a tool?
t
Absolutely! An agent can update the chat context using a tool, and I’m here to guide you through how to do that. This is done by calling the
update_chat_ctx()
method within the tool's implementation. Let’s walk through it together: 1. Define the Tool: You’ll want to create a function tool where you can modify the chat context. Here’s a simple example to get you started:
Copy code
from livekit.agents.llm import function_tool
from livekit.agents.voice import RunContext

RunContext_T = RunContext[UserData]

@function_tool
async def update_chat_context_tool(self, new_message: str, context: RunContext_T):
    # Access the current chat context
    chat_ctx = context.chat_ctx

    # Add a new message to the context
    chat_ctx.messages.append({"role": "user", "content": new_message})

    # Update the chat context
    await context.agent.update_chat_ctx(chat_ctx)
    return "Chat context updated successfully."
2. Call the Tool: Then, you can use this tool during the agent's execution whenever you need to dynamically update the chat context. This way, you’re ensuring the chat context stays updated safely and stays in sync with the server, which helps keep everything consistent throughout your session. If you have any questions or want to explore this further, I’m here to help! Sources: livekit-plugins/livekit-plugins-openai/livekit/plugins/openai/realtime/real... | Agents v0.x migration guide - Python | LiveKit Docs