chilly-soccer-432
11/05/2025, 4:52 PMtall-airline-16756
11/05/2025, 4:52 PMtall-airline-16756
11/05/2025, 4:52 PMconversation_item_added to capture committed agent/user chat items and persist them. Docs
◦ Listen for user_input_transcribed to store user speech-to-text (fields like transcript, is_final, language). Docs
• On session end, persist any remaining history:
◦ Call await session.aclose() to flush incomplete agent turns, then read session.history and save it, or rely on the default behavior that flushes on disconnect. Guide Reference
• If you need timestamps for agent speech:
◦ Add a transcription_node to gather agent transcription segments and, when supported, TTS-aligned timing. (Experimental; Python-only.) Details Overview
• Important: LiveKit doesn’t store text streams long-term—implement your own DB/storage for persistence. Note
Would you like a short code sketch (Python or Node) showing these handlers writing to your DB?
Sources: Events and error handling | LiveKit docs | Session recording and transcripts | LiveKit Docs | Pipeline nodes and hooks | LiveKit docs | Text and transcriptions | LiveKit docs | Sending text | LiveKit docschilly-soccer-432
11/05/2025, 4:58 PMtall-airline-16756
11/05/2025, 4:59 PMuser_input_transcribed and conversation_item_added
• A transcription_node example (optional, for timestamps)
• add_shutdown_callback + session.history on close
• Simple DB writes (SQLite/Postgres placeholder)
If Node.js, I’ll provide the same flow using the JS Agents SDK.
Sources: Python Agents Core Architecture | livekit/livekit_composite | DeepWiki | AI Agents Framework | livekit/livekit_composite | DeepWiki | Events and error handling | LiveKit docs | Session recording and transcripts | LiveKit Docs | Job lifecycle | LiveKit Docschilly-soccer-432
11/05/2025, 5:02 PMtall-airline-16756
11/05/2025, 5:03 PMuser_input_transcribed and conversation_item_added
• Persists records to a DB (SQLite example via aiosqlite)
• Saves a final history snapshot on shutdown using add_shutdown_callback
• Ensures incomplete agent turns are flushed with session.aclose()
References: Events, Session recording & transcripts, How to capture real-time transcriptions
import asyncio
import json
import aiosqlite
from datetime import datetime
# Replace these with actual LiveKit imports used in your app
# from livekit.agents import AgentSession
# from livekit.agents.worker import JobContext
DB_PATH = "transcripts.db"
CREATE_TABLES_SQL = """
CREATE TABLE IF NOT EXISTS transcripts (
id INTEGER PRIMARY KEY AUTOINCREMENT,
session_id TEXT,
type TEXT, -- 'user_transcript' | 'conversation_item' | 'history_snapshot'
role TEXT, -- 'user' | 'assistant' (for conversation items)
content TEXT, -- transcript text or message content (JSON for items)
language TEXT,
is_final INTEGER, -- 0/1
speaker_id TEXT,
created_at TEXT
);
"""
class DB:
def __init__(self, path: str):
self.path = path
self.conn: aiosqlite.Connection | None = None
async def connect(self):
self.conn = await aiosqlite.connect(self.path)
await self.conn.execute("PRAGMA journal_mode=WAL;")
await self.conn.execute(CREATE_TABLES_SQL)
await self.conn.commit()
async def insert(self, session_id: str, rec: dict):
assert self.conn
await self.conn.execute(
"""
INSERT INTO transcripts (session_id, type, role, content, language, is_final, speaker_id, created_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
""",
(
session_id,
rec.get("type"),
rec.get("role"),
rec.get("content"),
rec.get("language"),
1 if rec.get("is_final") else 0 if rec.get("is_final") is not None else None,
rec.get("speaker_id"),
datetime.utcnow().isoformat(),
),
)
await self.conn.commit()
async def close(self):
if self.conn:
await self.conn.close()
self.conn = None
# Helper: serialize message content safely
def to_json_safe(value):
try:
return json.dumps(value, ensure_ascii=False)
except Exception:
return json.dumps(str(value), ensure_ascii=False)
# Entrypoint invoked by your worker
async def entrypoint(ctx): # ctx: JobContext
# session = AgentSession(...) # Create/configure your session as you normally do
session = ctx.session # If your framework provides it on the context
db = DB(DB_PATH)
await db.connect()
session_id = getattr(session, "id", None) or "unknown-session"
# User STT segments (language, transcript, is_final, speaker_id)
async def on_user_input_transcribed(ev):
await db.insert(
session_id,
{
"type": "user_transcript",
"content": ev.transcript,
"language": getattr(ev, "language", None),
"is_final": getattr(ev, "is_final", None),
"speaker_id": getattr(ev, "speaker_id", None),
},
)
# Committed chat items (agent or user). ev.item is a ChatMessage.
async def on_conversation_item_added(ev):
item = ev.item
record = {
"type": "conversation_item",
"role": getattr(item, "role", None), # 'user' or 'assistant'
"content": to_json_safe(getattr(item, "content", None)),
}
await db.insert(session_id, record)
# Register event handlers
session.on("user_input_transcribed", on_user_input_transcribed)
session.on("conversation_item_added", on_conversation_item_added)
# Shutdown: flush incomplete agent turns and persist final history
async def on_shutdown():
try:
# Flush any incomplete agent turn
await session.aclose()
except Exception:
pass
# Persist final history snapshot
history = getattr(session, "history", None)
if history is not None:
await db.insert(
session_id,
{
"type": "history_snapshot",
"content": to_json_safe(history),
},
)
await db.close()
ctx.add_shutdown_callback(on_shutdown)
# Keep running while the session is active
await session.wait_until_closed()
# Optional: transcription node for agent TTS-aligned timestamps (experimental, Python-only)
# You can wire this into your pipeline to capture richer timing.
class MyTranscriptionNode:
def __init__(self, db: DB, session_id: str):
self.db = db
self.session_id = session_id
async def on_transcription(self, segment):
# segment may be a TimedString or provider-specific structure
# Persist as JSON for flexibility
payload = to_json_safe({
"text": getattr(segment, "text", None),
"start_time": getattr(segment, "start_time", None),
"end_time": getattr(segment, "end_time", None),
})
await self.db.insert(
self.session_id,
{
"type": "conversation_item",
"role": "assistant",
"content": payload,
},
)
# If you need a standalone runner (outside the worker), you could do:
# asyncio.run(entrypoint(my_job_context))
Want this adapted to Postgres (asyncpg/SQLAlchemy) or to include a runnable Session setup?
Sources: Building voice agents | LiveKit Docs | Events and error handling | LiveKit docs | Node.js Agents Architecture | livekit/livekit_composite | DeepWiki | Job lifecycle | LiveKit Docs | How to capture real-time agent transcriptions during conversations