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.
To help keep your agent connected even if the network hiccups or the browser refreshes, here are some friendly tips you can try out: • Client-Side State Management: Store important session info like room names, user IDs, and conversation context in persistent storage (think localStorage or sessionStorage). Tools like Zustand can make managing this state a breeze. • Reconnection Logic: Set up automatic reconnection with exponential backoff to smoothly handle any network interruptions. Make sure your client tries to rejoin the same room with the same agent once it’s back online. • Session Recovery: After a browser refresh, check if there’s an existing session and use that stored data to jump right back into the conversation. • Graceful Cleanup: Use shutdown hooks and session close callbacks to tidy things up properly when a session really ends. This means closing activity handlers, ending spans, and canceling any ongoing tasks. If you want, I’d be happy to help you more specifically! Could you tell me a bit about: • Are you building a web app where users might refresh their browser during a chat with an agent? • Do you want to keep the conversation history and context intact even after reconnecting? • Are you using particular client SDKs like JavaScript or React to build this? • What kind of state do you want to keep across interruptions — conversation context, user preferences, session data, or something else?
g
• Are you building a web app where users might refresh their browser during a chat with an agent? yes • Do you want to keep the conversation history and context intact even after reconnecting? yes • Are you using particular client SDKs like JavaScript or React to build this? react with next js • What kind of state do you want to keep across interruptions — conversation context, user preferences, session data. all these
t
To keep your conversation flowing smoothly, remember user preferences, and hold onto session data even when your React Next.js app refreshes the browser using LiveKit, here are some friendly tips you can try out: 1. Persistent User Preferences: You can use
localStorage
or cookies to save things like theme choices or other settings. This way, when the page reloads, your app can easily bring those preferences back. 2. Conversation History: Storing chat messages locally with
IndexedDB
(using handy libraries like Dexie) helps keep your conversation history intact, even after a refresh. 3. Session State: LiveKit lets you sync session data across participants by using participant attributes and room metadata. This means you can save user preferences and shared session info right there. 4. State Management: Consider using a state management library like Zustand or Redux with persistence middleware. They’re great for managing and saving your app’s state, including session data and conversation context. 5. Agent Context Preservation: For LiveKit agents, keep the chat context alive with the
ChatContext
feature. When you spin up new agent instances, just pass along the existing context so everything stays connected. Using these approaches will help your app remember what matters most—user preferences, conversation history, and session state—even across browser refreshes, all while staying in sync with LiveKit’s real-time magic. If you want, I’d be happy to walk you through detailed examples for any of these steps!
g
provide some useful links with examples if possible
t
I've gathered some handy resources and examples to help you with persistent state, conversation history, and session data in your React Next.js app using LiveKit. Hope you find them useful! • Chat History Persistence: Check out the agents-chatbot repo—it shows how to keep your chat history saved using a database like Vercel KV, with clear examples for saving and retrieving conversations. • Local Storage for Session State: The gemini-playground repo is a great example of using localStorage to keep session settings like API keys and user presets persistent across sessions. • Agent-Side Conversation History: LiveKit agents let you access session history that you can save when the session ends. This is super helpful if you want to keep conversations on the server side. • Starter Templates: If you're looking for a starting point, the agent-starter-react repo offers a simple React app with session management, and the meet repo has some neat video conferencing examples. These should give you some practical ideas and code snippets to get persistence working smoothly in your app. If you want me to dive deeper into any of these or have questions, just let me know—I'm here to help! Sources: client/components/header.tsx | web/src/hooks/use-playground-state.tsx | web/src/hooks/use-playground-state.tsx | Session recording and transcripts | LiveKit Docs | Agents Core Architecture | livekit/livekit_composite | DeepWiki
g
how to save conversation history, like chat transript and retrive it when a user joins a room ? LiveKit Assistant [12:09 AM] 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
t
Hey there! If you want to save and pull up your conversation history, like chat transcripts, in LiveKit, here’s a friendly guide to get you started: • Saving Conversation History: You can use the
session.history
object to keep track of the chat during an AI agent session. To save it, try using a shutdown callback or listen for real-time events like
conversation_item_added
or
user_input_transcribed
. Then, store the transcript as JSON or directly in your database—Supabase works great for this! • Retrieving Conversation History: When someone joins a room, just fetch the saved conversation from your database and send it to the frontend. This way, they’ll see the full chat context, including all the earlier messages. • Custom Backend Logic: Since LiveKit doesn’t save chat history by default, you’ll want to set up some backend logic to handle storing and retrieving your chat data. Supabase, built on PostgreSQL, is a solid option to keep things smooth. Here are some handy resources and examples to help you along the way: • Session recording and transcripts | LiveKit Docs • client/app/actions.ts • hooks/useChatAndTranscription.ts • Sending text | LiveKit Docs If you want, I’d be happy to share some specific code examples for integrating this with Supabase or any other database you’re using—just let me know!
g
how to save the llm generated text during a voice chat ?
t
To save LLM-generated text during a voice chat in LiveKit, here are some friendly ways you can do it: • Event-Based Capture: You can listen for events like
conversation_item_added
or
agent_stopped_speaking
to grab the LLM-generated text as it happens. For example, logging messages when the agent creates text or when user input is transcribed works great. • Real-Time Pipeline Access: Another handy option is using the
llm_node
or
transcription_node
in your pipeline to get text transcripts in real-time. This way, you catch both user and agent messages right as they come in. • Session History: You can also tap into the
session.history
property anytime to pull the full conversation history. It’s perfect for saving everything to a file or database once the session wraps up. • Shutdown Callbacks: Lastly, using the
add_shutdown_callback
method lets you save the conversation history after the user leaves and the room closes, so nothing gets lost. Here’s a simple example of how to capture user speech in Python:
Copy code
from datetime import datetime

@agent.on("user_speech_committed")
def on_user_speech_committed(msg):
    log_queue.put_nowait(f"[{datetime.now()}] USER:\n{msg.content}\n\n")
If you want, I’d be happy to share more detailed code examples or help you integrate this with your specific setup—just let me know! Sources: Recording agent sessions | LiveKit Docs | Session recording and transcripts | LiveKit Docs | VoicePipelineAgent | LiveKit Docs