c
hi
t
Thanks for reaching out, Joshua. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
Hi — welcome to LiveKit. How can I help you today? If you’re starting from scratch, tell me what you’re building (platform, SDK/language, and goal). If you’re troubleshooting, share the error message, room ID, and a brief description of what steps you’ve tried.
c
any idea why the agents go completely silent after a transfer to subagent or a tool call?
t
Thanks — I’m responding about agents going silent after a transfer to a subagent or a tool call. Likely causes and quick checks: • TTS / LiveKit API client not initialized for the subagent. Confirm
livekit_api
is present in
userdata
for the subagent so audio can be generated. • Handoff not preserving conversation state. Ensure you pass
chat_ctx
when calling
session.update_agent()
so the new agent resumes the dialogue. • Audio was disabled and never re-enabled. Check that
session.input.set_audio_enabled(...)
and
session.output.set_audio_enabled(...)
are re-enabled after the tool call or transfer (use a
finally
block if the tool can error). • Subagent lacks a TTS plugin or voice override. Verify the subagent’s constructor config includes a valid TTS model/voice. • Silence detection or timeout disconnected the room. Confirm any
SILENCE_THRESHOLD
or silence-detection logic isn’t ending the session during long tool calls. What I need from you to narrow this down: 1. Are you using a handoff (subagent) or a tool call when silence occurs? 2. Share the sequence: what the agent does, the transfer/tool call code snippet (especially
session.update_agent()
and any audio enable/disable calls), and any error logs or exceptions around the transfer. 3. Does the main agent speak normally before the transfer? Does silence start immediately after transfer/tool returns, or after a delay? Send those details and I’ll point to the exact lines to check and a minimal fix. Sources: Company directory phone assistant | LiveKit docs | Agents and handoffs | LiveKit docs | Text and transcriptions | LiveKit docs | Agents Framework | livekit/livekit_composite | DeepWiki
c
were using gemini live api and a cartisia tts model, were also doing this thing with silent transfers and an audio that plays. We are also doing this thing where when the audio plays we route and when a tool call occurs we route
t
Thanks — I’m following up about silence after silent transfers, audio playback routing, and tool calls with Gemini Live API + Cartisia TTS. Quick checklist to confirm (these are the highest-impact places to check first): • Is
livekit_api
initialized and present in the subagent’s
userdata
so the TTS audio can be generated and injected after transfer? • After you perform the silent transfer and/or tool call, do you explicitly re-enable audio output with
session.output.set_audio_enabled(True)
(and input if needed) in a
finally
block? • Does the subagent have a TTS plugin/voice configured (Cartisia model) or an override in its constructor so `say()`/TTS calls actually produce audio? • When you “route” during audio playback or tool calls, are you changing the session/room state (e.g., switching tracks, muting participants, or reattaching sinks) that could stop audio from reaching the participant? • Any silence-detection or
SILENCE_THRESHOLD
logic that might disconnect or suppress output during long tool calls? To diagnose further, please share: 1. Whether silence happens immediately after the transfer/tool returns or after a delay. 2. Short code snippets showing: ◦ the transfer call (
session.update_agent(...)
) including how you pass `chat_ctx`/`userdata`, ◦ where you enable/disable audio (
session.input.set_audio_enabled
,
session.output.set_audio_enabled
), ◦ the routing logic you run during audio playback and on tool calls. 1. Any error logs or exceptions around the transfer, tool execution, or TTS generation. Send those snippets/log lines and I’ll point to exact lines or a minimal patch to fix the silent behavior.
c
we have generate replies written to each each via base agent code for routing the subagent they have a generate reply with instructions sent that the root agent did like collected info we pass that along using generate reply the agent currently does not say anything after transfer or sometimes we see the transfer is super late is well and then the agent speak but there is still a considerable silence of about 10s sometimes
t
Thanks — I’m responding about the delayed/quiet behavior after your silent transfer + routed audio + tool calls with Gemini Live + Cartisia TTS. A few targeted questions so I can pinpoint the problem and give a minimal patch: 1. Does the subagent ever call
say()
or
generate_reply().say()
immediately after
session.update_agent()
? If not, is
generate_reply()
invoked as part of the subagent’s activation flow or only later? 2. Show the exact
session.update_agent(...)
call (how you pass
chat_ctx
and
userdata
). Also show how you attach/initialize
livekit_api
and the TTS plugin for the subagent. 3. Show the code where you disable/enable audio around the transfer/tool call (any
session.input.set_audio_enabled(...)
or
session.output.set_audio_enabled(...)
), including try/finally blocks. 4. Show the routing code you run during audio playback and on tool calls (how you switch sinks/tracks or mute/unmute participants). 5. Paste relevant logs around a problematic transfer: timestamps for transfer start/completion, TTS generation start/completion, and the first outgoing audio packet or
say()
call. Quick hypotheses while you gather snippets: • The subagent may be created but not immediately calling `say()`; transfer latency + TTS generation combined produce the 10s gap. •
livekit_api
or TTS not available instantly in
userdata
, causing delayed initialization before speech. • Routing changes (re-attaching sinks/tracks or muting) introduce extra time before audio reaches the user. • Audio was disabled during tool call and re-enable happens after delays (or not in a
finally
), causing silence. If you share the snippets/log lines above I’ll point to the specific lines to change (minimal code fixes and where to re-enable audio or pre-warm TTS/livekit_api). Would you like me to prioritize looking for transfer timing vs audio routing issues first?
c
async def on_enter(self): agent_name = self.class.name print("current agent", agent_name) userdata: UserData = self.session.userdata chat_ctx = self.chat_ctx.copy() if userdata.prev_agent: items_copy = self._truncate_chat_ctx( userdata.prev_agent.chat_ctx.items, keep_function_call=False ) 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) if userdata.greet: summary = userdata.summarize() instructions = ( "Continue the conversation naturally as the same voice assistant that can talk. " "Do not mention transfers or internal modules.\n\n" f"Verified patient data:\n{summary if summary else 'No verified patient data available.'}" ) await self.session.generate_reply(instructions=instructions) else: await self.update_instructions( self._instructions.replace( "associated_phone_number_var", userdata.caller_phone_number ) ) if userdata.was_dispatched: logger.info( f"🚨 RootAgent was dispatched by router agent - skipping initial greeting" ) instructions = self.ROOT_TRANSFER_INSTRUCTION_TEMPLATE.format( agent_name=agent_name, core_data=userdata.summarize_router(), transfer_intent=userdata.get_transfer_intent(), information_collected_from_patient=userdata.collected_information_by_last_agent(), ) logger.info(f"Instructions sent to LLM: {instructions}") await self.mute(True) self.session.generate_reply(instructions=instructions) await self.mute(False) else: await self.mute(True) await self.speech_audio(audio="greeting") await self.mute(False) userdata.greet = True def _truncate_chat_ctx( self, items: list, keep_last_n_messages: int = 80, keep_system_message: bool = False, keep_function_call: bool = False, ) -> list: """Truncate the chat context to keep the last n messages.""" def _valid_item(item) -> bool: if ( not keep_system_message and item.type == "message" and item.role == "system" ): return False if not keep_function_call and item.type in [ "function_call", "function_call_output", ]: return False return True new_items = [] for item in reversed(items): if _valid_item(item): new_items.append(item) if len(new_items) >= keep_last_n_messages: break new_items = new_items[::-1] while new_items and new_items[0].type in [ "function_call", "function_call_output", ]: new_items.pop(0) return new_items async def _transfer_to_agent( self, name: str, context: RunContext_T, transfer_reason: Optional[str] = None ) -> Agent: """Transfer to another agent while preserving context and capturing intent""" userdata = context.userdata current_agent = context.session.current_agent next_agent = userdata.persona[name] # capture transfer reason/intent if provided if transfer_reason: userdata.transfer_reason = transfer_reason try: if transfer_reason not in userdata.intent: userdata.intent.append(transfer_reason) except Exception: pass userdata.prev_agent = current_agent return next_agent async def mute(self, flag: bool): try: lkapi = api.LiveKitAPI() response = await lkapi.room.list_participants( api.ListParticipantsRequest(room=self.ctx.room.name) ) for p in response.participants: if p.identity.startswith("sip_"): identity = p.identity track_sid = p.tracks[0].sid await lkapi.room.mute_published_track( api.MuteRoomTrackRequest( room=self.ctx.room.name, identity=identity, track_sid=track_sid, muted=flag, ) ) print(f'{p.identity} is {"Muted" if flag else "Unmuted"}') break except Exception as ex: print(f"Unexpected error in mute. Details : {ex} ") async def speech_audio(self, audio: Literal["tool", "greeting"] = "tool"): try: stream = audio_frames_from_file(f"./utils/{audio}_audio.wav") handle = await self.session.say(text="", audio=stream) await handle.wait_for_playout() except Exception as e: print(f"{e}")
t
Thanks — I’m responding to the code you pasted and the 10s silence after transfers. Immediate issues I see and minimal fixes to try first: 1) generate_reply is not awaited in some places • You call
self.session.generate_reply(instructions=instructions)
without awaiting it in two places (the dispatched branch and the transfer branch’s initial greeting branch uses await but dispatched branch does not). Not awaiting can delay when the LLM/TTS work actually starts. Fix: await the call so reply generation (and subsequent TTS) begins immediately. 2) Muting logic may block audio delivery during TTS • You call
await self.mute(True)
before
self.session.generate_reply(...)
and then
await self.mute(False)
after — but if generate_reply is not awaited, you may unmute too early or too late. After you await generate_reply, ensure mute/unmute surround the actual TTS/playout: ◦ await self.mute(True) ◦ await self.session.generate_reply(... ) <-- await this ◦ await self.mute(False) 3) speech_audio uses
say(text="", audio=stream)
which depends on session and LiveKit routing • Confirm
say()
returns a handle and you await
handle.wait_for_playout()
(you do), but ensure
livekit_api
and TTS are available in userdata before calling
say()
or generate_reply. If TTS or LiveKit client needs warm-up, pre-initialize them earlier in the flow. 4) Potential race between transfer and agent activation • Your
_transfer_to_agent
returns next_agent but I don’t see code that calls session.update_agent(...) or awaits the new agent’s
on_enter
. Ensure the root flow calls
await session.update_agent(next_agent, chat_ctx=...)
(or equivalent) immediately so the new agent runs its
on_enter
without delay. Passing
chat_ctx
explicitly prevents re-generating context and avoids extra LLM latency. 5) Routing/mute via LiveKit API can be slow • Your
mute()
calls list participants and then mute the first sip_ participant. That REST call and track mutation can add latency. To reduce silence: ◦ Minimize LiveKit API calls during the critical path. Pre-compute participant and track SIDs when possible. ◦ If you must mute/unmute, do it only when necessary, and avoid muting the TTS output track—mute only the caller inbound track. 6) Add instrumentation/logging with timestamps • Log timestamps for: session.update_agent start/end, generate_reply start/end, TTS/audio playout start/end, mute/unmute start/end. That will show whether the delay is in LLM/TTS generation, LiveKit mute calls, or routing. Quick targeted changes to try now (apply in order): 1. Await every
self.session.generate_reply(...)
call. 2. Surround the awaited generate_reply with mute(True) before and mute(False) after (both awaited). 3. Pre-warm or ensure `livekit_api`/TTS are initialized in userdata before transfer (initialize once at session start). 4. Cache participant identity and track SID so
mute()
skips the list call on the hot path. 5. Add logs around each step to measure where the ~10s gap comes from. If you want, share logs after adding timestamped prints for: update_agent start, generate_reply start, generate_reply resolved, say/playout start, mute/unmute calls. I’ll point to the exact line to change based on which step is slow.
c
but i dont see that anywhere tho .updateagent
t
You’re right to flag that —
session.update_agent(...)
(or your framework’s equivalent) is required to actually activate the next agent after setting
userdata.prev_agent
in
_transfer_to_agent
. I don’t see any call to update the session/activate the subagent in the snippets you shared, which explains why the new agent’s
on_enter
(and its TTS/say) may be delayed or not run immediately. What to do next: 1. Add a call where you perform the transfer, e.g.: ◦ await session.update_agent(next_agent, chat_ctx=chat_ctx, userdata=userdata) ◦ Pass the prepared
chat_ctx
and
userdata
so the subagent starts with the right context and livekit/TTS clients. 1. Ensure you await the update and then await the generated reply/say inside the new agent’s
on_enter
. Please share the code that calls
_transfer_to_agent
(or the transfer trigger) — I’ll show exactly where to insert
await session.update_agent(...)
and how to pass `chat_ctx`/`userdata` to avoid the 10s gap.