billions-apple-82268
08/23/2025, 10:55 PMtall-airline-16756
08/23/2025, 10:56 PMtall-airline-16756
08/23/2025, 10:56 PM@function_tool
async def my_tool_function(self, ctx: RunContext):
current_speech = ctx.session.current_speech
if current_speech:
await current_speech.wait_for_playout()
return "Tool executed after speech finished"
• Using PlaybackFinished Event: You can listen for the playback_finished event to know exactly when the agent has stopped speaking:
from livekit.agents.voice.io import PlaybackFinishedEvent
@session.output.audio.on("playback_finished")
def _on_playback_finished(ev: PlaybackFinishedEvent):
logger.info(f"playback finished: {ev.interrupted}")
# This is where you can trigger your tool execution
• Coordinating with Speech Generation: Another approach is to generate the reply, wait for the speech to wrap up, and then run your tool logic like this:
# Generate speech first
handle = await session.generate_reply(instructions="I'll process that for you now.")
# Wait for the speech to complete
await handle.wait_for_playout()
# Now execute your tool logic
result = await my_tool_function()
These options help make sure your tool only kicks in after the agent has finished talking. If you want me to walk you through any part of this or have more questions, just let me know—I’m here to help!
Sources: livekit-agents/livekit/agents/voice/agent_activity.py | How to detect when an agent has finished speakingbillions-apple-82268
08/23/2025, 11:03 PMtall-airline-16756
08/23/2025, 11:04 PM@function_tool
async def end_session(self, ctx: RunContext):
# Wait for the current speech to finish
current_speech = ctx.session.current_speech
if current_speech:
await current_speech.wait_for_playout()
# Close the session
await ctx.session.aclose()
• Another option: You can generate a final reply first, then close the session like this:
@function_tool
async def goodbye(self):
await self.session.generate_reply(instructions="Say goodbye to the user")
current_speech = self.session.current_speech
if current_speech:
await current_speech.wait_for_playout()
await self.session.aclose()
These approaches help the session wrap up smoothly after the playback finishes. If you want a hand with anything else, just let me know—I’m here to help!
Sources: livekit-agents/livekit/agents/voice/agent.py | How to detect when an agent has finished speaking | Agent speech and audio | LiveKit Docs | basics/exit_message.py