i'd like to understand a proper use case for using...
# ask-ai
g
i'd like to understand a proper use case for using chatCtx. What are the key benefits of using ChatContext (chatCtx) in LiveKit voice agents, particularly for maintaining conversation memory, handling interruptions, and improving response quality over the course of a multi-turn dialogue? ie.
Copy code
const handle = session.generateReply({
        allowInterruptions: true,
      });

      await handle.waitForPlayout();

      session.chatCtx.addMessage({
        ...(handle.chatMessage ?? {
          role: 'system',
          content: '',
        }),
      });
in other words, In a workflow-based voice assistant like mine, how does using ChatContext help with maintaining conversation coherence when users jump between different workflow steps or ask follow-up questions?"
t
Thanks for reaching out, James. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
Using
ChatContext
(
chatCtx
) in LiveKit voice agents brings some really helpful perks for keeping conversations smooth, handling interruptions, and making responses better in multi-turn chats: • Keeping the Conversation Memory:
ChatContext
remembers the whole chat history, so the agent can keep track across multiple turns. This means the conversation stays connected, even if the session restarts, supporting ongoing chats and memory across sessions. • Handling Interruptions: If someone interrupts,
ChatContext
saves any partial or finished responses and tags them with interruption info. This way, the agent can handle interruptions smoothly and even pick up where it left off, keeping things flowing nicely. • Boosting Response Quality: By sharing the full conversation history with the LLM each turn,
ChatContext
helps generate responses that really fit the context and feel natural. It also includes helpful details like message roles and timestamps, so the LLM understands the conversation better. In your workflow-based voice assistant,
ChatContext
makes sure users can jump between steps or ask follow-up questions without losing track, making the whole experience feel seamless and easy. Sources: livekit-agents/livekit/agents/voice/agent_activity.py | agents/src/voice/agent_activity.ts | Testing and evaluation | LiveKit Docs | Model Context Protocol Integration | livekit/livekit_composite | DeepWiki | Bringing AI avatars to voice agents
g
what if i have a lot of this information within the instructions already? is there an advantage to using chat context over just having this information within the instructions?
t
Using
ChatContext
comes with some pretty neat benefits compared to just stuffing all the info into static instructions: • Dynamic Updates: With
ChatContext
, the conversation history can update in real-time. This means responses get smarter and more relevant as new info pops up during your chat. • Preservation of History: It keeps a well-organized record of the conversation that you can use again later or when passing things off to another agent, so everything stays smooth and connected. • Structured Data:
ChatContext
handles roles, timestamps, and even different types of content like text, images, or audio — stuff that’s tricky to manage with plain instructions. • Separation of Concerns: Think of instructions as the “rules,” and
ChatContext
as the “story so far.” This keeps things modular and easier to reuse. • Tool Integration: It keeps track of tools used and their results, helping the agent make smarter decisions based on what’s happened before. So, to wrap it up,
ChatContext
offers flexibility, room to grow, and better ways to manage the conversation’s state — perfect for complex, interactive workflows where the context is always changing. Sources: External data and RAG | LiveKit Docs | External data and RAG | LiveKit Docs | Workflows | LiveKit Docs | Workflows | LiveKit Docs | agents/src/voice/agent_activity.ts
p
does the ChatContext always get sent to the LLM for processing, what if we have a long running conversation
t
Hey there! Just a quick heads-up about the
ChatContext
— it’s always sent to the LLM to give it the conversation history and context it needs to craft relevant responses. But when chats go on for a while, there are some handy ways to keep things from getting too bulky: • Truncation: You can use the
before_llm_cb
callback (or
llm_node
in newer versions) to trim down the
ChatContext
before it reaches the LLM. For example, keeping just the last 15 messages helps keep things neat and tidy. • Built-in Truncate Method: The
ChatContext
class has a
truncate
method that smartly removes older messages but keeps important ones, like the very first system message. • LLM-Specific Limits: Some LLM integrations, such as AWS Realtime Model, take care of message limits automatically — like trimming to 40 messages and managing individual message sizes — so everything runs smoothly. All these features work together to make sure your
ChatContext
stays efficient and manageable during longer conversations, while still giving the LLM just what it needs to respond thoughtfully. Sources: examples/voice_agents/long_running_function.py | VoicePipelineAgent | LiveKit Docs | Agents 0.x migration guide | LiveKit Docs
p
Im using the new nodejs Agents V1, where do i add the before_llm_cb
t
Hey there! Just a heads-up that the
before_llm_cb
callback has been replaced in Agents V1 with some new ways to customize how the LLM behaves. Could you share a bit more about what you’re hoping to do with this callback? For example, are you trying to truncate the
ChatContext
, tweak messages, or do something else before sending data to the LLM? I’m here to help!
p
yes im trying to truncate the
ChatContext
t
Hey there! In Node.js Agents V1, you’ve got a handy way to trim down your
ChatContext
using its built-in
truncate
method. This little helper lets you keep the context to a set number of items, making sure important stuff like the initial system message stays safe and sound. Check this out:
Copy code
// Truncate the chat context to keep only the last 10 items
chatContext.truncate(10);
What’s great is that this method updates the
ChatContext
right where it is, keeping everything neat and coherent—no half-done function calls, and it holds onto that crucial system message if there is one. If you’re plugging this into your pipeline, just pop the truncation step in the right spot (like inside an
llmNode
) before your LLM gets to work on the context. Sources: agents/src/llm/utils.test.ts | VoicePipelineAgent | LiveKit Docs | VoicePipelineAgent | LiveKit Docs | livekit-agents/livekit/agents/voice/agent.py
p
we are using the Realtime OAI workflow though
t
I don't have the answer you're looking for. You could also try asking your question: • in one of the other Slack channels or • to https://deepwiki.com/livekit/livekit_composite which is trained on all LiveKit source code If you find the answer, please post it here to help others!
p
my question is, does this work with a Realtime session, class MyAgent extends voice.Agent { // override method from superclass to customize behavior async *llmNode*( _chatCtx_: llm.ChatContext, _toolCtx_: llm.ToolContext, _modelSettings_: voice.ModelSettings, ): Promise<ReadableStream<llm.ChatChunk | string> | null> { // Truncate the chat context to keep only the last 5 items chatCtx.truncate(5); return voice.Agent.prototype.llmNode.call( this, chatCtx, toolCtx, modelSettings, ); } }