I'm using livekit agents on livekit cloud, I want ...
# ask-ai
n
I'm using livekit agents on livekit cloud, I want to create a room which stays alive for 10 mins after participant disconnects. I want to achive the following. 1. The agent should stay in the call, even if the participant disconnects 2. The participant should be able to join the same room again How do i do that?
t
Thanks for reaching out, Hari. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
I'm glad you're looking to create a room in LiveKit Cloud that stays alive for 10 minutes after a participant disconnects, while keeping agents in the call and allowing participants to rejoin. Let's walk through the steps together: 1. Set the
departureTimeout
to 600 seconds:
This way, the room will stay active for 10 minutes after the last participant leaves, giving everyone a bit of extra time. 2. Specify agents in the room creation request: This makes sure the designated agents stay in the room throughout its lifetime. 3. Use the
RoomServiceClient.createRoom()
method:
Available in SDKs like Node.js, this method lets you configure the room with all the options you need. Here's a friendly example using Node.js to help you get started:
Copy code
import { RoomServiceClient } from 'livekit-server-sdk';

const client = new RoomServiceClient(
  '<LIVEKIT_CLOUD_URL>',
  '<API_KEY>',
  '<API_SECRET>'
);

await client.createRoom({
  name: 'my-room',
  departureTimeout: 600, // Keep room alive for 10 minutes after last participant leaves
  agents: [
    {
      identity: 'agent-1',
      name: 'voice-agent',
      // Additional agent configuration if needed
    }
  ],
});
This setup ensures your room stays active for those 10 minutes, agents remain in the call, and participants can easily rejoin. If you have any questions or need further assistance, feel free to ask—I'm here to help! Sources: packages/livekit-server-sdk/src/RoomServiceClient.ts
n
How do i crate the token so that participant rejoins the same room?
t
I'd be happy to help you create a token that lets a participant rejoin the same room in LiveKit Cloud. To do this, you'll want to generate a new access token using the same room name and participant identity, making sure to include the
roomJoin
permission. Here are two friendly ways to generate the token: 1. Using LiveKit CLI: `lk token create \ --api-key <your_api_key> \ --api-secret <your_api_secret> \ --room <room_name> \ --identity <participant_identity> \ --join \ --valid-for 1h`The
--join
flag is key here—it lets the participant rejoin the room. You can also adjust
--valid-for
to set how long the token stays valid. 2. Using a Server SDK (like Node.js): `import { AccessToken, VideoGrant } from 'livekit-server-sdk'; const at = new AccessToken(API_KEY, API_SECRET, { identity: 'user123', ttl: '1h', }); const grant: VideoGrant = { room: 'my-room', roomJoin: true, canPublish: true, canSubscribe: true, }; at.addGrant(grant); const token = await at.toJwt();`This snippet will help you programmatically generate a token with the right permissions. Just a quick tip: make sure the
identity
matches the participant’s original identity so they can reconnect as the same user. If you have any questions or want me to walk you through this, feel free to ask—I’m here to help! Sources: cmd/lk/token.go | CLI Tools & Token Management | livekit/livekit_composite | DeepWiki | complex-agents/nova-sonic/nova-sonic-form-agent/app/api/connection-details/... | Connecting to LiveKit | LiveKit Docs | Managing participants | LiveKit Docs
n
I'm right now using automatic dispatch method, where i only create the participant token and room gets created automatically. Im using python SDk. What do i have to change
t
Thanks for reaching out! Since you're using the automatic dispatch method with the Python SDK, you won’t be able to set the
departure_timeout
directly during token creation. But no worries! To keep the room alive for 10 minutes after the last participant leaves, you’ll want to pre-create the room with the settings you need. Here’s a friendly example of how to pre-create the room using the Python SDK:
Copy code
from livekit.api import LiveKitAPI, RoomConfiguration
import asyncio

async def create_room_with_timeout():
    lkapi = LiveKitAPI(
        url="<LIVEKIT_CLOUD_URL>",
        api_key="<API_KEY>",
        api_secret="<API_SECRET>"
    )

    room_config = RoomConfiguration(
        name="my-room",
        departure_timeout=600  # Keep room alive for 10 minutes
    )

    room = await lkapi.room.create_room(room_config)
    print(f"Room created: {room.name}, SID: {room.sid}")
    await lkapi.aclose()

asyncio.run(create_room_with_timeout())
If you’re relying on automatic room creation, the room will use the default server settings. For LiveKit Cloud, it might be helpful to reach out to support so they can adjust the default
departure_timeout
to 600 seconds for you. Please feel free to ask if you have any more questions or need a hand with anything else—I’m here to help! Sources: Rooms, participants, and tracks | LiveKit Docs | examples/agent_dispatch.py | config-sample.yaml
n
What is the difference between departure_timeout and empty_timeout
t
I’d love to help clarify the
departure_timeout
and
empty_timeout
settings in LiveKit—they each play a special role in managing your room’s lifecycle: • `empty_timeout`: This setting determines how long a room stays open if nobody joins after it’s created. For instance, if a room is created but remains empty, it will automatically close once the
empty_timeout
period passes. This helps keep things tidy by not letting unused rooms stay active forever. • `departure_timeout`: This one controls how long the room stays open after the last participant leaves. It’s great because it gives people a chance to come back within that time without needing to create a new room. After the timeout, the room will close. So, to sum it up:
empty_timeout
is for when no one has joined yet, and
departure_timeout
kicks in after everyone has left. If you have any questions or want me to walk you through it more, just let me know—I’m here to help! Sources: config-sample.yaml | livekit/livekit_room.pb.go
n
Does agent also leave if participant disconnects?
t
Just so you know, by default, an agent will leave a LiveKit room when the linked participant disconnects. This is managed by the
close_on_disconnect
option, which is set to
True
by default. What this means is that the agent session will automatically close if the participant disconnects for reasons like
CLIENT_INITIATED
,
ROOM_DELETED
, or
USER_REJECTED
. If you'd prefer the agent to stay in the room even after the participant disconnects, you can easily change this by setting
close_on_disconnect=False
in your configuration. Please feel free to reach out if you'd like me to walk you through how to set this up—I’m here to help! Sources: examples/avatar_agents/audio_wave/avatar_runner.py | pkg/service/roommanager.go
n
Copy code
2025-10-15 09:34:41,128 - INFO livekit.agents - process exiting {"reason": "", "pid": 80260, "job_id": "AJ_CCgUMGerhWnF"}
2025-10-15 09:34:41,127 - DEBUG livekit.agents - shutting down job task {"room": "TESTROOM", "reason": "", "user_initiated": false, "pid": 80260, "job_id": "AJ_CCgUMGerhWnF"}
2025-10-15 09:34:41,129 - WARNING livekit - livekit::rtc_engine:453:livekit::rtc_engine - received session close: "signal client closed: \"stream closed\"" UnknownReason Resume {"room": "TESTROOM", "pid": 80260, "job_id": "AJ_CCgUMGerhWnF"}
2025-10-15 09:34:41,136 - INFO agent - Usage: UsageSummary(llm_prompt_tokens=0, llm_prompt_cached_tokens=0, llm_input_audio_tokens=0, llm_completion_tokens=0, llm_output_audio_tokens=0, tts_characters_count=631, tts_audio_duration=34.14204081632662, stt_audio_duration=1.812) {"room": "TESTROOM", "pid": 80260, "job_id": "AJ_CCgUMGerhWnF"}
Transcript with 14 logged events for TESTROOM saved to /tmp/transcript_TESTROOM.json
2025-10-15 09:34:41,140 - DEBUG livekit.agents - input stream detached {"room": "TESTROOM", "participant": "voice_assistant_user_5709", "source": "SOURCE_UNKNOWN", "accepted_sources": ["SOURCE_MICROPHONE"], "pid": 80260, "job_id": "AJ_CCgUMGerhWnF"}
2025-10-15 09:34:41,144 - DEBUG livekit.agents - session closed {"room": "TESTROOM", "reason": "job_shutdown", "error": null, "pid": 80260, "job_id": "AJ_CCgUMGerhWnF"}
2025-10-15 09:34:44,631 - INFO agent - Webhook event sent successfully: transcript_available {"room": "TESTROOM", "pid": 80260, "job_id": "AJ_CCgUMGerhWnF"}
Transcript webhook with logged events sent for TESTROOM
2025-10-15 09:34:44,633 - DEBUG livekit.agents - http_session(): closing the httpclient ctx {"room": "TESTROOM", "pid": 80260, "job_id": "AJ_CCgUMGerhWnF"}
2025-10-15 09:34:44,634 - WARNING livekit.plugins.elevenlabs - websocket closed unexpectedly {"room": "TESTROOM", "pid": 80260, "job_id": "AJ_CCgUMGerhWnF"}
await session.start( agent=assistant, room=ctx.room, room_input_options=RoomInputOptions( noise_cancellation=noise_cancellation.BVC(), close_on_disconnect=False, ), )
This is my session, the agent got closed after participant left
t
I completely understand how it can be a bit confusing when an agent session closes even with
close_on_disconnect=False
. There are a few other reasons this might happen, and I’m here to walk you through them: 1. Unrecoverable Errors: Sometimes, if important components like LLM, STT, or TTS face repeated issues (usually after 3 failures by default), the session will close automatically. You can actually customize this behavior by adjusting
max_unrecoverable_errors
. 2. Manual Closure: It’s also possible that the session was closed intentionally in your code using methods such as
session.aclose()
or
session.shutdown()
. 3. External Room Deletion: If the room gets deleted through the LiveKit API, the agent session will end no matter what the
close_on_disconnect
setting is. 4. Worker or Job Shutdown: When the worker process stops—maybe due to scaling or deployment updates—all active sessions will be terminated. To help you pinpoint exactly why the session closed, a good approach is to listen for the
close
event in your session and log the
reason
and
error
details like this:
Copy code
@session.on("close")
def on_close(ev):
    print(f"Session closed. Reason: {ev.reason}")
    if ev.error:
        print(f"Error: {ev.error.type}, Message: {ev.error.error}")
Please feel free to reach out if you’d like a hand troubleshooting this further or if you want to tweak your configuration. I’m here to help! Sources: livekit-agents/livekit/agents/voice/agent_activity.py | Events and error handling | LiveKit Docs | Knowledge Management & Documentation System | livekit/livekit_composite | D... | Development Tools | livekit/livekit_composite | DeepWiki | Job lifecycle | LiveKit Docs
n
close reason is
CloseReason.JOB_SHUTDOWN
t
The
CloseReason.JOB_SHUTDOWN
means that the agent session was closed because the job it was linked to was intentionally shut down. This usually happens in situations like: • Worker Shutdown: When the worker process hosting the job is stopped, maybe due to scaling, deployment updates, or a manual shutdown. • Deployment Updates: During rolling updates, older agent instances are gently shut down once they finish their active sessions. • System-Initiated Cleanup: Sometimes, the platform ends jobs as part of managing resources or the job lifecycle. This event happens at the platform level and isn’t caused by participant disconnections or errors. If you'd like, I’m here to help you troubleshoot further or guide you on how to adjust your deployment to reduce these interruptions. Just let me know! Sources: livekit-agents/livekit/agents/voice/agent_session.py | Deploying to production | LiveKit Docs
n
Does the job shutdown, if i close the browser tab, meaning participant disconnected? I basically want if the participant joins the same room, the agent should continue where it left off
t
I understand how important it is to keep your agent sessions running smoothly! Closing the browser tab or a participant disconnecting doesn’t directly trigger
CloseReason.JOB_SHUTDOWN
. However, if your room is set up to end the job when everyone leaves, the job will shut down, and the agent session will end. By default, jobs keep running until all participants leave or the job is explicitly stopped. To help your agent pick up right where it left off when someone rejoins, here are a few friendly tips: 1. Keep the room alive temporarily: Try using
delete_room_on_close=False
to keep the room and session active for a little while (like 20 seconds) after someone disconnects. 2. Track participant sessions: It’s helpful to keep a record of participant identities linked to agent sessions, so you can easily recreate or resume the session when they come back. 3. Save session state: Use shutdown callbacks to save important details like conversation history when the job ends. This way, you can restore everything smoothly when the participant rejoins. If you'd like, I’m here to help you implement these strategies or tweak your setup—just let me know! Sources: tests/test_ipc.py | Job lifecycle | LiveKit Docs | Development Tools | livekit/livekit_composite | DeepWiki
n
Can you share some examples where the agent stays/joins back the room if participant disconnects?
t
I'm glad you're looking into ways to keep an agent connected or help them rejoin a room after a participant disconnects. Here are some helpful examples and strategies to guide you through this: 1. Keep the Agent in the Room: You can set
close_on_disconnect=False
in
RoomInputOptions
. This simple step prevents the agent session from closing when a participant disconnects, so the agent stays active and ready. 2. Rejoin After Disconnection: If the agent loses connection because of network hiccups, LiveKit has your back by automatically trying to reconnect using ICE restarts or a full reconnection process. This helps the agent smoothly get back into the room and continue the session. 3. Use Departure Timeout: Consider configuring the room with a
departure_timeout
. This keeps the room open for a set time (like 10 minutes) after the last participant leaves, giving the agent a comfortable window to rejoin if needed. 4. Custom Reconnection Logic: You might want to add some custom logic in your app to watch for participant disconnections and recreate the agent session when they reconnect. Using events like
participantDisconnected
and
participantConnected
can really help manage the session lifecycle smoothly. If you'd like, I’m more than happy to provide detailed code examples or walk you through any of these steps. Just let me know how I can assist you further! Sources: examples/avatar_agents/audio_wave/avatar_runner.py | agent-console/lib/event-types.ts | Connecting to LiveKit | LiveKit Docs | pkg/rtc/room.go
n
please do provide detailed to do thid
t
Here’s a detailed guide to help you ensure an agent stays in or re-joins a room after a participant disconnects. I’m here to walk you through each step, so don’t hesitate to ask if anything isn’t clear! • Keep the Agent in the Room: To make sure the agent doesn’t leave when a participant disconnects, you can set
close_on_disconnect=False
in
RoomInputOptions
. Here’s a simple example:
Copy code
await session.start(
    agent=MyAgent(),
    room=ctx.room,
    room_input_options=RoomInputOptions(
        close_on_disconnect=False,  # Prevent agent from leaving
        delete_room_on_close=False  # Keep room open after agent session ends
    ),
)
• Rejoin After Disconnection: Sometimes network hiccups happen, and if the agent disconnects, LiveKit will try to reconnect automatically. You can also listen for the
Reconnecting
and
Reconnected
events to handle this smoothly in your code:
Copy code
@session.on("reconnecting")
def on_reconnecting():
    print("Agent is reconnecting...")

@session.on("reconnected")
def on_reconnected():
    print("Agent has reconnected successfully.")
• Use Departure Timeout: Another handy tip is to configure the room with a
departure_timeout
. This keeps the room open for a set time after the last participant leaves, giving everyone a bit of breathing room. Here’s how you can do it:
Copy code
from livekit.api import LiveKitAPI, RoomConfiguration
import asyncio

async def create_room_with_timeout():
    lkapi = LiveKitAPI(
        url="<LIVEKIT_CLOUD_URL>",
        api_key="<API_KEY>",
        api_secret="<API_SECRET>"
    )

    room_config = RoomConfiguration(
        name="my-room",
        departure_timeout=600  # Keep room alive for 10 minutes
    )

    room = await lkapi.room.create_room(room_config)
    print(f"Room created: {room.name}, SID: {room.sid}")
    await lkapi.aclose()

asyncio.run(create_room_with_timeout())
• Custom Reconnection Logic: If you want to get a bit more hands-on, you can track when participants disconnect and recreate the agent session when they reconnect. Here’s a straightforward example to guide you:
Copy code
class MyAgent:
    def __init__(self):
        self.sessions = {}

    def on_participant_connected(self, participant):
        if participant.identity not in self.sessions:
            self.sessions[participant.identity] = self.create_session(participant)

    def on_participant_disconnected(self, participant):
        session = self.sessions.pop(participant.identity, None)
        if session:
            session.close()

    def create_session(self, participant):
        # Logic to create a new session for the participant
        pass
Please feel free to reach out if you’d like me to clarify anything or provide more examples. I’m here to help you every step of the way!
n
I'm unable to hear my agent's speech once i rejoin the interview
t
I'm sorry to hear you're having trouble hearing the agent's speech after rejoining the room. Let's work through some common causes and solutions together to get this sorted out: 1. Track Republishing: When you rejoin, the agent's audio track needs to be republished. Please make sure the agent's session is correctly handling track republishing during reconnection. It’s important to check that the
_on_reconnected
handler is republishing the audio track and that the subscription is successfully established. 2. Browser Audio Policies: Some browsers require user interaction before allowing audio playback. On iOS, try playing a silent dummy audio element to meet this requirement. For web clients, calling
startAudio()
after rejoining can help enable playback. 3. Playback State Management: Double-check that the agent's playback state is properly synchronized after reconnection. Make sure playback is enabled and the audio forwarding task is running smoothly. 4. TTS Pipeline: It’s good to verify that the Text-to-Speech (TTS) pipeline resumes as expected after reconnection. Also, look out for any errors in the audio frame capture process. 5. Agent-to-Agent Communication: If agents need to communicate with each other, please ensure the
RoomInputOptions.participant_kinds
includes
PARTICIPANT_KIND_AGENT
. If you'd like, I can provide more detailed steps on any of these points or assist you further. Just let me know—I'm here to help! Sources: examples/voice_agents/resume_interrupted_agent.py | Connecting to LiveKit | LiveKit Docs | src/room/Room.ts | How to Enable Agent-to-Agent Speech Detection in LiveKit