cool-salesmen-60705
12/02/2025, 1:09 PMtall-airline-16756
12/02/2025, 1:09 PMtall-airline-16756
12/02/2025, 1:10 PMuser_input_transcribed event or by reading conversation items from conversation_item_added.
• To get a full transcript at any time, export the session history (e.g., session.history.to_dict() and save it). Example:
with open("transcript.json", "w") as f:
json.dump(session.history.to_dict(), f, indent=2)
• If you need earlier/near-real-time captions, add a separate STT plugin (Google, Deepgram, Azure, etc.) alongside the Realtime model. That provides incremental transcriptions at the cost of an additional service.
Would you like example code for listening to user_input_transcribed in your language/SDK or help wiring up an STT plugin?
Sources: Realtime model plugins | LiveKit Docs | How to capture real-time agent transcriptions during conversations | Understanding Transcript Timing in Voice Conversations | Observability data hooks | LiveKit docscool-salesmen-60705
12/02/2025, 1:17 PMtall-airline-16756
12/02/2025, 1:17 PMuser_input_transcribed event (and optionally conversation_item_added) and handle each event as it comes. Each event includes a timestamp and the transcribed text.
2) Append events to your log in order
• When you receive an event, write a log entry immediately with its timestamp and text. This keeps your logs chronological as the session progresses.
3) If events can arrive out of order, sort before persisting
• Buffer incoming transcription events briefly (e.g., 100–500 ms) and sort by the event timestamp before writing to your persistent log to correct small ordering race conditions.
4) Example pseudocode flow
• On `user_input_transcribed`:
◦ extract timestamp and text
◦ push into an in-memory queue/buffer
• Periodically flush the buffer:
◦ sort by timestamp
◦ append sorted entries to your log/storage
5) Want code for your environment?
• I can provide a short example in JavaScript, Python, or the SDK you use to show subscribing to user_input_transcribed, buffering, and writing ordered log entries. Which language/SDK would you like?cool-salesmen-60705
12/02/2025, 1:19 PMtall-airline-16756
12/02/2025, 1:20 PMuser_input_transcribed only contains transcriptions of user speech, not agent text.
• To capture agent text (and keep a single chronological log of everything), listen to conversation_item_added — it emits both user and agent messages as they’re committed.
• If you need agent timing/aligned text, use speech_created or enable TTS-aligned transcripts (use_tts_aligned_transcript=True) to get TimedString entries for agent speech.
Would you like a small code example (JS or Python) showing how to subscribe to conversation_item_added and append ordered log entries?
Sources: Events and error handling | LiveKit docs | Text and transcriptions | LiveKit docscool-salesmen-60705
12/02/2025, 1:58 PMcool-salesmen-60705
12/02/2025, 1:59 PMtall-airline-16756
12/02/2025, 1:59 PMconversation_item_added and log them in chronological order. Below are concise examples for Python and TypeScript.
Python (sync handler):
from livekit.agents import AgentSession, ConversationItemAddedEvent
from livekit.plugins import openai
import json
import threading
# assume session created/connected already
session = AgentSession(llm=openai.realtime.RealtimeModel(voice="alloy"))
log_lock = threading.Lock()
log_path = "conversation_log.jsonl"
def append_log(entry):
with log_lock:
with open(log_path, "a", encoding="utf-8") as f:
f.write(json.dumps(entry, ensure_ascii=False) + "\n")
@session.on("conversation_item_added")
def on_conversation_item_added(event: ConversationItemAddedEvent):
item = event.item
entry = {
"timestamp": getattr(item, "created_at", None) or getattr(item, "timestamp", None),
"role": item.role,
"text": item.text_content or "",
"interrupted": bool(getattr(item, "interrupted", False)),
"id": getattr(item, "id", None),
}
append_log(entry)
print(f"[{entry['role'].upper()}] {entry['text']}")
TypeScript / Node (async handler):
import fs from "fs";
import { AgentSession, AgentSessionEventTypes, ConversationItemAddedEvent } from "@livekit/agents";
import { RealtimeModel } from "@livekit/plugins-openai";
const session = new AgentSession({ llm: new RealtimeModel({ voice: "alloy" }) });
const logPath = "conversation_log.jsonl";
function appendLog(entry: any) {
fs.appendFileSync(logPath, JSON.stringify(entry) + "\n", { encoding: "utf8" });
}
session.on(AgentSessionEventTypes.ConversationItemAdded, (event: ConversationItemAddedEvent) => {
const item = event.item;
const entry = {
timestamp: item.createdAt ?? item.timestamp ?? null,
role: item.role,
text: item.textContent ?? "",
interrupted: !!item.interrupted,
id: item.id ?? null,
};
appendLog(entry);
console.log(`[${entry.role.toUpperCase()}] ${entry.text}`);
});
Notes:
• Use item.created_at / createdAt or item.timestamp for ordering.
• Write each event as a newline JSON record (JSONL) so you can stream/process logs incrementally.
• If events may arrive out of order, buffer briefly and sort by timestamp before persisting.
Would you like a ready-to-run example for your exact SDK/runtime or a buffered implementation that reorders out-of-order events?
Sources: Events and error handling | LiveKit docs | Text and transcriptions | LiveKit docstall-airline-16756
12/02/2025, 1:59 PMconversation_item_added, extracts message fields, and appends chronological JSONL log entries. It includes a small buffer to reorder events that may arrive slightly out of order.
import json
import threading
import time
from collections import deque
from typing import Dict, Any
from livekit.agents import AgentSession, ConversationItemAddedEvent
from livekit.plugins import openai
# Assume session is created and connected elsewhere
session = AgentSession(llm=openai.realtime.RealtimeModel(voice="alloy"))
log_lock = threading.Lock()
log_path = "conversation_log.jsonl"
# Buffer to hold incoming events briefly for ordering
buffer_lock = threading.Lock()
event_buffer = deque()
BUFFER_DELAY = 0.2 # seconds to wait before flushing to ensure order
def append_log(entry: Dict[str, Any]):
with log_lock:
with open(log_path, "a", encoding="utf-8") as f:
f.write(json.dumps(entry, ensure_ascii=False) + "\n")
def _get_timestamp(item) -> float:
# Try common timestamp fields
ts = getattr(item, "created_at", None) or getattr(item, "createdAt", None) or getattr(item, "timestamp", None)
if ts is None:
return time.time()
# If ts is a string, try parsing; otherwise assume numeric
try:
return float(ts)
except Exception:
return time.time()
def flush_buffer():
with buffer_lock:
if not event_buffer:
return
# sort by timestamp, then append to log
items = sorted(event_buffer, key=lambda e: e["timestamp"])
for e in items:
append_log(e)
print(f"[{e['role'].upper()}] {e['text']}")
event_buffer.clear()
def periodic_flusher():
while True:
time.sleep(BUFFER_DELAY)
flush_buffer()
# Start background flusher thread
flusher = threading.Thread(target=periodic_flusher, daemon=True)
flusher.start()
@session.on("conversation_item_added")
def on_conversation_item_added(event: ConversationItemAddedEvent):
item = event.item
entry = {
"timestamp": _get_timestamp(item),
"role": item.role,
"text": item.text_content or "",
"interrupted": bool(getattr(item, "interrupted", False)),
"id": getattr(item, "id", None),
}
# Add to buffer; flusher will sort & persist
with buffer_lock:
event_buffer.append(entry)
Notes:
• The buffer delay (BUFFER_DELAY) is small (200 ms) to fix minor ordering races; increase if you see larger reorderings.
• Each line in conversation_log.jsonl is a JSON record (easy to stream/process).
• If you prefer no buffering, call append_log(entry) directly inside the handler.
Would you like this adapted to asyncio (async handler) or a version that also stores agent TTS timing (use_tts_aligned_transcript=True)?