Suppose I set the departure_timeout to be the same...
# ask-ai
f
Suppose I set the departure_timeout to be the same as the ttl for a livekit access token. If a participant left the room midway, and the room does not close. When the access token for the room expire, will the room close automatically? or will it wait for the entire duration of departure timeout even though access token has expired?
t
Thanks for reaching out, Mok. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
I understand this can be a bit confusing, so let me clarify it for you. When a LiveKit access token expires, it doesn't automatically close the room. Instead, the room stays open based on the
departure_timeout
setting, which decides how long the room remains available after the last participant leaves. Also, if a participant’s token expires while they’re still in the room, their session won’t end right away. LiveKit has ways, like token refresh, to keep the session going smoothly. The room will only close once the
departure_timeout
period has passed after the last person leaves, no matter what happens with token expiration. Sources: livekit-api/src/services/room.rs | livekit-api/livekit/api/access_token.py | livekit/livekit_models.pb.go | Authentication | LiveKit Docs | config-sample.yaml
f
Say if the person is still in the room when the token expire, when the person leave the room and try to use that very same token to join the room, will it work? does the token refresh reset the time of that particular token or issue a new refresh token for the participant in the room?
t
Hey there! I totally understand how frustrating it can be when trying to rejoin a LiveKit room with an expired token. Just so you know, if a participant attempts to reconnect using an expired token, the connection won’t go through because those tokens are declined right at the start. But here’s some good news: during an active session, LiveKit kindly issues a brand-new token (not just a reset of the old one) with a fresh expiration time—usually about 10 minutes. This new token is sent to the client to help make sure reconnections are smooth if someone gets disconnected. So, if a participant leaves the room and wants to come back, they’ll need to use this refreshed token from their session rather than the original expired one. I hope this clears things up and helps you have a better experience! Sources: protobufs/livekit_rtc.proto | livekit-protocol/src/livekit.rs | livekit-android-test/src/test/java/io/livekit/android/room/RTCEngineMockE2E... | spec/livekit/token_verifier_spec.rb | Authentication | LiveKit Docs
f
is there a way to not refresh the token during an active session? where is it possible to kick the participant out if the token expire during an active session and close the room?
t
Hi there! I wanted to share that LiveKit automatically refreshes tokens during active sessions to keep everything running smoothly. Could you help me understand a bit more about why you'd like to disable token refresh and have the session disconnect when the token expires? For instance, are you looking to have tighter control over sessions or handle room closures in a specific way? Knowing this will really help me assist you better and find the best solution together.
f
i am looking for tighter control over sessions, whereby i want to restrict the timing the user can access the room. After a certain timing, i want to stop the user from using the room.
t
To help you restrict user access to a LiveKit room after a certain time, a good approach is to use token expiration. When you generate the access token, you can set a short TTL (Time-To-Live) to control how long the token stays valid. For instance, you might set the token to expire after 10 minutes like this:
Copy code
const at = new AccessToken(process.env.LIVEKIT_API_KEY, process.env.LIVEKIT_API_SECRET, {
  identity: participantName,
  ttl: '10m', // Token expires after 10 minutes
});
at.addGrant({ roomJoin: true, room: roomName });
After the token expires, the user won’t be able to join the room again unless your backend issues a new token for them. If you ever need to remove a participant before their token expires, you can use the
RemoveParticipant
API. Just keep in mind, this doesn’t invalidate the token itself, so the participant could potentially rejoin if their token is still valid. To avoid that, make sure your backend doesn’t issue a new token to that participant. Sources: Authentication | LiveKit Docs | Generating tokens | LiveKit Docs | Managing participants | LiveKit Docs
f
is there a max limit on the departure_timing for a room?
t
Thanks for reaching out! I’d love to help clarify the
departure_timeout
setting for you. This setting’s maximum limit is based on its data type, which is a
uint32
. That means it can handle values up to 4,294,967,295 seconds — that’s roughly 136 years! Of course, in real-world use, most people stick to much shorter, more manageable durations. By default,
departure_timeout
is set to 20 seconds, as you can see in the sample configuration. While you’re free to set it higher, just keep in mind that very long timeouts might not be the most practical choice and could affect how your server manages resources. If you have any questions about what duration might work best for you, I’m here to help! Sources: livekit/livekit_room.pb.go | pkg/config/config.go
f
when the participant leaves the room, and the room is still open, what resources are being consumed? will it take up extra memory where it retains the context?
t
I’m glad you asked about what happens when all participants leave a LiveKit room! When that happens, the room actually stays open for a little while—specifically, for the duration of the
departure_timeout
, which is set to 20 seconds by default. During this time, the server keeps just enough information, like metadata and the room’s state, so that participants can reconnect smoothly if needed. However, any active media processing, like audio or video streaming, will stop as soon as the last participant leaves. After the
departure_timeout
period ends, the room will automatically close and free up its resources, including the memory used for the room object and its internal state. If for some reason the room stays open longer—maybe due to server hooks or agents—it will keep using memory until you explicitly delete it. To help keep things running efficiently, you can also delete the room programmatically using the server API right after the session ends. This way, you make sure resources are freed up immediately. If you have any questions about how to do that, I’m here to help! Sources: pkg/rtc/room.go | Rooms, participants, and tracks | LiveKit Docs | Docs::Agents
f
is there a way, i can put in the callback function that i make LLM perform a closing remark before I close the room? THe usecase is that, i wish to restrict the user duration within a room, but also do not want it to happen abruptly. Is there a way for me to make the LLM make a closing remark before I close the room for the participant?
t
Thanks so much for reaching out! I wanted to let you know that LiveKit doesn’t currently have a built-in feature for integrating LLMs to handle closing remarks before a room closes. Could you share a bit about how you’re managing room closures right now? For example: • Are you using server-side hooks or APIs to manage the room lifecycle? • Do you already have an integration with an LLM or a particular platform you’re thinking of? Understanding this will really help me guide you toward the best approach for your needs. Looking forward to hearing from you!
f
I am planning to use livekit API to close the room. Is there any other way to simulate such a behaviour where LLM handle the closing remark before the room closes?
t
I'm happy to guide you through how to simulate a behavior where an LLM provides a closing remark before closing the room. Here's a simple approach you can try: 1. First, use the LiveKit API to delay closing the room until after the closing remark has been sent. For example, you can programmatically send a message or audio from the LLM to the participants, like saying "Goodbye for now," and wait for it to finish before closing the room. 2. Here’s a sample flow to help illustrate this:
Copy code
handle = session.say("Goodbye for now.", allow_interruptions=False)
handle.waitForPlayout().then(async () => {
    await new Promise((resolve) => setTimeout(resolve, 500));
    await hangUpCall();
});
In this example,
hangUpCall()
is where you would implement the room deletion using the LiveKit API:
Copy code
async def hangup_call():
    ctx = get_job_context()
    if ctx is None:
        return
    await ctx.api.room.delete_room(
        api.DeleteRoomRequest(
            room=ctx.room.name,
        )
    )
This way, you can be sure the LLM’s closing remark is delivered warmly and clearly before the room closes. If you have any questions or need further help, feel free to ask—I’m here to support you! Sources: Docs::Agents | Docs::Agents | Agents telephony integration | LiveKit Docs
f
The issue is that, I have a fastapi, and a livekit worker running concurrently. I plan to use the fastapi, to call livekit api to close the room. But if i do so, the agent will just abruptly end, without any graceful ending the session. Is there a way such that, i can put the timer within AgentSession, and then trigger a function that invokes LLM to perform the ending speech, and then closes the room? OR what other ways is there for me to trigger the LLM to start wrapping up the session? before the room closes
t
To help you gracefully end a session with a warm, LLM-generated closing speech before closing the room, you can use the
on_exit
method in the LiveKit
AgentSession
. This method is called right before the session closes, making it a perfect spot to have the LLM deliver a heartfelt farewell message. Here’s a simple way to set it up: 1. Inside the
on_exit
method, use
session.generate_reply()
to create a thoughtful closing remark, like this:
Copy code
async def on_exit(self):
    await self.session.generate_reply(instructions="Say a heartfelt goodbye and summarize the conversation.")
2. Once the closing speech is delivered, you can delete the room using the LiveKit API:
Copy code
job_ctx = get_job_context()
await job_ctx.api.room.delete_room(api.DeleteRoomRequest(room=job_ctx.room.name))
3. If you want to tie this into FastAPI, you can create an endpoint that triggers the session shutdown, which will then call the
on_exit
method. For example:
Copy code
@router.post("/close-room")
async def close_room():
    await agent_session.shutdown()
    return {"status": "room closing"}
This way, the LLM gets to share a nice closing message before the room closes. If you’d like, I’m here to help you with any part of the implementation or answer any questions you have! Sources: realtime/openai-realtime-tools.py
f
wait, i can call agent_session.shutdown()? instead of calling the room api to close the room??
t
I understand this can be a bit confusing! The
agent_session.shutdown()
method actually just disconnects the agent from the room—it doesn’t close the room completely. If your goal is to close the room, you’ll want to use the LiveKit API’s
delete_room()
method instead. Here’s a simple example in Python to help you out:
Copy code
api_client = api.LiveKitAPI(
    os.getenv("LIVEKIT_URL"),
    os.getenv("LIVEKIT_API_KEY"),
    os.getenv("LIVEKIT_API_SECRET"),
)
await api_client.room.delete_room(api.DeleteRoomRequest(
    room=ctx.job.room.name,
))
Also, if you'd like the room to be deleted automatically when the agent session ends, you can set this up using
delete_room_on_close
in the
RoomInputOptions
. Just let me know if you'd like me to walk you through that configuration—I’m here to help! Sources: livekit-agents/livekit/agents/voice/room_io/room_io.py | Anatomy of an Agent | LiveKit Docs