How to log or print agent context window on each c...
# ask-ai
m
How to log or print agent context window on each conversation
t
Thanks for reaching out, Rajadurai. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
Could you help me understand a bit more about what you mean by "agent context window"? Are you talking about logging specific details from conversations, like metadata or transcripts, or is it something different? I'm here to help!
m
I mean Chat ctx, I want to print how is chat context is changing in each turn
t
To help you keep track of chat context changes at each turn, you can use the
on_user_turn_completed
hook from the
VoiceAgent
class. This method is called right after the user finishes speaking and just before the LLM generates a response, making it a perfect spot to check and log the chat context. Here’s a friendly example of how you might override this method to print out the chat context:
Copy code
async def on_user_turn_completed(
    self, turn_ctx: llm.ChatContext, new_message: llm.ChatMessage
):
    # Let's print the entire chat context so you can see what's going on
    for message in turn_ctx.items:
        print(f"{message.role}: {message.text_content}")

    # Or, if you prefer, convert it to a dictionary for easier logging
    print("Chat context updated:", turn_ctx.to_dict())
If you’re working with a custom LLM node, like in a RAG pipeline, you can also add logging inside the
llm_node
method when you update the chat context. For instance, when you inject retrieved context, logging the updated instructions can be really helpful:
Copy code
print(f"update instructions: {instructions[:100].replace('\n', '\n')}...")
And just a quick tip: for more structured logging in a production environment, using Python’s built-in logging module to output JSON-formatted logs can make things much clearer. You can even add custom fields like room name or session ID to keep everything organized. Sources: livekit-agents/livekit/agents/voice/agent_activity.py | Job lifecycle | LiveKit Docs