Can I give instructions to an agent mid conversati...
# ask-ai
c
Can I give instructions to an agent mid conversation, from the entrypoint? Like can I make a function call to the agent ask it to say a line?
t
Thanks for reaching out, Subham. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
You're able to give instructions mid-conversation from the entrypoint and make the agent speak a specific line. Two simple options: • Use
generate_reply
on the running `AgentSession`:
Copy code
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:
Copy code
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 docs
c
That's wonderful, thank you.
I want to check if a remote participant has left the call, how do I check that?
t
You're welcome — regarding detecting when a remote participant leaves a call: Which platform are you using (JavaScript, iOS/Swift, Android/Kotlin, Flutter/Dart, or server-side)? I can give the exact event code for your platform — or, if you prefer, show webhook handling for backend detection. Sources: Handling events | LiveKit docs | Connecting to LiveKit | LiveKit docs | Participant attributes and metadata | LiveKit docs | Webhooks | LiveKit docs | server-sdk-ruby | livekit/livekit_composite | DeepWiki
c
python
t
Regarding Python — use the room event for participant disconnection or webhooks on the server. 1) Client-side (Python SDK) — listen for `participant_disconnected`:
Copy code
from 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:
Copy code
{
  "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)?
c
do I get information of it's a remote participant?
t
Yes — the
participant
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.
c
is my agent the local participant? Answer for both inbound and outbound calls.
t
The agent is the local participant in both inbound and outbound calls. • Inbound call (someone calls the agent): the agent that answers is the local participant; the caller is a remote participant. • Outbound call (agent calls someone): the agent that initiates the call is the local participant; the callee is a remote participant. In Python you can confirm in code by comparing SIDs or identities:
Copy code
# 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.
c
so anybody added through the sip will be remote participant right?
t
Yes — SIP participants are remote participants. They appear in the room like any other remote participant and will trigger the same events (e.g.,
participant_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.
c
Copy code
@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()
t
Good catch — a small logic issue. The
participant_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:
Copy code
@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?
c
Does my entrypoint still run or it closes when my agent leaves the room?
t
Short answer: your entrypoint keeps running unless you explicitly shut it down. Details and a minimal Python pattern: • The entrypoint (job coroutine) does not automatically close when the agent disconnects. It continues until you call shutdown/close or other configured cleanup occurs (e.g., auto-cleanup or room deletion). • Typical flow to detect agent disconnect and then stop the entrypoint:
Copy code
import 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 docs
c
Copy code
self._closing_task = asyncio.create_task(self.session.aclose())
this is implemented in the agent class, does this do the same?
t
Yes — creating a task that runs
self.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.
c
Does this mean that this stops the entrypoint too, and I can't access the room after this is run?
t
Short answer: calling
self.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:
Copy code
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?
c
can I see the entry point logs in lk agent logs?
t
Yes — entrypoint logs appear in
lk 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 docs
c
Can i add a check to see if the agent is present in the room or has left?
t
Yes — you can detect whether the agent (local participant) is present or has left. Two reliable approaches in Python: 1) Event listener for local disconnects • Listen for the room/connection
disconnected
event and react when it fires.
Copy code
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.
Copy code
# 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?
c
Copy code
await 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?
t
Calling the RemoveParticipant API to remove the local participant (agent) from the room will disconnect that session, but it does not automatically stop your entrypoint — unless your code shuts it down. What happens when you run that call: • The agent's local participant is removed from the room and the AgentSession connection is closed. • After removal you cannot use that session to interact with the room (no publishes, RPCs, etc.). • The entrypoint coroutine continues running until you explicitly end it (e.g., await
session.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)?
c
if ctx.room.local_participant is None:
will this give none when the local participant has left the call?
t
No —
ctx.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)
Copy code
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