victorious-midnight-79553
11/17/2025, 12:47 PMtall-airline-16756
11/17/2025, 12:47 PMtall-airline-16756
11/17/2025, 12:48 PMmetrics_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:
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...victorious-midnight-79553
11/17/2025, 12:49 PMtall-airline-16756
11/17/2025, 12:51 PMRealtimeModelMetrics 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:
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:
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:
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 Docsvictorious-midnight-79553
11/17/2025, 1:35 PMModuleNotFoundError: No module named 'rich'tall-airline-16756
11/17/2025, 1:35 PMModuleNotFoundError: 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:
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!victorious-midnight-79553
11/17/2025, 1:39 PMNameError: name 'llm' is not definedtall-airline-16756
11/17/2025, 1:40 PMNameError: 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:
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!victorious-midnight-79553
11/17/2025, 1:45 PMAttributeError: module 'livekit.agents.llm' has no attribute 'on'tall-airline-16756
11/17/2025, 1:46 PMvictorious-midnight-79553
11/17/2025, 1:49 PMvictorious-midnight-79553
11/17/2025, 1:53 PM