fast-egg-39595
08/24/2025, 7:19 PMtall-airline-16756
08/24/2025, 7:19 PMtall-airline-16756
08/24/2025, 7:20 PMchat_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:
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 Docsfast-egg-39595
08/24/2025, 7:33 PMtall-airline-16756
08/24/2025, 7:34 PMsession.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 Docsfast-egg-39595
08/24/2025, 7:37 PMtall-airline-16756
08/24/2025, 7:37 PMfrom 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:
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:
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.pyfast-egg-39595
08/24/2025, 7:38 PMtall-airline-16756
08/24/2025, 7:40 PMsession.session_update() method is your friend for updating turn detection parameters dynamically. Here’s a quick example:
@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 Agentsfast-egg-39595
08/24/2025, 9:10 PMgoogle.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
# 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 LLMtall-airline-16756
08/24/2025, 9:12 PMfrom 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
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
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 Docsfast-egg-39595
08/24/2025, 9:21 PMtall-airline-16756
08/24/2025, 9:22 PMupdate_agent method on your AgentSession instance. Here are a few ways you can do this:
1. Direct Agent Update
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:
@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:
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:
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.pyfast-egg-39595
08/24/2025, 9:57 PMtall-airline-16756
08/24/2025, 9:58 PMchat_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.pyfast-egg-39595
08/24/2025, 11:19 PMsession.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?tall-airline-16756
08/24/2025, 11:20 PMsession.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 Docsfast-egg-39595
08/25/2025, 4:07 AMtall-airline-16756
08/25/2025, 4:07 AMchat_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 Docsfast-egg-39595
08/25/2025, 5:52 AMtall-airline-16756
08/25/2025, 5:52 AMsession.history to get the full conversation history. For example:
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:
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:
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