b
hi
t
Thanks for reaching out, Yashpratap. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
Hi — how can I help today? Tell me what you're trying to do or any issue you're seeing (error messages, SDK/language, project/room IDs if relevant) and I’ll help you next.
b
how to add latency logging for STT,TTS and LLM
t
You're asking how to add latency logging for STT, TTS, and LLM. You can capture those latencies by subscribing to the AgentSession
metrics_collected
event and logging the metrics provided there. 1) Subscribe to metrics • Python
Copy code
from livekit.agents import metrics, MetricsCollectedEvent

@session.on("metrics_collected")
def _on_metrics_collected(ev: MetricsCollectedEvent):
    metrics.log_metrics(ev.metrics)  # logs all metrics
• Node.js / TypeScript
Copy code
import { voice, metrics } from '@livekit/agents';

session.on(voice.AgentSessionEventTypes.MetricsCollected, (ev) => {
  metrics.logMetrics(ev.metrics);
});
2) Which latency fields to log • STT:
ttfb
(time to first byte, seconds),
duration
(total processing time). • LLM:
ttft
(time to first token, seconds),
duration
(total inference time). • TTS:
ttfb
(time to first byte, seconds),
duration
(total synthesis time). 3) Aggregation / summaries • Use
UsageCollector
to accumulate metrics across a session and produce summaries for post-session analysis or dashboards. Example (Python)
Copy code
usage_collector = metrics.UsageCollector()

@session.on("metrics_collected")
def _on_metrics_collected(ev: MetricsCollectedEvent):
    usage_collector.collect(ev.metrics)

# later
summary = usage_collector.get_summary()
logger.info(f"Usage: {summary}")
These metrics are also included in LiveKit Cloud trace spans and visible in the dashboard for visualization. Would you like a sample that forwards these latencies to Prometheus, Datadog, or a log file format? Sources: Observability data hooks | LiveKit docs
b
does this also work if I host the livekit instead of using livekit cloud?
t
Yes — the same latency metrics (STT, LLM, TTS) are emitted by the Agents SDK when you self-host LiveKit. You can subscribe to the
metrics_collected
event and log the fields (e.g., STT `ttfb`/`duration`, LLM `ttft`/`duration`, TTS `ttfb`/`duration`) exactly the same way as in Cloud. Key differences when self-hosting: • No built-in dashboard or managed log storage — you must export/store metrics yourself. • Set up your own pipeline to forward/log metrics (file, Prometheus, Datadog, ELK, etc.). • Use
UsageCollector
to aggregate session summaries for reporting. If you want, tell me which backend/monitoring stack you use (Prometheus, Datadog, plain logs, etc.) and I’ll give a short example for forwarding these metrics there. Sources: Observability data hooks | LiveKit docs | Say hello to improved Cloud analytics | Log collection | LiveKit Docs
b
how to add a fallback message to say to the user when the processing of any node(STT,TTS,LLM) fails in the python based livekit agent?
t
You're asking how to send a fallback message to the user when any node (STT, LLM, TTS) fails in a Python LiveKit agent. Use the session's
error
event to detect failures and
session.say()
to speak a fallback. Example:
Copy code
from livekit.agents import AgentSession

# assume session is your AgentSession instance

@session.on("error")
def on_error(ev):
    # ev.source identifies which node failed (e.g., "stt", "llm", "tts")
    # ev.error.recoverable is a boolean you can check
    print(f"Error from {ev.source}: {ev.error}")

    # send user-facing fallback when not recoverable (or always, if you prefer)
    if not ev.error.recoverable:
        session.say("I'm sorry — I'm having technical difficulties and can't respond right now.")
If you want more resilience before sending a fallback: • Wrap providers with
FallbackAdapter
to try alternatives automatically. • Send a brief interim message for recoverable/transient errors (e.g., "One moment, trying again...") and only send the final fallback when errors persist or are non-recoverable. Would you like a sample that includes
FallbackAdapter
configuration or an example that logs and forwards these error events to your monitoring system? Sources: Events and error handling | LiveKit docs
b
example of error events
t
Below is a concrete Python example that shows typical
ErrorEvent
fields and how to handle them in an AgentSession. It demonstrates inspecting the event, logging useful fields, sending a fallback message, and optionally retrying for recoverable errors.
Copy code
from livekit.agents import AgentSession
from typing import Any

# assume `session` is your AgentSession instance already created

@session.on("error")
def on_error(ev: Any):
    """
    ev is an ErrorEvent with fields such as:
      - ev.source           : str  (e.g., "stt", "llm", "tts")
      - ev.error            : object (error details)
          - ev.error.message     : str
          - ev.error.code        : optional str/int
          - ev.error.recoverable : bool
      - ev.model_config     : dict or config object for the failed model
      - ev.timestamp        : optional datetime or iso string
      - ev.raw              : optional raw provider error/details
    """

    # Basic logging
    src = getattr(ev, "source", "unknown")
    err = getattr(ev, "error", None)
    msg = getattr(err, "message", str(err)) if err else "no message"
    code = getattr(err, "code", None)
    recoverable = getattr(err, "recoverable", False)

    print(f"[ErrorEvent] source={src} recoverable={recoverable} code={code} message={msg}")
    # Optional: inspect model_config and raw provider error
    print("model_config:", getattr(ev, "model_config", None))
    print("raw:", getattr(ev, "raw", None))

    # Behavior examples:
    if recoverable:
        # Inform user briefly and attempt retry logic if appropriate
        session.say("One moment — I'm trying that again.")
        # Example retry: you might re-run the last node or call a wrapper retry function
        # retry_last_node()  # implement according to your agent flow
    else:
        # Non-recoverable: send final fallback message
        session.say("I'm sorry — I'm having technical difficulties and can't respond right now.")
        # Optionally end the session or mark it as failed/notify monitoring
        # session.end()  # if you want to terminate
Notes: •
ev.source
tells which node failed. •
ev.error.recoverable
is the key boolean for deciding retry vs. final fallback. •
ev.model_config
and
ev.raw
can hold provider-specific details useful for debugging and logging. • Use
FallbackAdapter
for automatic provider failover before relying on manual retry/fallback. Would you like a version that logs these events to a monitoring system (Datadog/Prometheus) or an example that retries a specific node automatically?
b
i want to monitor latency in livekit for llm, stt, and tts and I want to use the Langfuse for this purpose.
t
You're looking to send LiveKit latency metrics (LLM `ttft`/`duration`, STT `ttfb`/`duration`, TTS `ttfb`/`duration`) to Langfuse. I can help—quick question first: Which runtime are you using for your agent code so I can give an exact example? • Python (preferred) or • Node.js/TypeScript Also tell me: • Are you self-hosting LiveKit or using LiveKit Cloud? • Do you already have a Langfuse project/api key available? Once you confirm, I’ll provide a concise example showing: 1. Subscribing to
metrics_collected
in your agent. 2. Mapping LiveKit metric fields to Langfuse event/trace fields. 3. Sending those events to Langfuse (code sample + retries/ batching note).
b
Python, currently using Livekit cloud I have a Langfuse project/apikey available.
t
You're using Python on LiveKit Cloud and want to send LLM/STT/TTS latency metrics to Langfuse. Below is a concise, runnable example showing: • setting up Langfuse (OTLP) exporter with OpenTelemetry, • wiring LiveKit Agents' tracer provider, • subscribing to
metrics_collected
to log/annotate spans (optional), • environment variables required. 1) Install deps:
Copy code
pip install livekit-agents opentelemetry-sdk opentelemetry-exporter-otlp-proto-http langfuse
2) Example code:
Copy code
import os
import base64
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
from livekit.agents.telemetry import set_tracer_provider
from livekit.agents import AgentSession, metrics, MetricsCollectedEvent

# Configure Langfuse OTLP exporter and set as tracer provider for LiveKit agents
def setup_langfuse():
    public_key = os.environ["LANGFUSE_PUBLIC_KEY"]
    secret_key = os.environ["LANGFUSE_SECRET_KEY"]
    host = os.environ.get("LANGFUSE_HOST", "https://cloud.langfuse.com").rstrip("/")
    # Basic auth header required by Langfuse OTLP endpoint
    auth = f"{public_key}:{secret_key}".encode()
    basic = base64.b64encode(auth).decode()
    headers = {"Authorization": f"Basic {basic}"}

    provider = TracerProvider()
    exporter = OTLPSpanExporter(
        endpoint=f"{host}/api/public/otlp/v1/traces",
        headers=headers
    )
    provider.add_span_processor(BatchSpanProcessor(exporter))
    set_tracer_provider(provider)

# Example session setup (replace with your actual STT/LLM/TTS configs)
def create_session():
    # create AgentSession with your providers (omitted for brevity)
    session = AgentSession()
    return session

# Optional: on metrics_collected, add attributes or log before spans export
def attach_metrics_handler(session: AgentSession):
    @session.on("metrics_collected")
    def on_metrics(ev: MetricsCollectedEvent):
        m = ev.metrics
        # Inspect STT/LLM/TTS metrics and log or attach to monitoring
        if getattr(m, "stt", None):
            print("STT ttfb:", m.stt.ttfb, "duration:", getattr(m.stt, "duration", None))
        if getattr(m, "llm", None):
            print("LLM ttft:", m.llm.ttft, "duration:", getattr(m.llm, "duration", None))
        if getattr(m, "tts", None):
            print("TTS ttfb:", m.tts.ttfb, "duration:", getattr(m.tts, "duration", None))
        # LiveKit Agents already generates spans that include these metrics;
        # this handler is useful for custom annotations, batching, or additional logs.

async def run_agent(ctx):
    setup_langfuse()
    session = create_session()
    attach_metrics_handler(session)

    # connect/start logic for AgentSession and JobContext
    await ctx.connect()
    await session.start(ctx.room)
3) Required env vars • LANGFUSE_PUBLIC_KEY • LANGFUSE_SECRET_KEY • LANGFUSE_HOST (optional — defaults to https://cloud.langfuse.com) Notes: • LiveKit Agents already emits OpenTelemetry spans that include LLM `ttft`/`duration`, STT `ttfb`/`duration`, and TTS `ttfb`/`duration`. The code above wires the tracer to Langfuse OTLP so spans and metrics appear in Langfuse. • Use the
metrics_collected
handler if you want to add extra attributes to spans, batch metrics, or forward specific metric events beyond the automatic spans. • For production, configure robust retry/backoff for OTLP export and secure secret management. Would you like a fuller example showing how to attach metrics as custom span attributes or how to batch/send them directly to the Langfuse Events API? Sources: Observability data hooks | LiveKit docs
b
yes
t
Below is a focused Python example that shows: • wiring LiveKit Agents' OpenTelemetry tracer to Langfuse (OTLP), • subscribing to
metrics_collected
, • attaching STT/LLM/TTS latency metrics as custom span attributes, • optionally sending metric events directly to Langfuse Events API (example included). 1) Install:
Copy code
pip install livekit-agents opentelemetry-sdk opentelemetry-exporter-otlp-proto-http requests
2) Example code:
Copy code
import os
import base64
import time
import json
import requests
from contextlib import contextmanager
from opentelemetry import trace
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
from livekit.agents.telemetry import set_tracer_provider
from livekit.agents import AgentSession, metrics, MetricsCollectedEvent

# --- Langfuse OTLP setup ---
def setup_langfuse_otlp():
    public_key = os.environ["LANGFUSE_PUBLIC_KEY"]
    secret_key = os.environ["LANGFUSE_SECRET_KEY"]
    host = os.environ.get("LANGFUSE_HOST", "https://cloud.langfuse.com").rstrip("/")
    auth = f"{public_key}:{secret_key}".encode()
    basic = base64.b64encode(auth).decode()
    headers = {"Authorization": f"Basic {basic}"}

    provider = TracerProvider()
    exporter = OTLPSpanExporter(
        endpoint=f"{host}/api/public/otlp/v1/traces",
        headers=headers
    )
    provider.add_span_processor(BatchSpanProcessor(exporter))
    set_tracer_provider(provider)

# --- Optional: direct Langfuse Events API sender ---
def send_langfuse_event(event_name: str, attributes: dict):
    host = os.environ.get("LANGFUSE_HOST", "https://cloud.langfuse.com").rstrip("/")
    public_key = os.environ["LANGFUSE_PUBLIC_KEY"]
    secret_key = os.environ["LANGFUSE_SECRET_KEY"]
    api_key = f"{public_key}:{secret_key}"
    basic = base64.b64encode(api_key.encode()).decode()
    headers = {
        "Authorization": f"Basic {basic}",
        "Content-Type": "application/json",
    }
    # Adjust path if your Langfuse project requires /projects/{project_id}/events
    payload = {
        "name": event_name,
        "timestamp": int(time.time() * 1000),
        "payload": attributes,
    }
    url = f"{host}/api/public/events"  # verify with your Langfuse host if different
    try:
        resp = requests.post(url, headers=headers, json=payload, timeout=5)
        resp.raise_for_status()
    except Exception as e:
        print("Failed to send Langfuse event:", e)

# --- Helper to add attributes to the current active span ---
def add_attrs_to_active_span(attrs: dict):
    span = trace.get_current_span()
    if span and span.is_recording():
        for k, v in attrs.items():
            span.set_attribute(k, v)

# --- Metrics handler ---
def attach_metrics_handler(session: AgentSession, send_direct_events: bool = False):
    @session.on("metrics_collected")
    def on_metrics(ev: MetricsCollectedEvent):
        m = ev.metrics
        attrs = {}
        # STT
        stt = getattr(m, "stt", None)
        if stt:
            attrs.update({
                "livekit.stt.ttfb": getattr(stt, "ttfb", None),
                "livekit.stt.duration": getattr(stt, "duration", None),
                "livekit.stt.audio_duration": getattr(stt, "audio_duration", None),
            })
        # LLM
        llm = getattr(m, "llm", None)
        if llm:
            attrs.update({
                "livekit.llm.ttft": getattr(llm, "ttft", None),
                "livekit.llm.duration": getattr(llm, "duration", None),
                "livekit.llm.input_tokens": getattr(llm, "input_tokens", None),
                "livekit.llm.output_tokens": getattr(llm, "output_tokens", None),
            })
        # TTS
        tts_m = getattr(m, "tts", None)
        if tts_m:
            attrs.update({
                "livekit.tts.ttfb": getattr(tts_m, "ttfb", None),
                "livekit.tts.duration": getattr(tts_m, "duration", None),
                "livekit.tts.characters": getattr(tts_m, "characters_count", None),
            })

        # Attach attributes to the active span so they appear in Langfuse traces
        add_attrs_to_active_span(attrs)

        # Optionally send a direct event to Langfuse for metrics dashboards or custom processing
        if send_direct_events:
            send_langfuse_event("livekit_metrics_collected", attrs)

# --- Example usage in agent entrypoint ---
async def entrypoint(ctx):
    # 1) setup tracer -> Langfuse
    setup_langfuse_otlp()

    # 2) create your AgentSession with desired providers (omitted here)
    session = AgentSession()  # configure STT/LLM/TTS as needed

    # 3) attach handler; pass send_direct_events=True to also POST events to Langfuse Events API
    attach_metrics_handler(session, send_direct_events=True)

    # 4) connect and start session as normal
    await ctx.connect()
    await session.start(ctx.room)
3) Notes and recommendations • LiveKit Agents auto-generates OTLP spans for operations; adding attributes in
metrics_collected
ensures latency fields appear in the Langfuse trace details. • Use meaningful attribute keys (e.g.,
livekit.llm.ttft
) so you can filter/search in Langfuse. • For high-throughput environments, prefer OTLP spans (above) and avoid sending one HTTP event per metric unless batched. • Secure secrets with your environment/secret manager; don’t hardcode. • Add retry/backoff for the OTLP exporter and for the direct Events API calls in production. If you want, I can: • show a version that batches events before posting to Langfuse Events API, • show exactly how to add these attributes to a named span (e.g., the LLM request span) instead of the active span, • or produce a complete runnable example including STT/LLM/TTS provider configs. Which would you like?
b
can we pass the language parameter to the session.say() method
t
You cannot pass a
language
parameter to
session.say()
directly. The spoken language is determined by the TTS model configuration on the AgentSession. Set the language when you configure the TTS provider and then call
session.say()
as usual. Example:
Copy code
from livekit.agents import AgentSession, inference

session = AgentSession(
    tts=inference.TTS(
        model="cartesia/sonic-3",
        voice="your-voice-id",
        language="fr"  # set language here
    ),
    # stt, llm, etc.
)

await session.say("Bonjour !")  # spoken using the TTS language configured above
If you need to switch languages at runtime, you can: • Create multiple TTS provider configs (one per language) and switch the session's TTS instance before calling
say()
, or • Reconfigure/recreate the AgentSession with a different TTS
language
setting for that interaction. Want a short example showing how to switch the TTS provider at runtime? Sources: Agent speech and audio | LiveKit docs | Rime TTS | LiveKit docs | Cartesia TTS | LiveKit docs
b
I'm configuring the target_language in the TTS as "hi-IN" but I'm passing the argument in english langugage to the session.say() method. For example - session.say("Hello, how are you") How would it work then?
t
If your TTS is configured with
language="hi-IN"
but you call
session.say("Hello, how are you")
, the TTS will synthesize that English text using the Hindi voice/language settings. That means: • The TTS model will attempt to pronounce the English words using Hindi phonetics/voice; output may sound accented, garbled, or unintelligible. •
session.say()
does not auto-translate the text or change the language on a per-call basis. Options to get correct Hindi output: • Translate the text to Hindi before calling
session.say()
(use your LLM or a translation service), then synthesize the Hindi text with the
hi-IN
TTS. • Use a multilingual TTS model that supports both English and Hindi and set its
language
parameter to match the text, or swap the TTS provider/config at runtime to an English-configured TTS before calling
say()
. • Maintain two TTS configs (English/Hindi) and choose the appropriate one per utterance. If you want, I can provide a short example that: • auto-detects language and switches TTS providers, or • translates via the LLM before calling
session.say()
— which would fit your current AgentSession setup. Which would you prefer?
b
i'm using sarvam TTs which is bilingual, how will it work?
t
If you configure Sarvam TTS with
target_language_code="hi-IN"
but pass English text like
session.say("Hello, how are you")
, Sarvam will synthesize audio in the Hindi output mode (Hindi phonetics/prosody) using the chosen speaker. That means: • The TTS will attempt to render the English words using the Hindi-targeted synthesis, so pronunciation may be accented, odd, or unintelligible. • Sarvam does not auto-translate input text. The output language is controlled by
target_language_code
. • Sarvam handles mixed or Hinglish input better than strict mismatches, but it still follows the Hindi output setting. Recommendations: • Translate English text to Hindi before calling
session.say()
if you want natural Hindi speech. • For dynamic bilingual behavior, detect the input language and set
target_language_code
accordingly (or switch TTS configs at runtime). • If you need mixed-language pronunciation, test representative phrases—Sarvam may preserve common English terms reasonably within Hindi output. If you want, I can provide: • a short example that auto-detects language and switches the Sarvam TTS
target_language_code
before
session.say()
, or • a small snippet showing how to translate via your LLM and then call
session.say()
with Hindi text. Which would you prefer? Sources: Sarvam TTS plugin guide | LiveKit Docs
b
Yes, please provide the example for both
t
Below are two concise Python examples for Sarvam TTS with LiveKit Agents: 1) Auto-detect language and switch Sarvam
target_language_code
before calling
session.say()
2) Translate text via LLM, then call
session.say()
with the translated Hindi text Both assume you have an existing
AgentSession
and are using the Sarvam plugin. Adjust imports/configs to match your project. Example 1 — detect language and switch TTS provider at runtime
Copy code
from langdetect import detect  # pip install langdetect
from livekit.agents import AgentSession
from livekit.plugins import sarvam

# create two Sarvam TTS configs (one for Hindi, one for English)
tts_hi = sarvam.TTS(target_language_code="hi-IN", speaker="anushka")
tts_en = sarvam.TTS(target_language_code="en-IN", speaker="anushka")

# assume session is created without a fixed TTS, or you can replace session.tts later
session = AgentSession()  # other config as required

def set_session_tts(session: AgentSession, tts):
    # Replace session's tts provider; exact attribute may vary—this demonstrates intent.
    session.tts = tts

async def say_with_auto_lang(session: AgentSession, text: str):
    try:
        lang = detect(text)  # returns 'hi' or 'en' etc.
    except Exception:
        lang = "en"

    if lang.startswith("hi"):
        set_session_tts(session, tts_hi)
    else:
        set_session_tts(session, tts_en)

    await session.say(text)
Notes: •
langdetect
is a simple detector; replace with your preferred detector if desired. • Switching
session.tts
like this works if your AgentSession allows replacing the TTS instance at runtime. If your session is immutable, recreate the session or use a TTS router/wrapper to delegate to the chosen Sarvam instance. • For brief latency-sensitive flows, switching provider instances is fast but recreate/re-init overhead may vary—test in your environment. Example 2 — translate via LLM, then synthesize in Hindi
Copy code
from livekit.agents import AgentSession
from livekit.plugins import sarvam
# Example LLM usage — replace with your LLM provider code
from your_llm_client import translate_text_to_hindi  # implement with your LLM

tts_hi = sarvam.TTS(target_language_code="hi-IN", speaker="anushka")
session = AgentSession(tts=tts_hi)  # session TTS fixed to Hindi

async def say_translated_to_hindi(session: AgentSession, text: str):
    # 1) Use your LLM to translate to Hindi
    hindi_text = await translate_text_to_hindi(text)  # should return Hindi string

    # 2) Synthesize Hindi text with Sarvam configured for hi-IN
    await session.say(hindi_text)
Simple LLM translation example (pseudo-implementation)
Copy code
# Example using an async LLM call pattern — adapt to your LLM SDK
async def translate_text_to_hindi(text: str) -> str:
    prompt = f"Translate the following to Hindi (Devanagari):\n\n{text}"
    # call your LLM here and return the translated string
    resp = await llm_client.complete(prompt)  # replace with real call
    return resp.text.strip()
Recommendations • If your app must handle mixed-language (Hinglish) input, prefer translating full sentences via LLM before TTS for best naturalness. • For short phrases or common names/terms, Sarvam may handle mixed text reasonably when
target_language_code
is
hi-IN
. • Test latency and switching overhead; if switching session TTS is costly, use a lightweight routing layer that keeps both providers instantiated and selects the right one per utterance. • Use SSML if you need finer pronunciation control (check Sarvam SSML support). Would you like a runnable example that: • demonstrates switching without recreating the session (using a TTS wrapper), or • shows a concrete LLM translation call using a specific provider (OpenAI/Azure/etc.)?
b
I'm using the Sarvam TTS and STT plugin in my python livekit agent. I want to maintain the conversational history for each session. I want to use the real time transcript for one of my tool call as well.
t
I can help—below is a focused plan plus concise Python examples showing: • how to keep per-session conversational history, • how to consume real-time Sarvam STT transcripts, • how to invoke a tool immediately on transcript (and also how to attach transcript to history), • optional persistence to a DB at session end. Please confirm if you want in-memory only or persistent storage (Postgres/Redis/Firestore/etc.), and whether your tool should be called on every interim transcript or only on final transcripts. Examples assume an existing AgentSession named
session
and JobContext
ctx
. 1) Maintain session history (in-memory + access)
Copy code
# Access built-in session history
# session.history contains messages, agent responses, and tool calls
# Example: read entire history as dict
hist_dict = session.history.to_dict()
2) Subscribe to real-time transcript event and call a tool
Copy code
# Example handler: trigger tool only on final transcripts
def is_final_transcript(ev) -> bool:
    # depends on STT provider; check ev.is_final or ev.partial flag if provided
    return getattr(ev, "is_final", True)

@session.on("user_input_transcribed")
def on_user_input_transcribed(ev):
    # ev may contain fields: text, is_final, timestamp, speaker, raw
    text = getattr(ev, "text", None)
    if not text:
        return

    # attach transcript to session history as user input (optional)
    session.history.append_user_message(text)

    # call tool on final transcripts only (or remove the guard to call on interim)
    if is_final_transcript(ev):
        # fire-and-forget background task if you don't want to block
        ctx.create_task(call_my_tool_and_record(text))

async def call_my_tool_and_record(text: str):
    # Call your external tool (HTTP, RPC, etc.)
    result = await my_tool_api_call(text)  # implement this
    # record the tool call / response in session history
    session.history.append_tool_call(name="my_tool", input=text, output=result)
    # Optionally send tool result back to user via session.say()
    await session.say(result)
3) Using tool via LLM function-tool (LLM decides when to call)
Copy code
from livekit.agents import function_tool

@function_tool()
async def my_tool(text: str) -> str:
    # synchronous/async call to your external service
    return await my_tool_api_call(text)

# Register tool with your Agent/Session so LLM can call it in the flow
# When LLM invokes tool, the framework will record the call in session.history
4) Persisting history at session end
Copy code
# Save history when session ends or job shuts down
async def save_history_to_db():
    data = session.history.to_dict()
    await db.save_session_history(session.id, data)  # implement persistence

ctx.add_shutdown_callback(save_history_to_db)
# Or listen to session end event if available
@session.on("end")
async def on_end(ev):
    await save_history_to_db()
5) Notes & best practices • Sarvam streams interim and final transcripts; prefer calling tools on final transcripts to avoid duplicate/tool flooding unless your tool is designed for streaming. • Use
session.history
methods to append user messages, agent messages, and tool calls so history stays consistent with the AgentSession model. • Use background tasks (
ctx.create_task
) for network calls to avoid blocking the agent main loop. • For persistence, store both raw transcripts and normalized entries (speaker, final/interim flag, timestamps). • If you need traceability/observability, attach metrics via
metrics_collected
and error events to capture latency and failures for tool calls. If you confirm persistence choice (in-memory vs Postgres/Redis) and whether to trigger the tool on interim transcripts or final only, I’ll provide a complete runnable snippet wired to your storage and an example
my_tool_api_call
implementation. Sources: Agents and handoffs | LiveKit docs | Agent session | LiveKit docs | Sarvam STT plugin guide | LiveKit Docs | Agents v0.x migration guide - Node.js | LiveKit Docs | Sarvam TTS plugin guide | LiveKit Docs
b
how to access the sarvam interim and final transcript. And explain the session.history method and it's usage by example
t
I'll show exactly how to access Sarvam interim and final transcripts in a Python LiveKit agent and how to use
session.history
with short, runnable examples. 1) Configure Sarvam STT in your AgentSession
Copy code
from livekit.agents import AgentSession
from livekit.plugins import sarvam

session = AgentSession(
    stt=sarvam.STT(
        language="hi-IN",       # or "en-IN"
        model="saarika:v2.5"
    ),
    # tts, llm, etc.
)
2) Listen for interim and final transcripts
Copy code
# handler receives an event with fields like: transcript/text, is_final, language, timestamp
@session.on("user_input_transcribed")
def on_user_input_transcribed(event):
    text = getattr(event, "transcript", None) or getattr(event, "text", None)
    is_final = getattr(event, "is_final", False)
    lang = getattr(event, "language", None)

    if is_final:
        print(f"[Final][{lang}] {text}")
        # handle final transcript (tool call, save, append to history, etc.)
    else:
        print(f"[Interim][{lang}] {text}")
        # use interim for UI updates or streaming tools (avoid heavy calls)
Notes: • Sarvam emits interim (partial) updates while the user speaks and a final transcript when the utterance completes. Use
event.is_final
to distinguish. • Some STT providers expose
event.is_final
or
event.partial
— check which field is present and adapt accordingly. 3) How
session.history
works (access, append, persist) • session.history is the AgentSession's canonical conversation record. It automatically receives user transcripts and assistant responses when using built-in flows, but you can read, iterate, and add entries. Quick examples: a) Read full history as a dict
Copy code
hist = session.history.to_dict()
# hist contains items with fields like role, text_content, timestamp, id, interrupted
print(hist)
b) Iterate programmatically
Copy code
for item in session.history.items:        # .items is a list of history entries
    print(item.role, item.text_content)
c) Manually append user/assistant/tool entries (if needed)
Copy code
# append a user message if you captured transcript externally
session.history.append_user_message("Hello, how are you?")

# append an assistant message
session.history.append_assistant_message("I'm good, thank you.")

# record a tool call and result
session.history.append_tool_call(name="my_tool", input="query", output="result")
d) Persist history at session end
Copy code
import json
from datetime import datetime

async def save_history():
    data = session.history.to_dict()
    fname = f"session_{datetime.utcnow().strftime('%Y%m%d_%H%M%S')}.json"
    with open(fname, "w", encoding="utf-8") as f:
        json.dump(data, f, ensure_ascii=False, indent=2)

@session.on("close")
async def on_close(ev):
    await save_history()
4) Example: use final transcript to call a tool and record result
Copy code
@session.on("user_input_transcribed")
def on_user_input_transcribed(event):
    if not getattr(event, "is_final", False):
        return

    text = event.transcript
    # session.history will already include the user turn, but optionally append:
    # session.history.append_user_message(text)

    # call tool asynchronously (ctx.create_task recommended in JobContext)
    ctx.create_task(handle_tool_call(text))

async def handle_tool_call(text: str):
    result = await my_tool_api_call(text)          # implement this
    # record the tool interaction in history
    session.history.append_tool_call(name="my_tool", input=text, output=result)
    # optionally speak or send the result to the user
    await session.say(result)
5) Best practices • Trigger external tools on final transcripts to avoid duplicate or noisy calls from interim results. • Use interim transcripts only for UI feedback or light streaming processing. • Prefer the built-in session.history for consistent audit and to let the agent framework correlate tool calls, messages, and timestamps. • Persist history at session end or periodically for long sessions. • Use background tasks (e.g., ctx.create_task) for network calls so you don’t block event handlers. If you want, I can: • provide a full runnable example wired to your Sarvam STT/TTS config, • show how to store history in Postgres/Redis, or • show a sample that triggers a tool on interim frames with debouncing. Which would you like? Sources: Sarvam STT plugin guide | LiveKit Docs | Events and error handling | LiveKit docs | Observability data hooks | LiveKit docs