stocky-tailor-95498
08/14/2025, 7:35 AMtall-airline-16756
08/14/2025, 7:35 AMtall-airline-16756
08/14/2025, 7:36 AMUsageCollector
for aggregated metrics or create custom metrics for specific data points. Here’s a friendly guide on how to get that set up:
• Start by initializing the UsageCollector
to gather your metrics:
• Then, collect metrics as your session runs:
• When it’s time to wrap up, log a summary at shutdown:
• If you want to track something more specific, define a custom metric and emit it like this:
• And don’t forget to handle those custom metrics in an event listener:
This way, you can easily keep track of and log your metrics during the session. If you want to dive deeper or have any questions, just let me know—I’m here to help!stocky-tailor-95498
08/14/2025, 7:37 AMtall-airline-16756
08/14/2025, 7:37 AMlog_usage
function inside the entrypoint
and register it as a shutdown callback like this:
• Make sure to include the @session.on
event handlers within the entrypoint
so they’re properly connected to the session:
This way, your metrics get collected and logged smoothly throughout the session. If anything’s unclear or you want to dive deeper, just let me know—I’m here to help!stocky-tailor-95498
08/14/2025, 7:44 AMtall-airline-16756
08/14/2025, 7:45 AMinitializeProcessTimeout
value in your WorkerOptions
. Here’s a quick example:
• Implementing error handling: It’s a good idea to catch timeout exceptions so your app can handle them smoothly. Like this:
• Monitoring system resources: Make sure your system has enough CPU and memory to handle the initialization without a hitch.
• Checking logs: Take a peek at the timeout and initialization failure logs—they can give you clues about what’s going on behind the scenes.
If you want to chat more about this or need a hand with any of these steps, just let me know! I’m here to help.stocky-tailor-95498
08/14/2025, 7:45 AMtall-airline-16756
08/14/2025, 7:46 AMfrom livekit.agents import WorkerOptions
# Adjust the process timeout
worker_options = WorkerOptions(
initialize_process_timeout=30.0 # Set timeout to 30 seconds
)
This will bump the timeout for process initialization up to 30 seconds. Feel free to change the value to whatever works best for you. If you want me to walk you through it or have any questions, just let me know!stocky-tailor-95498
08/14/2025, 7:48 AMstocky-tailor-95498
08/14/2025, 7:48 AMtall-airline-16756
08/14/2025, 7:48 AMasync def entrypoint(ctx: agents.JobContext):
worker_options = WorkerOptions(
initialize_process_timeout=30.0 # Set timeout to 30 seconds
)
# Use worker_options when initializing your process pool or other components
pool = ProcPool(
initialize_process_fnc=your_init_func,
job_entrypoint_fnc=your_job_func,
num_idle_processes=your_num_processes,
initialize_timeout=worker_options.initialize_process_timeout
)
await pool.start()
If anything’s unclear or you want to dive deeper, just let me know—I’m here to help!stocky-tailor-95498
08/14/2025, 8:03 AMtall-airline-16756
08/14/2025, 8:03 AMresponse_time_ms
with the actual latency value you have in milliseconds.
• Capturing Conversation Latency: You can combine different metrics like end-of-utterance delay, time to first token, and time to first byte to get a full picture: `total_latency = eou.end_of_utterance_delay + llm.ttft + tts.ttfb`This way, you get a nice comprehensive view of the conversation latency.
• Custom Metrics: If you want to get a bit more detailed, custom metrics are your friend: # Increment a counter
metrics_collector.record_counter("custom_latency_counter", 1)
# Track dynamic values
metrics_collector.record_gauge("custom_latency_gauge", latency_value)
If you want me to walk you through any part of this or need some specific examples for your script, just let me know—I’m here to help! Sources: pkg/telemetry/prometheus/packets.go | Logs, metrics, and telemetry | LiveKit Docs | Capturing metrics | LiveKit Docsstocky-tailor-95498
08/14/2025, 8:04 AMtall-airline-16756
08/14/2025, 8:05 AMasync def entrypoint(ctx: agents.JobContext):
session = AgentSession(
stt=deepgram.STT(),
llm=openai.LLM(model="gpt-4o-mini"),
tts=cartesia.TTS(
model="sonic-2",
voice="28ca2041-5dda-42df-8123-f58ea9c3da00",
language="hi"
),
vad=silero.VAD.load(),
turn_detection=MultilingualModel(),
use_tts_aligned_transcript=True
)
@session.on("metrics_collected")
def _on_metrics_collected(ev: MetricsCollectedEvent):
usage_collector.collect(ev.metrics)
async def log_usage():
summary = usage_collector.get_summary()
<http://logger.info|logger.info>(f"Usage: {summary}")
# Calculate conversational latency
eou_delay = summary.get("eou.end_of_utterance_delay", 0)
llm_ttft = summary.get("llm.ttft", 0)
tts_ttfb = summary.get("tts.ttfb", 0)
total_latency = eou_delay + llm_ttft + tts_ttfb
<http://logger.info|logger.info>(f"Latency: {total_latency} ms")
ctx.add_shutdown_callback(log_usage)
await session.start(
room=ctx.room,
agent=Translator(),
room_input_options=RoomInputOptions(
noise_cancellation=noise_cancellation.BVC(),
),
room_output_options=RoomOutputOptions(
transcription_enabled=True,
sync_transcription=True
),
)
await ctx.connect()
await session.generate_reply(
instructions="Greet 'Hello I'm a translator'"
)
This setup will neatly log the total conversational latency when the session shuts down. If you want to tweak it or have any questions, just let me know—I’m here to help!stocky-tailor-95498
08/14/2025, 8:14 AMtall-airline-16756
08/14/2025, 8:15 AMgpt-3.5-turbo
, gpt-3.5-turbo-16k
, and some others with specific date-stamped versions.
• GPT-4 Models: Including gpt-4
, gpt-4-turbo
, gpt-4-vision-preview
, plus their date-stamped versions.
• GPT-4o Models: Such as gpt-4o
, gpt-4o-mini
, and their date-specific versions.
If you want to chat more about which model might be best for you or need any extra info, just let me know! I'm here to help. Sources: plugins/openai/src/llm.ts | livekit-plugins/livekit-plugins-openai/livekit/plugins/openai/llm.py | LLM Integrations | livekit/livekit_composite | DeepWiki | OpenAI LLM integration guide | LiveKit Docsstocky-tailor-95498
08/14/2025, 8:16 AMtall-airline-16756
08/14/2025, 8:17 AMstocky-tailor-95498
08/14/2025, 8:41 AMtall-airline-16756
08/14/2025, 8:42 AMasync def log_usage():
summary = usage_collector.get_summary()
<http://logger.info|logger.info>(f"Usage: {summary}")
# Verify and calculate total latency
eou_delay = summary.get("eou.end_of_utterance_delay", 0)
llm_ttft = summary.get("llm.ttft", 0)
tts_ttfb = summary.get("tts.ttfb", 0)
total_latency = eou_delay + llm_ttft + tts_ttfb
<http://logger.info|logger.info>(f"Latency: {total_latency} ms")
If you don’t see these metrics in the summary, double-check that they’re being collected during the session. Feel free to reach out if you want me to help you dig a little deeper! Sources: Logs, metrics, and telemetry | LiveKit Docsstocky-tailor-95498
08/14/2025, 8:44 AMtall-airline-16756
08/14/2025, 8:45 AM@session.on("metrics_collected")
def _on_metrics_collected(ev: MetricsCollectedEvent):
usage_collector.collect(ev.metrics)
2. Check Metric Availability: Make sure the metrics eou.end_of_utterance_delay, llm.ttft, and tts.ttfb are actually being emitted during the session. If they’re missing, it might help to confirm that the relevant parts (like STT, LLM, TTS) are configured to send these metrics. 3. Debug Missing Metrics: If you still don’t see these metrics, try logging the raw metrics inside the _on_metrics_collected handler to see what’s coming through. Feel free to reach out if you want a hand checking or setting this up!stocky-tailor-95498
08/14/2025, 8:46 AMtall-airline-16756
08/14/2025, 8:46 AM@session.on("metrics_collected")
def _on_metrics_collected(ev: MetricsCollectedEvent):
print(f"Raw metrics collected: {ev.metrics}")
usage_collector.collect(ev.metrics)
2. Take a Look at the Logged Metrics: Run your script and check the output to see if the metrics eou.end_of_utterance_delay, llm.ttft, and tts.ttfb show up. 3. Double-Check Your Component Setup: Make sure the components you’re using (like STT, LLM, TTS) are set up to send these metrics. For instance, verify that your LLM and TTS models support metrics collection. If you hit any snags or want me to walk you through it, just let me know—I’m here to help!stocky-tailor-95498
08/14/2025, 8:50 AMtall-airline-16756
08/14/2025, 8:50 AMasync def log_usage():
summary = usage_collector.get_summary()
<http://logger.info|logger.info>(f"Usage: {summary}")
# Access attributes directly
eou_delay = getattr(summary, "eou_end_of_utterance_delay", 0)
llm_ttft = getattr(summary, "llm_ttft", 0)
tts_ttfb = getattr(summary, "tts_ttfb", 0)
total_latency = eou_delay + llm_ttft + tts_ttfb
<http://logger.info|logger.info>(f"Latency: {total_latency} ms")
This way, getattr helps you safely grab those attributes and falls back to 0 if something’s missing. If you want me to walk you through it or have any other questions, just let me know—I’m here to help!stocky-tailor-95498
08/14/2025, 8:52 AMtall-airline-16756
08/14/2025, 8:53 AM@session.on("metrics_collected")
def _on_metrics_collected(ev: MetricsCollectedEvent):
print(f"Raw metrics collected: {ev.metrics}")
usage_collector.collect(ev.metrics)
2. Take a Peek at Raw Metrics: Try logging the raw metrics in the _on_metrics_collected handler to see if these metrics are actually being emitted. 3. Check Your Components: Confirm that the components you’re using (like STT, LLM, TTS) support and emit these metrics. Sometimes, certain models or setups might not provide them. If you want, I’m here to help you dig into this or walk through the setup! Just let me know.stocky-tailor-95498
08/14/2025, 8:57 AMCollecting logs, metrics, and telemetry data from your agent for debugging and insights.## Overview LiveKit Agents provides built-in support for logging, collecting, and analyzing metrics to help you monitor and optimize your agent's performance. Agent sessions emit structured metrics events that can be logged in real time or aggregated to analyze latency and usage patterns. In addition to per-event metrics, LiveKit’s OpenTelemetry integration provides trace-based observability. This enables you to capture the execution flow of an agents's lifecycle—from session start to individual [node](https://docs.livekit.io/agents/build/nodes.md) operations. You can use any OpenTelemetry-compatible provider to collect and analyze telemetry data, giving you insight into conversation latency, tool usage, and performance bottlenecks. For information on log levels, see the [worker options](https://docs.livekit.io/agents/worker/options.md#log-levels) page. ## Logging events Agent metrics events are fired by the
AgentSession
whenever there is a new metrics object available during an active session.
A log_metrics
helper function is also provided to format logging output for each metric type.
python
from livekit.agents import metrics, MetricsCollectedEvent
...
@session.on("metrics_collected")
def _on_metrics_collected(ev: MetricsCollectedEvent):
metrics.log_metrics(ev.metrics)
## Aggregating metrics
The metrics
module also includes a UsageCollector
helper class for aggregating usage metrics across a session. It tracks metrics such as LLM, TTS, and STT API usage, which can help estimate session cost.
python
from livekit.agents import metrics, MetricsCollectedEvent
...
usage_collector = metrics.UsageCollector()
@session.on("metrics_collected")
def _on_metrics_collected(ev: MetricsCollectedEvent):
usage_collector.collect(ev.metrics)
async def log_usage():
summary = usage_collector.get_summary()
<http://logger.info|logger.info>(f"Usage: {summary}")
# At shutdown, generate and log the summary from the usage collector
ctx.add_shutdown_callback(log_usage)
## Metrics reference

### Speech-to-text (STT)
STTMetrics
is emitted after the STT model has processed the audio input. This metrics is only available when an STT component is used, which does not apply to Realtime APIs.
| Metric | Description |
| audio_duration
| The duration (seconds) of the audio input received by the STT model. |
| duration
| For non-streaming STT, the amount of time (seconds) it took to create the transcript. Always 0
for streaming STT. |
| streamed
| True
if the STT is in streaming mode. |
### LLM
LLMMetrics
is emitted after each LLM inference completes. If the response includes tool calls, the event does not include the time taken to execute those calls. Each tool call response triggers a separate LLMMetrics
event.
| Metric | Description |
| duration
| The amount of time (seconds) it took for the LLM to generate the entire completion. |
| completion_tokens
| The number of tokens generated by the LLM in the completion. |
| prompt_tokens
| The number of tokens provided in the prompt sent to the LLM. |
| prompt_cached_tokens
| The number of cached tokens in the input prompt. |
| speech_id
| An unique identifier representing a turn in the user input. |
| total_tokens
| Total token usage for the completion. |
| tokens_per_second
| The rate of token generation (tokens/second) by the LLM to generate the completion. |
| ttft
| The amount of time (seconds) that it took for the LLM to generate the first token of the completion. |
### Text-to-speech (TTS)
TTSMetrics
is emitted after a TTS has generated speech from text input.
| Metric | Description |
| audio_duration
| The duration (seconds) of the audio output generated by the TTS model. |
| characters_count
| The number of characters in the text input to the TTS model. |
| duration
| The amount of time (seconds) it took for the TTS model to generate the entire audio output. |
| ttfb
| The amount of time (seconds) that it took for the TTS model to generate the first byte of its audio output. |
| speech_id
| An identifier linking to a user's turn. |
| streamed
| True
if the TTS is in streaming mode. |
### End-of-utterance (EOU)
EOUMetrics
is emitted when the user is determined to have finished speaking. It includes metrics related to end-of-turn detection and transcription latency.
This event is only available in Realtime APIs when turn_detection
is set to either VAD or LiveKit's turn detector plugin. When using server-side turn detection, EOUMetrics is not emitted, as this information is not available.
| Metric | Description |
| end_of_utterance_delay
| Time (in seconds) from the end of speech (as detected by VAD) to the point when the user's turn is considered complete. This includes any transcription_delay
. |
| transcription_delay
| Time (seconds) between the end of speech and when final transcript is available |
| on_user_turn_completed_delay
| Time (in seconds) taken to execute the on_user_turn_completed
callback. |
| speech_id
| A unique identifier indicating the user's turn. |
## Measuring conversation latency
Total conversation latency is defined as the time it takes for the agent to respond to a user's utterance. Given the metrics above, it can be computed as follows:
python
total_latency = eou.end_of_utterance_delay + llm.ttft + tts.ttfb
## Telemetry
LiveKit's [OpenTelemetry](https://opentelemetry.io/docs/) integration automatically collects telemetry data from your agents and publishes it to any OpenTelemetry-compatible provider you choose. This enables monitoring and analysis of your agent's behavior and performance.
### Collected data
A trace represents the execution flow of a single request within an LLM application. It captures all relevant steps, including duration and metadata.
Agent telemetry records traces for the following activities:
- Session start
- Agent turn
- LLM node
- Function tool
- TTS node
- End-of-turn detection
- LLM and TTS metrics
### Enabling telemetry
To enable telemetry, configure a tracer provider using set_tracer_provider
in your entrypoint function. You can use any [OpenTelemetry-compatible provider](https://opentelemetry.io/ecosystem/vendors/).
The following example uses [LangFuse](https://langfuse.com/docs/opentelemetry/get-started). Set the required public key, secret key, and host as environment variables:
python
import base64
import os
from livekit.agents.telemetry import set_tracer_provider
def setup_langfuse(
host: str | None = None, public_key: str | None = None, secret_key: str | None = None
):
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor
public_key = public_key or os.getenv("LANGFUSE_PUBLIC_KEY")
secret_key = secret_key or os.getenv("LANGFUSE_SECRET_KEY")
host = host or os.getenv("LANGFUSE_HOST")
if not public_key or not secret_key or not host:
raise ValueError("LANGFUSE_PUBLIC_KEY, LANGFUSE_SECRET_KEY, and LANGFUSE_HOST must be set")
langfuse_auth = base64.b64encode(f"{public_key}:{secret_key}".encode()).decode()
os.environ["OTEL_EXPORTER_OTLP_ENDPOINT"] = f"{host.rstrip('/')}/api/public/otel"
os.environ["OTEL_EXPORTER_OTLP_HEADERS"] = f"Authorization=Basic {langfuse_auth}"
trace_provider = TracerProvider()
trace_provider.add_span_processor(BatchSpanProcessor(OTLPSpanExporter()))
set_tracer_provider(trace_provider)
async def entrypoint(ctx: JobContext):
setup_langfuse() # set up the langfuse tracer provider
# ...
### Trace example
The following diagram shows a trace of an agent session with user turns.

### Example
For a full example, see the following in the LiveKit Agents GitHub repository.
- **[LangFuse trace example](https://github.com/livekit/agents/blob/main/examples/voice_agents/langfuse_trace.py)**: An example of an agent using LangFuse as the tracer provider.
---
This document was rendered at 2025-08-14T085723.387Z.
For the latest version of this document, see [https://docs.livekit.io/agents/build/metrics.md](https://docs.livekit.io/agents/build/metrics.md).
To explore all LiveKit documentation, see [llms.txt](https://docs.livekit.io/llms.txt).tall-airline-16756
08/14/2025, 8:57 AM@session.on("metrics_collected")
def _on_metrics_collected(ev: MetricsCollectedEvent):
print(f"Raw metrics collected: {ev.metrics}")
usage_collector.collect(ev.metrics)
3. Check What You’ve Got: Look at the logged output to see if eou.end_of_utterance_delay, llm.ttft, and tts.ttfb show up. If any are missing, it’s worth double-checking your component setup. If you want, I’m here to help you verify or tweak these metrics—just let me know!stocky-tailor-95498
08/14/2025, 8:59 AMRoomInputOptions.close_on_disconnect=False
)
2025-08-14 142209,502 - INFO livekit.agents - closing agent session due to participant disconnect (disable via RoomInputOptions.close_on_disconnect=False
) {"participant": "voice_assistant_user_7822", "reason": "CLIENT_INITIATED"}
DEBUGlivekit.agentsstream closed
2025-08-14 142209,503 - DEBUG livekit.agents - stream closed {"participant": "voice_assistant_user_7822", "source": "SOURCE_MICROPHONE"}
DEBUGlivekit.agentsinput stream detached
2025-08-14 142209,510 - DEBUG livekit.agents - input stream detached {"participant": "voice_assistant_user_7822", "source": "SOURCE_UNKNOWN", "accepted_sources": ["SOURCE_MICROPHONE"]}
DEBUGlivekit.agentssession closed
2025-08-14 142209,518 - DEBUG livekit.agents - session closed {"reason": "participant_disconnected", "error": null}
DEBUGlivekit.agentsshutting down job task
2025-08-14 142231,234 - DEBUG livekit.agents - shutting down job task {"reason": "", "user_initiated": false}
DEBUGlivekit.agentsjob exiting
2025-08-14 142231,238 - DEBUG livekit.agents - job exiting {"reason": "", "tid": 16756, "job_id": "AJ_RStaTFF9MwwV"}
INFO mp main Usage: UsageSummary(llm_prompt_tokens=126, llm_prompt_cached_tokens=0, llm_completion_tokens=22, tts_characters_count=57, tts_audio_duration=3.204333333333333, stt_audio_duration=10.04999999999998)
2025-08-14 142231,242 - INFO __mp_main__ - Usage: UsageSummary(llm_prompt_tokens=126, llm_prompt_cached_tokens=0, llm_completion_tokens=22, tts_characters_count=57, tts_audio_duration=3.204333333333333, stt_audio_duration=10.04999999999998)tall-airline-16756
08/14/2025, 9:00 AM@session.on("metrics_collected")
def _on_metrics_collected(ev: MetricsCollectedEvent):
for metric in ev.metrics:
if metric.type == "eou_metrics":
eou_delay = metric.end_of_utterance_delay
elif metric.type == "llm_metrics":
llm_ttft = metric.ttft
elif metric.type == "tts_metrics":
tts_ttfb = metric.ttfb
total_latency = eou_delay + llm_ttft + tts_ttfb
<http://logger.info|logger.info>(f"Total Latency: {total_latency} seconds")
2. Double-Check Metric Types: Make sure the metrics are popping up with the right types (eou_metrics, llm_metrics, and tts_metrics) and that they include the attributes you need. 3. Add Logs to Help Debug: Throw in some debug logs so you can keep an eye on whether the metrics are being caught and handled properly. If you want a hand with any of this or run into any bumps, just let me know — I’m here to help!