How do i get the chat history message in livekit p...
# ask-ai
e
How do i get the chat history message in livekit python
t
Thanks for reaching out, Aditya. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
You're asking how to get chat history messages in LiveKit using Python — specifically how to access and save conversation history. Here are the ways you can do that. 1) From an active AgentSession • Access the full history via
session.history
(a
ChatContext
). • Convert to a dict for inspection/serialization:
Copy code
history_dict = session.history.to_dict()
2) Save a transcript when the session ends • Register a shutdown callback and write
session.history.to_dict()
to a file:
Copy code
from datetime import datetime
import json

def entrypoint(ctx: JobContext):
    async def write_transcript():
        current_date = datetime.now().strftime("%Y%m%d_%H%M%S")
        filename = f"/tmp/transcript_{ctx.room.name}_{current_date}.json"
        with open(filename, "w") as f:
            json.dump(session.history.to_dict(), f, indent=2)
        print(f"Transcript for {ctx.room.name} saved to {filename}")

    ctx.add_shutdown_callback(write_transcript)
3) Get messages in real time as they're added • Listen for the
conversation_item_added
event:
Copy code
@session.on("conversation_item_added")
def on_conversation_item_added(event: ConversationItemAddedEvent):
    print(f"Message from {event.item.role}: {event.item.text_content}")
Notes •
session.history
is available only inside an active
AgentSession
. • If you’re not using
AgentSession
, you must store messages yourself (e.g., on your server or via a text stream). Would you like a short example showing how to initialize an AgentSession around this code, or do you need help exporting history to a database or a particular file format? Sources: Observability data hooks | LiveKit docs | Events and error handling | LiveKit docs | Text and transcriptions | LiveKit docs