We have voice chat agents that should persist when...
# ask-ai
g
We have voice chat agents that should persist when users have network hiccups or refresh the browser, but currently agents die on room disconnection. Manual exit/rejoin works perfectly with close_on_disconnect=False, but browser refresh causes the agent to exit with 'room disconnected'. What's the recommended pattern for maintaining agent persistence across network interruptions while still cleaning up properly when the session truly ends?
t
Thanks for reaching out, Vrishabh. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
g
you there ?
t
To make sure we get your agent staying persistent through network hiccups and browser refreshes, could you help me understand a bit more? • Are you hoping to keep the agent’s conversation history and state even if the browser gets refreshed? • Do you want the agent to keep running on the server side while the client reconnects? • Is your agent a specific type, like voice, chat, or maybe both? • Would storing data on the client side (like localStorage or sessionStorage) work for you, or do you need something managed on the server side?
Just to make sure I’m on the right track and can help you best with keeping your agent persistent through network hiccups and browser refreshes, could you share a bit more? • Are you hoping to keep the agent’s conversation history intact even if the browser refreshes? • Do you want the agent to keep running on the server side while the client reconnects? • Is your agent a specific type, like voice, chat, or maybe both? • Would something like client-side persistence (think localStorage or sessionStorage) work for you, or do you need something managed on the server side?
g
1. Are you hoping to keep the agent’s conversation history intact even if the browser refreshes? yes 2. Do you want the agent to keep running on the server side while the client reconnects? sure 3. Is your agent a specific type, like voice, chat, or maybe both? maybe both 4. Would something like client-side persistence (think localStorage or sessionStorage) work for you, or do you need something managed on the server side? we will keep the conversation history in db
t
To keep your agent going strong through network hiccups and browser refreshes, while also saving the conversation history in a database, here’s a friendly approach you might find helpful: • Server-Side Persistence: Grab the
session.history
object to capture and save chat history in your database when the session wraps up. You could use a shutdown callback to do this smoothly. Setting up a database like Redis or SQLite to store and pull conversation history will make sure your agent’s state and history stick around, even after a browser refresh. • Agent Session State Management: Use the
ChatContext
object to keep the conversation context alive and pass it between agents if needed. You can also add session replacement logic to manage agent sessions on the fly, all while keeping the chat history intact. • Client-Side State Restoration: On the client side, tools like React components can help manage state across refreshes. Syncing the frontend with the server lets you restore sessions smoothly. Plus, LiveKit’s built-in state synchronization and RPC features make sharing custom state between the frontend and agent super easy. Following these steps will help your agents stay persistent through interruptions and refreshes, while also cleaning up properly when sessions truly end. If you want, I’m happy to share more details or examples to get you started! Sources: Session recording and transcripts | LiveKit Docs | client/components/chat.tsx | complex-agents/personal_shopper/README.md | Workflows | LiveKit Docs | agent/main.py
g
We're building voice chat lessons where agents should persist through network hiccups but clean up when sessions truly end. Currently: Working: Manual exit/rejoin (agent stays alive) Broken: Browser refresh/network disconnect (agent dies, user stuck reconnecting to dead room) Our Backend Setup: - Python agents on Modal with close_on_disconnect=False - Webhook manages lifecycle (room_started spawns agent, room_finished cleans up) - Persistent room names: lesson-{unitId}-{userId} Questions: 1. What's the recommended pattern for agent persistence across network interruptions? 2. How do you detect 'zombie rooms' (rooms exist but agents are dead)? 3. Any built-in LiveKit features for agent health checking or room cleanup? 4. Should we handle this at the room level, agent level, or webhook level?"
t
Here’s a friendly guide to help you tackle agent persistence, zombie room detection, and health checks in your LiveKit setup: • Agent Persistence Across Interruptions: Keep an eye on connection states to spot disconnections and set up reconnection logic. You can monitor the
room.connectionState
property and listen for
Disconnected
events. Also, make sure your backend supports reconnections by saving agent states and restarting sessions when users come back. • Zombie Room Detection: To avoid those pesky abandoned rooms, try pinging users every now and then during inactivity. If you don’t hear back after a few tries, it’s a good idea to close the session and delete the room. This keeps things tidy and efficient. • Agent Health Checks: LiveKit’s built-in user state tracking, like
listening
,
speaking
, and
away
, is super handy for monitoring activity. You can set up timeouts to spot inactivity and clean up idle agents automatically. • Room Cleanup: Use server-side room management tools to clear out expired participant states and handle disconnections smoothly. For example, a cleanup worker that regularly checks and removes inactive participants can make a big difference. • Deployment Considerations: Consider a blue-green deployment approach so active conversations can finish naturally while new instances take on fresh connections. Also, keep in mind any platform-specific timeout limits and plan for graceful handling if sessions get forcibly closed. Following these tips will help you keep agent persistence solid, catch those zombie rooms early, and clean up resources properly. If you want, I’m here to share more details or walk you through some examples—just let me know! Sources: pkg/rtc/room.go | fly.io/fly.toml | Agents Core Architecture | livekit/livekit_composite | DeepWiki | examples/voice_agents/inactive_user.py | Web and mobile frontends | LiveKit Docs
g
when we refresh the broswer or if there is a network hiccup should we use the same room or create fresh room?
t
Hey there! If you refresh your browser or hit a little network glitch, it’s best to stick with the same room instead of making a new one. LiveKit has some handy built-in reconnection features that take care of things like resuming your connection, restarting ICE, and republishing tracks automatically. Starting fresh rooms can sometimes cause tricky issues, like race conditions or problems with reusing room IDs—especially if the old room hasn’t fully wrapped up yet. Keeping the same room helps everything run smoothly, keeps your session in sync, and makes the whole experience much nicer. If you want me to walk you through it or have any questions, just give me a shout—I’m here to help! Sources: Connecting to LiveKit | LiveKit Docs | Avoiding Room ID Reuse When Re-Creating Rooms With the Same Name
g
i am using webhook based approach with modal labs
t
Using a webhook-based approach with Modal Labs for room and agent management is a solid strategy. Here are some friendly tips and things to keep in mind: • Webhook Configuration: Make sure your webhook endpoints are set up to handle LiveKit events like
room_started
,
room_finished
,
participant_joined
, and
participant_left
. It’s helpful to use LiveKit's webhook receiver libraries to securely validate and process these events. • Agent Lifecycle Management: You can use
room_started
events to kick off Modal Labs functions that deploy agents, and
room_finished
events to tidy things up by cleaning resources. This way, agents are managed dynamically based on what’s happening in the room. • Room and Agent State: Keeping track of room and agent state in a database or cache is a great idea to handle reconnections and keep things running smoothly. Using persistent room names like
lesson-{unitId}-{userId}
helps map events to the right resources easily. • Error Handling: It’s smart to add retry logic for your webhook-triggered Modal Labs functions to handle any temporary hiccups. LiveKit will retry webhook deliveries a few times, but having graceful error handling in your functions will give you extra peace of mind. • Scaling and Resource Management: Use room events to adjust agent resources on Modal Labs dynamically. For example, deploy agents when participants join and scale down when the room is empty to keep things efficient. If you’re facing any specific challenges or have workflows you want to chat about when integrating LiveKit webhooks with Modal Labs, just let me know! I’m here to help with tailored advice. Sources: Webhooks | LiveKit Docs | examples/webhooks-nextjs/README.md | pkg/telemetry/events.go
g
i am using supabase for my db. why did you say redis ?
t
Hey! Redis was brought up as an example for storing and retrieving conversation history. Since you’re working with Supabase, you can totally apply the same ideas to your setup. Supabase, built on PostgreSQL, is great at handling persistent storage for things like room and agent state, plus your conversation history. If you want, I’d be happy to share some specific examples or tips tailored just for Supabase to help manage your LiveKit data. Just let me know how I can help!
g
how to save conversation history, like chat transript and retrive it when a user joins a room ?
t
Hey there! If you want to save and retrieve conversation history, like chat transcripts, in LiveKit, here’s a simple way to do it: • Saving Conversation History: You can use the
session.history
object to keep track of the entire conversation during an AI agent session. Then, save this data to your Supabase database—either by using a shutdown callback or by listening to real-time events like
conversation_item_added
or
user_input_transcribed
. For example, you might save the transcript as JSON or directly into your database. • Retrieving Conversation History: When someone joins a room, just fetch the stored conversation history from your Supabase database and send it to the frontend. This way, they’ll see the full chat context, including messages from earlier sessions. • Custom Backend Logic: Since LiveKit doesn’t save chat history on its own, you’ll need to set up your own backend logic to store and pull chat data. Supabase, being PostgreSQL-based, fits perfectly for this. If you’d like, I can share some specific code examples to help you integrate this with Supabase—just let me know! Sources: Session recording and transcripts | LiveKit Docs | client/app/actions.ts | hooks/useChatAndTranscription.ts | Sending text | LiveKit Docs | Sending text | LiveKit Docs