I want to save the chatcontext in the on_close eve...
# ask-ai
a
I want to save the chatcontext in the on_close event. How do I get this?
t
Thanks for reaching out, Malte. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
Hey there! If you want to save the chat context when the
on_close
event happens, you can grab the session's
history
property—it has the full conversation history. Here's a quick rundown: • Set up a callback for the
session.on("close")
event, which fires when the session ends. • Get the chat messages from
session.history.items
, where you'll find all the details like role, text content, and type. • Then, you can serialize that history and save it to a file or database. Here’s a simple example in Python:
Copy code
import json

@session.on("close")
def on_close(ev):
    history_data = [
        {"role": item.role, "text": item.text_content}
        for item in session.history.items if item.type == "message"
    ]
    with open("chat_history.json", "w") as f:
        json.dump(history_data, f, indent=2)
This way, your chat history gets saved to a JSON file as soon as the session closes. If you want me to walk you through it or help with anything else, just let me know! Sources: Session recording and transcripts | LiveKit Docs | Workflows | LiveKit Docs | livekit-agents/livekit/agents/voice/agent.py