need to add basic latency tracking to backend pyth...
# ask-ai
s
need to add basic latency tracking to backend python script in livekit versions 1.x
t
Thanks for reaching out, Nakshatra. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
Hey there! If you want to add some basic latency tracking to your backend Python script using LiveKit versions 1.x, you can totally use the built-in metrics system. Here’s a quick and easy example to get you started:
Copy code
from 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:
Copy code
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.py
s
somehow, this is only showing 0 in all the values
t
Hey there! Seeing metrics with zero values can happen for a few reasons, like components not processing data or maybe the event handler isn’t set up quite right. Could you share a bit more about your setup? For example: • Are your STT, LLM, or TTS components actually processing data? • How are you initializing and configuring these components? • Are you using a
UsageCollector
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 Docs
s
import logging from livekit import agents from livekit.agents import AgentSession, Agent, RoomInputOptions, RoomOutputOptions, metrics, MetricsCollectedEvent, WorkerOptions from livekit.plugins import ( openai, cartesia, deepgram, noise_cancellation, silero, ) from livekit.plugins.turn_detector.multilingual import MultilingualModel from livekit.agents import UserInputTranscribedEvent from dotenv import load_dotenv load_dotenv(dotenv_path=".env.local") logging.basicConfig(level=logging.INFO) logger = logging.getLogger(name) usage_collector = metrics.UsageCollector() class Translator(Agent): def __init__(self) -> None: super().__init__( instructions="Translate English speech to Hindi only, say nothing else" ) async def entrypoint(ctx: agents.JobContext): _# worker_options= WorkerOptions(initialize_process_timeout=30)_ session = AgentSession( stt=deepgram.STT(), llm=openai.LLM(model="gpt-4o-mini"), #4o mini is the lightest modl 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, # enables TTS-aligned transcription for realtime sync ) _# @session.event("conversation_item_added")_ _# async def on_conversation_item_added(item):_ # print(f"[BACKEND] Conversation item added: {item}") @session.on("user_input_transcribed") def on_user_input_transcribed(event: UserInputTranscribedEvent): print(f"User input transcribed: {event.transcript}, final: {event.is_final}, speaker id: {event.speaker_id}") await session.start( room=ctx.room, agent=Translator(), room_input_options=RoomInputOptions( noise_cancellation=noise_cancellation.BVC(), ), room_output_options=RoomOutputOptions( transcription_enabled=True, # ensure STT transcriptions are forwarded sync_transcription=True # word-by-word sync with speech ), ) await ctx.connect() await session.generate_reply( instructions="Greet 'Hello I'm a translator'" ) @session.on("metrics_collected") def _on_metrics_collected(ev: MetricsCollectedEvent): print(f"Raw metrics collected: {ev.metrics}") _# metrics.log_metrics(ev)_ _# usage_collector.collect(ev)_ _# eou_delay = ev.end_of_utterance_delay_ _# llm_ttft = ev.ttft_ _# tts_ttfb = ev.ttfb_ _# total_latency = eou_delay + llm_ttft + tts_ttfb_ _# logger.info(f"\nLatency: {total_latency} ms\n")_ async def log_usage(): summary = usage_collector.get_summary() logger.info(f"Usage: {summary}\n") _# 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_ _# logger.info(f"\nLatency: {total_latency} ms\n")_ ctx.add_shutdown_callback(log_usage) def prewarm(proc: agents.JobProcess): proc.userdata["vad"] = silero.VAD.load() if name == "__main__": agents.cli.run_app(agents.WorkerOptions(entrypoint_fnc=entrypoint, prewarm_fnc=prewarm)) and it is all functional
t
Thanks so much for sharing your setup! Since your script is working but the metrics are showing zero, let’s look at a few possible reasons and some easy ways to troubleshoot: • Metrics Collection: Double-check that metrics collection is turned on and set up correctly. Make sure the
metrics_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.md
s
how to check if it is firing?
t
Hey there! To see if the
metrics_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:
Copy code
@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!
s
i am getting raw metrics printed for stt_metrics, vad_metrics, eou_metrics,
t
Since you're seeing raw metrics for
stt_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!
s
'llm_metrics' label='livekit.plugins.openai.llm.LLM' request_id='chatcmpl-C70DPuieFuaF2SP1WytMPPVZXRBol' timestamp=1755785160.5875275 duration=1.7659693679961492 ttft=1.1159158239970566 cancelled=False completion_tokens=4 prompt_tokens=66 prompt_cached_tokens=0 total_tokens=70 tokens_per_second=2.2650449506600516 speech_id='speech_40f0a8b353c4' Raw metrics collected: type='stt_metrics' label='livekit.plugins.deepgram.stt.STT' request_id='d0b5b3c3-9fac-4f70-bd29-68f931f2c640' timestamp=1755785160.846585 duration=0.0 audio_duration=4.99999999999999 streamed=True Raw metrics collected: type='tts_metrics' label='livekit.plugins.cartesia.tts.TTS' request_id='fbd9356b9061' timestamp=1755785161.0461967 ttfb=0.3159967259998666 duration=0.45800891700491775 audio_duration=0.6965833333333334 cancelled=False characters_count=8 streamed=True segment_id='8adff44c7f0f' speech_id='speech_40f0a8b353c4' Raw metrics collected: type='vad_metrics' label='livekit.plugins.silero.vad.VAD' timestamp=1755785161.4465268 idle_time=2.99968428700231 inference_duration_total=0.028698885995254386 inference_count=32 these values are not 0, usage summary has data with 0 values: Usage: UsageSummary(llm_prompt_tokens=0, llm_prompt_cached_tokens=0, llm_input_audio_tokens=0, llm_completion_tokens=0, llm_output_audio_tokens=0, tts_characters_count=0, tts_audio_duration=0.0, stt_audio_duration=0.0)
t
It looks like the
UsageCollector
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:
Copy code
@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 Docs
s
code: @session.on("metrics_collected") def _on_metrics_collected(ev: MetricsCollectedEvent): print(f"Raw metrics collected: {ev.metrics}") _# metrics.log_metrics(ev)_ usage_collector.collect(ev) so yes, usage_collector.colelct(ev) is being called Usage: UsageSummary(llm_prompt_tokens=0, llm_prompt_cached_tokens=0, llm_input_audio_tokens=0, llm_completion_tokens=0, llm_output_audio_tokens=0, tts_characters_count=0, tts_audio_duration=0.0, stt_audio_duration=0.0)
t
Since
usage_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:
Copy code
@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:
Copy code
@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 Docs
s
i changed usage_collector.collect(ev) to usage_collector.collect(ev.metrics) and it worked: Usage: UsageSummary(llm_prompt_tokens=455, llm_prompt_cached_tokens=0, llm_input_audio_tokens=0, llm_completion_tokens=27, llm_output_audio_tokens=0, tts_characters_count=70, tts_audio_duration=5.7584583333333335, stt_audio_duration=75.29999999999984)
t
I'm so glad to hear that updating
usage_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!
s
how do i show live latency now
?
t
Hey there! If you want to show live latency in your LiveKit setup, you can tap into the metrics collected during your session. Here are some handy examples for different types of latency: • Speech-to-Text (STT) Latency:
Copy code
@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:
Copy code
@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:
Copy code
@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.py
If you want to see live latency in your LiveKit setup, a great way is to use the
metrics_collected
event to log or show latency metrics as they happen. Here’s a simple example for different parts: • Speech-to-Text (STT):
Copy code
@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):
Copy code
@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):
Copy code
@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!
s
i just need to show overall latency in the moment that refreshes every turn
t
Hey there! To keep track of the overall latency that updates with each turn, you can simply add up the relevant metrics for every turn. Here’s a quick example:
Copy code
@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!
s
what would be the import for eoumetrics, llmmetrics and ttsmetrics?
t
If you want to import
EOUMetrics
,
LLMMetrics
, and
TTSMetrics
, you can do it like this:
Copy code
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!
s
Raw metrics collected: type='llm_metrics' label='livekit.plugins.openai.llm.LLM' request_id='chatcmpl-C70aOTNJTzHcsyLRQ8XWLPnVEkTMR' timestamp=1755786585.238805 duration=0.9728176680000615 ttft=0.8400011740013724 cancelled=False completion_tokens=4 prompt_tokens=42 prompt_cached_tokens=0 total_tokens=46 tokens_per_second=4.111767427315832 speech_id='speech_91f7c9da7e83' ERRORlivekitfailed to emit event metrics_collected Traceback (most recent call last): File "/home/naksh/wslvenv/lib/python3.12/site-packages/livekit/rtc/event_emitter.py", line 58, in emit callback(*callback_args) File "/mnt/c/Users/Acer/Desktop/transys/backend/main.py", line 84, in _on_metrics_collected total_latency = eou_delay + llm_ttft + tts_ttfb ^^^^^^^^^ UnboundLocalError: cannot access local variable 'eou_delay' where it is not associated with a value ERRORlivekitfailed to emit event metrics_collected Traceback (most recent call last): File "/home/naksh/wslvenv/lib/python3.12/site-packages/livekit/rtc/event_emitter.py", line 58, in emit callback(*callback_args) File "/mnt/c/Users/Acer/Desktop/transys/backend/main.py", line 84, in _on_metrics_collected total_latency = eou_delay + llm_ttft + tts_ttfb ^^^^^^^^^ UnboundLocalError: cannot access local variable 'eou_delay' where it is not associated with a value 2025-08-21 142945,239 - ERROR livekit - failed to emit event metrics_collected Traceback (most recent call last): File "/home/naksh/wslvenv/lib/python3.12/site-packages/livekit/rtc/event_emitter.py", line 58, in emit callback(*callback_args) File "/mnt/c/Users/Acer/Desktop/transys/backend/main.py", line 84, in _on_metrics_collected total_latency = eou_delay + llm_ttft + tts_ttfb ^^^^^^^^^ UnboundLocalError: cannot access local variable 'eou_delay' where it is not associated with a value {"pid": 4646, "job_id": "AJ_R3CyunSasiq
t
It looks like the error happens because the variables
eou_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:
Copy code
@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!
s
okay it works now, I am getting the latency metric in the backend terminal. Now, i wish to show it to the user on the frontend UI as well, how do I do that? I am using Next.js for frontend
t
Hey there! If you want to show the backend latency metric on your Next.js frontend in real-time, here are a few friendly ways to do it: • WebSocket Communication: You can set up a WebSocket connection between your backend and frontend to send latency updates as they happen. • HTTP API: Another option is to create an API endpoint in your Next.js app that fetches the latest latency data every so often. • LiveKit Data Messages: Or, you could use LiveKit's room service to send data messages straight to the frontend. If you're aiming for real-time updates, I’d recommend going with WebSocket communication. Here’s a simple example to get you started: Backend (Python):
Copy code
import 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):
Copy code
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 Docs
s
where does the frontend piece of code go? page.tsx?
t
Hey! You can add the frontend code for showing latency inside a React component. If you'd like it to show up on a particular page, just pop it into that page’s
page.tsx
file. Here’s a quick example:
Copy code
// 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!
s
i made a new empty components/latencyDisplay.tsx file
t
Awesome! You can go ahead and add the following code to your
components/latencyDisplay.tsx
file:
Copy code
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`:
Copy code
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!
s
it's a websocket problem, I am running both frontend and backend locally, what websocket addresses shall i use for ('ws://your-backend-url/ws') and ('ws://your-frontend-url/ws')?
t
If you’re running both the frontend and backend locally, you can simply use
localhost
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:
Copy code
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!
s
but running a python livekit script doesn't need a websocket address for the backend?
t
You're absolutely right that running a Python LiveKit script doesn’t automatically need a WebSocket address for the backend. But if you’re aiming to send real-time latency metrics from your Python backend over to your Next.js frontend, you’ll want to set up a WebSocket server in your Python backend to make that communication happen smoothly. For example, you could use the
websockets
library in Python to create a WebSocket server like this:
Copy code
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:
Copy code
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!
s
how do i update that in this script: import logging import asyncio import websockets import json from livekit import agents from livekit.agents import AgentSession, Agent, RoomInputOptions, RoomOutputOptions, metrics, MetricsCollectedEvent, WorkerOptions, UserInputTranscribedEvent from livekit.plugins import ( openai, cartesia, deepgram, noise_cancellation, silero, ) from livekit.plugins.turn_detector.multilingual import MultilingualModel from livekit.agents.metrics import EOUMetrics, LLMMetrics, TTSMetrics from dotenv import load_dotenv load_dotenv(dotenv_path=".env.local") logging.basicConfig(level=logging.INFO) logger = logging.getLogger(name) usage_collector = metrics.UsageCollector() class Translator(Agent): def __init__(self) -> None: super().__init__( instructions="Translate English speech to Hindi only, say nothing else" ) async def entrypoint(ctx: agents.JobContext): _# worker_options= WorkerOptions(initialize_process_timeout=30)_ session = AgentSession( stt=deepgram.STT(), llm=openai.LLM(model="gpt-4o-mini"), #4o mini is the lightest modl 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, # enables TTS-aligned transcription for realtime sync ) _# @session.event("conversation_item_added")_ _# async def on_conversation_item_added(item):_ # print(f"[BACKEND] Conversation item added: {item}") @session.on("user_input_transcribed") def on_user_input_transcribed(event: UserInputTranscribedEvent): print(f"User input transcribed: {event.transcript}, final: {event.is_final}, speaker id: {event.speaker_id}") await session.start( room=ctx.room, agent=Translator(), room_input_options=RoomInputOptions( noise_cancellation=noise_cancellation.BVC(), ), room_output_options=RoomOutputOptions( transcription_enabled=True, # ensure STT transcriptions are forwarded sync_transcription=True # word-by-word sync with speech ), ) await ctx.connect() await session.generate_reply( instructions="Greet 'Hello I'm a translator'" ) @session.on("metrics_collected") def _on_metrics_collected(ev: MetricsCollectedEvent): eou_delay = 0 llm_ttft = 0 tts_ttfb = 0 print(f"\nRaw metrics collected: {ev.metrics}\n") 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") _# metrics.log_metrics(ev)_ usage_collector.collect(ev.metrics) _# eou_delay = ev.end_of_utterance_delay_ _# llm_ttft = ev.ttft_ _# tts_ttfb = ev.ttfb_ _# total_latency = eou_delay + llm_ttft + tts_ttfb_ _# logger.info(f"\nLatency: {total_latency} ms\n")_ 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)) print(f"\ndata being sent to frontend: {latency_data}\n") await asyncio.sleep(1) async def log_usage(): summary = usage_collector.get_summary() logger.info(f"Usage: {summary}\n") _# 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_ _# logger.info(f"\nLatency: {total_latency} ms\n")_ ctx.add_shutdown_callback(log_usage) def prewarm(proc: agents.JobProcess): proc.userdata["vad"] = silero.VAD.load() if name == "__main__": agents.cli.run_app(agents.WorkerOptions(entrypoint_fnc=entrypoint, prewarm_fnc=prewarm))
t
Hey there! To help you send latency metrics to your frontend using WebSocket, you'll want to set up a WebSocket server on your backend. Here's a friendly step-by-step on how to tweak your script: 1. Start a WebSocket Server: This will handle connections from your frontend.
Copy code
import 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.
Copy code
@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!
s
couldn't i just have shared the metrics that are already being collected by livekit that I am showing on the backend and just showed them on the frontend itself
t
Absolutely! You can definitely share the metrics that LiveKit is already collecting and showing on the backend with your frontend. The easiest way to do this is by setting up an HTTP API endpoint on your backend that serves the metrics data, and then fetching this data from your Next.js frontend. Here’s a simple walkthrough: 1. Add an HTTP API to Your Backend:
Copy code
from 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:
s
repeat
t
Absolutely, you can share the metrics that LiveKit is already collecting and showing on the backend with your frontend. Here’s a friendly way to do it: you’ll create an HTTP API endpoint on your backend to serve up those metrics, and then your Next.js frontend can fetch that data. Let me walk you through it: 1. Add an HTTP API to Your Backend:
Copy code
from 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:
s
your Fetch Metrics in Your Next.js Frontend step isnt loading
t
Hey there! If the "Fetch Metrics in Your Next.js Frontend" step isn't loading, no worries—here are some friendly troubleshooting tips to help get things working: 1. Double-check your Backend API: Make sure your backend API is up and running. You can test it by popping
<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:
Copy code
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:
s
i meant, your reply containing 2nd step for 2. Fetch Metrics in Your Next.js Frontend: isn't showing anything, it is empty
t
Thanks so much for catching that! Here’s the updated step to fetch metrics in your Next.js frontend: 2. Fetch Metrics in Your Next.js Frontend:
s
still nothing
t
If the frontend still isn’t showing anything, no worries! Let’s walk through a quick checklist together to figure out what’s going on: 1. Verify Backend API: Try opening your browser or using a tool like Postman to visit
<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:
Copy code
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: