We’re using LiveKit transcription and want to (1) ...
# ask-ai
c
We’re using LiveKit transcription and want to (1) see transcripts live during a call and (2) if we join the room later (e.g. 5 minutes into the call) still be able to see all earlier transcript segments from that call. Right now, when we join later we only get new
lk.transcription
events, not the previous ones.
What is the recommended way to capture and retrieve the full call transcript history so that late‑joining clients (or our backend) can access everything that’s been transcribed so far? we are using python agent and we don't want to store the full transcript in DB. Can the agent just keep transcription in memory?
t
Thanks for reaching out, Jakub. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
You're correct: late-joining clients only receive new
lk.transcription
events because LiveKit does not persist text stream history. To give late joiners the full transcript without a DB, have your Python agent keep the transcript in memory during the session and replay it to new participants when they connect. Recommended approach (concise): 1. Capture transcripts in the agent • Listen to
user_input_transcribed
(store only final segments). • Append segments to an in-memory list with metadata (speaker_id, text, timestamp). 1. Replay to late joiners • On participant connect, send the stored history via
sendText()
on a custom topic (e.g.,
lk.transcript_history
) or as a single JSON payload. • Frontend should listen for both
lk.transcription
(live) and
lk.transcript_history
(history) and merge/display accordingly. 1. Notes and tradeoffs • In-memory storage is ephemeral and lost if the agent restarts/crashes. • For long calls or many segments, memory can grow; consider truncation or chunking if needed. • If you later need durability or cross-process sharing, add Redis/DB. If you’d like, I can: • Provide a short Python snippet showing
user_input_transcribed
capture and
participant_connected
replay, or • Show an example frontend handler to merge history + live events. Which would help most? Sources: Sending text | LiveKit docs | Observability data hooks | LiveKit docs | Text and transcriptions | LiveKit docs
c
• Provide a short Python snippet showing
user_input_transcribed
capture and
participant_connected
replay, or
t
Below is a short Python snippet that demonstrates capturing
user_input_transcribed
events into an in-memory list and replaying that history to a participant when they connect via
participant_connected
. Adjust imports and API names to match your agent/room objects if yours differ.
Copy code
import json
import asyncio

# In-memory transcript store for the session
transcript_history = []

# Example handler for transcription events
# Replace with actual decorator/registration used by your LiveKit agent
@session.on("user_input_transcribed")
def on_user_input_transcribed(event):
    # store only final segments (if your event provides is_final)
    if getattr(event, "is_final", True):
        segment = {
            "speaker_id": getattr(event, "speaker_id", None),
            "text": event.transcript,
            "timestamp": getattr(event, "timestamp", None),
        }
        transcript_history.append(segment)

# Example handler for participant connect
@room.on("participant_connected")
async def on_participant_connected(participant):
    if not transcript_history:
        return

    # Send as a single JSON payload on a custom topic
    payload = json.dumps(transcript_history)
    # participant.send_text is async in this example — adjust as needed
    await participant.send_text(payload, topic="lk.transcript_history")

    # Alternatively, stream chunks if the history is large:
    # for chunk in chunked(json.dumps(transcript_history), 1024*8):
    #     await participant.send_text(chunk, topic="lk.transcript_history_chunk")

# Frontend should listen for "lk.transcript_history" and parse the JSON,
# then continue to listen for live "lk.transcription" events and merge them.
Would you like a version that chunks large histories, or a matching small frontend handler example?
c
t
Thanks — here's a concise, adapted snippet showing how to add in-memory transcript capture and replay into the multi-user transcriber pattern. It captures final transcript segments and replays them to late joiners on the
lk.transcription
topic so frontends handle them like normal transcription events. Adjust names/imports to match the example file.
Copy code
import asyncio
import json
from typing import List, Dict

# shared in-memory transcript history for the session
transcript_history: List[Dict] = []

# 1) capture final transcription items (conversation_item_added or user_input_transcribed)
@session.on("conversation_item_added")
async def on_conversation_item_added(event):
    item = event.item
    # only store user final segments (skip interim)
    if item.role == "user" and not getattr(item, "interim", False):
        entry = {
            "segment_id": getattr(item, "segment_id", None),
            "participant_identity": getattr(item, "participant_identity", None),
            "text": item.text_content or "",
            "timestamp": getattr(item, "created_at", None),
        }
        transcript_history.append(entry)

# 2) replay history to late joiners
@ctx.room.on("participant_connected")
async def on_participant_connected(participant: rtc.Participant):
    # small delay to let subscriptions stabilize
    await asyncio.sleep(1)
    if not transcript_history:
        return

    # replay as reliable data packets on the lk.transcription topic
    for entry in transcript_history:
        try:
            await ctx.room.local_participant.publish_data(
                entry["text"].encode("utf-8"),
                kind=rtc.DataPacket.Kind.RELIABLE,
                topic="lk.transcription",
                attributes={
                    "lk.transcription_final": "true",
                    "lk.segment_id": entry.get("segment_id") or "",
                    "participant_identity": entry.get("participant_identity") or "",
                },
                destination_sids=[participant.sid],  # send only to the joining participant
            )
        except Exception as e:
            print(f"replay failed: {e}")

# 3) ensure the agent subscribes to all user mics (same as multi-user example)
@ctx.room.on("track_published")
async def on_track_published(pub: rtc.TrackPublication, participant: rtc.Participant):
    if pub.source == rtc.TrackSource.SOURCE_MICROPHONE:
        await pub.track.subscribe()

# Optional: chunking if history is large
async def replay_chunked(participant, text: str, chunk_size=8*1024):
    for i in range(0, len(text), chunk_size):
        chunk = text[i : i + chunk_size].encode("utf-8")
        await ctx.room.local_participant.publish_data(
            chunk,
            kind=rtc.DataPacket.Kind.RELIABLE,
            topic="lk.transcription",
            destination_sids=[participant.sid],
        )
Notes: • Use final-only segments to avoid duplicates. • Replay on
lk.transcription
so SDKs treat these like live transcripts. • Sending to the joining participant only avoids re-broadcasting history to everyone. • In-memory history is ephemeral; consider limits or chunking for long calls. Want a version that replays as a single JSON payload on a custom topic (easier for very large histories) or a matching small frontend handler example? Sources: Text and transcriptions | LiveKit docs
c
is it ok to store history in the root? Wouldn't it the be reused between different dispatches?
t
Good question — do not store session transcript history in a module-level (root/global) variable. Global state can be reused across dispatches and sessions, causing data leakage, cross-session contamination, and race issues. What to do instead: • Scope history to the session or agent instance. ◦ Use
session.userdata
or a session-scoped object to store custom transcript lists. ◦ Or attach the list to the session/agent (e.g.,
session.transcript_history = []
or
self.transcript_history
on the agent instance). • Use
session.history
if you only need the agent’s conversation history (it's isolated per session). • For concurrency safety, avoid shared globals; if you must share across processes, use an external store (Redis/DB) with proper isolation. If you want, I can show a tiny code example of storing/replaying using
session.userdata
or
session.transcript_history
. Which would you prefer? Sources: Agents and handoffs | LiveKit docs | Job lifecycle | LiveKit docs | Agent session | LiveKit docs | Building Multi-Agent Architectures with LiveKit Agents
c
• Show an example frontend handler to merge history + live events. Which would help most in react app
t
Below is a compact React example showing how to fetch transcript history from the agent (via a simple REST/RPC endpoint) and merge it with live
lk.transcription
text-stream events from LiveKit. It handles interim → final updates, deduplicates by
segment_id
, and displays merged results. Adjust endpoints, attribute names, and SDK imports to fit your app.
Copy code
import React, { useEffect, useRef, useState } from "react";
import { useRoom } from "@livekit/components-react";
import type { Room, RemoteParticipant } from "livekit-client";

type TranscriptItem = {
  segmentId: string;
  participant: string;
  text: string;
  isFinal: boolean;
  timestamp?: string;
};

export function useMergedTranscripts(fetchHistoryUrl: string | null) {
  const room = useRoom() as unknown as Room | undefined;
  const [items, setItems] = useState<TranscriptItem[]>([]);
  const indexRef = useRef<Record<string, TranscriptItem>>({});

  // 1) Fetch history once on join (from your agent)
  useEffect(() => {
    if (!fetchHistoryUrl || !room) return;
    let mounted = true;

    (async () => {
      try {
        const res = await fetch(fetchHistoryUrl); // e.g., /api/transcript/:roomName
        if (!res.ok) return;
        const history = await res.json(); // expect array of { segment_id, participant_identity, text, timestamp }
        const mapped: TranscriptItem[] = history.map((h: any) => {
          const seg = {
            segmentId: h.segment_id ?? `history-${Math.random()}`,
            participant: h.participant_identity ?? "unknown",
            text: h.text ?? "",
            isFinal: true,
            timestamp: h.timestamp,
          };
          indexRef.current[seg.segmentId] = seg;
          return seg;
        });
        if (!mounted) return;
        setItems(mapped);
      } catch (e) {
        console.error("fetch transcript history failed", e);
      }
    })();

    return () => {
      mounted = false;
    };
  }, [fetchHistoryUrl, room]);

  // 2) Merge live lk.transcription events
  useEffect(() => {
    if (!room) return;
    const handler = room.registerTextStreamHandler(
      "lk.transcription",
      async (reader, participant: RemoteParticipant | undefined) => {
        // Read the full text payload
        const payload = await reader.readAll();
        const text = typeof payload === "string" ? payload : new TextDecoder().decode(payload);
        const attrs = reader.info?.attributes ?? {};
        const isFinal = attrs["lk.transcription_final"] === "true";
        const segmentId = attrs["lk.segment_id"] || `live-${Date.now()}-${Math.random()}`;
        const participantName = participant?.identity ?? attrs["participant_identity"] ?? "unknown";

        setItems((prev) => {
          const existing = indexRef.current[segmentId];
          if (existing) {
            // Update interim -> final or refresh interim text
            existing.text = text;
            existing.isFinal = isFinal;
            // Keep ordering: replace item in array
            return prev.map((p) => (p.segmentId === segmentId ? { ...existing } : p));
          } else {
            // New segment; append
            const newItem: TranscriptItem = {
              segmentId,
              participant: participantName,
              text,
              isFinal,
              timestamp: new Date().toISOString(),
            };
            indexRef.current[segmentId] = newItem;
            return [...prev, newItem];
          }
        });
      },
      // optional participant filter: pass undefined to accept all
      undefined
    );

    return () => {
      handler.off();
    };
  }, [room]);

  return items;
}
Example usage in a component:
Copy code
export default function TranscriptPanel({ fetchHistoryUrl }: { fetchHistoryUrl: string | null }) {
  const transcripts = useMergedTranscripts(fetchHistoryUrl);

  return (
    <div>
      <h4>Transcript</h4>
      <div>
        {transcripts.map((t) => (
          <div key={t.segmentId} style={{ opacity: t.isFinal ? 1 : 0.7 }}>
            <strong>{t.participant}:</strong> {t.text}
            {!t.isFinal && <em> (listening…)</em>}
          </div>
        ))}
      </div>
    </div>
  );
}
Notes: • The agent should expose history via a small endpoint (REST or RPC) returning an array with
segment_id
,
participant_identity
,
text
, and optional
timestamp
. • Deduplication is by
segment_id
so interim updates and final updates map to the same entry. • For large histories, fetch/paginate or replay in chunks instead of one big payload. Sources: Text and transcriptions | LiveKit docs | Events and error handling | LiveKit docs | Observability data hooks | LiveKit docs | Agent session | LiveKit docs | React quickstart | LiveKit docs