how do I log latency metrics when using a realtime...
# ask-ai
v
how do I log latency metrics when using a realtime model? help with a python code sample if possible
t
Thanks for reaching out, Ruchir. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
Hi there! To help you log latency metrics when using a realtime model in LiveKit, you can listen to the
metrics_collected
event and use the
log_metrics
utility function to output the collected metrics. I’ve put together a Python code sample below to get you started:
Copy code
import logging
from dotenv import find_dotenv, load_dotenv
from livekit.agents import JobContext, JobProcess, VoicePipelineAgent, cli, llm, metrics
from livekit.plugins import deepgram, openai, silero, turn_detector

load_dotenv(find_dotenv())
logger = logging.getLogger("voice-agent")

def prewarm(proc: JobProcess):
    proc.userdata["vad"] = silero.VAD.load()

async def entrypoint(ctx: JobContext):
    initial_ctx = llm.ChatContext().append(
        role="system",
        text=(
            "You are a voice assistant. Use short and concise responses. "
            "You were created as a demo for LiveKit's agents framework."
        ),
    )

    await ctx.connect(auto_subscribe=AutoSubscribe.AUDIO_ONLY)
    participant = await ctx.wait_for_participant()

    agent = VoicePipelineAgent(
        vad=ctx.proc.userdata["vad"],
        stt=deepgram.STT(),  # or another STT provider
        llm=openai.LLM(model="gpt-4o-mini"),
        tts=deepgram.TTS(),  # or another TTS provider
        turn_detector=turn_detector.EOUModel(),
        chat_ctx=initial_ctx,
    )

    usage_collector = metrics.UsageCollector()

    # Listen to metrics and log them
    @agent.on("metrics_collected")
    def on_metrics_collected(agent_metrics: metrics.AgentMetrics):
        metrics.log_metrics(agent_metrics)  # This logs TTFT, duration, tokens, etc.
        usage_collector.collect(agent_metrics)

    agent.start(ctx.room, participant)
    await agent.say("Hey, how can I help you today?", allow_interruptions=True)

if __name__ == "__main__":
    cli.run_app(
        WorkerOptions(
            entrypoint_fnc=entrypoint,
            prewarm_fnc=prewarm,
        ),
    )
This code will help you capture important latency metrics like: • ttft (Time To First Token) – the latency until the very first token is generated • duration – the total time taken for generation • tokens_per_second – how fast the output is generated • input_tokens, output_tokens, total_tokens – details on token usage If you have any questions or need a hand with anything else, please don’t hesitate to ask. I’m here to help! Sources: agent-examples/agent_examples/pipeline_agent.py | livekit-plugins/livekit-plugins-openai/livekit/plugins/openai/realtime/real...
v
what if I'm using a realtime speech 2 speech model like gpt-realtime?
t
When working with a real-time speech-to-speech model like GPT-Realtime, you can easily keep track of latency metrics by using the
RealtimeModelMetrics
system. This handy tool captures important performance details such as time-to-first-token (TTFT), token throughput, and audio processing info. Here’s a simple example to help you get started:
Copy code
from livekit.agents import metrics, MetricsCollectedEvent

@session.on("metrics_collected")
def _on_metrics_collected(ev: MetricsCollectedEvent):
    metrics.log_metrics(ev.metrics)  # Logs TTFT, duration, tokens, etc.
If you want to dive a bit deeper and have more detailed logging, you can create a custom handler like this:
Copy code
from livekit.agents.metrics import RealtimeModelMetrics
from rich.console import Console
from rich.table import Table
from datetime import datetime

console = Console()

async def on_realtime_metrics_collected(metrics: RealtimeModelMetrics):
    table = Table(title="[bold blue]RealtimeModel Metrics Report[/bold blue]", show_header=True, header_style="bold cyan")
    table.add_column("Metric", style="bold green")
    table.add_column("Value", style="yellow")

    timestamp = datetime.fromtimestamp(metrics.timestamp).strftime('%Y-%m-%d %H:%M:%S')
    table.add_row("TTFT", f"{metrics.ttft:.4f}s")
    table.add_row("Duration", f"{metrics.duration:.4f}s")
    table.add_row("Tokens/Second", f"{metrics.tokens_per_second:.2f}")
    table.add_row("Input Tokens", str(metrics.input_tokens))
    table.add_row("Output Tokens", str(metrics.output_tokens))
    table.add_row("Total Tokens", str(metrics.total_tokens))
    table.add_row("Timestamp", timestamp)

    console.print(table)

# Attach the handler
if isinstance(llm, RealtimeModel):
    llm.on("metrics_collected", on_realtime_metrics_collected)
Also, if you’d like to gather metrics over the whole session, the
UsageCollector
is a great tool to use for that:
Copy code
usage_collector = metrics.UsageCollector()

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

async def log_usage():
    summary = usage_collector.get_summary()
    logger.info(f"Session Usage Summary: {summary}")

ctx.add_shutdown_callback(log_usage)
Please feel free to reach out if you’d like me to walk you through any part of this or if you have any questions about the implementation — I’m here to help! Sources: metrics/metrics_stt.py | Agent Testing & CI/CD | livekit/livekit_composite | DeepWiki | livekit-agents/livekit/agents/telemetry/trace_types.py | Real-time AI Models & Streaming | livekit/livekit_composite | DeepWiki | Logs, metrics, and telemetry | LiveKit Docs
v
getting error:
ModuleNotFoundError: No module named 'rich'
t
It looks like you're seeing the error
ModuleNotFoundError: No module named 'rich'
because the
rich
library isn’t installed in your Python environment yet. Don’t worry, it’s an easy fix! You can install it by running this command:
Copy code
pip install rich
After that, go ahead and try running your code again. If you run into any other bumps along the way, just let me know—I’m here to help!
v
error -
NameError: name 'llm' is not defined
t
It looks like you're encountering the error
NameError: name 'llm' is not defined
, which usually means that the variable
llm
hasn't been set up in your code yet. To help you get past this, make sure you've properly created the
llm
object before trying to use it. Here's a little example to guide you:
Copy code
from livekit.agents import llm

# Example initialization of the LLM
llm = llm.RealtimeModel(model="gpt-realtime")
Just swap out
gpt-realtime
with the model you're working with. Also, double-check that this initialization happens before you add any event handlers or work with the
llm
object elsewhere in your code. If anything’s unclear or you’d like me to walk you through it step-by-step, please don’t hesitate to ask—I’m here to help!
v
error -
AttributeError: module 'livekit.agents.llm' has no attribute 'on'
t
I don't have the answer you're looking for. You could also try asking your question: • in one of the other Slack channels or • to https://deepwiki.com/livekit/livekit_composite which is trained on all LiveKit source code If you find the answer, please post it here to help others!
v
bad!
not helpful!