using 1.x agent , if I have mutiple agents that I ...
# ask-ai
f
using 1.x agent , if I have mutiple agents that I switch to and from throughout a given session, is the context managed for me, or do I need to build my own context management system? For example if I start with a 'realtime google live api' agent and move to an open ai agent that isn't realtime, will the context of the conversation that took place with google's model transfer to the open ai one?
t
Thanks for reaching out, Doug. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
Hey there! Just a heads-up: LiveKit 1.x agents don’t automatically keep track of context when you switch between different agents during a session. By default, each new agent starts fresh with a clean slate for their LLM prompt. If you want to keep the conversation flowing smoothly and preserve context across agent switches, you’ll need to handle this in your code. A great way to do this is by setting the
chat_ctx
parameter in the
Agent
constructor. This lets you copy the previous agent’s
chat_ctx
or create a new one based on what makes sense for your setup, so the context stays relevant. Here’s a handy pattern to follow: • Keep a reference to the previous agent in your user data. • In the
on_enter
method, copy the chat context from that previous agent and add any important details to the current agent’s context. • Don’t forget to trim the conversation history to keep only the most important messages (like the last N messages) so things don’t get too bulky. For example:
Copy code
async def on_enter(self):
    chat_ctx = self.chat_ctx.copy()

    # If there was a previous agent, inherit its chat context
    if userdata.prev_agent:
        items_copy = self._truncate_chat_ctx(
            userdata.prev_agent.chat_ctx.items, 
            keep_function_call=True,
            keep_last_n_messages=200
        )
        existing_ids = {item.id for item in chat_ctx.items}
        items_copy = [item for item in items_copy if item.id not in existing_ids]
        chat_ctx.items.extend(items_copy)

    await self.update_chat_ctx(chat_ctx)
Also, just so you know, the full conversation history for the session is stored in
session.history
, which you can tap into if you ever need the complete picture. Sources: multi-agent/long_or_short_agent.py | Workflows | LiveKit Docs
f
if I"m using a realtime model like google live API, does the session.say (with allow_interruptions = false) work? Or is that only for non realtime models?
t
Hey there! Just a heads-up: when you're using a realtime model like Google Live API with server-side turn detection turned on,
session.say
combined with
allow_interruptions=False
won’t work as expected. The system will give a warning and skip that setting. This happens because realtime models depend on server-side turn detection, which doesn’t play well with uninterruptible speech. But don’t worry! To get uninterruptible speech with realtime models, you’ve got a couple of options: • Turn off turn detection in the RealtimeModel. • Or, use Voice Activity Detection (VAD) on the AgentSession instead. Another approach is to try the
generate_reply()
method with
allow_interruptions=False
, which might work better with realtime model setups. If you want a hand setting this up or figuring out the best approach, just give me a shout—I’m here to help! Sources: livekit-agents/livekit/agents/voice/agent_activity.py | Agent speech and audio | LiveKit Docs
f
what do you mean by "turn off detection in the realtimeModel?
t
Hey there! If you want to disable turn detection in a RealtimeModel, it really depends on which provider you're using. Let me break it down for you: For OpenAI Realtime API:
Copy code
from livekit.plugins import openai

llm = openai.realtime.RealtimeModel(
    voice="alloy",
    turn_detection=None,  # This will turn off server-side turn detection
    input_audio_transcription=None,  # Optional: disable if you’re using separate STT
)
For Gemini Live API:
Copy code
from google.genai import types
from livekit.plugins import google

llm = google.beta.realtime.RealtimeModel(
    realtime_input_config=types.RealtimeInputConfig(
        automatic_activity_detection=types.AutomaticActivityDetection(
            disabled=True,
        ),
    ),
    input_audio_transcription=None,  # Optional: disable if you’re using separate STT
)
Now, if you turn off server-side turn detection, you can totally use LiveKit’s own turn detection model instead. Here’s a quick example to get you started:
Copy code
from livekit.agents import AgentSession
from livekit.plugins.turn_detector.multilingual import MultilingualModel
from livekit.plugins import deepgram

session = AgentSession(
    turn_detection=MultilingualModel(),
    stt=deepgram.STT(),  # You’ll need this for LiveKit’s turn detection
    llm=openai.realtime.RealtimeModel(
        voice="alloy",
        turn_detection=None,  # Disables OpenAI’s turn detection
        input_audio_transcription=None,
    ),
)
If you have any questions or want me to walk you through this setup, just give me a shout—I’m here to help! Sources: Gemini Live API integration guide | LiveKit Docs | Turn detection and interruptions | LiveKit Docs | livekit-agents/livekit/agents/voice/agent_activity.py
f
can I dynamically change that setting throughout a session (switching vad types and responsbilities)?
t
Yes, you can definitely adjust turn detection settings, like VAD types and their roles, on the fly during a session—especially when you're working with realtime models. With realtime models, the
session.session_update()
method is your friend for updating turn detection parameters dynamically. Here’s a quick example:
Copy code
@ctx.room.local_participant.register_rpc_method("pg.updateConfig")
async def update_config(data: rtc.rpc.RpcInvocationData):
    new_config = parse_session_config(json.loads(data.payload))
    if config != new_config:
        session = model.sessions[0]
        session.session_update(
            instructions=new_config.instructions,
            voice=new_config.voice,
            temperature=new_config.temperature,
            max_response_output_tokens=new_config.max_response_output_tokens,
            turn_detection=new_config.turn_detection,
            modalities=new_config.modalities,
        )
Here are the parameters you can tweak dynamically: • `threshold`: Controls VAD sensitivity (between 0.0 and 1.0) • `silence_duration_ms`: How long silence needs to be before a turn ends • `prefix_padding_ms`: Minimum speech length to kick off a turn If you’re using non-realtime models, updating on the fly is a bit trickier and might mean restarting the session or switching agents. Just give me a shout if you want a hand with that! Sources: livekit-plugins/livekit-plugins-openai/livekit/plugins/openai/stt.py | Turn detection and interruptions | LiveKit Docs | agent/main.py | SessionUpdateEvent | LiveKit Agents
f
"How do I switch from Gemini Realtime to OpenAI Realtime mid-session with context preservation?" I'm trying to switch LLM backends during an active session: • Start:
google.beta.realtime.RealtimeModel
(Gemini) • Switch to:
openai.realtime.RealtimeModel
(OpenAI) • After 30-60 seconds Current approach using
session.update_agent(new_agent)
doesn't work - it keeps using Gemini's backend even after the switch (confirmed by Google API warnings appearing after switch). Requirements: 1. Switch the actual LLM backend, not just agent instructions 2. Preserve conversation context across the switch 3. Change voice from Gemini's Puck to OpenAI's echo Is this possible with LiveKit 1.x? If so, what's the correct pattern? Code attempt: python
Copy code
# Initial session with Gemini
session = AgentSession(
    llm=google.beta.realtime.RealtimeModel(...)
)
await session.start(room=ctx.room, agent=GeminiAgent())
# Later, trying to switch (doesn't work)
openai_agent = OpenAIAgent()  # Has different instructions
session.update_agent(openai_agent)  # Only updates instructions, not LLM
t
Hey there! Just wanted to share how you can smoothly switch from Gemini Realtime to OpenAI Realtime mid-session without losing any context, using agent handoff and the unified ChatContext API. Here's a simple walkthrough: Step 1: Create Both Realtime Model Instances
Copy code
from livekit.plugins import openai, google

# Initialize both realtime models
gemini_model = google.beta.realtime.RealtimeModel()
openai_model = openai.realtime.RealtimeModel()
Step 2: Implement Context-Preserving Agent Classes
Copy code
class GeminiRealtimeAgent(Agent):
    def __init__(self, chat_ctx=None):
        super().__init__(
            instructions="You are using Gemini Realtime API",
            llm=gemini_model,
            chat_ctx=chat_ctx  # Keep the existing context intact
        )

    @function_tool
    async def switch_to_openai(self):
        # Grab the current chat context
        current_context = self.session.chat_ctx.copy()
        return OpenAIRealtimeAgent(chat_ctx=current_context)

class OpenAIRealtimeAgent(Agent):
    def __init__(self, chat_ctx=None):
        super().__init__(
            instructions="You are now using OpenAI Realtime API",
            llm=openai_model,
            chat_ctx=chat_ctx  # Preserve the conversation history
        )
Step 3: Handle Context Transfer Both Gemini and OpenAI realtime models support the
chat_ctx
property and
update_chat_ctx
method. You can copy and, if needed, trim the context to keep only the important messages. Step 4: Example Implementation
Copy code
class RealtimeProviderSwitcher(Agent):
    def __init__(self):
        super().__init__(
            instructions="Multi-provider realtime agent",
            llm=gemini_model
        )
        self.current_provider = "gemini"

    @function_tool
    async def switch_to_openai_realtime(self):
        if self.current_provider == "openai":
            return "You're already using OpenAI Realtime API!"

        current_context = self.session.chat_ctx.copy()
        new_context = llm.ChatContext()
        new_context.items.extend(current_context.items)
        new_context.add_message(
            role="system",
            content="Switching to OpenAI Realtime API. Let's keep the conversation flowing smoothly."
        )
        return OpenAIRealtimeAgent(chat_ctx=new_context)
This way, you keep the conversation going seamlessly even when switching between LLM backends. If you'd like, I’m here to help you set this up or tweak it to fit your needs—just let me know! Sources: livekit-plugins/livekit-plugins-google/livekit/plugins/google/beta/realtime... | Agents 0.x migration guide | LiveKit Docs
f
what if I want to trigger the agent change directly and not as part of a function being called by the LLM?
t
Hey there! You can easily trigger an agent change right in LiveKit 1.x without needing to rely on LLM function calls by using the
update_agent
method on your
AgentSession
instance. Here are a few ways you can do this: 1. Direct Agent Update
Copy code
session.update_agent(new_agent_instance)
2. Using RPC Methods You can register an RPC method that lets external clients trigger agent changes like this:
Copy code
@ctx.room.local_participant.register_rpc_method("change_agent")
async def on_change_agent(data: rtc.RpcInvocationData):
    if data.payload == "short_agent":
        new_agent = ShortAgent()
    elif data.payload == "long_agent":
        new_agent = LongAgent()
    session.update_agent(new_agent)
3. Based on Room Events Another neat way is to trigger agent changes based on room events, such as when participants connect:
Copy code
async def entrypoint(ctx: JobContext):
    session = AgentSession()
    await session.start(agent=InitialAgent(), room=ctx.room)

    @ctx.room.on("participant_connected")
    def on_participant_connected(participant):
        if participant.name.startswith("vip"):
            session.update_agent(VIPAgent())
4. Conditional Agent Changes You can also switch agents based on participant properties or other conditions during the agent’s lifecycle:
Copy code
class ConditionalAgent(Agent):
    async def on_enter(self):
        if self.session.participant.name.startswith("sip"):
            self.session.update_agent(PhoneAgent())
        else:
            self.session.generate_reply()
These options give you lots of flexibility to control agent transitions based on whatever external conditions or events you have going on. If you want a hand setting any of these up, just let me know—I’m here to help! Sources: examples/voice_agents/toggle_io.py | basics/change_agent_instructions.py
f
'AgentSession' object has no attribute 'chat_ctx'. Did you mean: '_chat_ctx'?
t
Hey there! Just a quick heads-up: the right attribute to access the chat context in LiveKit 1.x is
chat_ctx
(without the underscore). The
_chat_ctx
is actually for internal use, so it’s best not to touch that one directly. If you’re running into any errors, double-check that you’re using
chat_ctx
when working with the public API of
AgentSession
or
Agent
. And if you’re still stuck or want me to explain anything further, just give me a shout—I’m here to help! Sources: examples/voice_agents/restaurant_agent.py
f
using this as my agent "_#!/usr/bin/env python3_ """ Minimal test demonstrating chat_ctx AttributeError Testing LiveKit's claim that 'chat_ctx' is the correct public API """ import os import sys import logging import asyncio from dotenv import load_dotenv # Suppress ALL verbose logging BEFORE importing LiveKit logging.getLogger("websockets").setLevel(logging.ERROR) logging.getLogger("websockets.client").setLevel(logging.ERROR) logging.getLogger("websockets.server").setLevel(logging.ERROR) logging.getLogger("websockets.protocol").setLevel(logging.ERROR) logging.getLogger("livekit").setLevel(logging.ERROR) logging.getLogger("google").setLevel(logging.ERROR) logging.getLogger("urllib3").setLevel(logging.ERROR) logging.getLogger("asyncio").setLevel(logging.ERROR) logging.getLogger("httpcore").setLevel(logging.ERROR) logging.getLogger("httpx").setLevel(logging.ERROR) # Now import LiveKit from livekit import agents from livekit.agents import AgentSession, Agent from livekit.plugins import google # Setup load_dotenv() logging.basicConfig(level=logging.ERROR, format='%(message)s') logger = logging.getLogger("chat_ctx_test") class TestAgent(Agent): def __init__(self): super().__init__( instructions="Test agent", llm=google.beta.realtime.RealtimeModel( model="gemini-2.5-flash-exp-native-audio-thinking-dialog", api_key=os.getenv("GOOGLE_GEMINI_API_KEY") ) ) async def entrypoint(ctx: agents.JobContext): print("="*60) print("CHAT CONTEXT ATTRIBUTE TEST") print("="*60) # Create and start session session = AgentSession() await session.start( room=ctx.room, agent=TestAgent() ) print("✅ Session started successfully\n") print("TESTING CHAT CONTEXT ACCESS:") print("-"*40) # Test 1: Try public API as LiveKit claims print("1. Trying session.chat_ctx (LiveKit says this is correct):") try: context = session.chat_ctx print(f" ✅ SUCCESS: {type(context)}") except AttributeError as e: print(f" ❌ FAILED: {e}") # Test 2: Try what error message suggests print("\n2. Trying session._chat_ctx (error suggests this):") try: context = session._chat_ctx print(f" ✅ EXISTS: {type(context)}") except AttributeError as e: print(f" ❌ FAILED: {e}") # Test 3: Try history print("\n3. Trying session.history:") try: history = session.history print(f" ✅ EXISTS: {type(history)}") except AttributeError as e: print(f" ❌ FAILED: {e}") # Show available attributes print("\n" + "="*60) print("AVAILABLE ATTRIBUTES WITH 'chat' or 'context':") for attr in dir(session): if 'chat' in attr.lower() or 'context' in attr.lower() or 'history' in attr.lower(): print(f" - {attr}") print("="*60) # Wait a moment before shutting down await asyncio.sleep(2) if name == "__main__": agents.cli.run_app(agents.WorkerOptions(entrypoint_fnc=entrypoint))" We get "TESTING CHAT CONTEXT ACCESS: ---------------------------------------- 1. Trying session.chat_ctx (LiveKit says this is correct): ❌ FAILED: 'AgentSession' object has no attribute 'chat_ctx' 2. Trying session._chat_ctx (error suggests this): ✅ EXISTS: <class 'livekit.agents.llm.chat_context.ChatContext'> 3. Trying session.history: ✅ EXISTS: <class 'livekit.agents.llm.chat_context.ChatContext'> ============================================================ AVAILABLE ATTRIBUTES WITH 'chat' or 'context': - _chat_ctx - _job_context_cb_registered - _root_span_context - history ============================================================ process exiting" as a result, but You said
session.chat_ctx
is the correct public API, but it doesn't exist.. Facts: •
session.chat_ctx
does NOT exist (AttributeError) •
session._chat_ctx
exists but you said it's internal •
session.history
also exists and is the same type My use case: I need to switch from Gemini to OpenAI agent mid-session and preserve conversation context. Please clarify: 1. Should I use
session.history
instead of
session.chat_ctx
? 2. Is there documentation showing
session.chat_ctx
actually working? 3. What's the correct way to pass context when switching agents?
t
Hey there! I wanted to help clear things up about preserving context when you switch agents mid-session. Here’s a quick rundown: 1. Should I use
session.history
instead of
session.chat_ctx
?
Great question! Yes,
session.history
is the way to go if you want the full conversation history. The
chat_ctx
is tied to each individual agent, while
session.history
gives you the whole picture of the session’s context. 2. Is there documentation showing
session.chat_ctx
actually working?
So, the
chat_ctx
lives on each agent, not directly on
AgentSession
. To keep the context when switching, you’ll want to pass the agent’s
chat_ctx
over to the new agent during the handoff. 3. What’s the best way to pass context when switching agents? The easiest and cleanest way is to explicitly pass the chat context during the handoff. Here’s a quick example: `class NewAgent(Agent): def __init__(self, chat_ctx): super().__init__( instructions="New agent instructions", chat_ctx=chat_ctx ) # During the switch current_context = session.history # Or use the current agent's chat_ctx new_agent = NewAgent(chat_ctx=current_context) session.update_agent(new_agent)`This way, your conversation flow stays smooth and nothing gets lost between agents. If you want me to walk you through this or need any more help, just let me know—I’m here for you! Sources: Workflows | LiveKit Docs | complex-agents/role-playing/README.md | livekit-agents/livekit/agents/llm/chat_context.py | Agents v0.x migration guide | LiveKit Docs | Agents 0.x migration guide | LiveKit Docs
f
what is the difference between the content in chat.ctx and session.history?
t
Let me help you understand the difference between
chat_ctx
and
session.history
in LiveKit 1.x — it mainly comes down to their scope and what they’re used for: • `chat_ctx`: Think of this as the conversation context just for one agent. It includes the prompt history sent to the LLM and can be tailored or reset for each agent. It helps manage how that agent interacts with the LLM and can be updated or passed along if you switch agents. • `session.history`: This is the full conversation history for the whole session. It sticks around even if agents change, acting like a complete log of everything that’s happened during the session. Unlike
chat_ctx
, it’s not reset or customized per agent. So, to sum it up:
chat_ctx
is all about each individual agent’s interaction with the LLM, while
session.history
keeps track of the entire conversation throughout the session. If you want me to explain anything more, just let me know—I’m here to help! Sources: Agents v0.x migration guide | LiveKit Docs | Pipeline nodes and hooks | LiveKit Docs | Voice pipeline nodes | LiveKit Docs | Workflows | LiveKit Docs | Workflows | LiveKit Docs
f
making progress, but The Issue • ✅ Gemini → OpenAI: Context preserved • ❌ OpenAI → Gemini: Context lost (Gemini doesn't remember) Here is my agent """" Voice Test - Ultra-simple test to verify voice changes Each model announces itself clearly """ import os import asyncio from dotenv import load_dotenv load_dotenv(".env") from livekit import agents from livekit.agents import AgentSession, Agent from livekit.plugins import google, openai class GeminiVoiceTest(Agent): def __init__(self, ctx=None): super().__init__( llm=google.beta.realtime.RealtimeModel( model="gemini-2.5-flash-exp-native-audio-thinking-dialog", voice="Puck", # Male voice api_key=os.getenv("GOOGLE_GEMINI_API_KEY"), ), instructions="Start every response with: 'This is Puck from Gemini speaking.' Speak slowly and clearly.", chat_ctx=ctx ) async def on_enter(self): print("\n>>> GEMINI/PUCK ACTIVE - Listen for male voice <<<\n") await asyncio.sleep(20) ctx = self.session.history.copy() if self.session.history else None self.session.update_agent(OpenAIVoiceTest(ctx)) class OpenAIVoiceTest(Agent): def __init__(self, ctx=None): super().__init__( llm=openai.realtime.RealtimeModel( model="gpt-4o-realtime-preview", voice="shimmer", # Female voice ), instructions="Start every response with: 'This is Shimmer from OpenAI speaking.' Speak slowly and clearly.", chat_ctx=ctx ) async def on_enter(self): print("\n>>> OPENAI/SHIMMER ACTIVE - Listen for female voice <<<\n") await asyncio.sleep(20) ctx = self.session.history.copy() if self.session.history else None self.session.update_agent(GeminiVoiceTest(ctx)) async def entrypoint(ctx: agents.JobContext): print("\n" + "="*60) print("VOICE TEST - 20 second switches") print("PUCK (Gemini) = Male voice") print("SHIMMER (OpenAI) = Female voice") print("Each should announce itself") print("="*60 + "\n") session = AgentSession() await session.start(room=ctx.room, agent=GeminiVoiceTest()) if name == "__main__":"
t
It looks like the context might be getting lost when switching from OpenAI Realtime to Gemini Realtime because Gemini's RealtimeModel isn’t receiving or handling the context properly. Here’s a friendly step-by-step to help you fix this: 1. Grab the Current Context: Before switching agents, use
session.history
to get the full conversation history. For example:
Copy code
ctx = self.session.history.copy() if self.session.history else None
1. Send the Context to the New Agent: When you create the new agent, make sure to pass
chat_ctx
explicitly like this:
Copy code
self.session.update_agent(GeminiVoiceTest(ctx))
1. Double-Check Compatibility: Make sure Gemini's RealtimeModel can handle the context you're passing. If needed, you can add a system message to keep things flowing smoothly:
Copy code
ctx.add_message(
    role="system",
    content="Switching back to Gemini. Please continue the conversation seamlessly."
)
If you hit any snags or want me to help debug further, just let me know—I’m here to help! Sources: livekit-plugins/livekit-plugins-openai/livekit/plugins/openai/realtime/real... | agent/main.py | Workflows | LiveKit Docs