<#C088ZNU7QQ5|ask-ai> @function_tool() async ...
# ask-ai
i
#ask-ai @function_tool() async def disconnect_call(self) -> Dict[str, Any]: """Disconnect the call and end the conversation politely. CRITICAL: Only call this AFTER customer confirms they are done. """ logger.info(f"πŸ”§ 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}! " f"Have a wonderful day! Goodbye!" ) await self._safe_generate_reply( instructions=f"Say exactly this: '{farewell_message}'" ) # 2. FORCE HANGUP: Remove the SIP participant from the room # This is the step that actually ends the phone call if self.session.room: room_name = self.session.room.name # Initialize API Client (ensure env vars are set) lk_api = api.LiveKitAPI( LIVEKIT_CONFIG.url, os.getenv("LIVEKIT_API_KEY"), os.getenv("LIVEKIT_API_SECRET"), ) # Iterate through remote participants (the customer) and kick them for participant_id, participant in self.session.room.remote_participants.items(): logger.info(f"Terminating SIP leg for participant: {participant.identity}") await lk_api.room.remove_participant( room=room_name, identity=participant.identity ) await lk_api.close() # 3. Shutdown the Agent self.session.shutdown(drain=False) logger.info(f"βœ… Call disconnected for {restaurant_name}") except Exception as e: logger.error(f"❌ Error disconnecting call: {e}") # Fallback: Just disconnect agent if API fails if hasattr(self.session, "room") and self.session.room: await self.session.room.disconnect() return { "status": "success", "message": "Call disconnected", } i want to have disconnect functionality using sip twilio session disconnect but sip call still connect
t
Thanks for reaching out, Maaz. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
You're seeing the SIP call stay active because removing a participant does not terminate the SIP leg. Regarding your code and question, I'm responding to your request about "disconnect functionality using SIP Twilio session disconnect but SIP call still connect." What you can do β€’ Use the LiveKit DeleteRoom API to end the call. Deleting the room properly terminates SIP legs for all participants and ends the call. β€’ Replace the participant-removal step with a room deletion call on the server side, for example:
Copy code
await 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 docs
i
#ask-ai @function_tool() async def disconnect_call(self) -> Dict[str, Any]: """Disconnect the call and end the conversation politely. CRITICAL: Only call this AFTER customer confirms they are done. """ import os logger.info(f"πŸ”§ 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}! " f"Have a wonderful day! Goodbye!" ) await self._safe_generate_reply( instructions=f"Say exactly this: '{farewell_message}'" ) # 2. FORCE HANGUP: Delete the room to properly terminate SIP call # This is the correct way to end SIP calls - deleting the room terminates all SIP legs if self.room: room_name = self.room.name # Initialize API Client (ensure env vars are set) lk_api = api.LiveKitAPI( LIVEKIT_CONFIG.url, os.getenv("LIVEKIT_API_KEY"), os.getenv("LIVEKIT_API_SECRET"), ) try: # Delete the room - this properly terminates SIP calls 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 Exception as api_error: logger.error(f"❌ Error deleting room via API: {api_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}") finally: await lk_api.close() # 3. Shutdown the Agent self.session.shutdown(drain=False) logger.info(f"βœ… Call disconnected for {restaurant_name}") except Exception as e: logger.error(f"❌ Error disconnecting call: {e}") # Final fallback: Just shutdown the session try: self.session.shutdown(drain=False) except Exception as shutdown_error: logger.error(f"❌ Error shutting down session: {shutdown_error}") return { "status": "success", "message": "Call disconnected", } generate_reply timed out waiting for generation_created event. default ▁ ▁ ▁ ▁ ▁ ▁ ▁ ▁ ▁ ▁ ▁ ▁ ▁ ▁ <Ctrl+T> Text Mode[2025-12-09 200017] [INFO ] [Thread: 125217825355328] [/home/mazz-ullah/Desktop/OtherProjects/Restaurant/restaurant-ai-v1/agents/new_complete_restaurant_agent.py:310] Deleting room mock_room to terminate SIP call default β–ƒ β–‚ β–‚ β–‚ ▁ ▁ ▁ ▁ ▁ ▁ ▁ ▁ ▁ ▁ <Ctrl+T> Text Mode[2025-12-09 200019] [ERROR ] [Thread: 125217825355328] [/home/mazz-ullah/Desktop/OtherProjects/Restaurant/restaurant-ai-v1/common/restaurant_logger.py:106] ❌ Error deleting room via API: TwirpError(code=not_found, message=requested room does not exist, status=404) Traceback (most recent call last): File "/home/mazz-ullah/Desktop/OtherProjects/Restaurant/restaurant-ai-v1/agents/new_complete_restaurant_agent.py", line 311, in disconnect_call await lk_api.room.delete_room( File "/home/mazz-ullah/Desktop/OtherProjects/Restaurant/AI/.venv/lib/python3.10/site-packages/livekit/api/room_service.py", line 108, in delete_room return await self._client.request( File "/home/mazz-ullah/Desktop/OtherProjects/Restaurant/AI/.venv/lib/python3.10/site-packages/livekit/api/twirp_client.py", line 129, in request raise TwirpError( livekit.api.twirp_client.TwirpError: TwirpError(code=not_found, message=requested room does not exist, status=404) [2025-12-09 200019] [ERROR ] [Thread: 125217825355328] [/home/mazz-ullah/Desktop/OtherProjects/Restaurant/restaurant-ai-v1/common/restaurant_logger.py:106] ❌ Error disconnecting call: 'LiveKitAPI' object has no attribute 'close' Traceback (most recent call last): File "/home/mazz-ullah/Desktop/OtherProjects/Restaurant/restaurant-ai-v1/agents/new_complete_restaurant_agent.py", line 323, in disconnect_call await lk_api.close() AttributeError: 'LiveKitAPI' object has no attribute 'close'. Did you mean: 'aclose'? 200019.711 ERROR asyncio Unclosed client session client_session: <aiohttp.client.ClientSession object at 0x71e2a825f850> 200019.717 ERROR asyncio Unclosed connector connections: ['deque([(<aiohttp.client_proto.ResponseHandler object at 0x71e2a8237700>, 16835.749908261)])'] connector: <aiohttp.connector.TCPConnector object at 0x71e2a825fdc0> 200019.721 DEBUG livekit.agents tools execution completed {"speech_id": "speech_dda10185f22c"} 200019.726 DEBUG livekit.plugins… send task finished.
t
You're right to delete the room to terminate the SIP leg β€” I'll address the specific errors in your logs and give concise fixes. What I'm responding to: your 404 "requested room does not exist" when calling
delete_room
, and the AttributeError from calling
lk_api.close()
. Actionable fixes 1. Check room existence before calling delete:
Copy code
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.
i
#ask-ai @function_tool() async def disconnect_call(self) -> Dict[str, Any]: """Disconnect the call and end the conversation politely. CRITICAL: Only call this AFTER customer confirms they are done. """ import os logger.info(f"πŸ”§ 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}! " f"Have a wonderful day! Goodbye!" ) await self._safe_generate_reply( instructions=f"Say exactly this: '{farewell_message}'" ) # 2. FORCE HANGUP: Delete the room to properly terminate SIP call # This is the correct way to end SIP calls - deleting the room terminates all SIP legs if self.room: room_name = self.room.name # Initialize API Client (ensure env vars are set) lk_api = api.LiveKitAPI( LIVEKIT_CONFIG.url, os.getenv("LIVEKIT_API_KEY"), os.getenv("LIVEKIT_API_SECRET"), ) try: # Delete the room - this properly terminates SIP calls 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 Exception as api_error: logger.error(f"❌ Error deleting room via API: {api_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}") finally: await lk_api.close() # 3. Shutdown the Agent self.session.shutdown(drain=False) logger.info(f"βœ… Call disconnected for {restaurant_name}") except Exception as e: logger.error(f"❌ Error disconnecting call: {e}") # Final fallback: Just shutdown the session try: self.session.shutdown(drain=False) except Exception as shutdown_error: logger.error(f"❌ Error shutting down session: {shutdown_error}") return { "status": "success", "message": "Call disconnected", } generate_reply timed out waiting for generation_created event. default ▁ ▁ ▁ ▁ ▁ ▁ ▁ ▁ ▁ ▁ ▁ ▁ ▁ ▁ <Ctrl+T> Text Mode[2025-12-09 200017] [INFO ] [Thread: 125217825355328] [/home/mazz-ullah/Desktop/OtherProjects/Restaurant/restaurant-ai-v1/agents/new_complete_restaurant_agent.py:310] Deleting room mock_room to terminate SIP call default β–ƒ β–‚ β–‚ β–‚ ▁ ▁ ▁ ▁ ▁ ▁ ▁ ▁ ▁ ▁ <Ctrl+T> Text Mode[2025-12-09 200019] [ERROR ] [Thread: 125217825355328] [/home/mazz-ullah/Desktop/OtherProjects/Restaurant/restaurant-ai-v1/common/restaurant_logger.py:106] ❌ Error deleting room via API: TwirpError(code=not_found, message=requested room does not exist, status=404) Traceback (most recent call last): File "/home/mazz-ullah/Desktop/OtherProjects/Restaurant/restaurant-ai-v1/agents/new_complete_restaurant_agent.py", line 311, in disconnect_call await lk_api.room.delete_room( File "/home/mazz-ullah/Desktop/OtherProjects/Restaurant/AI/.venv/lib/python3.10/site-packages/livekit/api/room_service.py", line 108, in delete_room return await self._client.request( File "/home/mazz-ullah/Desktop/OtherProjects/Restaurant/AI/.venv/lib/python3.10/site-packages/livekit/api/twirp_client.py", line 129, in request raise TwirpError( livekit.api.twirp_client.TwirpError: TwirpError(code=not_found, message=requested room does not exist, status=404) [2025-12-09 200019] [ERROR ] [Thread: 125217825355328] [/home/mazz-ullah/Desktop/OtherProjects/Restaurant/restaurant-ai-v1/common/restaurant_logger.py:106] ❌ Error disconnecting call: 'LiveKitAPI' object has no attribute 'close' Traceback (most recent call last): File "/home/mazz-ullah/Desktop/OtherProjects/Restaurant/restaurant-ai-v1/agents/new_complete_restaurant_agent.py", line 323, in disconnect_call await lk_api.close() AttributeError: 'LiveKitAPI' object has no attribute 'close'. Did you mean: 'aclose'? 200019.711 ERROR asyncio Unclosed client session client_session: <aiohttp.client.ClientSession object at 0x71e2a825f850> 200019.717 ERROR asyncio Unclosed connector connections: ['deque([(<aiohttp.client_proto.ResponseHandler object at 0x71e2a8237700>, 16835.749908261)])'] connector: <aiohttp.connector.TCPConnector object at 0x71e2a825fdc0> 200019.721 DEBUG livekit.agents tools execution completed {"speech_id": "speech_dda10185f22c"} 200019.726 DEBUG livekit.plugins… send task finished.
#ask-ai getting the error
t
You're handling the right stepsβ€”I'll respond to the two errors you showed (404 on delete_room and AttributeError from calling close) and give a concise, ready-to-use async implementation that includes proper checks, error handling, and resource cleanup. Key fixes I'm addressing: β€’ Treat a 404 from DeleteRoom as success (room already gone). β€’ Use
await 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):
Copy code
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?
Thanks β€” I see the two errors you hit: the 404 from
delete_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:
Copy code
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 docs
i
#ask-ai @function_tool() async def disconnect_call(self) -> Dict[str, Any]: """Disconnect the call and end the conversation politely. CRITICAL: Only call this AFTER customer confirms they are done. """ import os logger.info(f"πŸ”§ 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}! " f"Have a wonderful day! Goodbye!" ) await self._safe_generate_reply( instructions=f"Say exactly this: '{farewell_message}'" ) # 2. FORCE HANGUP: Delete the room to properly terminate SIP call # This is the correct way to end SIP calls - deleting the room terminates all SIP legs if self.room: room_name = self.room.name # Skip API call for mock/test rooms (console mode) if room_name and room_name.startswith("mock_") or room_name == "FAKE_RM_": logger.info(f"Skipping room deletion for test room: {room_name}") # Just disconnect the room directly for test rooms try: await self.room.disconnect() except Exception as disconnect_error: logger.warning(f"Could not disconnect test room: {disconnect_error}") else: # Initialize API Client (ensure env vars are set) lk_api = None try: lk_api = api.LiveKitAPI( LIVEKIT_CONFIG.url, os.getenv("LIVEKIT_API_KEY"), os.getenv("LIVEKIT_API_SECRET"), ) # Delete the room - this properly terminates SIP calls 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 api.TwirpError as twirp_error: # Handle 404 (room doesn't exist) gracefully - might already be deleted if twirp_error.code == "not_found": logger.warning(f"Room {room_name} not found (may already be deleted): {twirp_error.message}") else: logger.error(f"❌ Error deleting room via API: {twirp_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}") except Exception as api_error: logger.error(f"❌ Error deleting room via API: {api_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}") finally: # Properly close the API client using aclose() if lk_api: try: await lk_api.aclose() except Exception as close_error: logger.warning(f"Error closing API client: {close_error}") # 3. Shutdown the Agent self.session.shutdown(drain=False) logger.info(f"βœ… Call disconnected for {restaurant_name}") except Exception as e: logger.error(f"❌ Error disconnecting call: {e}") # Final fallback: Just shutdown the session try: self.session.shutdown(drain=False) except Exception as shutdown_error: logger.error(f"❌ Error shutting down session: {shutdown_error}") return { "status": "success", "message": "Call disconnected", } for the given code i want to wait till it does not say final messag
t
You're asking how to wait until the farewell message finishes playing (or is confirmed sent) before performing the room deletion and shutdown. I’ll show a concise, reliable pattern to do that and a drop-in async code snippet for your function. Key approach β€’ Send the farewell and await confirmation that speech/output finished. β€’ Only after that completes, call
delete_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):
Copy 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?