I have chat history file downloaded through ```jso...
# ask-ai
b
I have chat history file downloaded through
Copy code
json.dump(session.history.to_dict(), f, indent=4)
It has both user & agent conversations as transcribed text, it is written as json. Task: Now I want to load that chat message to agent through ChatContext(), can you provide code snippet for that?
t
Thanks for reaching out, Gopi. 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 load your saved JSON chat history (produced by
session.history.to_dict()
and
json.dump(...)
) into an agent via
ChatContext()
. Below is a concise Python example that: • loads the JSON file, • reconstructs
ChatMessage
entries (handles simple text and nested text fragments), • adds them to a
ChatContext
, • starts or updates an agent with that context. Adjust field names if your JSON structure differs (e.g., different keys for role/content).
Copy code
import json
from livekit.agents import ChatContext, ChatMessage, ChatRole, Assistant

# path to your dumped file
PATH = "transcript_file.json"

def _extract_text_from_content(content_list):
    text = ""
    for part in content_list:
        if isinstance(part, str):
            text += part
        elif isinstance(part, dict):
            # common shapes: {"text": "..."} or {"type": "text", "text": "..."}
            if "text" in part:
                text += part["text"]
            elif "content" in part and isinstance(part["content"], str):
                text += part["content"]
    return text

# Load JSON
with open(PATH, "r", encoding="utf-8") as f:
    data = json.load(f)

# Build ChatContext
chat_ctx = ChatContext()

# `items` is the typical key produced by `session.history.to_dict()`
for item in data.get("items", []):
    role = item.get("role")
    # content may be a list of strings/dicts or a single string
    content_raw = item.get("content", [])
    if isinstance(content_raw, str):
        content_text = content_raw
    else:
        content_text = _extract_text_from_content(content_raw)

    # map role string to ChatRole; ensure role names match enum (e.g., "user", "agent")
    try:
        chat_role = getattr(ChatRole, role.upper())
    except Exception:
        # fallback: treat unknown roles as user
        chat_role = ChatRole.USER

    msg = ChatMessage(role=chat_role, content=content_text)
    chat_ctx.add_message(msg)

# Example: start an agent with this context (adjust to your session API)
# await session.start(room=room, agent=Assistant(chat_ctx=chat_ctx))

# Or update an existing agent
# await agent.update_chat_ctx(chat_ctx)
If your JSON includes function calls or function-call outputs (not plain messages), tell me which fields they appear under and I’ll extend the snippet to reconstruct those types as well. Would you like that? Sources: External data and RAG | LiveKit Docs