I'm having an issue aggregating the latency metric...
# ask-ai
r
I'm having an issue aggregating the latency metrics of a single call. The metrics events gets fired sometimes once or sometimes several times per user/agent interaction. This happens mostly with the TTS and LLM metrics, for example:
Copy code
2025-10-08 12:44:23,223 - multi-room-worker - DEBUG - Job AJ_bGTELLKRKU5d - PID: 3071 - Agent state changed to speaking.
2025-10-08 12:44:23,234 - multi-room-worker - DEBUG - Job AJ_bGTELLKRKU5d - PID: 3071 - Metric entry - TTSMetrics(type='tts_metrics', label='livekit.plugins.google.tts.TTS', request_id='c3e1b2fbbff4', timestamp=1759927463.234188, ttfb=0.4261798500083387, duration=0.43851730413734913, audio_duration=2.2399999999999998, cancelled=False, characters_count=25, streamed=False, segment_id=None, speech_id='speech_1f3cfb56c98e')
2025-10-08 12:44:23,290 - multi-room-worker - DEBUG - Job AJ_bGTELLKRKU5d - PID: 3071 - Metric entry - LLMMetrics(type='llm_metrics', label='livekit.agents.llm.fallback_adapter.FallbackAdapter', request_id='chatcmpl-CONo2AuMHgYhdRyo3BGumLCiqfdR1', timestamp=1759927463.290626, duration=1.4243672103621066, ttft=0.8580261799506843, cancelled=False, completion_tokens=48, prompt_tokens=2043, prompt_cached_tokens=1920, total_tokens=2091, tokens_per_second=33.69917507985691, speech_id='speech_1f3cfb56c98e')
2025-10-08 12:44:23,977 - multi-room-worker - DEBUG - Job AJ_bGTELLKRKU5d - PID: 3071 - Metric entry - TTSMetrics(type='tts_metrics', label='livekit.plugins.google.tts.TTS', request_id='a431b84fc312', timestamp=1759927463.9774241, ttfb=0.664231285918504, duration=0.7380605791695416, audio_duration=4.560000000000001, cancelled=False, characters_count=76, streamed=False, segment_id=None, speech_id='speech_1f3cfb56c98e')
2025-10-08 12:44:24,628 - multi-room-worker - DEBUG - Job AJ_bGTELLKRKU5d - PID: 3071 - Metric entry - TTSMetrics(type='tts_metrics', label='livekit.plugins.google.tts.TTS', request_id='2e7239d30ed2', timestamp=1759927464.6284814, ttfb=0.5724537316709757, duration=0.6349088116548955, audio_duration=3.8800000000000012, cancelled=False, characters_count=61, streamed=False, segment_id=None, speech_id='speech_1f3cfb56c98e')
2025-10-08 12:44:25,267 - multi-room-worker - DEBUG - Job AJ_bGTELLKRKU5d - PID: 3071 - Metric entry - TTSMetrics(type='tts_metrics', label='livekit.plugins.google.tts.TTS', request_id='53b24fd93456', timestamp=1759927465.2667618, ttfb=0.5580748268403113, duration=0.6247200248762965, audio_duration=3.8800000000000012, cancelled=False, characters_count=62, streamed=False, segment_id=None, speech_id='speech_1f3cfb56c98e')
2025-10-08 12:44:25,696 - multi-room-worker - DEBUG - Job AJ_bGTELLKRKU5d - PID: 3071 - Metric entry - STTMetrics(type='stt_metrics', label='livekit.agents.stt.fallback_adapter.FallbackAdapter', request_id='5a101a97-e00d-4e11-baa5-4fec4e2d1e07', timestamp=1759927465.6962907, duration=0.0, audio_duration=5.04999999999999, streamed=True)
2025-10-08 12:44:30,696 - multi-room-worker - DEBUG - Job AJ_bGTELLKRKU5d - PID: 3071 - Metric entry - STTMetrics(type='stt_metrics', label='livekit.agents.stt.fallback_adapter.FallbackAdapter', request_id='5a101a97-e00d-4e11-baa5-4fec4e2d1e07', timestamp=1759927470.6963618, duration=0.0, audio_duration=4.99999999999999, streamed=True)
If I aggregate all those latency elements, the resulting total latencty becomes irrealistic and not compatible with the observations. What should I do to properly aggregate those metrics?
t
Thanks for reaching out, Alejandro. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
I'm glad you're looking into aggregating latency metrics for TTS, LLM, and STT in LiveKit! A great way to do this is by using the
UsageCollector
class from the LiveKit Agents SDK. It’s designed to help you easily collect and summarize metrics from each component. Here’s a friendly guide on how you can approach it: • LLM Metrics: You’ll want to look at fields like
ttft
(Time to First Token) and
duration
to get a good sense of latency. • TTS Metrics: Try aggregating fields such as
ttfb
(Time to First Byte),
duration
, and
audioDuration
for a clear picture. • STT Metrics: For non-streaming STT, the
duration
field is helpful. For streaming STT, you can infer latency from timestamps or end-of-utterance delays. Here’s a simple example in Python to get you started:
Copy code
collector = UsageCollector()
collector.collect(metrics)  # Can be LLMMetrics, TTSMetrics, or STTMetrics
summary = collector.get_summary()
Also, don’t forget that LiveKit offers OpenTelemetry integration, which is fantastic for end-to-end latency analysis. It helps you trace the entire agent lifecycle and spot any bottlenecks that might come up. If you’d like to dive deeper, the LiveKit Metrics Documentation is a wonderful resource. Sources: docs/index.yaml | Logs, metrics, and telemetry | LiveKit Docs | agents/src/metrics/utils.ts
r
UsageCollector is not providing any latency information at the moment for me, this is the output of the metrics data I get with it
Copy code
UsageSummary(llm_prompt_tokens=938,                                                                                                                                                              
             llm_prompt_cached_tokens=0,                                                                                                                                                         
             llm_input_audio_tokens=0,                                                                                                                                                           
             llm_completion_tokens=105,                                                                                                                                                          
             llm_output_audio_tokens=0,                                                                                                                                                          
             tts_characters_count=508,                                                                                                                                                           
             tts_audio_duration=28.612,                                                                                                                                                          
             stt_audio_duration=70.44999999999986)
t
The
UsageCollector
in LiveKit is thoughtfully designed to gather usage-related metrics like token counts, character counts, and audio durations. It doesn’t include latency information, and that’s intentional. If you’re looking to monitor latency, LiveKit offers an OpenTelemetry integration that’s really helpful for tracing agent lifecycle events and measuring conversation latency. Plus, cloud analytics dashboards can give you valuable insights into latency metrics, connection quality, and time-to-connect data. If you’d like, I’m here to help you set up OpenTelemetry or access any latency data you need—just let me know, and we’ll work through it together. Sources: Logs, metrics, and telemetry | LiveKit Docs | Say hello to improved Cloud analytics | agents/src/metrics/index.ts | livekit-agents/livekit/agents/metrics/usage_collector.py
r
how can I setup OpenTelemetry
t
I'd be happy to guide you through setting up OpenTelemetry in LiveKit for latency monitoring. Just follow these simple steps: 1. Install Dependencies: First, you'll want to install the necessary OpenTelemetry packages along with the LiveKit Agents SDK:
Copy code
pip install opentelemetry-sdk opentelemetry-exporter-otlp
1. Configure Environment Variables: Next, set up the following environment variables for your OpenTelemetry backend, such as LangFuse: •
LANGFUSE_PUBLIC_KEY
•
LANGFUSE_SECRET_KEY
•
LANGFUSE_HOST
(for example,
https://cloud.langfuse.com
) 1. Initialize the Tracer Provider: You can use this Python code to configure OpenTelemetry smoothly:
Copy code
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor, OTLPSpanExporter
from livekit.agents.telemetry import set_tracer_provider
import os

def setup_telemetry():
    os.environ["OTEL_EXPORTER_OTLP_ENDPOINT"] = f"{os.getenv('LANGFUSE_HOST')}/api/public/otel"
    os.environ["OTEL_EXPORTER_OTLP_HEADERS"] = f"Authorization=Basic {base64.b64encode(f'{os.getenv('LANGFUSE_PUBLIC_KEY')}:{os.getenv('LANGFUSE_SECRET_KEY')}'.encode()).decode()}"

    provider = TracerProvider()
    processor = BatchSpanProcessor(OTLPSpanExporter())
    provider.add_span_processor(processor)

    set_tracer_provider(provider, metadata={"lk.room_name": "test-room"})
1. Enable Telemetry in Your Agent: Just call
setup_telemetry()
before you start your agent session like this:
Copy code
async def entrypoint(ctx: JobContext):
    setup_telemetry()
    session = AgentSession()
    await session.start(agent=MyAgent(), room=ctx.room)
With this setup, you'll have trace-based observability to monitor latency metrics such as LLM response times, TTS delays, and end-of-utterance detection. If you have any questions or need a hand with any step, please don’t hesitate to ask—I’m here to help! Sources: livekit-agents/livekit/agents/telemetry/trace_types.py | docs/index.yaml | pkg/telemetry/prometheus/packets.go | Logs, metrics, and telemetry | LiveKit Docs
r
I got this error
Copy code
File "/usr/local/lib/python3.10/runpy.py", line 196, in _run_module_as_main                  
    return _run_code(code, main_globals, None,                                                 
  File "/usr/local/lib/python3.10/runpy.py", line 86, in _run_code                             
    exec(code, run_globals)                                                                    
  File "/app/src/agent/main.py", line 23, in                                           
    from opentelemetry.sdk.trace.export import BatchSpanProcessor, OTLPSpanExporter            
ImportError: cannot import name 'OTLPSpanExporter' from 'opentelemetry.sdk.trace.export' (/usr/
local/lib/python3.10/site-packages/opentelemetry/sdk/trace/export/__init__.py)
t
It looks like the error is happening because the
OTLPSpanExporter
isn’t found in
opentelemetry.sdk.trace.export
. No worries though! To fix this, you can update your import statement to:
Copy code
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
Also, just double-check that you have the necessary package installed by running:
Copy code
pip install opentelemetry-exporter-otlp
Once you’ve made these changes, your OpenTelemetry setup should be up and running smoothly. If you run into any other issues or have questions, feel free to reach out—I’m here to help! Sources: livekit-agents/livekit/agents/llm/mcp.py | metrics/langfuse_tracing.py | Logs, metrics, and telemetry | LiveKit Docs
r
The telemetry data that I get from Langfuse is not correct. The duration metric is interpreted as latency, while data as TTFB and TTFT are nowhere to be seen
t
Let's work together to make sure your telemetry data for TTFT (Time To First Token) and TTFB (Time To First Byte) in Langfuse is accurate. Here are some helpful steps you can follow: 1. Verify OpenTelemetry Configuration: Please double-check that your tracer is set up correctly with your Langfuse credentials (
LANGFUSE_PUBLIC_KEY
,
LANGFUSE_SECRET_KEY
, and
LANGFUSE_HOST
). This is key to getting the right data. 2. Check Metrics Collection: TTFT is gathered during LLM streaming, and TTFB during TTS generation. These metrics show up in spans under
lk.llm_metrics
and
lk.tts_metrics
. It's good to confirm they're being captured properly. 3. Inspect Trace Data: You can use the Langfuse dashboard to look for spans that include attributes like
ttft
,
ttfb
, and
duration
. If any of these are missing, it might point to configuration or connectivity hiccups. 4. Minimize Network Latency: Try to deploy agents close to your LLM and TTS services. This helps reduce round-trip time (RTT), since high network latency can make TTFT and TTFB values appear higher than they really are. 5. Check for Retries: Sometimes, TTFT might not be reported if LLM requests fail or get retried without producing tokens. It’s worth checking your retry logs to spot any such cases. If you’re still running into issues after these steps, please don’t hesitate to reach out. I’m here to help and can guide you through more troubleshooting whenever you need. Sources: agents/src/metrics/utils.ts | Getting Help & Troubleshooting | livekit/livekit_composite | DeepWiki | SIP & Telephony Applications | livekit/livekit_composite | DeepWiki | How can I reduce latency in voice agents using STT, TTS and LLM? | Logs, metrics, and telemetry | LiveKit Docs