during conversatiin, how can I inject some context...
# ask-ai
f
during conversatiin, how can I inject some contexts into that conversation?
t
Thanks for reaching out, Kuniaki. 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 inject context into a conversation. Here are the practical ways you can do that in LiveKit Agents and when to use each. • Initial context (before the session): Preload data into the session's
ChatContext
(user name, preferences, metadata). Good for static session-wide info. ◦ Example: add an assistant message with the user's profile to
ChatContext
before
AgentSession.start
. • Dynamic context during the conversation (RAG-style): Use the
on_user_turn_completed
hook to fetch relevant data (KB, DB, embeddings) based on the latest user message and add it to the turn’s chat context. ◦ After adding messages to the turn context, call
update_chat_ctx()
to persist changes. • Tool calls for external lookups: Define tools (functions) the agent can call to retrieve live data. Tool outputs are appended to the conversation so the agent can use them in its reply. • Modify the incoming user message: In
on_user_turn_completed
you can edit or augment
new_message
(e.g., normalize intent, add tags or interpreted intent) so that the enriched content becomes part of the history. • Real-time status updates: If lookups take time, generate interim replies (e.g., “Searching the knowledge base…”) so users get verbal feedback while background context is retrieved. If you want, tell me which method you prefer and your stack (Python or Node), and I’ll provide a short code example tailored to that. Sources: External data and RAG | LiveKit Docs | Pipeline nodes and hooks | LiveKit docs | Testing and evaluation | LiveKit Docs | Agents v0.x migration guide - Node.js | LiveKit Docs
f
have 2 thoughts: • some contexts need to interrupt the conversation eg, emergency information • some contexts must notinterrupt the conversation but for the next conversation turn, agent's response should be based on that context. possible? then how?
t
You're asking if you can (1) inject context that immediately interrupts the conversation (e.g., emergency info) and (2) inject context that should affect the next turn only. Yes — both are possible. Here’s how to implement each pattern and when to use them. 1) Immediate interrupt (emergency / high-priority) • When you detect emergency info, add an assistant message with a clear high-priority instruction into the current turn context and immediately generate a reply so the user/participants hear it now. • Implementation pattern: a. Detect emergency (webhook, background monitor, or
on_user_turn_completed
logic). b. Add an assistant message to the live
ChatContext
describing the emergency (explicitly labeled). c. Call the session’s reply generation immediately (e.g.,
session.generate_reply(...)
) so the agent emits the interruption. • Notes: Make the message explicit and short (e.g., “EMERGENCY: Evacuate now — fire detected in building A”). Use this only for real high-priority signals to avoid unnecessary interruptions. 2) Non‑interrupting, affect next turn only • Add context into the chat context for the session or the next turn without producing an immediate reply, so the agent uses it when composing its next response. • Implementation pattern: a. Detect or assemble the context (background job, RAG lookup, tool output). b. In
on_user_turn_completed
(or via
update_chat_ctx()
), append the context as an assistant/system message or structured metadata on the
ChatContext
. c. Persist the change with
update_chat_ctx()
so the next time the agent composes a reply, that context is present. • Notes: If you want the context to only influence the next turn and not persist afterward, mark it and remove or overwrite it after the agent uses it. Practical tips and distinctions • Interrupt vs. next-turn is controlled by whether you trigger reply generation immediately. Adding the context + generating a reply = interrupt. Adding the context + persisting without generating = next-turn behavior. • Use clear roles/labels (assistant/system/metadata) and priority flags so hooks can treat messages differently. • For complex logic, implement a small priority queue: emergencies -> immediate add + generate; background enrichments -> append + persist for next turn. • If latency matters, send a brief interim reply (“Checking urgent data…”) while long lookups complete, then follow with the full context-driven response. Would you like a short Python or Node example showing (a) immediate interrupt generation and (b) appending context for the next turn?
f
python would be great
t
Below are concise Python examples showing both patterns using LiveKit Agents concepts: 1) Immediate interrupt (emergency): add a high-priority assistant/system message to the active chat context and immediately generate a reply so the agent speaks the interruption now.
Copy code
# Immediate interrupt example (emergency)
from livekit.agents import AgentSession, ChatContext, ChatMessage, MessageRole

async def handle_emergency(session: AgentSession, emergency_text: str):
    # Create a high-priority assistant/system message
    interrupt_msg = ChatMessage(role=MessageRole.ASSISTANT, content=f"EMERGENCY: {emergency_text}")
    # Add to the live session chat context
    session.chat_ctx.add_message(interrupt_msg)
    # Immediately generate and send a reply so it interrupts the conversation
    # You can customize instructions to ensure concise, urgent phrasing
    await session.generate_reply(instructions="Deliver the emergency message immediately and stop other processing.")
2) Non‑interrupting, apply to the next turn only: append context to the session chat context and persist it; do not generate an immediate reply. Optionally mark it so you can remove it after the next agent response.
Copy code
# Next-turn-only context example
from livekit.agents import AgentSession, ChatContext, ChatMessage, MessageRole

async def add_context_for_next_turn(session: AgentSession, context_text: str, mark_key: str = "one_time"):
    # Add as assistant/system message so the agent will see it on next turn
    ctx_msg = ChatMessage(role=MessageRole.ASSISTANT, content=f"[{mark_key}] {context_text}")
    session.chat_ctx.add_message(ctx_msg)
    # Persist the updated chat context so the agent includes it when composing the next reply
    await session.update_chat_ctx(session.chat_ctx)

async def cleanup_one_time_context(session: AgentSession, mark_key: str = "one_time"):
    # After the agent has used the context (e.g., in a subsequent hook or after detecting it's been consumed),
    # remove messages with the mark so they don't persist beyond the intended turn.
    new_msgs = [m for m in session.chat_ctx.messages if not (m.content and m.content.startswith(f"[{mark_key}]"))]
    session.chat_ctx.messages = new_msgs
    await session.update_chat_ctx(session.chat_ctx)
Practical notes: • Interrupt vs next-turn behavior is controlled by whether you call
generate_reply()
immediately after adding the context. • Use clear labels/flags (like
"[one_time]"
) so you can identify and remove one-time context after the agent consumes it. • For emergency sources, run detection in a webhook/monitor or in
on_user_turn_completed
, add the interrupt message, then call
generate_reply()
to ensure immediate output. • For time-consuming lookups, consider sending a brief interim reply before or while enriching context. Would you like this adapted to a complete Agent class with
on_user_turn_completed
hooks showing both flows?
f
yes
t
Thanks — below is a complete, concise Python Agent class that implements both patterns you asked for: • Immediate interrupt (emergency): injected and delivered right away by canceling the current reply and generating an emergency reply. • Non-interrupting, next-turn-only context: injected in
on_user_turn_completed
, persisted for the next turn, then cleaned up after use. Copy-paste and adapt the snippets for your STT/LLM/TTS plugins and environment.
Copy code
import asyncio
from dataclasses import dataclass
from typing import Optional, AsyncIterable

from livekit import rtc
from livekit.agents import (
    Agent,
    AgentSession,
    ChatContext,
    ChatMessage,
    MessageRole,
    JobContext,
    stt,
    llm,
    tts,
    vad,
)


@dataclass
class AgentState:
    urgent_alert: Optional[str] = None
    one_time_mark: str = "[ONE_TIME]"


class ContextAgent(Agent):
    def __init__(self, chat_ctx: ChatContext, stt_plugin: stt.STT, llm_plugin: llm.LLM, tts_plugin: tts.TTS, vad_plugin: vad.VAD):
        super().__init__(chat_ctx=chat_ctx, stt=stt_plugin, llm=llm_plugin, tts=tts_plugin, vad=vad_plugin)
        self.state = AgentState()

    async def on_enter(self) -> None:
        await self.session.generate_reply(instructions="Greet the user and offer help.")

    async def on_user_turn_completed(self, turn_ctx: ChatContext, new_message: ChatMessage) -> None:
        # Non-urgent: enrich context for next turn only
        # Example: if user mentions "order", add one-time order info to be used on next reply
        if new_message.text_content and "order" in new_message.text_content.lower():
            turn_ctx.add_message(
                role=MessageRole.SYSTEM,
                content=f"{self.state.one_time_mark} User's last order: #1234 (delivered Tue). Use this when answering next turn."
            )
            # Persist so LLM sees it for the next reply
            await self.update_chat_ctx(turn_ctx)

    async def stt_node(self, audio: AsyncIterable[rtc.AudioFrame], model_settings: stt.ModelSettings) -> Optional[AsyncIterable[stt.SpeechEvent]]:
        # Early interruption point: if an urgent alert exists, interrupt and generate emergency reply immediately
        if self.state.urgent_alert:
            # stop any in-progress generation
            self.session.cancel_reply()
            # Inject an emergency assistant message into session chat context
            self.session.chat_ctx.add_message(ChatMessage(role=MessageRole.ASSISTANT, content=f"EMERGENCY: {self.state.urgent_alert}"))
            # Immediately generate and output the urgent reply
            await self.session.generate_reply(instructions="Deliver the emergency message immediately, concisely, and clearly.")
            # clear the alert so we don't repeat
            self.state.urgent_alert = None
            return None  # abort normal STT processing for this pass

        # Otherwise proceed with default STT processing
        return await Agent.default.stt_node(self, audio, model_settings)

    async def llm_node(self, chat_ctx: llm.ChatContext, model_settings: llm.ModelSettings):
        # Optionally inject urgent/system context just before LLM runs
        if self.state.urgent_alert:
            chat_ctx.add_message(role="system", content=f"URGENT: {self.state.urgent_alert}")
            # don't clear here if you want stt_node to control immediate generation
        # Run default LLM node (streams replies)
        async for chunk in await Agent.default.llm_node(self, chat_ctx, model_settings):
            yield chunk

    # Optional helper to schedule an external urgent alert (simulate webhook/monitor)
    def push_urgent_alert(self, text: str):
        self.state.urgent_alert = text

    # Optional cleanup helper to remove one-time messages after they've been used
    async def cleanup_one_time_messages(self):
        mark = self.state.one_time_mark
        msgs = [m for m in self.session.chat_ctx.messages if not (m.content and m.content.startswith(mark))]
        self.session.chat_ctx.messages = msgs
        await self.update_chat_ctx(self.session.chat_ctx)


# Example job entrypoint wiring the agent into a session and simulating an external alert
async def entrypoint(ctx: JobContext):
    agent = ContextAgent(
        chat_ctx=ChatContext(),
        stt_plugin=stt.YourSTTPlugin(language="en"),
        llm_plugin=llm.YourLLMPlugin(model="gpt-4o-mini"),
        tts_plugin=tts.YourTTSPlugin(),
        vad_plugin=vad.YourVADPlugin(),
    )

    # Simulate an external emergency arriving later
    async def emergency_simulator():
        await asyncio.sleep(5)
        agent.push_urgent_alert("Fire alarm triggered in building A — evacuate immediately.")
    asyncio.create_task(emergency_simulator())

    session = AgentSession(agent=agent)
    await session.start(ctx.room)
Notes: • To make context non-persistent beyond the next turn, mark it (here
"[ONE_TIME]"
) and remove it after the agent uses it (call
cleanup_one_time_messages()
from a suitable hook or after the LLM reply). • Interrupt behavior is triggered by setting
state.urgent_alert
from any external monitor/webhook;
stt_node
cancels current generation and forces immediate output. • Adjust roles (system/assistant) and instruction text to match desired LLM behavior and verbosity. Would you like this adapted to a minimal runnable example with a specific STT/LLM/TTS plugin (I can tailor to your stack)? Sources: Pipeline nodes and hooks | LiveKit docs
f
do I need to create a new sub class of Agent?
t
Short answer: Yes — subclassing Agent is the typical and recommended way to implement both interrupting and next-turn context injection, because you need to override lifecycle hooks (like
on_user_turn_completed
,
stt_node
, and
llm_node
) and call session methods (
generate_reply
,
cancel_reply
,
update_chat_ctx
). Why subclassing helps: • Lets you implement
on_user_turn_completed
to append RAG/lookups for the next turn. • Lets you inspect/intercept audio or STT in
stt_node
to detect urgent signals and call
session.cancel_reply()
+
generate_reply()
for immediate interrupts. • Lets you inject or modify LLM input in
llm_node
if you need last‑moment context. • Keeps state (flags/one-time marks) on the agent instance for easy coordination. Alternatives: • If your environment provides hooks/callbacks at the session layer (outside of Agent), you can implement similar logic there. But you still need to call the same session methods to persist context or force replies. • If you only need simple one-off context (no STT interception), you can manipulate
ChatContext
directly from an external process and call
update_chat_ctx()
/
generate_reply()
without subclassing — but that’s less flexible and harder to coordinate for real-time interrupts. If you want, I can: • Show a minimal subclass focused only on the two hooks you need, or • Show how to implement the same behavior from outside an Agent (session-level callbacks). Which would you prefer?