any Python samples for agents to load /save chat h...
# ask-ai
f
any Python samples for agents to load /save chat history from/to external storage?
t
Thanks for reaching out, Kuniaki. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
You're asking for Python samples to load/save agent chat history to external storage — here are concise examples and notes you can drop into your agent. 1) Save full session report at session end (JSON file)
Copy code
from datetime import datetime
import json
from livekit.agents import JobContext

async def on_session_end(ctx: JobContext) -> None:
    report = ctx.make_session_report()
    report_dict = report.to_dict()

    current_date = datetime.now().strftime("%Y%m%d_%H%M%S")
    filename = f"/tmp/session_report_{ctx.room.name}_{current_date}.json"

    with open(filename, "w") as f:
        json.dump(report_dict, f, indent=2)

    print(f"Session report for {ctx.room.name} saved to {filename}")
Register this with your RTC server entrypoint using the
on_session_end
hook. 2) Save only conversation history on shutdown (uses session.history)
Copy code
from datetime import datetime
import json
from livekit.agents import JobContext

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(ctx.session.history.to_dict(), f, indent=2)
        print(f"Transcript for {ctx.room.name} saved to {filename}")

    ctx.add_shutdown_callback(write_transcript)
3) Load saved history into a new AgentSession
Copy code
import json
from livekit.agents import AgentSession, ChatContext

# load previously saved file
with open("/tmp/session_report_previous.json", "r") as f:
    data = json.load(f)

initial_ctx = ChatContext()
for item in data.get("history", []):
    initial_ctx.add_message(role=item["role"], content=item["content"])

session = AgentSession()
await session.start(room=ctx.room, agent=Assistant(chat_ctx=initial_ctx))
4) Pre-populate context from job metadata (example)
Copy code
import json
from livekit.agents import ChatContext

metadata = json.loads(ctx.job.metadata or "{}")
user_name = metadata.get("user_name", "unknown")

initial_ctx = ChatContext()
initial_ctx.add_message(role="assistant", content=f"The user's name is {user_name}.")
Notes and recommendations • Replace file I/O with your preferred storage backend (Postgres, Redis, S3) by writing/reading JSON to that store. • Persist the fields you need (full session report vs. just history) to keep storage efficient. • If you want, I can provide an example using a specific backend (Postgres, S3, or Redis). Which storage do you plan to use? Sources: Observability data hooks | LiveKit docs | External data and RAG | LiveKit Docs
f
how about saving/loading for each conversation turn?
t
You're asking how to save/load chat history for each conversation turn. Below are concise, practical Python patterns you can use—pick the one that fits your storage backend. Do you want an example for Postgres, Redis, or S3? 1) Hook per completed user turn (write incremental turn)
Copy code
import json
from livekit.agents import ChatMessage

async def on_user_turn_completed(self, turn_ctx: ChatContext, new_message: ChatMessage) -> None:
    # Serialize the updated full session history (safe choice)
    payload = self.session.history.to_dict()
    # Replace with your storage write (DB, S3, Redis). Example: write to file:
    with open(f"/tmp/chat_history_{self.session.room.name}.json", "w") as f:
        json.dump(payload, f)
2) Load history before starting/processing a turn (restore prior turns)
Copy code
import json
from livekit.agents import ChatContext, AgentSession

# Load stored history (file example)
try:
    with open(f"/tmp/chat_history_{ctx.room.name}.json", "r") as f:
        data = json.load(f)
        chat_ctx = ChatContext.from_dict(data)
except FileNotFoundError:
    chat_ctx = ChatContext()

session = AgentSession()
await session.start(room=ctx.room, agent=Assistant(chat_ctx=chat_ctx))
3) Low-latency option: append-only per-turn writes • Serialize only the new turn instead of full history to reduce I/O:
Copy code
# Example append line (JSONL)
turn_record = {"ts": time.time(), "role": new_message.role, "content": new_message.content}
with open(f"/tmp/chat_history_{self.session.room.name}.jsonl", "a") as f:
    f.write(json.dumps(turn_record) + "\n")
• On load, stream the JSONL and reconstruct ChatContext:
Copy code
chat_ctx = ChatContext()
with open(file_path, "r") as f:
    for line in f:
        item = json.loads(line)
        chat_ctx.add_message(role=item["role"], content=item["content"])
Best practices • Persist
session.history.to_dict()
for completeness (includes function calls and metadata). • For production, use a proper backend (Postgres/Redis/S3) instead of local files to ensure durability and concurrency. • Avoid blocking I/O in the request path — use async writes, background tasks, or a fast store like Redis for low latency. • Use append-only (JSONL) or incremental records to minimize write size; occasionally compact to a snapshot if needed. Which storage backend should I provide a complete sample for (Postgres, Redis, or S3)? Sources: Pipeline nodes and hooks | LiveKit docs | Agents and handoffs | LiveKit docs | Sending text | LiveKit docs | Agents v0.x migration guide - Python | LiveKit docs
f
can you show me full python code sample, not partial?
t
Below is a complete, runnable Python example that saves chat history on each user turn (append-only JSONL) and loads it on agent start. It uses a simple file-backed storage; swap the storage functions for Redis/Postgres/S3 in production. Paste into a file (e.g., agent.py) and run with your LiveKit agent runner.
Copy code
import asyncio
import json
import os
import time
from typing import Optional

from livekit import rtc
from livekit.agents import (
    Agent,
    AgentSession,
    JobContext,
    Worker,
)
from livekit.agents.llm import ChatContext, ChatMessage

# ---------------------------
# Config / Storage Utilities
# ---------------------------
STORAGE_DIR = "/tmp/livekit_agent_history"
os.makedirs(STORAGE_DIR, exist_ok=True)


def _jsonl_path(session_id: str) -> str:
    return os.path.join(STORAGE_DIR, f"{session_id}.jsonl")


def append_turn_record(session_id: str, record: dict) -> None:
    """Append a single-turn JSON record (JSONL)."""
    path = _jsonl_path(session_id)
    with open(path, "a", encoding="utf-8") as f:
        f.write(json.dumps(record, ensure_ascii=False) + "\n")


def load_all_turns(session_id: str) -> Optional[list]:
    """Load JSONL lines and return list of records, or None if no file."""
    path = _jsonl_path(session_id)
    if not os.path.exists(path):
        return None
    records = []
    with open(path, "r", encoding="utf-8") as f:
        for line in f:
            line = line.strip()
            if not line:
                continue
            records.append(json.loads(line))
    return records


# ---------------------------
# Assistant Agent
# ---------------------------
class AssistantAgent(Agent):
    def __init__(self, session: AgentSession):
        super().__init__(session=session, instructions="You are a helpful assistant.")
        self.session = session
        # Use room name as session id by default (customize if needed)
        self.session_id = getattr(session.context.room, "name", "unknown_session")

    async def on_enter(self) -> None:
        """Load persisted turns and reconstruct chat context on agent start."""
        stored = load_all_turns(self.session_id)
        if stored:
            # Rebuild chat context from saved turns
            for item in stored:
                role = item.get("role")
                content = item.get("content")
                meta = item.get("meta", {})
                # Use ChatContext API to add messages
                self.session.chat_ctx.add_message(role=role, content=content, metadata=meta)

        # Optionally send a greeting if no prior conversation
        if not self.session.chat_ctx.messages:
            await self.session.generate_reply(instructions="Greet the user warmly and ask how to help.")
        else:
            await self.session.generate_reply(instructions="Welcome back. Continue based on previous context.")

    async def on_user_turn_completed(self, turn_ctx: ChatContext, new_message: ChatMessage) -> None:
        """Persist the new user turn and the assistant response after each completed user turn."""
        # 1) Save the user turn
        user_record = {
            "ts": time.time(),
            "role": new_message.role,
            "content": new_message.content,
            "meta": {"message_id": getattr(new_message, 'id', None)},
        }
        append_turn_record(self.session_id, user_record)

        # 2) Option: generate assistant reply (if not auto-generated elsewhere)
        # Here, instruct the session to produce a reply and wait for it.
        await self.session.generate_reply(instructions="Respond helpfully to the user's message.")

        # 3) Save assistant reply(s) produced in this turn
        # The session.chat_ctx has been updated with assistant messages; find the latest assistant messages
        # and append them to storage. We save all assistant messages added since the last user turn.
        # For simplicity, iterate over chat_ctx messages and append any assistant messages that are not yet saved.
        # In production keep track of last-saved index or message IDs to avoid duplicates.

        for msg in self.session.chat_ctx.messages:
            if msg.role == "assistant":
                assistant_record = {
                    "ts": getattr(msg, "created_at", time.time()),
                    "role": "assistant",
                    "content": msg.content,
                    "meta": {"message_id": getattr(msg, "id", None)},
                }
                append_turn_record(self.session_id, assistant_record)

    async def on_exit(self) -> None:
        """Optional finalization on agent exit."""
        # Example: checkpoint full snapshot file (not required if using JSONL)
        snapshot_path = os.path.join(STORAGE_DIR, f"{self.session_id}_snapshot.json")
        with open(snapshot_path, "w", encoding="utf-8") as f:
            json.dump(self.session.chat_ctx.to_dict(), f, indent=2, ensure_ascii=False)


# ---------------------------
# Entrypoint / Worker
# ---------------------------
async def entrypoint(ctx: JobContext) -> None:
    # Connect to room (audio-only auto-subscribe as an example)
    await ctx.connect(auto_subscribe=rtc.AutoSubscribe.AUDIO_ONLY)

    # Build an AgentSession and Agent instance
    session = AgentSession(context=ctx)
    assistant = AssistantAgent(session=session)

    # Start the agent session
    await session.start(room=ctx.room, agent=assistant)

    # Keep alive while room is connected
    try:
        while ctx.room and ctx.room.connected:
            await asyncio.sleep(1)
    finally:
        # Ensure final snapshot when shutting down
        await assistant.on_exit()


if __name__ == "__main__":
    # Run the worker with the entrypoint function
    worker = Worker(entrypoint_fnc=entrypoint)
    worker.run()
If you'd like, I can: • Replace file-based storage with a full Redis, Postgres, or S3 example. • Add safe deduplication (track last-saved message ID) so assistant messages aren't saved repeatedly. • Show async/non-blocking storage writes (background task or queue) to avoid latency in turn handling. Which option do you prefer?