I want to add some additional chat context when us...
# ask-ai
e
I want to add some additional chat context when using the on_enter pipeline hook in python, how do i do that ?
t
Thanks for reaching out, Aditya. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
You're asking how to add extra chat context inside the
on_enter
pipeline hook in Python. You can add messages to the agent's
chat_ctx
and then persist those changes by calling
await self.update_chat_ctx(...)
. Example:
Copy code
from livekit.agents import Agent

class MyAgent(Agent):
    async def on_enter(self) -> None:
        # add a system message (or user/assistant as needed)
        self.chat_ctx.add_message(
            role="system",
            content="This is additional context provided when the agent enters the session."
        )

        # persist the updated chat context so subsequent prompts include it
        await self.update_chat_ctx(self.chat_ctx)
Want an example that adds multiple messages, uses dynamic data, or uses a different role (user/assistant)? Which would help you most? Sources: Pipeline nodes and hooks | LiveKit docs
e
and how do i do the same thing using the on_user_turn_completed pipeline hook ?
t
You're asking how to add extra chat context inside the
on_user_turn_completed
pipeline hook in Python. Use the provided
turn_ctx
(and optionally
new_message
) to add messages, then call
await self.update_chat_ctx(...)
to persist those changes so they are included in the agent's next LLM prompt. Example — add retrieved RAG content and persist it:
Copy code
from livekit.agents import Agent, ChatContext, ChatMessage

class MyAgent(Agent):
    async def on_user_turn_completed(self, turn_ctx: ChatContext, new_message: ChatMessage) -> None:
        # get additional context (e.g., from a vector DB)
        rag_content = await my_rag_lookup(new_message.text_content())

        # add as an assistant/system message so the LLM sees it
        turn_ctx.add_message(
            role="assistant",
            content=f"Relevant info: {rag_content}"
        )

        # persist the updated chat context so future turns include it
        await self.update_chat_ctx(turn_ctx)
Notes and options: • To modify the user's message before it persists, edit
new_message.content
. • To avoid persisting (only use for the immediate turn), add to
turn_ctx
but skip
update_chat_ctx
. • To stop the agent from replying, raise
StopResponse()
. Want an example that merges multiple RAG results, adds metadata, or uses different roles? Which would be most helpful? Sources: Pipeline nodes and hooks | LiveKit docs
e
if i use insert method instead of add_message, do i still need to update the chat ctx ?
t
Short answer: yes — if you use
insert
(or any in-memory modification) you still must call
await self.update_chat_ctx(...)
to persist the change. Why:
insert
only updates the in-memory
ChatContext
for that pipeline execution. To make the inserted message part of the agent’s long‑term conversation history (so future prompts include it), call
await self.update_chat_ctx(turn_ctx)
(or
self.chat_ctx
if that's what you modified). Example:
Copy code
async def on_user_turn_completed(self, turn_ctx: ChatContext, new_message: ChatMessage) -> None:
    turn_ctx.insert(0, ChatMessage(role="system", content="Inserted context"))
    await self.update_chat_ctx(turn_ctx)  # persist the insertion
Do you want an example that inserts at a specific index, or one that conditionally persists only some inserts? Sources: Pipeline nodes and hooks | LiveKit docs
e
but both add_message and insert are totally valid ways to add context to the chat right ?
t
Yes — both
add_message
and
insert
are valid ways to add context to the chat. • Use
add_message
to append a message (or add it in a straightforward way). • Use
insert
when you need to place a message at a specific position in the context. In both cases the change is only in-memory for the current pipeline run; call await self.update_chat_ctx(...) with the modified
ChatContext
to persist the change so future turns include it. Would you like a short example showing both methods and where to call
update_chat_ctx
?
e
async def on_enter(self) -> None: extractor = DOMExtractor(page=self.page) llm_context = await extractor.get_current_snapshot() interactive_elements = llm_context.elements_text annotated_screenshot = llm_context.annotated_screenshot message = ChatMessage( role="system", content=[ f"Latest DOM Snapshot1: {time.time()}", interactive_elements, annotated_screenshot, ], ) self.chat_ctx.insert(message) await self.update_chat_ctx(self.chat_ctx) is this correct ?
t
You're very close — one change is recommended. Issues and fixes: • Use
add_message
instead of
insert
.
insert
is not the documented method for adding messages. • Ensure
content
is the right type (string or structured content). If
annotated_screenshot
is an image, wrap it as image content. • Call
await self.update_chat_ctx(self.chat_ctx)
to persist the change. Corrected example:
Copy code
async def on_enter(self) -> None:
    extractor = DOMExtractor(page=self.page)
    llm_context = await extractor.get_current_snapshot()
    interactive_elements = llm_context.elements_text
    annotated_screenshot = llm_context.annotated_screenshot

    message = ChatMessage(
        role="system",
        content=[
            f"Latest DOM Snapshot: {time.time()}",
            interactive_elements,
            annotated_screenshot,  # wrap as image content if needed
        ],
    )

    self.chat_ctx.add_message(message)
    await self.update_chat_ctx(self.chat_ctx)
Do you want an example that wraps the screenshot as
ImageContent
or one that appends the message as a single string? Sources: External data and RAG | LiveKit Docs | Vision | LiveKit Docs | Pipeline nodes and hooks | LiveKit docs
e
RuntimeError: trying to modify a read-only chat context, please use .copy() and agent.update_chat_ctx() to modify the chat context what is this error ?
t
You're seeing that RuntimeError because
self.chat_ctx
is read-only during execution. To modify and persist the agent's chat context you must: 1. Make a writable copy with
.copy()
. 2. Modify the copy (use
add_message()
or
insert()
on the copy). 3. Persist the changes with
await self.update_chat_ctx(copied_ctx)
. Concise example for your on_enter code:
Copy code
async def on_enter(self) -> None:
    extractor = DOMExtractor(page=self.page)
    llm_context = await extractor.get_current_snapshot()

    message = ChatMessage(
        role="system",
        content=[
            f"Latest DOM Snapshot: {time.time()}",
            llm_context.elements_text,
            llm_context.annotated_screenshot,  # wrap as image content if required
        ],
    )

    # create a mutable copy, modify it, then persist
    chat_ctx = self.chat_ctx.copy()
    chat_ctx.add_message(message)
    await self.update_chat_ctx(chat_ctx)
If you modified
turn_ctx
inside
on_user_turn_completed
, that
turn_ctx
is already editable — but you still need
await self.update_chat_ctx(turn_ctx)
to persist. Do you want an example that wraps the screenshot as
ImageContent
? Sources: Pipeline nodes and hooks | LiveKit docs | External data and RAG | LiveKit Docs
e
yes please an example for the on user turn completed
t
Below is a concise example of
on_user_turn_completed
that retrieves a RAG result, wraps a screenshot as
ImageContent
, modifies the mutable
turn_ctx
, and persists the change with
await self.update_chat_ctx(turn_ctx)
.
Copy code
from livekit.agents import Agent, ChatMessage, ImageContent

class MyAgent(Agent):
    async def on_user_turn_completed(self, turn_ctx, new_message) -> None:
        # 1) fetch RAG / retrieval content based on the user's latest message
        rag_content = await my_rag_lookup(new_message.text_content())

        # 2) get screenshot (e.g., base64 or URL) from your extractor
        annotated_screenshot = await my_screenshot_extractor(new_message)

        # 3) add a text message with retrieved content
        turn_ctx.add_message(
            role="system",
            content=f"Retrieved info: {rag_content}"
        )

        # 4) add the screenshot as ImageContent so the LLM can consume it
        img_msg = ChatMessage(
            role="assistant",
            content=ImageContent(image=annotated_screenshot)
        )
        turn_ctx.add_message(img_msg)

        # 5) persist the modified turn_ctx so future turns include these messages
        await self.update_chat_ctx(turn_ctx)
Notes: •
turn_ctx
passed into
on_user_turn_completed
is editable; modify it directly. • Use
ImageContent(image=...)
when your screenshot is an image URL or base64. • Call
await self.update_chat_ctx(turn_ctx)
to persist changes.