famous-tailor-60615
12/02/2025, 2:36 PMtall-airline-16756
12/02/2025, 2:36 PMtall-airline-16756
12/02/2025, 2:37 PMfrom 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)
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
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)
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 Docsfamous-tailor-60615
12/02/2025, 2:43 PMtall-airline-16756
12/02/2025, 2:43 PMimport 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)
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:
# 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:
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 docsfamous-tailor-60615
12/02/2025, 2:47 PMtall-airline-16756
12/02/2025, 2:48 PMimport 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?