stocky-tailor-95498
08/21/2025, 12:38 PMtall-airline-16756
08/21/2025, 12:38 PMtall-airline-16756
08/21/2025, 12:39 PMfrom livekit.agents import metrics, MetricsCollectedEvent
# Subscribe to metrics collection events
@session.on("metrics_collected")
def _on_metrics_collected(ev: MetricsCollectedEvent):
metrics.log_metrics(ev.metrics)
Now, if you’re looking for something a bit more detailed, you can gather and aggregate metrics with the UsageCollector like this:
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()
logger.info(f"Usage: {summary}")
# When shutting down, create and log the summary
ctx.add_shutdown_callback(log_usage)
And hey, if you want to track custom latency for specific things like STT or EOU, just give me a shout—I’d be happy to help you out with more details!
Sources: Capturing metrics | LiveKit Docs | Logs, metrics, and telemetry | LiveKit Docs | metrics/metrics_stt.pystocky-tailor-95498
08/21/2025, 12:41 PMtall-airline-16756
08/21/2025, 12:42 PMUsageCollector or subscribing to metrics events directly?
• Is your agent session properly started and connected to a room?
Once I have a bit more info, I’d be happy to help you figure this out!
Sources: metrics/send-metrics-to-3p/send_metrics_to_3p.py | Capturing metrics | LiveKit Docsstocky-tailor-95498
08/21/2025, 1:13 PMtall-airline-16756
08/21/2025, 1:14 PMmetrics_collected event is actually firing when things are running.
• Component Activity: Check that your STT, LLM, and TTS components are actively processing data—metrics only update when these parts are doing their thing.
• UsageCollector: If you’re using UsageCollector, just confirm it’s gathering metrics properly and you’re calling get_summary() after the operations finish.
• Timing: Sometimes metrics show zero if you look too early—try checking after you’ve had some activity going on.
Could you let me know if the metrics_collected event is firing and if the components are busy processing data? I’m happy to help walk you through more debugging if you need it!
Sources: CHANGELOG.mdstocky-tailor-95498
08/21/2025, 1:39 PMtall-airline-16756
08/21/2025, 1:40 PMmetrics_collected event is actually firing, a quick way is to pop in a print statement or a log message right inside the event handler. Here's a little example:
@session.on("metrics_collected")
def _on_metrics_collected(ev: MetricsCollectedEvent):
print("Metrics event fired!")
print(f"Raw metrics: {ev.metrics}")
Just run your script and try out some actions like speech-to-text, text-to-speech, or generating replies. If everything’s working, you’ll spot the message "Metrics event fired!" showing up in your console or logs.
Give it a go and let me know if you see the message or if you want me to help you troubleshoot further. I’m here for you!stocky-tailor-95498
08/21/2025, 2:07 PMtall-airline-16756
08/21/2025, 2:08 PMstt_metrics, vad_metrics, and eou_metrics, it means the metrics_collected event is firing just as it should. That said, if those values are still showing up as zero, the hiccup might be happening when the components are processing the data.
Here are a few friendly suggestions to help you dig a little deeper:
• Check if Components Are Active: Make sure the STT, VAD, and EOU components are actually working on the data. For instance, is audio coming in and being handled by STT? Is VAD picking up any voice activity?
• Take a Closer Look at the Metrics: Peek at the raw metrics that are printed out to see exactly which values are zero. This can give you a clue about which component might be having trouble.
• Try a Simple Test: Run a quick test using a known input, like a pre-recorded audio file, to see if the components process it correctly.
Would you mind sharing a bit more about the raw metrics you're seeing or letting me know if the components seem to be actively processing data? I’m here to help you figure this out!stocky-tailor-95498
08/21/2025, 2:09 PMtall-airline-16756
08/21/2025, 2:10 PMUsageCollector might not be gathering the raw metrics properly. Let’s try a few steps to get this sorted out:
• Make sure Metrics Are Being Collected: Double-check that the UsageCollector.collect() method is triggered for every metrics_collected event. Here’s a quick example:
@session.on("metrics_collected")
def _on_metrics_collected(ev: MetricsCollectedEvent):
usage_collector.collect(ev.metrics)
• Verify Metric Types: The UsageCollector works with specific metric types like LLMMetrics, TTSMetrics, and STTMetrics. Make sure your raw metrics are instances of these.
• Take a Look at the Raw Metrics: Check that fields such as prompt_tokens, completion_tokens, characters_count, and audio_duration actually have values greater than zero.
• Initialization Matters: If your UsageCollector was just set up, it starts off with all summary values at zero until it processes valid metrics.
Could you let me know if UsageCollector.collect() is being called, and if the raw metrics look like the expected types? I’m here to help you get this working smoothly!
Sources: agents/src/metrics/usage_collector.ts | livekit-plugins/livekit-plugins-google/livekit/plugins/google/beta/realtime... | Capturing metrics | LiveKit Docsstocky-tailor-95498
08/21/2025, 2:16 PMtall-airline-16756
08/21/2025, 2:18 PMusage_collector.collect(ev) is being called, but the UsageSummary still shows zero values, let’s walk through some possible reasons and easy steps to troubleshoot together:
• Metrics Type: Double-check that the metrics you’re passing to collect() are the right kinds (LLMMetrics, TTSMetrics, STTMetrics, etc.). If they don’t match these types, the summary won’t update.
• Event Parameter: Make sure you're passing ev.metrics to collect(), not the whole event object. Here’s how it should look:
@session.on("metrics_collected")
def _on_metrics_collected(ev: MetricsCollectedEvent):
usage_collector.collect(ev.metrics)
• Zero Values: If the raw metrics have zero values (like no tokens used or no audio processed), the summary will stay at zero even when collect() is called.
• Logging: It might help to add some logging so you can see the type and content of the metrics being passed to collect(). For example:
@session.on("metrics_collected")
def _on_metrics_collected(ev: MetricsCollectedEvent):
print(f"Metrics type: {type(ev.metrics)}")
print(f"Metrics content: {ev.metrics}")
usage_collector.collect(ev.metrics)
Could you please check and share the type and content of the metrics you’re passing to collect()? That way, we can figure out if the issue is with the metrics themselves or how they’re being aggregated. I’m here to help!
Sources: agents/src/metrics/usage_collector.ts | examples/voice_agents/basic_agent.py | Capturing metrics | LiveKit Docsstocky-tailor-95498
08/21/2025, 2:22 PMtall-airline-16756
08/21/2025, 2:22 PMusage_collector.collect(ev) to usage_collector.collect(ev.metrics) did the trick! Now your UsageSummary is showing the right values.
If you have any more questions or need a hand with anything else, just let me know—I’m here to help!stocky-tailor-95498
08/21/2025, 2:24 PMstocky-tailor-95498
08/21/2025, 2:25 PMtall-airline-16756
08/21/2025, 2:25 PM@session.on("metrics_collected")
def _on_metrics_collected(ev: MetricsCollectedEvent):
if isinstance(ev.metrics, STTMetrics):
print(f"STT Latency: {ev.metrics.duration:.4f}s")
• LLM Latency:
@session.on("metrics_collected")
def _on_metrics_collected(ev: MetricsCollectedEvent):
if isinstance(ev.metrics, LLMMetrics):
print(f"LLM Time to First Token: {ev.metrics.ttft:.4f}s")
• Text-to-Speech (TTS) Latency:
@session.on("metrics_collected")
def _on_metrics_collected(ev: MetricsCollectedEvent):
if isinstance(ev.metrics, TTSMetrics):
print(f"TTS Time to First Byte: {ev.metrics.ttfb:.4f}s")
To keep things live and fresh, you can gather these metrics and print them out regularly or even create a simple dashboard to watch everything in real-time. If you'd like, I’d be happy to help you set up a live monitoring interface—just let me know!
Sources: Capturing metrics | LiveKit Docs | metrics/metrics_tts.py | livekit-agents/livekit/agents/voice/chat_cli.py | livekit-protocol/livekit/protocol/metrics.py | stream_audio.pytall-airline-16756
08/21/2025, 2:25 PMmetrics_collected event to log or show latency metrics as they happen. Here’s a simple example for different parts:
• Speech-to-Text (STT):
@session.on("metrics_collected")
def _on_metrics_collected(ev: MetricsCollectedEvent):
if isinstance(ev.metrics, STTMetrics):
print(f"STT Latency: {ev.metrics.duration:.4f}s")
• Text-to-Speech (TTS):
@session.on("metrics_collected")
def _on_metrics_collected(ev: MetricsCollectedEvent):
if isinstance(ev.metrics, TTSMetrics):
print(f"TTS Latency (TTFB): {ev.metrics.ttfb:.4f}s")
• End-of-Utterance (EOU):
@session.on("metrics_collected")
def _on_metrics_collected(ev: MetricsCollectedEvent):
if isinstance(ev.metrics, EOUMetrics):
print(f"EOU Latency: {ev.metrics.end_of_utterance_delay:.4f}s")
You can gather these metrics and update a live dashboard or console to keep an eye on things in real time. If you'd like, I’m happy to help you set up a specific latency tracker or a live monitoring tool—just let me know!stocky-tailor-95498
08/21/2025, 2:26 PMtall-airline-16756
08/21/2025, 2:26 PM@session.on("metrics_collected")
def _on_metrics_collected(ev: MetricsCollectedEvent):
if isinstance(ev.metrics, EOUMetrics):
eou_delay = ev.metrics.end_of_utterance_delay
elif isinstance(ev.metrics, LLMMetrics):
llm_ttft = ev.metrics.ttft
elif isinstance(ev.metrics, TTSMetrics):
tts_ttfb = ev.metrics.ttfb
# Calculate total latency
total_latency = eou_delay + llm_ttft + tts_ttfb
print(f"Overall Latency: {total_latency:.4f}s")
This little snippet sums up the end-of-utterance delay, LLM time-to-first-token, and TTS time-to-first-byte to give you the total latency for each turn. If you want to dive deeper or have any questions, just give me a shout—I’m here to help!stocky-tailor-95498
08/21/2025, 2:28 PMtall-airline-16756
08/21/2025, 2:28 PMEOUMetrics, LLMMetrics, and TTSMetrics, you can do it like this:
from livekit.agents.metrics import EOUMetrics, LLMMetrics, TTSMetrics
Just give me a shout if you need any help getting this set up—I’m here for you!stocky-tailor-95498
08/21/2025, 2:30 PMtall-airline-16756
08/21/2025, 2:30 PMeou_delay, llm_ttft, or tts_ttfb aren’t set up before they’re used in the calculation. A simple way to fix this is to give these variables some default values right at the start of your event handler, like this:
@session.on("metrics_collected")
def _on_metrics_collected(ev: MetricsCollectedEvent):
# Initialize variables with default values
eou_delay = 0
llm_ttft = 0
tts_ttfb = 0
# Update values based on the type of metrics
if isinstance(ev.metrics, EOUMetrics):
eou_delay = ev.metrics.end_of_utterance_delay
elif isinstance(ev.metrics, LLMMetrics):
llm_ttft = ev.metrics.ttft
elif isinstance(ev.metrics, TTSMetrics):
tts_ttfb = ev.metrics.ttfb
# Calculate total latency
total_latency = eou_delay + llm_ttft + tts_ttfb
print(f"Overall Latency: {total_latency:.4f}s")
This way, those variables are always ready to go, even if a certain metric type doesn’t show up during an event. If you want, I’m here to help you out with anything else!stocky-tailor-95498
08/21/2025, 2:33 PMtall-airline-16756
08/21/2025, 2:34 PMimport asyncio
import websockets
async def send_latency():
async with websockets.connect("ws://your-frontend-url/ws") as websocket:
while True:
latency_data = {"latency": total_latency}
await websocket.send(json.dumps(latency_data))
await asyncio.sleep(1) # Send updates every second
Frontend (Next.js):
import { useEffect, useState } from 'react';
export default function LatencyDisplay() {
const [latency, setLatency] = useState(0);
useEffect(() => {
const ws = new WebSocket('ws://your-backend-url/ws');
ws.onmessage = (event) => {
const data = JSON.parse(event.data);
setLatency(data.latency);
};
return () => ws.close();
}, []);
return Current Latency: {latency} ms;
}
If you want a hand setting up any of these methods or have questions, just let me know—I’m here to help!
Sources: metrics/send-metrics-to-3p/send_metrics_to_3p.py | agent-console/app/api/room/send-data/route.ts | Capturing metrics | LiveKit Docsstocky-tailor-95498
08/21/2025, 2:36 PMtall-airline-16756
08/21/2025, 2:36 PMpage.tsx file. Here’s a quick example:
// pages/latency.tsx
import { useEffect, useState } from 'react';
export default function LatencyDisplay() {
const [latency, setLatency] = useState(0);
useEffect(() => {
const ws = new WebSocket('ws://your-backend-url/ws');
ws.onmessage = (event) => {
const data = JSON.parse(event.data);
setLatency(data.latency);
};
return () => ws.close();
}, []);
return Current Latency: {latency} ms;
}
If you want this to live in a shared layout or be reusable, you can create a component file like components/LatencyDisplay.tsx and then import it wherever you want to show the latency.
Feel free to reach out if you want a hand getting this set up in your Next.js project—I’m happy to help!stocky-tailor-95498
08/21/2025, 2:47 PMtall-airline-16756
08/21/2025, 2:47 PMcomponents/latencyDisplay.tsx file:
import { useEffect, useState } from 'react';
export default function LatencyDisplay() {
const [latency, setLatency] = useState(0);
useEffect(() => {
const ws = new WebSocket('ws://your-backend-url/ws');
ws.onmessage = (event) => {
const data = JSON.parse(event.data);
setLatency(data.latency);
};
return () => ws.close();
}, []);
return Current Latency: {latency} ms;
}
After you’ve added that, you can easily import and use the LatencyDisplay component on any page. For example, in `pages/index.tsx`:
import LatencyDisplay from '../components/latencyDisplay';
export default function Home() {
return (
Welcome to the Latency Tracker
);
}
If you run into any questions or want me to walk you through anything else, just let me know—I’m here to help!stocky-tailor-95498
08/21/2025, 3:22 PMtall-airline-16756
08/21/2025, 3:22 PMlocalhost with the right ports for your WebSocket addresses. Here’s an example to make it clearer:
• Backend WebSocket Address: This is where your backend WebSocket server is up and running. So, if your backend is on port 8000, you’d use ws://localhost:8000/ws.
• Frontend WebSocket Address: Usually, you don’t need this unless your frontend is also acting as a WebSocket server. Most of the time, the frontend just connects to the backend WebSocket server.
Make sure your backend WebSocket server is listening on the right port and path (like /ws).
Then, update your frontend code to connect to the backend WebSocket address like this:
const ws = new WebSocket('ws://localhost:8000/ws');
If you want, I’m here to help you set up the WebSocket server or troubleshoot the connection—just let me know!stocky-tailor-95498
08/21/2025, 3:23 PMtall-airline-16756
08/21/2025, 3:23 PMwebsockets library in Python to create a WebSocket server like this:
import asyncio
import websockets
import json
async def send_latency(websocket, path):
while True:
latency_data = {"latency": total_latency} # Replace with your actual latency value
await websocket.send(json.dumps(latency_data))
await asyncio.sleep(1) # Send updates every second
start_server = websockets.serve(send_latency, "localhost", 8000)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
Then, on your Next.js frontend, you’d connect to this WebSocket server using ws://localhost:8000 like so:
const ws = new WebSocket('ws://localhost:8000');
This way, your Python backend can push those real-time latency updates right to your Next.js frontend. If you want me to walk you through any part of this or need a hand setting it up, just let me know—I’m here to help!stocky-tailor-95498
08/21/2025, 3:25 PMtall-airline-16756
08/21/2025, 3:25 PMimport threading
connected_clients = set()
def start_websocket_server():
async def handler(websocket, path):
connected_clients.add(websocket)
try:
await websocket.wait_closed()
finally:
connected_clients.remove(websocket)
server = websockets.serve(handler, "localhost", 8000)
asyncio.get_event_loop().run_until_complete(server)
# Run the WebSocket server in a separate thread
threading.Thread(target=start_websocket_server, daemon=True).start()
1. Send Latency Metrics to Connected Clients: Update the _on_metrics_collected function to share latency metrics with everyone connected via WebSocket.
@session.on("metrics_collected")
def _on_metrics_collected(ev: MetricsCollectedEvent):
eou_delay = 0
llm_ttft = 0
tts_ttfb = 0
if isinstance(ev.metrics, EOUMetrics):
eou_delay = ev.metrics.end_of_utterance_delay
elif isinstance(ev.metrics, LLMMetrics):
llm_ttft = ev.metrics.ttft
elif isinstance(ev.metrics, TTSMetrics):
tts_ttfb = ev.metrics.ttfb
total_latency = eou_delay + llm_ttft + tts_ttfb
print(f"Overall Latency: {total_latency:.4f}s")
# Broadcast latency to all connected WebSocket clients
latency_data = json.dumps({"latency": total_latency})
for client in connected_clients:
asyncio.create_task(client.send(latency_data))
And that’s it! With these updates, your backend will happily broadcast latency metrics to all connected WebSocket clients, so your frontend can show the info live. If you hit any bumps or want to chat more about this, just let me know—I’m here to help!stocky-tailor-95498
08/21/2025, 3:29 PMtall-airline-16756
08/21/2025, 3:30 PMfrom flask import Flask, jsonify
app = Flask(__name__)
# Keep the latest metrics handy in a global variable
latest_metrics = {}
@app.route('/metrics', methods=['GET'])
def get_metrics():
return jsonify(latest_metrics)
# Update the metrics inside your _on_metrics_collected function
@session.on("metrics_collected")
def _on_metrics_collected(ev: MetricsCollectedEvent):
global latest_metrics
eou_delay = 0
llm_ttft = 0
tts_ttfb = 0
if isinstance(ev.metrics, EOUMetrics):
eou_delay = ev.metrics.end_of_utterance_delay
elif isinstance(ev.metrics, LLMMetrics):
llm_ttft = ev.metrics.ttft
elif isinstance(ev.metrics, TTSMetrics):
tts_ttfb = ev.metrics.ttfb
total_latency = eou_delay + llm_ttft + tts_ttfb
latest_metrics = {
"eou_delay": eou_delay,
"llm_ttft": llm_ttft,
"tts_ttfb": tts_ttfb,
"total_latency": total_latency
}
print(f"Updated Metrics: {latest_metrics}")
2. Fetch Metrics in Your Next.js Frontend:stocky-tailor-95498
08/21/2025, 3:30 PMtall-airline-16756
08/21/2025, 3:30 PMfrom flask import Flask, jsonify
app = Flask(__name__)
# Store the latest metrics in a global variable
latest_metrics = {}
@app.route('/metrics', methods=['GET'])
def get_metrics():
return jsonify(latest_metrics)
# Update the metrics in your _on_metrics_collected function
@session.on("metrics_collected")
def _on_metrics_collected(ev: MetricsCollectedEvent):
global latest_metrics
eou_delay = 0
llm_ttft = 0
tts_ttfb = 0
if isinstance(ev.metrics, EOUMetrics):
eou_delay = ev.metrics.end_of_utterance_delay
elif isinstance(ev.metrics, LLMMetrics):
llm_ttft = ev.metrics.ttft
elif isinstance(ev.metrics, TTSMetrics):
tts_ttfb = ev.metrics.ttfb
total_latency = eou_delay + llm_ttft + tts_ttfb
latest_metrics = {
"eou_delay": eou_delay,
"llm_ttft": llm_ttft,
"tts_ttfb": tts_ttfb,
"total_latency": total_latency
}
print(f"Updated Metrics: {latest_metrics}")
2. Fetch Metrics in Your Next.js Frontend:stocky-tailor-95498
08/21/2025, 4:51 PMtall-airline-16756
08/21/2025, 4:52 PM<BACKEND_API_URL>/metrics into your browser or using a tool like Postman. You should see a JSON response with your metrics.
2. Look at your CORS settings: If your backend and frontend are on different origins (like different ports), your backend needs to allow cross-origin requests. If you're using Flask, the flask-cors library makes this easy:
from flask_cors import CORS
CORS(app)
1. Make sure your frontend fetch URL is correct: The URL your frontend uses to fetch data should match your backend's address. For example:stocky-tailor-95498
08/21/2025, 4:56 PMtall-airline-16756
08/21/2025, 4:56 PMstocky-tailor-95498
08/21/2025, 4:57 PMtall-airline-16756
08/21/2025, 4:57 PM<BACKEND_API_URL>/metrics. Make sure the API is sending back the JSON response you expect.
2. Check CORS Configuration: If your backend and frontend are on different origins (like different ports), double-check that your backend allows cross-origin requests. For Flask, you can add this:
from flask_cors import CORS
CORS(app)
1. Debug Frontend Fetch: Let’s add a console log to see if the fetch function is running and what response it’s getting: