why is this throwing error to me async def hangup(...
# ask-ai
s
why is this throwing error to me async def hangup(self): """Helper function to hang up the call by deleting the room""" job_ctx = get_job_context() await job_ctx.api.room.delete_room( api.DeleteRoomRequest( room=job_ctx.room.name, ) ) @function_tool() async def end_call(self, context: RunContext_T): """Called when the user wants to end the call or the call is completed.""" await context.wait_for_playout() await self.hangup()
t
Thanks for reaching out, Ajay. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
It looks like you’re running into an error when trying to delete a room using the LiveKit API. Let’s walk through some common reasons this might happen, and hopefully, we can get it sorted out together: • Incorrect Room Name: Double-check that the room name you’re trying to delete actually exists. You can list all rooms to make sure it’s there. • Authentication Issues: Make sure your API key and secret have the right permissions to perform deletions. • Network Issues: Sometimes network hiccups happen, so adding retry logic can help handle any temporary disconnections. • Improper Initialization: Confirm that your LiveKitAPI instance is set up correctly with the right URL, API key, and secret. • Race Conditions: Try to avoid deleting and recreating rooms with the same name too quickly, as this can cause conflicts. Also, having good error handling and logging in place can really help pinpoint what’s going wrong. If you want, feel free to share the specific part of your code that’s giving you trouble—I’m here to help you through it! Sources: livekit-agents/livekit/agents/voice/room_io/room_io.py | Avoiding Room ID Reuse When Re-Creating Rooms With the Same Name | livekit/livekit_room.twirp.go
s
2025-11-06 154633,838 - DEBUG livekit.agents - executing tool {"function": "end_call", "arguments": "{}", "speech_id": "speech_c326fb6e1a42"} 2025-11-06 154633,839 - DEBUG livekit.agents - http_session(): creating a new httpclient ctx 2025-11-06 154634,482 - ERROR livekit.agents - exception occurred while executing tool {"function": "end_call", "speech_id": "speech_c326fb6e1a42"} Traceback (most recent call last): File "D:\voicebots\livekit_venv\Lib\site-packages\livekit\agents\voice\generation.py", line 526, in _traceable_fnc_tool val = await function_callable() ^^^^^^^^^^^^^^^^^^^^^^^^^ File "D:\voicebots\realestate-agent\agents.py", line 141, in end_call await self.hangup() File "D:\voicebots\realestate-agent\agents.py", line 129, in hangup await job_ctx.api.room.delete_room( File "D:\voicebots\livekit_venv\Lib\site-packages\livekit\api\room_service.py", line 108, in delete_room return await self._client.request( ^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "D:\voicebots\livekit_venv\Lib\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-11-06 154634,504 - DEBUG livekit.agents - tools execution completed {"speech_id": "speech_c326fb6e1a42"} 2025-11-06 154634,509 - INFO google_genai.models - AFC is enabled with max remote calls: 10. 2025-11-06 154635,219 - DEBUG grpc._cython.cygrpc - [_cygrpc] Loaded running loop: id(loop)=2168551302992
t
It looks like the error is telling us that the room you're trying to delete doesn’t exist. This might happen if the room name was entered incorrectly or if the room has already been deleted. Here are a couple of friendly tips to help you move forward: • Double-Check the Room Name: Try using the
ListRooms
API to make sure you have the exact name of the room before you delete it. • Handle the Error Smoothly: If there’s a chance the room doesn’t exist (like during cleanup), you can catch the
NOT_FOUND
error and treat it as a non-critical issue, since the room is already gone, which is what you want! If you’d like, I’m here to help you with these steps or anything else you need. Just let me know! Sources: livekit-api/livekit/api/__init__.py | pkg/service/roomservice.go | livekit-agents/livekit/agents/job.py | Managing rooms | LiveKit docs
s
how come the room i am currently in does not exist
t
Sometimes, a room that’s currently in use might show a
NOT_FOUND
error because of timing or synchronization hiccups. Let’s explore a few reasons why this could happen and how you might address them: • Race Conditions: If a room was just created or deleted, there might be a slight delay before the system fully updates. Giving a little extra time between creating and deleting a room can help smooth things out. • Node Synchronization: In setups where multiple nodes are involved, they might not all have the latest info at the same time. Trying the operation again with some exponential backoff usually does the trick. • Database Delays: Sometimes, connectivity or replication delays in the database can cause temporary errors. Keeping an eye on your database health and logs can be really helpful here. Here are some immediate steps you can take: • Use the
ListRooms
API to double-check that the room actually exists before you try deleting it. • Make sure the room name matches exactly, including the case—it’s a common little detail that can make a big difference. • Consider using unique room names or allow a short delay of 1-2 minutes between deleting and recreating a room to avoid conflicts. If you’d like, I’m here to help you walk through any of these steps or answer any questions you might have. Just let me know! Sources: pkg/service/roomservice.go | Avoiding Room ID Reuse When Re-Creating Rooms With the Same Name | livekit-api/livekit/api/room_service.py
s
i am passing crt room name but still it throws error is there somethign elsse ia m missing
t
Thanks for sharing the room name! If you're still seeing a
NOT_FOUND
error, let's explore a few things together that might be causing this: • Room Already Deleted: Sometimes the room might have been deleted already. You can double-check by using the
ListRooms
API to see if it’s still there before trying to delete it. • Race Conditions: If the room was just created or deleted, there could be a slight delay in the system updating its status. To avoid this, try using unique room names or adding a short pause between actions. • Storage Layer Issues: Occasionally, temporary issues with the backend storage (like Redis) might cause the lookup to fail. It’s a good idea to peek at the server logs to see if there are any storage-related hiccups. • Agent Context: If you’re working with the LiveKit Python agent library, please make sure the agent isn’t running in console or debug mode, as this might skip the actual deletion process. I’m here to help if you want to dive deeper into any of these points or troubleshoot together! Sources: pkg/service/interfaces.go | Avoiding Room ID Reuse When Re-Creating Rooms With the Same Name | livekit-agents/livekit/agents/voice/room_io/room_io.py
s
can you give me code to do this
t
I'd love to help you with this! Here's a friendly example code snippet that checks if a room exists before deleting it, making sure everything goes smoothly:
Copy code
from livekit import api
import asyncio

async def delete_room_if_exists(room_name):
    # Initialize the LiveKit API client
    lkapi = api.LiveKitAPI(
        url=<LIVEKIT_SERVER_URL>,
        api_key=<LIVEKIT_API_KEY>,
        api_secret=<LIVEKIT_API_SECRET>
    )

    try:
        # List all rooms to verify the room's existence
        rooms = await lkapi.room.list_rooms(api.ListRoomsRequest())
        room_names = [room.name for room in rooms.rooms]

        if room_name in room_names:
            # Room exists, proceed to delete
            await lkapi.room.delete_room(api.DeleteRoomRequest(room=room_name))
            print(f"Room '{room_name}' deleted successfully.")
        else:
            print(f"Room '{room_name}' does not exist.")

    except api.TwirpError as e:
        print(f"Error occurred: {e.code} - {e.message}")

    finally:
        await lkapi.aclose()

# Example usage
asyncio.run(delete_room_if_exists("example-room-name"))
Here's what this code does for you: • It lists all rooms to make sure the one you want to delete actually exists. • If the room is there, it deletes it; if not, it nicely lets you know. • It handles any errors carefully and closes the API client properly, so you don’t have to worry about that. Just remember to replace
<LIVEKIT_SERVER_URL>
,
<LIVEKIT_API_KEY>
, and
<LIVEKIT_API_SECRET>
with your actual LiveKit server details. If you have any questions or need a hand with anything else, feel free to ask—I’m here to help!
s
no i am creating a telephone agent i want it to end the call by itself
t
I'm happy to help you with ending a call and deleting the room for your telephone agent programmatically. You can use the
delete_room
API to do this, which will disconnect all participants and remove the room from the server. Here’s a friendly example in Python to guide you through it:
Copy code
from livekit.api import DeleteRoomRequest

async def end_call_and_delete_room(job_ctx):
    try:
        # Delete the room to end the call
        await job_ctx.api.room.delete_room(
            DeleteRoomRequest(room=job_ctx.room.name)
        )
        print("Call ended and room deleted successfully.")
    except Exception as e:
        print(f"Error while ending call: {e}")
Just a few key things to keep in mind: • This approach ensures all participants are disconnected with the reason
ROOM_DELETED
. • It’s good to wrap the operation in a try-except block so any errors are handled smoothly. • Make sure your
job_ctx
object is properly set up with the room name and API client before you call this. If you’d like, I’m here to help you integrate this into your agent logic or answer any other questions you might have. Just let me know! Sources: livekit-agents/livekit/agents/voice/room_io/room_io.py | Connecting to LiveKit | LiveKit docs | livekit-api/livekit/api/room_service.py | Managing rooms | LiveKit docs | Job lifecycle | LiveKit Docs
s
is there any other way to do this
t
I’m happy to share some alternative ways to end a call and delete a room for your telephone agent that might make things easier for you: • Automatic Room Deletion: You can set
delete_room_on_close=True
in
RoomInputOptions
. This will automatically delete the room once the agent’s session ends, as long as no other participants are still connected. • Call Transfer: Another approach is using the
TransferSIPParticipant
API to transfer the caller to a different endpoint. This ends the caller’s session but doesn’t delete the room itself. If you want, you can pair this with a
delete_room
call to remove the room afterward. • External Deletion: You can also trigger the
delete_room
API from an external service or script using the LiveKit server SDKs or CLI. This method ensures the room is deleted and everyone is disconnected. Each of these options offers flexibility depending on what fits your needs best. That said, the
delete_room
API is usually the most straightforward and reliable way to fully end a call and delete the room. Please don’t hesitate to reach out if you’d like any help setting up or understanding these options—I’m here to support you! Sources: agent.py | Managing rooms | LiveKit docs | Agents telephony integration | LiveKit Docs | Job lifecycle | LiveKit Docs | livekit-agents/livekit/agents/voice/room_io/room_io.py