I have a hang_up function that is included in the ...
# ask-ai
a
I have a hang_up function that is included in the tool call. I instruct the realtime model to first call this after saying a goodbye message. However it seems to get called mid sentence - which i assume is due to it triggering the function when the response is done - not what the audio playback is finished. Im considering checking in my hang_up function, whether the agent is speaking and awaiting this to finish before triggering the actual hang_up code. How can i achieve this?
t
Thanks for reaching out, Malte. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
To make sure your hang-up function only triggers once the agent has finished speaking, you can use the
current_speech
property of the agent session. This handy property gives you the active
SpeechHandle
if the agent is speaking, or
None
if there’s no speech happening right now. From there, you can call the
wait_for_playout()
method on the
current_speech
handle to patiently wait until the speech playback is fully done before hanging up. Here’s a simple example to guide you:
Copy code
@function_tool()
async def end_call(self, ctx: RunContext):
    # Check if the agent is currently speaking
    current_speech = ctx.session.current_speech
    if current_speech:
        # Wait for the agent to finish speaking before hanging up
        await current_speech.wait_for_playout()

    # Proceed to hang up the call
    await hangup_call()  # or ctx.room.disconnect() depending on your setup
This way, you can avoid disconnecting the call right in the middle of a sentence, which keeps things smooth and professional. Also, if you’d like to keep an eye on when the agent starts and stops speaking, you can subscribe to the
agent_started_speaking
and
agent_stopped_speaking
events for real-time updates. Sources: Agent speech and audio | LiveKit docs | Agent speech and audio | LiveKit docs | Agents telephony integration | LiveKit docs | agent.py | agent/main.py