Can I resume a session after being closed? How sho...
# ask-ai
s
Can I resume a session after being closed? How should I manage the conversation context?
t
Thanks for reaching out, Roman. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
Yes, a session in LiveKit can be resumed after being closed or disconnected. Here’s how you can manage it: Resuming a Session: • Use the
restart()
method on the session (available in the Rust SDK) to attempt reconnection. If it fails, a full reconnection may be triggered. • LiveKit also supports automatic reconnection using ICE restart. If unsuccessful, it performs a full reconnect, emitting
Reconnecting
and
Reconnected
events to handle the UI. Managing Conversation Context: • Use the
chatCtx
property in
RealtimeSession
to preserve conversation history. Copy the context before closing and apply it to the new session. • When resuming, pass the preserved chat context to the new session to maintain continuity. Let me know if you need further details or assistance with implementation!
s
how do you save the conversation context if you want to resume a previous chat? I understand that context is lost once the session is over
t
Hey there! If you want to save your conversation in LiveKit and pick up right where you left off after your session ends, here’s a simple way to do it: 1. Access the Conversation History: • While your session is active, just use
session.history
to grab the full chat history. 2. Save the Conversation History: • Use the
add_shutdown_callback
method to save that history somewhere safe, like a database or a file. For example, you could save it as a JSON file like this:
Copy code
from datetime import datetime
import json

def on_shutdown(session):
    history = session.history
    timestamp = datetime.now().strftime("%Y%m%d-%H%M%S")
    filename = f"conversation_{timestamp}.json"
    with open(filename, 'w') as f:
        json.dump([{"role": item.role, "content": item.content} for item in history], f)
    print(f"Conversation saved to {filename}")

agent.add_shutdown_callback(on_shutdown)
3. Load the Conversation History: • When you’re ready to resume, just load that saved history and use the
ChatContext
class to pass it to your new agent like this:
Copy code
from livekit.agents import ChatContext

with open("conversation.json", 'r') as f:
    history_data = json.load(f)

chat_ctx = ChatContext()
for item in history_data:
    chat_ctx.add_message(role=item["role"], content=item["content"])

agent = MyAgent(chat_ctx=chat_ctx)
Just a couple of things to keep in mind: • You’ll want to set up your own storage for keeping conversations long-term, like a database. • It’s also a good idea to listen for events like
user_speech_committed
if you want to save messages as they happen. If you hit any bumps or want me to walk you through it, just let me know—I’m here to help!