```if hasattr(config, "user_registered") and confi...
# ask-ai
h
Copy code
if hasattr(config, "user_registered") and config.user_registered is False:
            drop_msg = (
                "We are sorry, but your phone number isn't registered in our system. "
                "Please contact the support team to get your number added before using this service."
            )
            await session.say(drop_msg, allow_interruptions=False)
            
            ctx.shutdown(reason="Unregistered user.")
            ctx.delete_room()
            
            return
i have return this conditon in my entrypoint and i ma expecting it should hang up the call after this message is spoken but when i test i see the message was spoken and the agent was stopped but the call was not hung up why so ?
t
Thanks for reaching out, Sahil. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
You're on the right track — the message is played and the agent stops because that part runs, but the SIP caller stays connected because stopping the agent doesn't automatically hang up the whole room. Two fixes you need: 1) Await the shutdown call so it actually runs to completion:
Copy code
await ctx.shutdown(reason="Unregistered user.")
2) Delete the room via the RoomService API to force all participants (including the SIP caller) to disconnect.
ctx.delete_room()
is not a valid method. Example:
Copy code
room_service = api.RoomServiceClient(
    url=os.getenv("LIVEKIT_URL"),
    api_key=os.getenv("LIVEKIT_API_KEY"),
    api_secret=os.getenv("LIVEKIT_API_SECRET"),
)
await room_service.delete_room(room=ctx.room.name)
Put those after your
await session.say(...)
, and
await
both async calls. That will stop the agent and hang up the call for the caller. Would you like a combined snippet with imports and error handling? Sources: Job lifecycle | LiveKit docs | Managing rooms | LiveKit docs | Agents telephony integration | LiveKit Docs
h
yes i want
t
Below is a complete example snippet that plays the message, awaits shutdown, and deletes the room via RoomServiceClient with basic error handling. Adjust imports and variable names to match your project.
Copy code
import os
import asyncio
from livekit import api  # adjust import based on your SDK packaging
# ensure you have access to `ctx`, `session`, and `config` in this scope

async def handle_unregistered_user(ctx, session, config):
    if hasattr(config, "user_registered") and config.user_registered is False:
        drop_msg = (
            "We are sorry, but your phone number isn't registered in our system. "
            "Please contact the support team to get your number added before using this service."
        )

        try:
            # Play message to caller and wait until finished
            await session.say(drop_msg, allow_interruptions=False)
        except Exception as e:
            # Log or handle TTS/playback errors as needed
            print("Error playing message:", e)

        try:
            # Properly await agent shutdown
            await ctx.shutdown(reason="Unregistered user.")
        except Exception as e:
            # Log shutdown failure but continue to attempt room deletion
            print("Error shutting down agent:", e)

        try:
            # Delete the room to force-disconnect all participants (including SIP caller)
            room_service = api.RoomServiceClient(
                url=os.getenv("LIVEKIT_URL"),
                api_key=os.getenv("LIVEKIT_API_KEY"),
                api_secret=os.getenv("LIVEKIT_API_SECRET"),
            )
            await room_service.delete_room(room=ctx.room.name)
        except Exception as e:
            # If room deletion fails, log and decide whether to retry or mark for cleanup
            print("Error deleting room:", e)

        return
Would you like this adapted into your existing entrypoint function or with retry/backoff behavior for the room deletion?
h
# Copyright 2023 LiveKit, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """LiveKit Server APIs for Python
pip install livekit-api
Manage rooms, participants, egress, ingress, SIP, and Agent dispatch. Primary entry point is
LiveKitAPI
. See https://docs.livekit.io/reference/server/server-apis for more information. """ # flake8: noqa # re-export packages from protocol from livekit.protocol.agent_dispatch import * from livekit.protocol.agent import * from livekit.protocol.egress import * from livekit.protocol.ingress import * from livekit.protocol.models import * from livekit.protocol.room import * from livekit.protocol.webhook import * from livekit.protocol.sip import * from .twirp_client import TwirpError, TwirpErrorCode from .livekit_api import LiveKitAPI from .access_token import ( InferenceGrants, ObservabilityGrants, VideoGrants, SIPGrants, AccessToken, TokenVerifier, ) from .webhook import WebhookReceiver from .version import version all = [ "LiveKitAPI", "room_service", "egress_service", "ingress_service", "sip_service", "agent_dispatch_service", "InferenceGrants", "ObservabilityGrants", "VideoGrants", "SIPGrants", "AccessToken", "TokenVerifier", "WebhookReceiver", "TwirpError", "TwirpErrorCode", ] i can see this in api in my livekit so can w euse api.RoomServiceClient ?
t
You're correct to question that — in the Python SDK
api.RoomServiceClient
is not available. Use
LiveKitAPI
and call its
.room.delete_room(...)
to delete the room and hang up the call. Here's a concise combined snippet you can drop into your entrypoint (adjust names/imports to match your code):
Copy code
import os
from livekit import api
from livekit.protocol.room import DeleteRoomRequest

async def handle_unregistered_user(ctx, session, config):
    if hasattr(config, "user_registered") and config.user_registered is False:
        drop_msg = (
            "We are sorry, but your phone number isn't registered in our system. "
            "Please contact the support team to get your number added before using this service."
        )

        await session.say(drop_msg, allow_interruptions=False)

        # await agent shutdown
        try:
            await ctx.shutdown(reason="Unregistered user.")
        except Exception as e:
            print("Error shutting down agent:", e)

        # use LiveKitAPI to delete the room and force-disconnect the caller
        livekit_url = os.getenv("LIVEKIT_URL")
        api_key = os.getenv("LIVEKIT_API_KEY")
        api_secret = os.getenv("LIVEKIT_API_SECRET")

        lkapi = api.LiveKitAPI(url=livekit_url, api_key=api_key, api_secret=api_secret)
        try:
            await lkapi.room.delete_room(DeleteRoomRequest(room=ctx.room.name))
        except Exception as e:
            print("Error deleting room:", e)
        finally:
            await lkapi.aclose()

        return
If you want, I can adapt this to include retry/backoff for
delete_room
, or integrate logging instead of prints. Which would you prefer? Sources: Managing rooms | LiveKit docs | Agents telephony integration | LiveKit Docs
h
Error shutting down agent: object NoneType can't be used in 'await' expression i got this in logs
t
Thanks — that error explains the issue. • Why it happened:
ctx.shutdown()
returns None in the Python agent API and is not awaitable. Calling
await ctx.shutdown()
raises "object NoneType can't be used in 'await' expression." • What to do: call
ctx.shutdown("reason")
without await, then delete the room via
LiveKitAPI
to force-disconnect the SIP caller. Correct minimal pattern:
Copy code
# play message
await session.say(drop_msg, allow_interruptions=False)

# shutdown agent (DO NOT await)
ctx.shutdown("Unregistered user.")

# delete room to hang up all participants
lkapi = api.LiveKitAPI(url=LIVEKIT_URL, api_key=LIVEKIT_API_KEY, api_secret=LIVEKIT_API_SECRET)
await lkapi.room.delete_room(api.DeleteRoomRequest(room=ctx.room.name))
await lkapi.aclose()
If you want, I can adapt this into your exact entrypoint with logging or retry/backoff for the delete_room call. Which would you prefer? Sources: Job lifecycle | LiveKit docs
h
2025-11-21 062058 [INFO] voice_agent_dynamic: Assistant item added: We are sorry, but your phone number isn’t registered in our system. Please contact the support team to get your number added before using this service. {"message": "failed to publish transcription\nTraceback (most recent call last):\n File \"/app/.venv/lib/python3.12/site-packages/livekit/agents/voice/room_io/_output.py\", line 300, in _publish_transcription\n await self._room.local_participant.publish_transcription(transcription)\n File \"/app/.venv/lib/python3.12/site-packages/livekit/rtc/participant.py\", line 285, in publish_transcription\n raise PublishTranscriptionError(cb.publish_transcription.error)\nlivekit.rtc.participant.PublishTranscriptionError: engine: connection error: engine is closed", "level": "WARNING", "name": "livekit.agents", "pid": 29, "job_id": "AJ_hUVbjUYsbbPb", "timestamp": "2025-11-21T062058.115173+00:00"} 2025-11-21 062058 [INFO] voice_agent_main: Done process_call.. {"message": "websocket closed unexpectedly", "level": "WARNING", "name": "livekit.plugins.elevenlabs", "pid": 29, "job_id": "AJ_hUVbjUYsbbPb", "timestamp": "2025-11-21T062100.247648+00:00"}
t
Thanks — those logs explain what's happening. • The transcription error and "websocket closed unexpectedly" are side effects of tearing down the agent/room while audio/TTS or transcription is still active. They happen because the engine/websocket is closed during in-flight publish requests. • Confirmed flow to avoid noisy errors: a. Play the message and wait for playout:
await session.say(drop_msg, allow_interruptions=False)
b. Give a short buffer to ensure audio playback/TTS flushes:
await asyncio.sleep(0.3)
(adjust as needed) c. Call
ctx.shutdown("reason")
— do NOT await it (it's not a coroutine). d. Delete the room via
LiveKitAPI
to force-disconnect the SIP caller:
Copy code
lkapi = api.LiveKitAPI(url=..., api_key=..., api_secret=...)
     await lkapi.room.delete_room(api.DeleteRoomRequest(room=ctx.room.name))
     await lkapi.aclose()
• If you still see frequent warnings: ◦ Increase the sleep to 0.5–1s to let TTS/transcription finish. ◦ Catch and ignore
PublishTranscriptionError
around transcription publishes. ◦ Add retry/backoff for
delete_room
if transient API errors occur. If you want, I can: • Add the small delay and error-handling into your exact entrypoint snippet, or • Provide a version that ignores transcription publish errors and logs them instead. Which would you like? Sources: Agents telephony integration | LiveKit Docs | Managing rooms | LiveKit docs | Job lifecycle | LiveKit docs