how to finish a call after session.say() ?
# ask-ai
n
how to finish a call after session.say() ?
t
Thanks for reaching out, Niv. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
To gracefully finish a call after using
session.say()
, here’s a simple approach you can follow: 1. Wait for the Speech to Complete: It’s a good idea to use
wait_for_playout()
on the
SpeechHandle
that
session.say()
returns. This way, the agent’s message finishes fully before the call ends, avoiding any abrupt cutoffs.
Copy code
handle = session.say("Goodbye for now.", allow_interruptions=False)
await handle.wait_for_playout()
2. End the Call Smoothly: Once the speech is done, you can use the
delete_room
API to close the call for everyone involved, ensuring all participants leave the room properly.
await ctx.job_context.api.room.delete_room(api.DeleteRoomRequest(room=ctx.job_context.room.name))
If you’d like, there’s also a handy predefined
hangup_call()
function you can use inside a
@function_tool
to make this process even easier:
Copy code
@function_tool
async def end_call(self, ctx: RunContext):
    await ctx.wait_for_playout()  # Wait for agent to finish speaking
    await hangup_call()  # Delete the room to end the call
Please don’t hesitate to reach out if you have any questions or need a bit more help—I’m here for you! Sources: Agent speech and audio | LiveKit Docs | Agents telephony integration | LiveKit Docs | Docs::Agents
n
can you give me a code example in python ?
t
Here's a friendly Python code example to help you finish a call after using `session.say()`:
Copy code
# Step 1: Make the agent say something
handle = session.say("Goodbye for now.", allow_interruptions=False)

# Step 2: Wait for the speech to finish
await handle.wait_for_playout()

# Step 3: End the call by deleting the room
await ctx.job_context.api.room.delete_room(api.DeleteRoomRequest(room=ctx.job_context.room.name))
If you happen to have a predefined function for hanging up, you can simply use it like this:
Copy code
@function_tool
async def end_call(self, ctx: RunContext):
    # Wait for the agent to finish speaking
    await ctx.wait_for_playout()

    # Delete the room to end the call
    await hangup_call()
Please feel free to reach out if you'd like me to walk you through this further or provide more examples. I'm here to help!
n
I'm want to use it in the @session.on("user_input_transcribed") def on_user_input_transcribed(event: UserInputTranscribedEvent): event
t
I'd love to share a helpful example on how to use
session.say()
and gracefully finish a call within the
@session.on("user_input_transcribed")
event:
Copy code
from livekit import UserInputTranscribedEvent

@session.on("user_input_transcribed")
async def on_user_input_transcribed(event: UserInputTranscribedEvent):
    if event.transcript.is_final and "goodbye" in event.transcript.transcript.lower():
        # Step 1: Say goodbye and wait for the speech to finish
        await session.say("Goodbye for now.", allow_interruptions=False)

        # Step 2: Close the session to end the call
        await session.aclose()
Key Points to keep in mind: • Use
await session.say()
to make sure the agent finishes speaking before closing the session. • Look out for specific keywords like "goodbye" in the user input to trigger the call ending smoothly. • Always remember to use
await session.aclose()
to properly close the session. If you have any questions or want me to walk you through more examples, just let me know—I’m here to help! Sources: pipeline-llm/interrupt_user.py | Docs::Agents | Events and error handling | LiveKit Docs | livekit-agents/livekit/agents/voice/room_io/room_io.py
n
Cannot register an async callback with
.on()
. Use
asyncio.create_task
within your synchronous callback instead.
t
It looks like the error is letting us know that the callback function registered with
@session.on()
needs to be synchronous. But don’t worry! To handle asynchronous operations like
await session.say()
or
await session.aclose()
, you can simply use
asyncio.create_task
inside your synchronous callback. Here’s a friendly example of how you might adjust your code:
Copy code
import asyncio
from livekit import UserInputTranscribedEvent

@session.on("user_input_transcribed")
def on_user_input_transcribed(event: UserInputTranscribedEvent):
    if event.transcript.is_final and "goodbye" in event.transcript.transcript.lower():
        # Use asyncio.create_task to run the async function
        asyncio.create_task(handle_goodbye())

async def handle_goodbye():
    # Step 1: Say goodbye and wait for the speech to finish
    await session.say("Goodbye for now.", allow_interruptions=False)

    # Step 2: Close the session to end the call
    await session.aclose()
This way, your callback stays synchronous, but you can still perform those async tasks smoothly with
asyncio.create_task
. Please feel free to reach out if you’d like me to walk you through this or if you have any other questions—I’m here to help!
n
its not closing the call
t
I understand how frustrating it can be when the call isn’t closing as expected. Let’s work through this together with a few helpful steps: 1. Verify the Callback: First, double-check that the
handle_goodbye()
function is actually being triggered. Adding a simple debug log or print statement can really help confirm this. 2. Check for Errors: Sometimes, errors during
session.aclose()
might be stopping the session from closing. To catch any issues, try wrapping the call in a try-except block like this:
Copy code
async def handle_goodbye():
    try:
        await session.say("Goodbye for now.", allow_interruptions=False)
        await session.aclose()
    except Exception as e:
        print(f"Error while closing the session: {e}")
3. Ensure Proper Session Context: It’s important to make sure the
session
object is still valid and active when you call
session.aclose()
. If the session is already closed or in an invalid state, it might not close properly. 4. Room Deletion: If your setup involves rooms, you might need to explicitly delete the room to make sure the call ends for everyone:
await ctx.job_context.api.room.delete_room(api.DeleteRoomRequest(room=ctx.job_context.room.name))
Please try these steps and let me know how it goes. I’m here to help if you need any further assistance!
n
the room not closing I got this warning WARNING livekit.agents - _SegmentSynchronizerImpl.resume called after close
t
I don't have the answer you're looking for. You could also try asking your question: • in one of the other Slack channels or • to https://deepwiki.com/livekit/livekit_composite which is trained on all LiveKit source code If you find the answer, please post it here to help others!
n
how to kick out participante from the room ?