how can i know when an agent finished speaking the...
# ask-ai
a
how can i know when an agent finished speaking the text generated by the llm and is waiting for user to reply?
t
Thanks for reaching out, Ali. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
I’m glad you asked! To detect when an agent has finished speaking the text generated by the LLM and is ready for a user reply, you can rely on the playback_finished event from the AudioOutput. This event is super helpful because it triggers exactly when the agent completes its TTS audio playback. Here’s a friendly walkthrough on how you can set this up: 1. First, use the
playback_finished
event in your agent's code to keep track of when the playback ends. For example:
Copy code
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}")
1. Next, to keep your web clients in the loop, you can set up an RPC (Remote Procedure Call) in your agent that broadcasts this playback finished event to the room. This way, your web clients can listen for the event and update their UI or enable user input seamlessly. If you’d like, I’m here to help you with detailed steps on setting up the RPC communication or integrating this with your web client. Just let me know! Sources: How to detect when an agent has finished speaking | complex-agents/turn-taking/README.md | Bringing AI avatars to voice agents | How does end-of-utterance detection work in conversations?
a
what about using wait_for_playout?
t
Absolutely, you can use
wait_for_playout
to know exactly when an agent has finished speaking. This method patiently waits for the entire assistant turn to finish playing back, including any final steps. Here’s a little example to help you out:
Copy code
# Get the current speech handle from the agent session
speech_handle = session.current_speech

if speech_handle:
    try:
        # Wait for the agent to completely finish speaking
        await speech_handle.wait_for_playout()
        print("Agent has finished speaking!")
    except RuntimeError as e:
        print(f"Error: {e}")
When working with function tools, it’s best to use
RunContext.wait_for_playout()
to avoid any circular waiting issues. If you’re looking for real-time detection, the
playback_finished
event is a great choice since it gives you detailed playback info and can trigger actions right away. If you’d like, I’m happy to walk you through more details on how to implement
wait_for_playout
or help compare it with `playback_finished`—just let me know! Sources: livekit-agents/livekit/agents/voice/chat_cli.py | Agent speech and audio | LiveKit Docs | How to detect when an agent has finished speaking
a
yes, let me know that
t
Let me help you understand the difference between
wait_for_playout
and
playback_finished
so you can choose the best fit for your needs: • `wait_for_playout`: This method works wonderfully when you want to coordinate tasks sequentially. It patiently waits for the entire assistant turn to finish playing back, including any wrap-up steps. It’s perfect when you want to make sure all speech has finished before moving on. Here’s a quick example:
Copy code
# Wait for the agent to finish speaking
speech_handle = session.current_speech
if speech_handle:
    await speech_handle.wait_for_playout()
•
playback_finished
Event:
This one’s great for catching playback completion in real-time. It fires right when playback ends and gives you extra details like whether it was interrupted or the exact playback position. This makes it super handy for things like updating your UI or letting users interact again. Here’s how you might use it:
Copy code
@session.output.audio.on("playback_finished")
def _on_playback_finished(ev):
    print(f"Playback finished: {ev.interrupted}")
Both are effective tools! Generally,
playback_finished
shines in real-time scenarios, while
wait_for_playout
is your go-to for ensuring tasks happen one after another smoothly. If you’d like, I’m here to help you implement either one—just let me know!
a
when i try wait for playout it triggers one sentence too early...
t
I'd love to help you get to the bottom of the issue where
wait_for_playout
seems to trigger one sentence too early. To better understand what's going on, could you please share a bit more about the following: • Which
wait_for_playout
method are you using:
SpeechHandle.wait_for_playout()
or
RunContext.wait_for_playout()
? • Are you working with function calls or regular speech generation? • Does the method return before the audio finishes playing, before the last sentence is spoken, or after a specific sentence completes? • Which TTS provider are you using, and is it streaming or non-streaming TTS? • Is this something that happens consistently, or only in certain situations? With these details, I’ll be in a much better position to help you find the right solution. Looking forward to your reply! Sources: livekit-agents/livekit/agents/voice/background_audio.py | Live Conversations with AI using ChatGPT and WebRTC
a
1. I tried both 2. Regular 3. Before last sentence 4. I tried openai and 11 labs 5. Consistently
t
Thank you so much for sharing these details! Since the issue happens consistently and
wait_for_playout
triggers before the last sentence, it looks like it might be related to the timing between text generation and audio playback. Let’s walk through a few steps that could help resolve this: 1. Use the
playback_finished
event:
This event fires when the audio playback is completely done, so it’s great for accurate detection. Here’s an example you can try:
Copy code
@session.output.audio.on("playback_finished")
def _on_playback_finished(ev):
    print(f"Playback finished: {ev.interrupted}")
1. Check audio buffering: Make sure the audio source is fully flushed and played out. Using
AudioOutput.wait_for_playout()
can give you more precise control here. 2. Verify TTS settings: Whether you’re using OpenAI or 11 Labs, double-check that the TTS output isn’t being cut off or streamed in a way that sends early completion signals. 3. Debug playback timing: Try logging the playback position and timing details with the
PlaybackFinishedEvent
to spot any mismatches. If you’d like, I’m here to help you step through these or assist with debugging the playback timing further. Just let me know!
a
is there a way to know on the client side when the audio is finished
t
To help you detect on the client side when the audio playback is finished, you can use the RPC (Remote Procedure Call) system to receive playback completion notifications from the agent. Let me guide you through how to set this up: 1. Agent-Side Setup: You'll want to configure your agent to listen for the
playback_finished
event from the AudioOutput and then broadcast it to the room using an RPC method. Here’s an example to get you started:
Copy code
@session.output.audio.on("playback_finished")
async def _broadcast_playback_finished(ev):
    await session.room.local_participant.perform_rpc(
        method="lk.playback_finished",
        payload=json.dumps({
            "playback_position": ev.playback_position,
            "interrupted": ev.interrupted,
            "synchronized_transcript": ev.synchronized_transcript
        })
    )
1. Client-Side RPC Handler: On the web client side, you’ll want to register an RPC handler to process the playback finished event. Here’s a simple example:
Copy code
room.localParticipant?.registerRpcMethod("lk.playback_finished", async (data) => {
    const playbackEvent = JSON.parse(data.payload);
    console.log(`Audio playback finished at ${playbackEvent.playback_position}s`);
    console.log(`Was interrupted: ${playbackEvent.interrupted}`);
    // Update UI or trigger actions
    updateUIForCompletion();
    return "ok";
});
This method helps ensure smooth and reliable communication between your agent and client, so you can accurately know when the audio playback ends. If you have any questions or need a hand with the implementation, please feel free to ask—I’m here to help! Sources: How to detect when an agent has finished speaking | livekit-agents/livekit/agents/voice/chat_cli.py | agents/src/voice/room_io/_output.ts | Bringing AI avatars to voice agents
a
how does it know in the front end that playback has finished? and isn't looking at any of the buffered buncks?
t
Hi there! I’d love to help you understand how playback completion is handled on the frontend. Basically, the agent sends out a
playback_finished
event through RPC once the audio has fully played. This way, the frontend doesn’t have to worry about tracking buffered chunks or incomplete playback—it gets a clear signal when everything is done. The agent keeps an eye on playback using the
AudioOutput
system and only sends that
playback_finished
event after every bit of audio has been played. This helps make sure the frontend always has the most accurate info about what’s happening with playback, without needing to peek into the audio buffers directly. If you’d like, I’m happy to walk you through more details on how the agent makes sure playback detection is spot on. Just let me know!