faint-ram-91413
12/09/2025, 1:18 AMContext.wait_for_playout doesn't quite work. It returns immediately for Realtime models (likely audio_output.wait_for_playout() returns immediately). Is that a known bug and are there any workarounds? The only thing I've found is sleep statements but that's not a real solution (edited)tall-airline-16756
12/09/2025, 1:18 AMtall-airline-16756
12/09/2025, 1:18 AMContext.wait_for_playout returning immediately for Realtime models: this is an architectural behavior, not a typical bug. Realtime models generate and stream audio natively (bypassing the normal TTS node and RoomIO playout tracking), so the usual playback_finished signal that wait_for_playout depends on may not fire reliably and can make wait_for_playout() return immediately.
Workarounds you can use instead:
• Listen for the RoomIO playback_finished event and act when it fires:
@session.output.audio.on("playback_finished")
def _on_playback_finished(ev: PlaybackFinishedEvent):
# handle completion (ev.interrupted indicates interruption)
• Await the Speech handle returned by generate_reply() (or use its playout-wait helper if available):
handle = session.generate_reply(instructions="...")
await handle
• Track RealtimeSession events like generation_created, input_speech_started, and input_speech_stopped to infer generation/playout lifecycle.
• If you need confirmation from the receiver side (remote playout), use an RPC callback from the client that signals when it has actually played the audio.
Would you like sample code for any of these approaches in your language/SDK (Python or Node.js), or help wiring the playback_finished handler into your current flow?
Sources: How to detect when an agent has finished speaking | Realtime model plugins | LiveKit Docs | Agent speech and audio | LiveKit docs | examples/voice_agents | livekit/livekit_composite | DeepWiki | Bringing AI avatars to voice agentsfaint-ram-91413
12/09/2025, 1:36 AMtall-airline-16756
12/09/2025, 1:36 AMwait_for_playout inside a function call can affect the Realtime flow. To help solve this I need a bit more info so I can give a specific fix:
1. Which SDK/language are you using (Python or Node.js)?
2. Can you paste the minimal code where you call wait_for_playout inside the function call?
3. Are you using a Realtime model that streams audio natively (e.g., OpenAI Realtime)?
4. Do you have any config around interruptions (e.g., allow_interruptions on speech actions) or are you using synchronous/blocking code in that function?
While you share that, try these approaches which usually prevent interruptions:
• Use event-driven detection instead of blocking inside the function: listen for playback_finished on the session output and respond after that event fires.
• Avoid blocking/waiting inside function calls — make the function async and await non-blocking handles (or return immediately and continue work when the playback event occurs).
• Ensure speech action interruption settings are configured (set allow_interruptions appropriately) so external actions or function results don't cancel ongoing audio.
• If you need confirmation from the client side, have the client RPC back when it finishes playout instead of relying on server-side waits.
Share the SDK and your code snippet and I’ll provide a targeted code example and the exact change to keep function calls from interrupting the Realtime model.faint-ram-91413
12/09/2025, 1:37 AMtall-airline-16756
12/09/2025, 1:37 AMwait_for_playout) interrupt or not wait correctly when using Gemini Realtime. That’s expected with Realtime models because audio is generated server-side and wait_for_playout() has nothing to await.
What’s happening
• Realtime models stream audio natively and bypass the local TTS/SpeechHandle plumbing. Context.wait_for_playout() returns immediately for Realtime models, and calling it inside a function can interfere with the realtime flow if that function blocks or changes session state.
What to do instead (practical steps)
1) Use the playback_finished event (recommended)
• Install a handler on session.output.audio and continue only after you receive playback_finished.
from livekit.agents.voice.io import PlaybackFinishedEvent
import asyncio
_playout_done = asyncio.Event()
@session.output.audio.on("playback_finished")
def _on_playback_finished(ev: PlaybackFinishedEvent):
_playout_done.set()
# elsewhere, to wait non-blocking
await _playout_done.wait()
_playout_done.clear()
2) Avoid blocking inside function tools
• Make your function async, return quickly, and do not call blocking waits inside it. Offload waiting to an event handler or separate task.
3) Use allow_interruptions=False for critical speech
• When you need the model not to be interrupted by user audio or downstream logic, set:
await ctx.session.generate_reply(instructions="...", allow_interruptions=False)
• This reduces interruptions, though server-side Realtime turn detection may still preempt in some edge cases.
4) If you need client-side confirmation of playout
• Have the client RPC back when it finishes actual playback (use an RPC call from the client player). This is the most reliable way to know the user actually heard the audio.
If you want, I can:
• Provide a focused example that wires a playback event into your current tool flow, or
• Review a small snippet of your tool/function where you call wait_for_playout() and show the minimal change to avoid interruptions. Which would you prefer? Sources: Agent speech and audio | LiveKit docs | Bringing AI avatars to voice agents | How to detect when an agent has finished speaking | examples/voice_agents | livekit/livekit_composite | DeepWikifaint-ram-91413
12/09/2025, 1:45 AMasync def wait_for_audio_playout(context: RunContext, timeout: float = 30.0) -> None:
"""
Wait for audio playout to complete before proceeding.
Uses the recommended LiveKit approach: listen for the playback_finished event
on session.output.audio. This is the most reliable method for Realtime models.
Args:
context: The RunContext from the function tool
timeout: Maximum time to wait in seconds
"""
session = context.session
audio_output = session.output.audio
if not audio_output or not session.output.audio_enabled:
logger.debug("No audio output configured, skipping wait")
return
# If agent is not speaking, nothing to wait for
if session.agent_state != "speaking":
logger.debug(f"Agent not speaking (state={session.agent_state}), skipping wait")
return
logger.debug("Waiting for audio playback to finish...")
# Use the recommended LiveKit approach: listen for playback_finished event
# However, for Realtime models, the event may fire immediately when the function
# tool interrupts, so we need to verify the agent actually finished speaking
playout_done = asyncio.Event()
playback_event: Optional[PlaybackFinishedEvent] = None
event_fired_time: Optional[float] = None
def _on_playback_finished(ev: PlaybackFinishedEvent) -> None:
nonlocal playback_event, event_fired_time
playback_event = ev
event_fired_time = time.time()
playout_done.set()
# Register the event listener
audio_output.on("playback_finished", _on_playback_finished)
try:
start_time = time.time()
# Wait for the event with timeout
try:
await asyncio.wait_for(playout_done.wait(), timeout=timeout)
elapsed = time.time() - start_time
# If event fired very quickly (< 200ms), it's likely from the function tool
# interruption, not actual audio finishing. In that case, we need to wait
# for the agent to actually stop speaking.
if elapsed < 0.2:
logger.debug(f"Event fired quickly ({elapsed:.3f}s), likely from interruption. Waiting for agent to finish speaking...")
# Wait for agent to actually stop speaking
poll_start = time.time()
while session.agent_state == "speaking":
if time.time() - poll_start >= timeout:
logger.warning("Timeout waiting for agent to finish speaking")
break
await asyncio.sleep(0.1)
logger.debug(f"Agent finished speaking (total wait: {time.time() - start_time:.3f}s)")
else:
# Event fired after reasonable time, audio likely finished
if playback_event:
logger.debug(f"Audio playback finished (interrupted={playback_event.interrupted}, elapsed={elapsed:.3f}s)")
else:
logger.debug(f"Audio playback finished (elapsed={elapsed:.3f}s)")
except asyncio.TimeoutError:
logger.warning(f"Timeout waiting for audio playback to finish after {timeout}s")
finally:
# Always clean up the event listener
audio_output.off("playback_finished", _on_playback_finished)tall-airline-16756
12/09/2025, 1:46 AMplayback_finished event (the recommended signal for Realtime).
• You avoid blind blocking by using asyncio.wait_for with a timeout.
• You guard against spurious immediate events by checking elapsed time and then polling session.agent_state.
• You always remove the listener in finally — good cleanup.
Small improvements
1. Use the event loop-safe pattern to set/clear the asyncio.Event from a sync callback:
loop = asyncio.get_running_loop()
def _on_playback_finished(ev: PlaybackFinishedEvent) -> None:
nonlocal playback_event, event_fired_time
playback_event = ev
event_fired_time = time.time()
loop.call_soon_threadsafe(playout_done.set)
This avoids potential race issues if the callback runs on a different thread.
1. Prefer checking session.agent_state before registering the listener to avoid a tiny race where playback finishes between your check and listener registration. You already check, but consider re-checking after registration:
if session.agent_state != "speaking":
return
# register listener
if session.agent_state != "speaking":
# playback finished between checks
audio_output.off("playback_finished", _on_playback_finished)
return
1. Make the “very quick” threshold configurable and document why 200ms was chosen. Some environments may need a slightly larger threshold (e.g., 300–500ms) depending on network timing.
2. When polling session.agent_state, yield a bit more (e.g., 0.05–0.1s is fine). You already use 0.1s which is reasonable.
3. Log the playback_event.interrupted value earlier if you care about interruption vs normal completion — it can help debugging.
Optional robustness
• If you need absolute client-side confirmation of audible playout, request an RPC callback from the client player when it finishes actual playback (most reliable for production).
• If multiple concurrent replies can happen, consider associating the event with a unique id per generated reply so you don't conflate playout events from other agents/utterances.
Conclusion
• Your approach is correct and appropriate for Gemini Realtime; apply the loop-safe event set, re-check agent state after registering the listener, and consider tuning the quick-fire threshold or using client RPCs for absolute confirmation.
If you’d like, paste the surrounding code where you call this helper and I’ll show the minimal edits to integrate the loop-safe callback and the post-registration re-check.faint-ram-91413
12/09/2025, 1:49 AMtall-airline-16756
12/09/2025, 1:49 AMawait ctx.session.generate_reply(instructions="...", allow_interruptions=False)
• Trigger your function only after the reply completes (see point 2).
2) Move playout-waiting earlier (event-driven)
• Don’t run the wait inside a function tool that may be invoked after interruption. Instead register the playback_finished handler immediately when you start the reply and continue your follow-up work from that handler or from a task that awaits its Event.
• Example pattern:
◦ Start reply
◦ Set up playback_finished -> set asyncio.Event or schedule coroutine
◦ When Event fires, run the post-playout logic (not as a function tool call)
3) Use client-side confirmation if you need guaranteed audible playout
• Have the client player RPC back when it finishes actual playback. This avoids server-side race conditions entirely.
4) If you must keep it in a function tool
• Make the function non-blocking: return quickly and perform the playout wait in a background task (so the function call itself doesn’t cause timing/state changes).
• Ensure the event callback sets an asyncio.Event via loop.call_soon_threadsafe(...) (thread-safe).
5) Diagnostic checks to find the source of interruption
• Log session.agent_state, playback_finished timestamps, and whether playback_event.interrupted is True. That will show whether the interruption is from VAD/user audio or from your own function flow.
Which would you prefer:
• I can show a minimal refactor that wires the playback_finished Event to run your post-playout logic outside the function tool, or
• I can show the background-task pattern so the function tool returns immediately and the wait runs safely afterwards.
Tell me which and I’ll provide the exact code snippet for your Python/Gemini setup.