creamy-tiger-14805
12/11/2025, 10:28 AMtall-airline-16756
12/11/2025, 10:28 AMtall-airline-16756
12/11/2025, 10:29 AMgenerate_reply on the running `AgentSession`:
await session.generate_reply(instructions="Say: 'Hello, I'm here to help you.'")
• Or directly call session.say() for a pre-defined utterance and control interruptions:
await session.say("This is a direct message from the entrypoint.", allow_interruptions=False)
These calls can run from the entrypoint, event handlers, or background tasks and will cause the agent to speak immediately (or queue/interrupt based on allow_interruptions). You don't need to create a special function tool to make the agent say something.
Sources: Agent speech and audio | LiveKit docscreamy-tiger-14805
12/11/2025, 10:32 AMcreamy-tiger-14805
12/12/2025, 12:48 PMtall-airline-16756
12/12/2025, 12:48 PMcreamy-tiger-14805
12/12/2025, 12:50 PMtall-airline-16756
12/12/2025, 12:50 PMfrom livekit import Room
room = Room()
@room.on("participant_disconnected")
def on_participant_disconnect(participant):
print(f"Participant {participant.identity} ({participant.sid}) has left")
Place this after you connect to the room so the handler is registered; it fires when a remote participant leaves.
2) Server-side (webhook) — handle participant_left POSTs:
• Configure your LiveKit server to send webhooks to your endpoint.
• Verify the Authorization header signature using your API secret.
• Example expected payload:
{
"event": "participant_left",
"room": {
"sid": "room-123",
"name": "my-room"
},
"participant": {
"sid": "pa-456",
"identity": "user123"
}
}
Process that POST to detect departures from the backend.
Which option do you want the full example for (client handler or webhook handler)?creamy-tiger-14805
12/12/2025, 12:51 PMtall-airline-16756
12/12/2025, 12:51 PMparticipant you receive in the participant_disconnected handler is a remote participant object.
Two simple ways to confirm it's remote:
• Type/handler context: the event delivers a RemoteParticipant instance (not the local participant).
• Compare SIDs: check participant.sid != room.local_participant.sid to ensure it isn’t the local participant.
If you want, I can show a short Python snippet that demonstrates the check in your disconnect handler.creamy-tiger-14805
12/12/2025, 12:54 PMtall-airline-16756
12/12/2025, 12:55 PM# inside your room event handler/context
local = room.local_participant
@room.on("participant_disconnected")
def on_participant_disconnect(participant):
if participant.sid == local.sid:
print("Local participant left")
else:
print(f"Remote participant left: {participant.identity} ({participant.sid})")
Use room.local_participant (or compare participant.identity) to determine whether the participant is local (the agent) or remote.creamy-tiger-14805
12/12/2025, 12:57 PMtall-airline-16756
12/12/2025, 12:57 PMparticipant_disconnected). You can identify them as remote by comparing participant.sid or participant.identity against room.local_participant, or by checking any SIP-specific attributes (such as sip.callStatus) if you record those when the participant joins.creamy-tiger-14805
12/12/2025, 1:00 PM@ctx.room.on("participant_disconnected")
def _on_participant_disconnected(participant: rtc.RemoteParticipant):
logger.info(f"Participant disconnected: {participant.identity} ({participant.sid})")
if participant.sid == ctx.room.local_participant.sid:
logger.info("agent disconnected from the call")
else:
logger.info(f"remote participant disconnected from the call")
ctx.delete_room()tall-airline-16756
12/12/2025, 1:00 PMparticipant_disconnected event only fires for remote participants, so participant.sid == ctx.room.local_participant.sid will never be true. Remove that local-participant check and treat the handler as handling remote departures. For example:
@ctx.room.on("participant_disconnected")
def _on_participant_disconnected(participant: rtc.RemoteParticipant):
logger.info(f"Remote participant disconnected: {participant.identity} ({participant.sid})")
ctx.delete_room()
If you still need to detect when the local agent leaves, listen for the room/connection state changes or handle that where you explicitly disconnect the local participant. Would you like a snippet for detecting local disconnects?creamy-tiger-14805
12/12/2025, 1:29 PMtall-airline-16756
12/12/2025, 1:29 PMimport asyncio
@server.rtc_session()
async def entrypoint(ctx: JobContext):
session = AgentSession(...)
await session.start(room=ctx.room, agent=MyAgent())
disconnect_event = asyncio.Event()
@ctx.room.on("disconnected")
def _on_disconnected():
disconnect_event.set()
# or listen for a specific local disconnect you trigger elsewhere
await disconnect_event.wait()
await session.aclose() # or ctx.shutdown() / session.shutdown()
Use room `disconnected`/connection-state events or your own logic to decide when to call session.aclose() or ctx.shutdown() to end the entrypoint. Would you like a snippet that reacts to the agent being removed versus network disconnects?
Sources: Job lifecycle | LiveKit docs | Company directory phone assistant | LiveKit docscreamy-tiger-14805
12/12/2025, 1:31 PMself._closing_task = asyncio.create_task(self.session.aclose())
this is implemented in the agent class, does this do the same?tall-airline-16756
12/12/2025, 1:31 PMself.session.aclose() will begin a graceful shutdown of the AgentSession (closing connections and cleaning up the session). That will typically cause the agent to stop interacting with the room.
Two important notes:
• Starting the task begins shutdown, but the entrypoint/job itself still runs until that task completes or you explicitly stop the entrypoint (for example by awaiting the task, calling ctx.shutdown(), or otherwise exiting the entrypoint coroutine).
• If you want the entrypoint to end as soon as shutdown starts, either await the task or set up a coordination point (an Event or call ctx.shutdown() when aclose() finishes).
If you want, I can show a short snippet that awaits the task or signals the entrypoint to exit when aclose() completes.creamy-tiger-14805
12/12/2025, 1:32 PMtall-airline-16756
12/12/2025, 1:32 PMself.session.aclose() closes the AgentSession and its connection to the room, so you can no longer interact with the room through that session. It does not automatically stop the entrypoint coroutine unless you coordinate it.
What happens and how to handle it:
• session.aclose() starts a graceful shutdown: it closes transports, stops the agent, and cleans up the session — after it completes you cannot use that session to access the room.
• If you only create a background task (e.g., self._closing_task = asyncio.create_task(self.session.aclose())) the entrypoint keeps running while shutdown proceeds in the background.
• To stop the entrypoint when shutdown begins or completes, coordinate explicitly:
◦ Await the task so the entrypoint waits for shutdown:
await self._closing_task
• Or signal the entrypoint to exit (e.g., ctx.shutdown() or set an asyncio.Event that the entrypoint awaits).
• Or both: trigger aclose() and then call ctx.shutdown() to stop the job immediately.
If you want, I can share a minimal pattern that cleanly triggers session.aclose(), waits for it, and ensures the entrypoint exits. Which behavior do you prefer — immediate exit when shutdown starts, or wait until shutdown completes?creamy-tiger-14805
12/12/2025, 1:35 PMtall-airline-16756
12/12/2025, 1:35 PMlk agent logs.
• Runtime logs (stdout/stderr, Python logging, print) from your entrypoint are streamed by the agent and shown with lk agent logs.
• You can add structured fields via ctx.log_context_fields to include room/workder info in those logs.
• Logs are also visible in the LiveKit Cloud Agent insights if observability is enabled.
Would you like a short snippet showing how to add ctx.log_context_fields or an example logger setup?
Sources: Log collection | LiveKit Docs | Deploying to production | LiveKit Docs | Job lifecycle | LiveKit docs | Agent insights in LiveKit Cloud | LiveKit docscreamy-tiger-14805
12/12/2025, 9:02 PMtall-airline-16756
12/12/2025, 9:02 PMdisconnected event and react when it fires.
disconnect_event = asyncio.Event()
@ctx.room.on("disconnected")
def _on_disconnected():
disconnect_event.set()
# elsewhere in entrypoint
await disconnect_event.wait()
# agent has left / been disconnected
2) Check session/room state directly
• Inspect room.local_participant and the session connection state. After session.aclose() or a disconnect event, the session will no longer be usable.
# quick presence check
if ctx.room.local_participant is None:
print("agent not present")
else:
print("agent present:", ctx.room.local_participant.sid)
Best practice: combine both — listen for disconnected to react immediately, and use session.aclose() or ctx.shutdown() to drive coordinated shutdown. Do you want a snippet that signals the entrypoint to exit when the agent disconnects?creamy-tiger-14805
12/12/2025, 9:18 PMawait job_ctx.api.room.remove_participant(api.RoomParticipantIdentity(
room=job_ctx.room.name,
identity=job_ctx.room.local_participant.identity
))
does it allow the entrypoint to run?tall-airline-16756
12/12/2025, 9:18 PMsession.aclose(), call ctx.shutdown(), or exit the entrypoint).
Practical options to coordinate cleanly:
• If you want the entrypoint to stop immediately when you remove the local participant:
a. Call remove_participant.
b. Then call await session.aclose() or ctx.shutdown() (or await the background aclose() task).
• If you want the entrypoint to keep running (e.g., to do cleanup, logging, or call other APIs) after removal:
◦ Start the remove call, then perform remaining work; just avoid using the closed session for room actions.
• Alternatively, listen for the room disconnected event and use that to trigger shutdown logic in the entrypoint.
Would you like a small snippet that removes the local participant and then ensures the entrypoint exits (either immediately or after cleanup)?creamy-tiger-14805
12/12/2025, 9:38 PMif ctx.room.local_participant is None:
will this give none when the local participant has left the call?tall-airline-16756
12/12/2025, 9:39 PMctx.room.local_participant is None is not a reliable way to detect the agent leaving.
Use the room disconnected event or the session lifecycle instead:
1. Event-based (recommended)
disconnect_event = asyncio.Event()
@ctx.room.on("disconnected")
def _on_disconnected():
disconnect_event.set()
# elsewhere in entrypoint
await disconnect_event.wait()
# agent has been disconnected — perform cleanup or exit
1. Coordinate shutdown when you remove the local participant
• After calling RemoveParticipant, call await session.aclose() or ctx.shutdown() (or await a background aclose() task) so your entrypoint can stop or finish cleanup.
1. Quick presence check (not for post-disconnect):
• While connected, ctx.room.local_participant is present and you can inspect it (e.g., .sid).
• Do not rely on it becoming None after disconnect — handle disconnects via events and explicit shutdown callbacks (ctx.add_shutdown_callback).
Would you like a snippet that removes the local participant, waits for aclose() to finish, and then exits the entrypoint?
Sources: Job lifecycle | LiveKit docs | Connecting to LiveKit | LiveKit docs | Events and error handling | LiveKit docs