What is the proper way to dynamically summarize th...
# ask-ai
r
What is the proper way to dynamically summarize the
ChatContext
during a session to keep it at a manageable size?
t
Thanks for reaching out, Alejandro. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
I'm glad you're looking to dynamically summarize and manage the
ChatContext
during a session! Here are some friendly strategies that can really help: • Truncate Chat Context: You can use the
truncate(max_items)
method to keep just the most recent messages. For example, in Python, you might do:
chat_ctx.truncate(max_items=50)
, or in TypeScript:
chatContext.truncate(50)
. This keeps things neat and focused! • Filter Context Items: It’s helpful to exclude messages that aren’t essential, like function calls, outputs, or empty messages, when you’re creating a new
ChatContext
. This way, you keep only what truly matters. • Custom Truncation: You might want to create your own methods to hold on to specific messages, like system messages or recent interactions, while letting go of others. This gives you more control over what stays in the conversation. • Automated Size Management: Real-time plugins can be a great friend here—they can merge consecutive messages or trim things down when the context gets too big, so you don’t have to worry about it. • Summarization: Another neat trick is to periodically summarize older messages with an LLM and replace them with a concise system message summary. This keeps the important info handy without the clutter. By using these methods, you’ll find it much easier to keep your chat context manageable while still preserving the key details that make your sessions flow smoothly. If you have any questions or want to dive deeper into any of these, I’m here to help! Sources: livekit-plugins/livekit-plugins-openai/livekit/plugins/openai/realtime/real... | agents/src/llm/chat_context.ts | complex-agents/personal_shopper/personal_shopper.py | Agent Session & Client Integration | livekit/livekit_composite | DeepWiki | Knowledge Management & Documentation System | livekit/livekit_composite | D...
r
Is the llm_node() agent function the correct place to summarize the ChatContext?
t
I'm glad you asked! Yes, the
llm_node()
function is indeed the perfect spot to summarize the
ChatContext
. It’s thoughtfully designed to handle the context before running inference with the LLM, which makes it great for summarization tasks—helping keep everything within token limits and highlighting the key points. Inside
llm_node()
, you have the flexibility to: • Filter and format the important messages, leaving out things like system instructions or function calls that aren’t essential. • Create a summary of the conversation and even add it back into the context as a system message if you’d like. • Customize how this works while still using
Agent.default.llm_node()
for the actual inference, so everything stays compatible. If you’d like, I’m happy to share more details or walk you through some examples on how to set this up—just let me know! Sources: livekit-agents/livekit/agents/llm/chat_context.py | Agents v0.x migration guide - Python | LiveKit docs | Pipeline nodes and hooks | LiveKit docs | Agent-assisted warm transfer | LiveKit docs
r
can you provide a code example of how to manage the ChatContext in the llm_node function?
t
I'd love to walk you through an example of managing the
ChatContext
in the
llm_node()
function by summarizing and filtering the context. Here it is:
Copy code
from livekit.agents import Agent, llm, ChatContext, ChatMessage, ModelSettings
from typing import AsyncIterable

class SummarizingAgent(Agent):
    async def llm_node(
        self,
        chat_ctx: llm.ChatContext,
        tools: list[llm.FunctionTool],
        model_settings: ModelSettings,
    ) -> AsyncIterable[llm.ChatChunk]:
        # Create a filtered copy of the chat context
        filtered_ctx = chat_ctx.copy(
            exclude_instructions=True,
            exclude_function_call=True,
            exclude_empty_message=True,
        )

        # Build a summary string from filtered messages
        summary_lines = []
        for item in filtered_ctx.items:
            if isinstance(item, ChatMessage):
                if item.role == "user":
                    summary_lines.append(f"User: {item.text_content}")
                elif item.role == "assistant":
                    summary_lines.append(f"Assistant: {item.text_content}")

        summarized_text = "\n".join(summary_lines)

        # Optionally inject the summary back into the context
        chat_ctx.add_message(
            role="system",
            content=f"Summary of conversation so far:\n{summarized_text}"
        )

        # Proceed with default LLM behavior using the updated context
        async for chunk in Agent.default.llm_node(self, chat_ctx, tools, model_settings):
            yield chunk
This example gently guides you through how to: • Filter the
ChatContext
to leave out non-essential items like instructions or function calls, keeping things tidy. • Summarize the conversation by going through user and assistant messages, making it easier to track. • Inject that summary back into the context as a system message, so the flow stays smooth and continuous. • Delegate to the default
llm_node()
for inference once the context is nicely updated. If anything feels unclear or you’d like me to share more examples, please don’t hesitate to ask—I’m here to help!