icy-apple-74167
12/09/2025, 2:43 PMtall-airline-16756
12/09/2025, 2:43 PMtall-airline-16756
12/09/2025, 2:43 PMawait ctx.api.room.delete_room(
api.DeleteRoomRequest(room=ctx.room.name)
)
Follow-up checks
β’ Do you call delete_room from a server with the LiveKit API key/secret (not from a client)?
β’ Are there any errors or logs when you call delete_room or when you previously called remove_participant?
β’ Are you using a Twilio SIP trunk configuration that might re-route or re-invite after termination?
If you share which SDK/language context youβre using and any error logs, Iβll give the exact code snippet and placement to reliably terminate the SIP call. Would you like that?
Sources: Agents telephony integration | LiveKit docs | Connecting to LiveKit | LiveKit docs | Job lifecycle | LiveKit docsicy-apple-74167
12/09/2025, 3:01 PMtall-airline-16756
12/09/2025, 3:01 PMdelete_room, and the AttributeError from calling lk_api.close().
Actionable fixes
1. Check room existence before calling delete:
try:
# try to delete only if room exists
await lk_api.room.delete_room(api.DeleteRoomRequest(room=room_name))
except TwirpError as e:
if e.code == "not_found":
logger.info(f"Room {room_name} not found; skipping delete")
else:
raise
1. Use the correct client close method:
β’ Replace await lk_api.close() with await lk_api.aclose() to properly close the client and avoid unclosed session warnings.
1. Order and fallbacks:
β’ Say the farewell first (you already do that).
β’ Attempt delete_room. If 404, log and proceed to the next fallback.
β’ As a fallback, call await self.room.disconnect() to try to disconnect client-side.
β’ Always call await lk_api.aclose() in a finally block (if lk_api was created).
1. Defensive checks and logging:
β’ Ensure room_name is the exact name used by LiveKit (check casing/namespace).
β’ If your code can be called when the room was already deleted, treat 404 as success (the SIP leg is already gone).
β’ Log full exception details for any non-404 errors so you can inspect API failures.
If youβd like, I can provide a compact, ready-to-drop-in async implementation showing these fixes in your functionβtell me which LiveKit Python client import names you use (or confirm the `api`/`TwirpError` symbols above are available) and Iβll generate it.icy-apple-74167
12/09/2025, 3:01 PMicy-apple-74167
12/09/2025, 3:01 PMtall-airline-16756
12/09/2025, 3:01 PMawait lk_api.aclose() instead of await lk_api.close() to close the client.
β’ Only call delete_room when you have a room name, and always close the client in a finally block to avoid unclosed session warnings.
β’ Keep your farewell reply first, then try delete_room, then fallback to self.room.disconnect() if needed, then shutdown the agent.
Compact async implementation (drop-in replacement):
import os
from livekit.api.twirp_client import TwirpError
async def disconnect_call(self) -> Dict[str, Any]:
logger.info("π§ TOOL CALLED: disconnect_call")
try:
# 1. Say goodbye
r_info = self.datapacket.knowledge_base.restaurant_info
restaurant_name = r_info.name if r_info else "our restaurant"
farewell_message = f"Thank you so much for calling {restaurant_name}! Have a wonderful day! Goodbye!"
await self._safe_generate_reply(instructions=f"Say exactly this: '{farewell_message}'")
# 2. Force hangup: delete the room to terminate SIP call
if getattr(self, "room", None) and self.room:
room_name = self.room.name
lk_api = api.LiveKitAPI(
LIVEKIT_CONFIG.url,
os.getenv("LIVEKIT_API_KEY"),
os.getenv("LIVEKIT_API_SECRET"),
)
try:
logger.info(f"Deleting room {room_name} to terminate SIP call")
await lk_api.room.delete_room(api.DeleteRoomRequest(room=room_name))
logger.info(f"β
Room {room_name} deleted successfully")
except TwirpError as e:
# treat not_found as success
if getattr(e, "code", None) == "not_found":
logger.info(f"Room {room_name} not found; assuming already deleted")
else:
logger.error(f"β Error deleting room via API: {e}")
except Exception as e:
logger.error(f"β Unexpected error deleting room: {e}")
finally:
# ensure client is closed
try:
await lk_api.aclose()
except Exception as e:
logger.error(f"β Error closing LiveKitAPI client: {e}")
# fallback: try to disconnect local room if still present
try:
await self.room.disconnect()
except Exception as e:
logger.error(f"β Error disconnecting room client-side: {e}")
# 3. Shutdown the agent
try:
self.session.shutdown(drain=False)
except Exception as e:
logger.error(f"β Error shutting down session: {e}")
except Exception as outer:
logger.error(f"β Error in disconnect_call: {outer}")
try:
self.session.shutdown(drain=False)
except Exception as e:
logger.error(f"β Error shutting down session in fallback: {e}")
return {"status": "success", "message": "Call disconnected"}
Would you like me to adapt that snippet to match your exact imports/names (for example if TwirpError comes from a different path) or generate a version that logs more details for debugging?tall-airline-16756
12/09/2025, 3:02 PMdelete_room (room already gone) and the AttributeError from calling lk_api.close(). Below is a compact, ready-to-drop-in async version of your function that:
β’ Says the farewell first
β’ Calls delete_room and treats 404 as success
β’ Falls back to client-side self.room.disconnect() if needed
β’ Uses await lk_api.aclose() to avoid unclosed session warnings
β’ Logs errors but preserves success return
Paste into your code, adjusting imports/names if yours differ:
import os
from livekit.api.twirp_client import TwirpError # adjust import if different
async def disconnect_call(self) -> Dict[str, Any]:
logger.info("π§ TOOL CALLED: disconnect_call")
try:
# 1) Say goodbye
r_info = self.datapacket.knowledge_base.restaurant_info
restaurant_name = r_info.name if r_info else "our restaurant"
farewell_message = f"Thank you so much for calling {restaurant_name}! Have a wonderful day! Goodbye!"
await self._safe_generate_reply(instructions=f"Say exactly this: '{farewell_message}'")
# 2) Force hangup: delete room to terminate SIP legs
if getattr(self, "room", None) and self.room:
room_name = self.room.name
lk_api = api.LiveKitAPI(
LIVEKIT_CONFIG.url,
os.getenv("LIVEKIT_API_KEY"),
os.getenv("LIVEKIT_API_SECRET"),
)
try:
logger.info(f"Deleting room {room_name} to terminate SIP call")
await lk_api.room.delete_room(api.DeleteRoomRequest(room=room_name))
logger.info(f"β
Room {room_name} deleted successfully")
except TwirpError as e:
# treat not_found as success (room already deleted)
if getattr(e, "code", None) == "not_found":
logger.info(f"Room {room_name} not found; assuming already deleted")
else:
logger.error(f"β Error deleting room via API: {e}")
except Exception as e:
logger.error(f"β Unexpected error deleting room: {e}")
finally:
try:
await lk_api.aclose()
except Exception as e:
logger.error(f"β Error closing LiveKitAPI client: {e}")
# Fallback: try client-side disconnect
try:
await self.room.disconnect()
except Exception as e:
logger.error(f"β Error disconnecting room client-side: {e}")
# 3) Shutdown agent session
try:
self.session.shutdown(drain=False)
except Exception as e:
logger.error(f"β Error shutting down session: {e}")
except Exception as outer:
logger.error(f"β Error in disconnect_call: {outer}")
try:
self.session.shutdown(drain=False)
except Exception as e:
logger.error(f"β Error shutting down session in fallback: {e}")
return {"status": "success", "message": "Call disconnected"}
If you still see the SIP leg staying active after this:
β’ Share the exact room name you attempted to delete (to confirm it matches LiveKit).
β’ Confirm your Twilio trunk settings support SIP REFER / PSTN transfer β if not enabled, Twilio behavior may differ.
Do you want me to adapt the snippet to different import paths or add extra debug logs around the API response?
Sources: Managing rooms | LiveKit docs | Job lifecycle | LiveKit docs | Call forwarding | LiveKit docs | Agents telephony integration | LiveKit docsicy-apple-74167
12/09/2025, 3:29 PMtall-airline-16756
12/09/2025, 3:30 PMdelete_room (treat 404 as success), aclose() the API client, try self.room.disconnect() as fallback, then shut down the session.
β’ If your TTS/voice send method returns no completion event, add a short safety wait or await an explicit βgeneration_completedβ/βplayback_finishedβ event from your voice subsystem.
Drop-in async implementation (adjust event names/imports to match your code):
import os
import asyncio
from livekit.api.twirp_client import TwirpError # adjust if different
async def disconnect_call(self) -> Dict[str, Any]:
logger.info("π§ TOOL CALLED: disconnect_call")
try:
# 1) Build and send farewell; wait for confirmation
r_info = self.datapacket.knowledge_base.restaurant_info
restaurant_name = r_info.name if r_info else "our restaurant"
farewell_message = f"Thank you so much for calling {restaurant_name}! Have a wonderful day! Goodbye!"
# send the message and wait for the generator/playback to finish
send_task = await self._safe_generate_reply(instructions=f"Say exactly this: '{farewell_message}'")
# Option A: if _safe_generate_reply returns/awaits until generation is done, you're done here.
# Option B: if it only starts generation, wait for an event your system emits when finished:
try:
# replace 'wait_for_generation_complete' with your actual event/wait API
await asyncio.wait_for(self.wait_for_generation_complete(send_task), timeout=8.0)
except AttributeError:
# no event available: fall back to a short sleep to allow playback to finish
await asyncio.sleep(2.0)
except asyncio.TimeoutError:
logger.warning("Farewell playback timeout; proceeding with disconnect")
# 2) Force hangup: delete room to terminate SIP legs (skip for mock/test rooms)
if getattr(self, "room", None) and self.room:
room_name = self.room.name
if room_name and (room_name.startswith("mock_") or room_name == "FAKE_RM_"):
logger.info(f"Skipping room deletion for test room: {room_name}")
try:
await self.room.disconnect()
except Exception as e:
logger.warning(f"Could not disconnect test room: {e}")
else:
lk_api = None
try:
lk_api = api.LiveKitAPI(
LIVEKIT_CONFIG.url,
os.getenv("LIVEKIT_API_KEY"),
os.getenv("LIVEKIT_API_SECRET"),
)
logger.info(f"Deleting room {room_name} to terminate SIP call")
await lk_api.room.delete_room(api.DeleteRoomRequest(room=room_name))
logger.info(f"β
Room {room_name} deleted successfully")
except TwirpError as twirp_error:
if getattr(twirp_error, "code", None) == "not_found":
logger.warning(f"Room {room_name} not found (may already be deleted): {twirp_error}")
else:
logger.error(f"β Error deleting room via API: {twirp_error}")
except Exception as api_error:
logger.error(f"β Error deleting room via API: {api_error}")
# continue to fallback disconnect below
finally:
if lk_api:
try:
await lk_api.aclose()
except Exception as close_error:
logger.warning(f"Error closing API client: {close_error}")
# fallback: try to disconnect the room directly
try:
await self.room.disconnect()
except Exception as disconnect_error:
logger.error(f"β Error disconnecting room: {disconnect_error}")
# 3) Shutdown agent session
try:
self.session.shutdown(drain=False)
except Exception as e:
logger.error(f"β Error shutting down session: {e}")
except Exception as outer:
logger.error(f"β Error in disconnect_call: {outer}")
try:
self.session.shutdown(drain=False)
except Exception as e:
logger.error(f"β Error shutting down session in fallback: {e}")
return {"status": "success", "message": "Call disconnected"}
Two practical notes
β’ If your _safe_generate_reply already waits until audio playback completes (or emits a generation/playback completion event), call it and proceedβno extra sleep needed.
β’ If you have no completion event, prefer a short explicit wait (1β3s) instead of immediate deletion so the caller hears the full farewell.
If you tell me which event name your system emits when generation/playback completes (or whether _safe_generate_reply already blocks until done), Iβll adapt the snippet to use it directly. Would you like that?