how to terminate connection from the agent's side ...
# ask-ai
a
how to terminate connection from the agent's side in livekit in python
t
Thanks for reaching out, Aditya. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
To gracefully end a connection from the agent's side in LiveKit using Python, you can use the
session.shutdown()
method (or its async version
await session.aclose()
) on an
AgentSession
instance. This will disconnect the agent from the room while keeping other participants connected. Here’s a simple example to guide you:
Copy code
@session.on("close")
def on_close(ev: CloseEvent):
    print(f"Agent Session closed, reason: {ev.reason}")

# To shut down the agent session
await session.aclose(reason=CloseReason.USER_INITIATED)
# Or use the synchronous wrapper
self.session.shutdown()
If your goal is to end the session for everyone in the room, you can use the server API’s
delete_room()
method like this:
Copy code
# End the entire room session
ctx.delete_room()  # from JobContext
Please feel free to reach out if you have any questions or need more help—I’m here for you! Sources: Agents telephony integration | LiveKit Docs | Docs::Telephony | Job lifecycle | LiveKit Docs | livekit-agents/livekit/agents/voice/agent_session.py | Events and error handling | LiveKit Docs
a
No I want to disonnect based on the my workflow
t
Hi there! To help you disconnect a participant based on your custom workflow in LiveKit using Python, here are some friendly methods you can try: 1. Forcibly Remove a Participant (Server API) You can use the
RoomServiceClient
to gently remove a participant from the backend like this:
Copy code
from livekit import api

# Initialize the RoomServiceClient
lk_api = api.RoomServiceClient(
    url="your-livekit-url",
    api_key="your-api-key",
    api_secret="your-api-secret"
)

# Remove a participant by room name and identity
await lk_api.room.remove_participant(
    room="room-name",
    identity="participant-identity"
)
This will disconnect the participant right away. To make sure they don’t rejoin, it’s a good idea to keep tokens short-lived or avoid reissuing them. 2. Graceful Disconnection via Agent or Participant If your workflow includes disconnection logic (like detecting inactivity), you could call
disconnect()
on the
Room
object. Here’s a simple example:
Copy code
SILENCE_THRESHOLD = 5  # seconds

async def monitor_interaction():
    while True:
        if time.time() - user_last_spoke_time > SILENCE_THRESHOLD:
            print("Silent for too long! Disconnecting.")
            await ctx.room.disconnect()  # Disconnects this participant
            break
        await asyncio.sleep(1)
3. Disconnect Everyone (End the Room) If you want to end the session for everyone, you can use the
delete_room()
API like this:
Copy code
# End the entire room session
await lk_api.room.delete_room(room="room-name")
This will disconnect all participants with the reason
ROOM_DELETED
. If you have any questions or need a hand implementing any of these, just let me know—I’m here to help! Sources: Managing participants | LiveKit Docs | agent/game_host.py | Agent Testing & CI/CD | livekit/livekit_composite | DeepWiki | How to detect and handle silence during calls | Connecting to LiveKit | LiveKit Docs
a
No, I want to disconnect the call once my agent workflow is done
t
Hi there! When you're ready to disconnect the call after your agent workflow is completed in LiveKit using Python, here are a couple of helpful methods you can use: 1. Disconnect Only the Agent You can use the
aclose()
method on the
AgentSession
object. This will disconnect the agent while letting other participants stay connected in the room:
Copy code
# Disconnect the agent session after completing the workflow
await self.customer_session.aclose()
This approach is great for workflows like warm transfers, where the agent leaves after finishing their part. 2. End the Call for All Participants If you want to end the entire session and disconnect everyone, you can use the
ctx.delete_room()
method:
Copy code
# End the room session for all participants
ctx.delete_room()
This makes sure the room is properly closed and all participants are disconnected. Example: Graceful Shutdown
Copy code
@llm.function_tool
async def close_session(self):
    logger.info("Closing session from function tool")
    await self.session.generate_reply(instructions="say goodbye to the user")
    self.session.shutdown()
If you have any questions or need a hand implementing these, just let me know—I’m here to help! Sources: examples/warm-transfer/warm_transfer.py | How to detect and handle silence during calls