How do i correctly add Messages to the chat_ctx ma...
# ask-ai
w
How do i correctly add Messages to the chat_ctx manually? So that the agent can see it immediatly?
t
Thanks for reaching out, Lukas. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
You're right to update the agent's chat context instead of mutating it directly. To add a message so the agent sees it immediately, create the ChatMessage, copy and modify the agent's ChatContext, then call
await agent.update_chat_ctx(chat_ctx)
. Example (Python):
Copy code
from livekit.agents import ChatContext, ChatMessage

# create the new message
new_message = ChatMessage(role="user", content="This is a manually added message.")

# copy current context, add the message
chat_ctx = agent.chat_ctx.copy()
chat_ctx.add_message(new_message)

# push the update so the agent sees it immediately
await agent.update_chat_ctx(chat_ctx)
Notes: • Do not modify
agent.chat_ctx.messages
directly; those changes are not guaranteed to be processed. • You can also seed
chat_ctx
when starting the session, but runtime changes require
update_chat_ctx()
. Sources: Agents v0.x migration guide - Python | LiveKit docs | External data and RAG | LiveKit Docs
w
and can i use _chat_ctx directly?_
t
Don't use
_chat_ctx
directly. It's an internal/private attribute and modifying it can cause inconsistent state or undefined behavior. Use
agent.update_chat_ctx()
(or the agent's provided
update_chat_ctx
call) to push changes so the agent processes them immediately. Example reminder:
Copy code
chat_ctx = agent.chat_ctx.copy()
chat_ctx.add_message(ChatMessage(role="user", content="..."))
await agent.update_chat_ctx(chat_ctx)
If you'd like, I can show how to add multiple messages at once or how to seed the context at session start. Sources: Agents v0.x migration guide - Python | LiveKit docs