ambitious-ice-35806
08/27/2025, 9:37 AMawait for session.generate_reply(instruction= "Tell the User:Thank you for your time. Have a great day! ")
await ctx.session.aclose()
async with api.LiveKitAPI() as lkapi:
await lkapi.room.delete_room(DeleteRoomRequest(room_name=ctx.userdata['room_name']))
also I have tried this :
this one is working
return "Thank you for your time. Have a great day!"
the Problem is it's Just saying it but never end the call
SO I tried to use it retruning the str & calling another func
retrun "Thank you for your time. Have a great day!",await end_room(ctx)
async def end_room(ctx):
await ctx.session.aclose()
async with api.LiveKitAPI() as lkapi:
await lkapi.room.delete_room(DeleteRoomRequest(room_name=ctx.userdata['room_name']))tall-airline-16756
08/27/2025, 9:37 AMambitious-ice-35806
08/27/2025, 9:37 AMtall-airline-16756
08/27/2025, 9:37 AMsession.generate_reply() to send your closing message (something like, "Thank you for your time. Have a great day!"). Make sure this message finishes playing before moving on.
2. Wait for Speech Playout: If the agent is still talking, use current_speech.wait_for_playout() so the message doesn’t get cut off.
3. Delete the Room: Use the delete_room API from the LiveKit server SDK to remove the room and disconnect everyone. Here’s an example:
@function_tool
async def end_call(self, ctx: RunContext):
await ctx.session.generate_reply(
instructions="Thank you for your time. I'll be ending this call now. Goodbye!"
)
current_speech = ctx.session.current_speech
if current_speech:
await current_speech.wait_for_playout()
job_ctx = get_job_context()
await job_ctx.api.room.delete_room(api.DeleteRoomRequest(room=job_ctx.room.name))
This way, the session wraps up nicely and all participants get disconnected smoothly. If you have any questions or want a hand with anything else, just let me know—I’m here to help!
Sources: main.py | Agents telephony integration | LiveKit Docs | agent.py | Job lifecycle | LiveKit Docs | Workflows | LiveKit Docstall-airline-16756
08/27/2025, 9:38 AMsession.generate_reply() to send that warm closing message. Make sure it finishes playing before moving on.
2. Wait for Speech Playout: If the bot is still talking, patiently wait for it to finish with current_speech.wait_for_playout(). This way, the message won’t get cut off.
3. Delete the Room: Then, use the LiveKit API to delete the room and disconnect everyone. Here’s a quick example:
async def end_call(ctx):
await ctx.session.generate_reply(
instructions="Thank you for your time. Have a great day!"
)
current_speech = ctx.session.current_speech
if current_speech:
await current_speech.wait_for_playout()
async with api.LiveKitAPI() as lkapi:
await lkapi.room.delete_room(DeleteRoomRequest(room_name=ctx.userdata['room_name']))
This way, your message gets delivered nicely, and the room closes out cleanly. Hope this helps!ambitious-ice-35806
08/27/2025, 9:54 AM@function_tool()
async def end_call(ctx: RunContext) -> None:
"""
Tool to end the call.
"""
print(f"{Back.YELLOW} ending call using custom method")
print(f"{Back.RED}Ctx methods: {dir(ctx)}")
print(f"{Back.YELLOW} Session History: {ctx.session.history}")
print(f"{Back.GREEN} room name: {ctx.userdata['room_name']}")
print("Call ended politely.")
await ctx.session.generate_reply(instructions="Thank you for your time. Have a great day!")
current_speech= ctx.session.current_speech
print(f"{Back.BLUE} Current Speech: {current_speech}")
if current_speech:
await current_speech.wait_for_playout()
async with api.LiveKitAPI() as lkapi:
await lkapi.room.delete_room(DeleteRoomRequest(room_name=ctx.userdata['room_name']))
Error:
ending call using custom method
Ctx methods: ['_annotations_', '_class_', '__class_getitem__', 'delattr', 'dict', 'dir', 'doc', 'eq', 'firstlineno', 'format', 'ge', 'getattribute', 'getstate', 'gt', 'hash', 'init', '__init_subclass__', 'le', 'lt', 'module', 'ne', 'new', '__orig_bases__', 'parameters', 'reduce', '__reduce_ex__', 'repr', 'setattr', 'sizeof', '__static_attributes__', 'str', 'subclasshook', 'weakref__', '_function_call', '_initial_step_idx', '_session', '_speech_handle', 'disallow_interruptions', 'function_call', 'session', 'speech_handle', 'userdata', 'wait_for_playout']
Session History: <livekit.agents.llm.chat_context.ChatContext object at 0x00000255B6001E80>
room name: playground-zatM-oshM
Call ended politely.
2025-08-27 145154,240 - ERROR livekit.agents - Error in _realtime_reply_task
Traceback (most recent call last):
File "C:\D\Python\livekit-build\.venv\Lib\site-packages\livekit\agents\utils\log.py", line 16, in async_fn_logs
return await fn(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\D\Python\livekit-build\.venv\Lib\site-packages\livekit\agents\voice\agent_activity.py", line 1775, in _realtime_reply_task
generation_ev = await self._rt_session.generate_reply(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
instructions=instructions or NOT_GIVEN
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
)
^
livekit.agents.llm.realtime.RealtimeError: generate_reply timed out waiting for generation_created event.
Current Speech: <livekit.agents.voice.speech_handle.SpeechHandle object at 0x00000255B9A404D0>
2025-08-27 145154,246 - ERROR livekit.agents - exception occurred while executing tool {"function": "end_call", "speech_id": "speech_f6ee30fc30ce"}
Traceback (most recent call last):
File "C:\D\Python\livekit-build\.venv\Lib\site-packages\livekit\agents\voice\generation.py", line 517, in _traceable_fnc_tool
val = await function_callable()
^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\D\Python\livekit-build\utils\tools.py", line 30, in end_call
await lkapi.room.delete_room(DeleteRoomRequest(room_name=ctx.userdata['room_name']))
~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
ValueError: Protocol message DeleteRoomRequest has no "room_name" field.
2025-08-27 145154,248 - DEBUG livekit.agents - tools execution completed {"speech_id": "speech_f6ee30fc30ce"}
2025-08-27 145238,391 - INFO livekit.agents - shutting down worker {"id": "AW_xtoUeF996VyD"}
2025-08-27 145238,400 - DEBUG livekit.agents - shutting down job task {"reason": "", "user_initiated": false}
2025-08-27 145238,404 - DEBUG livekit.agents - job exiting {"reason": "", "tid": 16364, "job_id": "AJ_xkwTMn4d6USq"}
2025-08-27 145238,415 - DEBUG livekit.agents - stream closed {"participant": "identity-SQMQ", "source": "SOURCE_MICROPHONE"}
2025-08-27 145238,742 - DEBUG livekit.agents - input stream detached {"participant": "identity-SQMQ", "source": "SOURCE_MICROPHONE", "accepted_sources": ["SOURCE_MICROPHONE"]}
2025-08-27 145238,744 - DEBUG livekit.plugins.google - send task finished.
2025-08-27 145238,901 - DEBUG livekit.agents - session closed {"reason": "job_shutdown", "error": null}
2025-08-27 145238,902 - DEBUG livekit.agents - http_session(): closing the httpclient ctx
2025-08-27 145238,902 - DEBUG livekit.agents - http_session(): creating a new httpclient ctx
2025-08-27 145239,135 - ERROR asyncio - Task exception was never retrieved
future: <Task finished name='AgentActivity.realtime_reply' coro=<AgentActivity._realtime_reply_task() done, defined at C\D\Python\livekit build\.venv\Lib\site packages\livekit\agents\utils\log.py13> exception=RealtimeError('generate_reply timed out waiting for generation_created event.')>
Traceback (most recent call last):
File "C:\D\Python\livekit-build\.venv\Lib\site-packages\livekit\agents\utils\log.py", line 16, in async_fn_logs
return await fn(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\D\Python\livekit-build\.venv\Lib\site-packages\livekit\agents\voice\agent_activity.py", line 1775, in _realtime_reply_task
generation_ev = await self._rt_session.generate_reply(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
instructions=instructions or NOT_GIVEN
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
)
^
livekit.agents.llm.realtime.RealtimeError: generate_reply timed out waiting for generation_created event.
PS C:\D\Python\livekit-build\utils>
---
session = AgentSession(userdata={"room_name":ctx.room.name})
super().__init__(instructions="You are a helpful voice AI assistant. when the User say end the call Kindly use 'end_call' tool to end the call politely. Always use the 'end_call' tool to end the call. Do not end the call by yourself.",
llm=google.beta.realtime.RealtimeModel( model="gemini-2.5-flash-preview-native-audio-dialog",voice="Fenrir",temperature=0.8,modalities=["AUDIO"],language="hi-IN"),
tools=[end_call]
)tall-airline-16756
08/27/2025, 9:55 AM