Blog

How to measure the latency of your Voice AI stack

How to measure the latency of your Voice AI stack

How to measure the latency of your Voice AI stack

When a voice agent feels slow, the first number most teams look at is end-to-end latency: the time between the user finishing a sentence and the agent starting to answer. That number tells you there is a problem. It does not tell you where.

This tutorial gives you a repeatable way to split that number into stages. You will build a small Python harness that replays a recording in real time, streams it to a speaker diarization model and a speech-to-text model at the same time, and logs every event against one audio clock. At the end, you will have p50 and p95 latency per stage, and a clear view of where speaker intelligence sits in your latency budget. It is written for teams building voice agents, live transcription, and agent-assist tools, who need to know which stage to fix when users say the product feels slow.

The examples use Live-1, pyannoteAI's streaming diarization model, and Deepgram for streaming ASR. The method works with any streaming provider.

Why one end-to-end number misleads

A voice app that "takes 1.2 seconds" can spend that time in at least five places: capturing and buffering audio, sending it over the network, transcribing it, generating a reply with an LLM, and turning that reply into speech. The fixes have nothing in common. A slow capture stage needs smaller buffers. A slow ASR stage may need to act on partial transcripts instead of finals. A slow LLM stage needs a shorter prompt, a smaller model or streamed output. A slow TTS stage needs a provider that starts speaking sooner.

Averages also hide the calls users remember. A comfortable median can sit next to a p95 that is several times higher, and the p95 calls are the ones that get described as broken. Before optimising anything, split the number by stage and look at the tail.

The metrics that matter

Measure each of these as a delay from a point on the audio timeline:

Metric

Starts at

Ends at

Time to first partial transcript

Start of speech

First interim ASR result

Time to final transcript

End of an utterance

Final ASR result for that utterance

Time to first speaker label

Start of a speaker turn

The diarization_speaker_start event

LLM time to first token

Prompt sent

First token received

TTS time to first audio

Text sent

First audio byte received

Turn latency

End of user speech

First audio of the reply played

Report each one as p50 and p95, and measure under the concurrency you run in production. A provider that answers quickly with one open stream can behave very differently with fifty.

Use one clock

Every stage reports time in its own way. Your ASR provider gives word timestamps relative to the start of its session. Live-1 gives speaker timestamps relative to the start of its stream. Your application logs use wall-clock time. Compare them directly, and most of what you see is noise.

Pick one reference, audio time measured from the first sample you capture, and convert everything to it. Record when each event arrives on a monotonic clock started at that same moment. The latency of an event is then simply its arrival time minus the audio time it refers to.

Small offsets matter. Suppose your diarization session starts 40 ms before your ASR session and nothing corrects for it. Every word timestamp is now 40 ms off relative to the speaker timeline. Most words still land in the right turn, but words near a turn boundary, which is exactly where fast exchanges and interruptions happen, get assigned to the previous speaker. The latency numbers look fine, and the attribution is wrong.

The simplest fix is structural: open both connections first, then send the same chunk to both at the same moment, starting from the first chunk. Both sessions then start their clocks on the same audio sample. The harness below does this.

Instrument each stage

Capture and network. Microphone buffers, jitter buffers, and network hops each add a fixed delay before any model hears the audio. Log the moment each chunk leaves your process.

Streaming diarization with Live-1. You create a session with POST <https://api.pyannote.ai/v1/live>, which returns a single-use WebSocket URL. You send 16 kHz mono audio as float32 PCM in 100 ms chunks, at real-time pace: the server keeps at most a 5-second buffer and closes connections that send audio faster than real time. Live-1 replies with two events, diarization_speaker_start and diarization_speaker_endeach carrying a speaker label and a timestamp in seconds from the start of the stream. If you enable heartbeats when you create the session, Live-1 also sends a heartbeat event with last_predicted_timestamp, the point up to which diarization is complete. That field is the most direct measure of how far behind live the speaker timeline runs.

Streaming ASR. Log both partial and final results, with the audio position each one covers. For Deepgram, that is start + duration on every result.

LLM and TTS. These are request and response stages. Time from the request to the first token or first audio byte, not to the end of the response.

One structural point before the code: diarization and ASR both work on the raw audio, and neither needs the other's output. Run them side by side on the same stream, not one after the other. We cover the full architecture in Designing a speaker-aware Voice AI pipeline.

Build the timing harness

The script below replays a WAV file in real time in 100 ms chunks, sends each chunk to Live-1 and to Deepgram at the same moment, and logs every event with its audio time and arrival time. It then prints p50 and p95 lag per event type and writes every event to latency_events.csv.

Each chunk is sent once its audio has been "spoken": the chunk that covers 0.0 to 0.1 s goes out at 0.1 s. This is how a microphone behaves, so the measured lag includes the 100 ms chunking delay, as it does in production.

# /// script
# requires-python = ">=3.10"
# dependencies = ["numpy", "requests", "websockets>=13"]
# ///
"""Measure per-stage latency for streaming diarization (pyannoteAI Live-1)
and streaming ASR (Deepgram) on the same audio, against one audio clock.

Usage:
    PYANNOTE_API_KEY=... DEEPGRAM_API_KEY=... uv run latency_harness.py call.wav

The WAV file must be 16 kHz, mono, 16-bit PCM.
"""
import asyncio
import csv
import json
import os
import sys
import time
import wave
from dataclasses import dataclass

import numpy as np
import requests
from websockets.asyncio.client import connect

SAMPLE_RATE = 16_000
CHUNK_SECONDS = 0.1
CHUNK_SAMPLES = int(SAMPLE_RATE * CHUNK_SECONDS)  # 1,600 samples

DEEPGRAM_URL = (
    "wss://api.deepgram.com/v1/listen?model=nova-3&encoding=linear16"
    "&sample_rate=16000&channels=1&interim_results=true"
)

@dataclass
class Event:
    stream: str        # "diarization" or "asr"
    kind: str          # "speaker_start", "speaker_end", "heartbeat", "partial", "final"
    audio_time: float  # seconds on the audio clock
    arrival: float     # seconds since the first chunk was captured
    detail: str = ""

    @property
    def lag(self) -> float:
        return self.arrival - self.audio_time

events: list[Event] = []
t0: float | None = None  # monotonic time of the first captured sample

def now() -> float:
    return time.monotonic() - t0

def load_chunks(path: str) -> list[tuple[bytes, bytes]]:
    """Split a WAV file into 100 ms chunks, as int16 (for ASR) and float32 (for Live-1)."""
    with wave.open(path, "rb") as wav:
        if (wav.getframerate(), wav.getnchannels(), wav.getsampwidth()) != (SAMPLE_RATE, 1, 2):
            sys.exit("Expected a 16 kHz, mono, 16-bit WAV file")
        pcm = np.frombuffer(wav.readframes(wav.getnframes()), dtype="<i2")
    chunks = []
    for start in range(0, len(pcm) - CHUNK_SAMPLES + 1, CHUNK_SAMPLES):
        chunk = pcm[start:start + CHUNK_SAMPLES]
        chunks.append((chunk.tobytes(), (chunk / 32768.0).astype("<f4").tobytes()))
    return chunks

def create_live_session() -> str:
    """Create a Live-1 stream with heartbeats every 500 ms, return its WebSocket URL."""
    response = requests.post(
        "<https://api.pyannote.ai/v1/live>",
        headers={"Authorization": f"Bearer {os.environ['PYANNOTE_API_KEY']}"},
        json={"heartbeat": {"enabled": True, "interval": 500}},
        timeout=30,
    )
    response.raise_for_status()
    return response.json()["url"]

async def send_audio(chunks, pyannote_ws, deepgram_ws) -> None:
    """Replay the file in real time and fan each chunk out to both streams."""
    global t0
    t0 = time.monotonic()
    for i, (pcm_i16, pcm_f32) in enumerate(chunks):
        # Chunk i holds audio from i*0.1 s to (i+1)*0.1 s. A microphone only has it
        # once that audio has been spoken, so send it at (i+1)*0.1 s on the audio clock.
        delay = (i + 1) * CHUNK_SECONDS - now()
        if delay > 0:
            await asyncio.sleep(delay)
        await asyncio.gather(pyannote_ws.send(pcm_f32), deepgram_ws.send(pcm_i16))
    await pyannote_ws.send(json.dumps({"type": "end_of_stream"}))
    await deepgram_ws.send(json.dumps({"type": "CloseStream"}))

async def read_diarization(ws) -> None:
    async for message in ws:
        if t0 is None or isinstance(message, bytes):
            continue
        msg = json.loads(message)
        kind = msg.get("type")
        if kind in ("diarization_speaker_start", "diarization_speaker_end"):
            data = msg["data"]
            events.append(Event("diarization", kind.removeprefix("diarization_"),
                                data["timestamp"], now(), data["speaker"]))
        elif kind == "heartbeat":
            events.append(Event("diarization", "heartbeat",
                                msg["data"]["last_predicted_timestamp"], now()))
        elif kind == "error":
            print("pyannoteAI error:", msg.get("message"))

async def read_asr(ws) -> None:
    async for message in ws:
        if t0 is None:
            continue
        msg = json.loads(message)
        if msg.get("type") != "Results":
            continue
        transcript = msg["channel"]["alternatives"][0]["transcript"]
        if not transcript:
            continue
        audio_end = msg["start"] + msg["duration"]
        kind = "final" if msg["is_final"] else "partial"
        events.append(Event("asr", kind, audio_end, now(), transcript))

def ms(values: list[float], q: float) -> float:
    return float(np.percentile(values, q)) * 1000 if values else float("nan")

def report() -> None:
    print(f"\n{'stage':<28}{'n':>6}{'p50 ms':>10}{'p95 ms':>10}")
    for stream, kind in [("diarization", "speaker_start"), ("diarization", "speaker_end"),
                         ("diarization", "heartbeat"), ("asr", "partial"), ("asr", "final")]:
        lags = [e.lag for e in events if e.stream == stream and e.kind == kind]
        print(f"{stream + ' ' + kind:<28}{len(lags):>6}{ms(lags, 50):>10.0f}{ms(lags, 95):>10.0f}")

    # For each new speaker turn: did the label or the first words arrive first?
    deltas = []
    for start in (e for e in events if e.kind == "speaker_start"):
        words = [e.arrival for e in events if e.stream == "asr" and e.audio_time > start.audio_time]
        if words:
            deltas.append(min(words) - start.arrival)
    if deltas:
        print(f"\nfirst words minus first label, per turn: "
              f"p50 {ms(deltas, 50):.0f} ms, p95 {ms(deltas, 95):.0f} ms "
              "(positive: the speaker label arrived first)")

    with open("latency_events.csv", "w", newline="") as f:
        writer = csv.writer(f)
        writer.writerow(["stream", "kind", "audio_time", "arrival", "lag", "detail"])
        for e in events:
            writer.writerow([e.stream, e.kind, f"{e.audio_time:.3f}", f"{e.arrival:.3f}",
                             f"{e.lag:.3f}", e.detail])

async def main(path: str) -> None:
    chunks = load_chunks(path)

    started = time.monotonic()
    live_url = await asyncio.to_thread(create_live_session)
    async with connect(live_url) as pyannote_ws, connect(
        DEEPGRAM_URL,
        additional_headers={"Authorization": f"Token {os.environ['DEEPGRAM_API_KEY']}"},
    ) as deepgram_ws:
        print(f"sessions ready after {(time.monotonic() - started) * 1000:.0f} ms")
        readers = [asyncio.create_task(read_diarization(pyannote_ws)),
                   asyncio.create_task(read_asr(deepgram_ws))]
        await send_audio(chunks, pyannote_ws, deepgram_ws)
        try:
            await asyncio.wait_for(asyncio.gather(*readers), timeout=30)
        except asyncio.TimeoutError:
            print("Timed out waiting for the last events")
    report()

if __name__ == "__main__":
    asyncio.run(main(sys.argv[1]))
# /// script
# requires-python = ">=3.10"
# dependencies = ["numpy", "requests", "websockets>=13"]
# ///
"""Measure per-stage latency for streaming diarization (pyannoteAI Live-1)
and streaming ASR (Deepgram) on the same audio, against one audio clock.

Usage:
    PYANNOTE_API_KEY=... DEEPGRAM_API_KEY=... uv run latency_harness.py call.wav

The WAV file must be 16 kHz, mono, 16-bit PCM.
"""
import asyncio
import csv
import json
import os
import sys
import time
import wave
from dataclasses import dataclass

import numpy as np
import requests
from websockets.asyncio.client import connect

SAMPLE_RATE = 16_000
CHUNK_SECONDS = 0.1
CHUNK_SAMPLES = int(SAMPLE_RATE * CHUNK_SECONDS)  # 1,600 samples

DEEPGRAM_URL = (
    "wss://api.deepgram.com/v1/listen?model=nova-3&encoding=linear16"
    "&sample_rate=16000&channels=1&interim_results=true"
)

@dataclass
class Event:
    stream: str        # "diarization" or "asr"
    kind: str          # "speaker_start", "speaker_end", "heartbeat", "partial", "final"
    audio_time: float  # seconds on the audio clock
    arrival: float     # seconds since the first chunk was captured
    detail: str = ""

    @property
    def lag(self) -> float:
        return self.arrival - self.audio_time

events: list[Event] = []
t0: float | None = None  # monotonic time of the first captured sample

def now() -> float:
    return time.monotonic() - t0

def load_chunks(path: str) -> list[tuple[bytes, bytes]]:
    """Split a WAV file into 100 ms chunks, as int16 (for ASR) and float32 (for Live-1)."""
    with wave.open(path, "rb") as wav:
        if (wav.getframerate(), wav.getnchannels(), wav.getsampwidth()) != (SAMPLE_RATE, 1, 2):
            sys.exit("Expected a 16 kHz, mono, 16-bit WAV file")
        pcm = np.frombuffer(wav.readframes(wav.getnframes()), dtype="<i2")
    chunks = []
    for start in range(0, len(pcm) - CHUNK_SAMPLES + 1, CHUNK_SAMPLES):
        chunk = pcm[start:start + CHUNK_SAMPLES]
        chunks.append((chunk.tobytes(), (chunk / 32768.0).astype("<f4").tobytes()))
    return chunks

def create_live_session() -> str:
    """Create a Live-1 stream with heartbeats every 500 ms, return its WebSocket URL."""
    response = requests.post(
        "<https://api.pyannote.ai/v1/live>",
        headers={"Authorization": f"Bearer {os.environ['PYANNOTE_API_KEY']}"},
        json={"heartbeat": {"enabled": True, "interval": 500}},
        timeout=30,
    )
    response.raise_for_status()
    return response.json()["url"]

async def send_audio(chunks, pyannote_ws, deepgram_ws) -> None:
    """Replay the file in real time and fan each chunk out to both streams."""
    global t0
    t0 = time.monotonic()
    for i, (pcm_i16, pcm_f32) in enumerate(chunks):
        # Chunk i holds audio from i*0.1 s to (i+1)*0.1 s. A microphone only has it
        # once that audio has been spoken, so send it at (i+1)*0.1 s on the audio clock.
        delay = (i + 1) * CHUNK_SECONDS - now()
        if delay > 0:
            await asyncio.sleep(delay)
        await asyncio.gather(pyannote_ws.send(pcm_f32), deepgram_ws.send(pcm_i16))
    await pyannote_ws.send(json.dumps({"type": "end_of_stream"}))
    await deepgram_ws.send(json.dumps({"type": "CloseStream"}))

async def read_diarization(ws) -> None:
    async for message in ws:
        if t0 is None or isinstance(message, bytes):
            continue
        msg = json.loads(message)
        kind = msg.get("type")
        if kind in ("diarization_speaker_start", "diarization_speaker_end"):
            data = msg["data"]
            events.append(Event("diarization", kind.removeprefix("diarization_"),
                                data["timestamp"], now(), data["speaker"]))
        elif kind == "heartbeat":
            events.append(Event("diarization", "heartbeat",
                                msg["data"]["last_predicted_timestamp"], now()))
        elif kind == "error":
            print("pyannoteAI error:", msg.get("message"))

async def read_asr(ws) -> None:
    async for message in ws:
        if t0 is None:
            continue
        msg = json.loads(message)
        if msg.get("type") != "Results":
            continue
        transcript = msg["channel"]["alternatives"][0]["transcript"]
        if not transcript:
            continue
        audio_end = msg["start"] + msg["duration"]
        kind = "final" if msg["is_final"] else "partial"
        events.append(Event("asr", kind, audio_end, now(), transcript))

def ms(values: list[float], q: float) -> float:
    return float(np.percentile(values, q)) * 1000 if values else float("nan")

def report() -> None:
    print(f"\n{'stage':<28}{'n':>6}{'p50 ms':>10}{'p95 ms':>10}")
    for stream, kind in [("diarization", "speaker_start"), ("diarization", "speaker_end"),
                         ("diarization", "heartbeat"), ("asr", "partial"), ("asr", "final")]:
        lags = [e.lag for e in events if e.stream == stream and e.kind == kind]
        print(f"{stream + ' ' + kind:<28}{len(lags):>6}{ms(lags, 50):>10.0f}{ms(lags, 95):>10.0f}")

    # For each new speaker turn: did the label or the first words arrive first?
    deltas = []
    for start in (e for e in events if e.kind == "speaker_start"):
        words = [e.arrival for e in events if e.stream == "asr" and e.audio_time > start.audio_time]
        if words:
            deltas.append(min(words) - start.arrival)
    if deltas:
        print(f"\nfirst words minus first label, per turn: "
              f"p50 {ms(deltas, 50):.0f} ms, p95 {ms(deltas, 95):.0f} ms "
              "(positive: the speaker label arrived first)")

    with open("latency_events.csv", "w", newline="") as f:
        writer = csv.writer(f)
        writer.writerow(["stream", "kind", "audio_time", "arrival", "lag", "detail"])
        for e in events:
            writer.writerow([e.stream, e.kind, f"{e.audio_time:.3f}", f"{e.arrival:.3f}",
                             f"{e.lag:.3f}", e.detail])

async def main(path: str) -> None:
    chunks = load_chunks(path)

    started = time.monotonic()
    live_url = await asyncio.to_thread(create_live_session)
    async with connect(live_url) as pyannote_ws, connect(
        DEEPGRAM_URL,
        additional_headers={"Authorization": f"Token {os.environ['DEEPGRAM_API_KEY']}"},
    ) as deepgram_ws:
        print(f"sessions ready after {(time.monotonic() - started) * 1000:.0f} ms")
        readers = [asyncio.create_task(read_diarization(pyannote_ws)),
                   asyncio.create_task(read_asr(deepgram_ws))]
        await send_audio(chunks, pyannote_ws, deepgram_ws)
        try:
            await asyncio.wait_for(asyncio.gather(*readers), timeout=30)
        except asyncio.TimeoutError:
            print("Timed out waiting for the last events")
    report()

if __name__ == "__main__":
    asyncio.run(main(sys.argv[1]))
# /// script
# requires-python = ">=3.10"
# dependencies = ["numpy", "requests", "websockets>=13"]
# ///
"""Measure per-stage latency for streaming diarization (pyannoteAI Live-1)
and streaming ASR (Deepgram) on the same audio, against one audio clock.

Usage:
    PYANNOTE_API_KEY=... DEEPGRAM_API_KEY=... uv run latency_harness.py call.wav

The WAV file must be 16 kHz, mono, 16-bit PCM.
"""
import asyncio
import csv
import json
import os
import sys
import time
import wave
from dataclasses import dataclass

import numpy as np
import requests
from websockets.asyncio.client import connect

SAMPLE_RATE = 16_000
CHUNK_SECONDS = 0.1
CHUNK_SAMPLES = int(SAMPLE_RATE * CHUNK_SECONDS)  # 1,600 samples

DEEPGRAM_URL = (
    "wss://api.deepgram.com/v1/listen?model=nova-3&encoding=linear16"
    "&sample_rate=16000&channels=1&interim_results=true"
)

@dataclass
class Event:
    stream: str        # "diarization" or "asr"
    kind: str          # "speaker_start", "speaker_end", "heartbeat", "partial", "final"
    audio_time: float  # seconds on the audio clock
    arrival: float     # seconds since the first chunk was captured
    detail: str = ""

    @property
    def lag(self) -> float:
        return self.arrival - self.audio_time

events: list[Event] = []
t0: float | None = None  # monotonic time of the first captured sample

def now() -> float:
    return time.monotonic() - t0

def load_chunks(path: str) -> list[tuple[bytes, bytes]]:
    """Split a WAV file into 100 ms chunks, as int16 (for ASR) and float32 (for Live-1)."""
    with wave.open(path, "rb") as wav:
        if (wav.getframerate(), wav.getnchannels(), wav.getsampwidth()) != (SAMPLE_RATE, 1, 2):
            sys.exit("Expected a 16 kHz, mono, 16-bit WAV file")
        pcm = np.frombuffer(wav.readframes(wav.getnframes()), dtype="<i2")
    chunks = []
    for start in range(0, len(pcm) - CHUNK_SAMPLES + 1, CHUNK_SAMPLES):
        chunk = pcm[start:start + CHUNK_SAMPLES]
        chunks.append((chunk.tobytes(), (chunk / 32768.0).astype("<f4").tobytes()))
    return chunks

def create_live_session() -> str:
    """Create a Live-1 stream with heartbeats every 500 ms, return its WebSocket URL."""
    response = requests.post(
        "<https://api.pyannote.ai/v1/live>",
        headers={"Authorization": f"Bearer {os.environ['PYANNOTE_API_KEY']}"},
        json={"heartbeat": {"enabled": True, "interval": 500}},
        timeout=30,
    )
    response.raise_for_status()
    return response.json()["url"]

async def send_audio(chunks, pyannote_ws, deepgram_ws) -> None:
    """Replay the file in real time and fan each chunk out to both streams."""
    global t0
    t0 = time.monotonic()
    for i, (pcm_i16, pcm_f32) in enumerate(chunks):
        # Chunk i holds audio from i*0.1 s to (i+1)*0.1 s. A microphone only has it
        # once that audio has been spoken, so send it at (i+1)*0.1 s on the audio clock.
        delay = (i + 1) * CHUNK_SECONDS - now()
        if delay > 0:
            await asyncio.sleep(delay)
        await asyncio.gather(pyannote_ws.send(pcm_f32), deepgram_ws.send(pcm_i16))
    await pyannote_ws.send(json.dumps({"type": "end_of_stream"}))
    await deepgram_ws.send(json.dumps({"type": "CloseStream"}))

async def read_diarization(ws) -> None:
    async for message in ws:
        if t0 is None or isinstance(message, bytes):
            continue
        msg = json.loads(message)
        kind = msg.get("type")
        if kind in ("diarization_speaker_start", "diarization_speaker_end"):
            data = msg["data"]
            events.append(Event("diarization", kind.removeprefix("diarization_"),
                                data["timestamp"], now(), data["speaker"]))
        elif kind == "heartbeat":
            events.append(Event("diarization", "heartbeat",
                                msg["data"]["last_predicted_timestamp"], now()))
        elif kind == "error":
            print("pyannoteAI error:", msg.get("message"))

async def read_asr(ws) -> None:
    async for message in ws:
        if t0 is None:
            continue
        msg = json.loads(message)
        if msg.get("type") != "Results":
            continue
        transcript = msg["channel"]["alternatives"][0]["transcript"]
        if not transcript:
            continue
        audio_end = msg["start"] + msg["duration"]
        kind = "final" if msg["is_final"] else "partial"
        events.append(Event("asr", kind, audio_end, now(), transcript))

def ms(values: list[float], q: float) -> float:
    return float(np.percentile(values, q)) * 1000 if values else float("nan")

def report() -> None:
    print(f"\n{'stage':<28}{'n':>6}{'p50 ms':>10}{'p95 ms':>10}")
    for stream, kind in [("diarization", "speaker_start"), ("diarization", "speaker_end"),
                         ("diarization", "heartbeat"), ("asr", "partial"), ("asr", "final")]:
        lags = [e.lag for e in events if e.stream == stream and e.kind == kind]
        print(f"{stream + ' ' + kind:<28}{len(lags):>6}{ms(lags, 50):>10.0f}{ms(lags, 95):>10.0f}")

    # For each new speaker turn: did the label or the first words arrive first?
    deltas = []
    for start in (e for e in events if e.kind == "speaker_start"):
        words = [e.arrival for e in events if e.stream == "asr" and e.audio_time > start.audio_time]
        if words:
            deltas.append(min(words) - start.arrival)
    if deltas:
        print(f"\nfirst words minus first label, per turn: "
              f"p50 {ms(deltas, 50):.0f} ms, p95 {ms(deltas, 95):.0f} ms "
              "(positive: the speaker label arrived first)")

    with open("latency_events.csv", "w", newline="") as f:
        writer = csv.writer(f)
        writer.writerow(["stream", "kind", "audio_time", "arrival", "lag", "detail"])
        for e in events:
            writer.writerow([e.stream, e.kind, f"{e.audio_time:.3f}", f"{e.arrival:.3f}",
                             f"{e.lag:.3f}", e.detail])

async def main(path: str) -> None:
    chunks = load_chunks(path)

    started = time.monotonic()
    live_url = await asyncio.to_thread(create_live_session)
    async with connect(live_url) as pyannote_ws, connect(
        DEEPGRAM_URL,
        additional_headers={"Authorization": f"Token {os.environ['DEEPGRAM_API_KEY']}"},
    ) as deepgram_ws:
        print(f"sessions ready after {(time.monotonic() - started) * 1000:.0f} ms")
        readers = [asyncio.create_task(read_diarization(pyannote_ws)),
                   asyncio.create_task(read_asr(deepgram_ws))]
        await send_audio(chunks, pyannote_ws, deepgram_ws)
        try:
            await asyncio.wait_for(asyncio.gather(*readers), timeout=30)
        except asyncio.TimeoutError:
            print("Timed out waiting for the last events")
    report()

if __name__ == "__main__":
    asyncio.run(main(sys.argv[1]))

Run it with your two API keys and a 16 kHz mono WAV file:

PYANNOTE_API_KEY=... DEEPGRAM_API_KEY=... uv run latency_harness.py call.wav
PYANNOTE_API_KEY=... DEEPGRAM_API_KEY=... uv run latency_harness.py call.wav
PYANNOTE_API_KEY=... DEEPGRAM_API_KEY=... uv run latency_harness.py call.wav

The harness covers the two streaming stages. To add the LLM and TTS stages, wrap any streamed response with a timer that records when the first item arrives:

async def time_to_first(label, stream):
    start = time.monotonic()
    first = True
    async for item in stream:
        if first:
            print(f"{label} time to first output: {(time.monotonic() - start) * 1000:.0f} ms")
            first = False
        yield item

# async for token in time_to_first("LLM", llm_stream):
# async for audio in time_to_first("TTS", tts_stream):
async def time_to_first(label, stream):
    start = time.monotonic()
    first = True
    async for item in stream:
        if first:
            print(f"{label} time to first output: {(time.monotonic() - start) * 1000:.0f} ms")
            first = False
        yield item

# async for token in time_to_first("LLM", llm_stream):
# async for audio in time_to_first("TTS", tts_stream):
async def time_to_first(label, stream):
    start = time.monotonic()
    first = True
    async for item in stream:
        if first:
            print(f"{label} time to first output: {(time.monotonic() - start) * 1000:.0f} ms")
            first = False
        yield item

# async for token in time_to_first("LLM", llm_stream):
# async for audio in time_to_first("TTS", tts_stream):

Turn latency uses the same audio clock: take the speaker_end timestamp of the user's turn, and subtract it from the moment the first byte of reply audio is played, measured with now().

Read the results

Use a recording of at least a few minutes with real turn-taking, and run it more than once. The script prints a table like this one:

Stage

p50

p95

diarization speaker_start

[from your run]

[from your run]

diarization speaker_end

[from your run]

[from your run]

diarization heartbeat

[from your run]

[from your run]

asr partial

[from your run]

[from your run]

asr final

[from your run]

[from your run]

first words minus first label

[from your run]

[from your run]

How to read each row:

  • speaker_start is the time to the first speaker label: the delay between a turn starting in the audio and Live-1 reporting it. It includes the 100 ms chunk.

  • speaker_end is larger by design. A turn can only be declared over once some silence has followed it, so this row is closer to an endpointing delay than a processing delay.

  • heartbeat shows how far behind live the speaker timeline runs at any moment, independent of when turns happen.

  • ASR partial and ASR final are time to first partial and time to final transcript.

  • first words minus first label compares the two streams turn by turn. A positive value means the speaker label arrived before the first words of that turn.

To see a single turn as a waterfall, open latency_events.csv and plot the events for one turn on the audio clock: speech starts, the label arrives, the first partial arrives, the final arrives. Add your LLM and TTS timings after the final, and you have the whole turn.

Parallel versus chained

In a parallel pipeline, the transcript path is capture, ASR, LLM, TTS. Diarization runs next to it and adds nothing to that path. If you chain diarization in front of ASR instead, waiting for a speaker label before sending audio on, the full label delay is added to every transcript.

There is one exception. If your application waits for a confirmed speaker label before acting on a transcript, the extra wait is the part of the label delay that exceeds the transcript delay. The "first words minus first label" row tells you whether that wait exists in your setup.

Measured this way, speaker intelligence does not slow the transcript down: it only adds to your voice AI stack, with signals that text cannot provide. Talk time, interruptions, and silences come straight from the speaker timeline, before a single word is transcribed. Bluejay, which tests and monitors voice agents, measures agent reaction time and interruptions from pyannoteAI timestamps rather than STT timestamps for this reason. And because speaker intelligence follows the flow of the voice rather than the words, these signals do not depend on the language, which matters most in conversations that are not in English. Notta, a meeting platform widely used in Japan with transcription in 58 languages, uses pyannoteAI to attribute speakers in conversations where short backchannels are frequent.

Common culprits

  • Oversized chunks: A 500 ms chunk adds up to 500 ms before any model hears the start of speech. Live-1 works on 100 ms chunks.

  • Jitter buffers sized for the worst network: A buffer large enough for the worst connection adds that delay to every call. Size it from measured jitter, not from the worst case.

  • Waiting for final transcripts when partials would do: Many replies can start preparing on stable partials while the final is still forming.

  • The LLM stage dominates: It is usually the largest stage. Stream its output, keep prompts short, and compute anything you can get from the speaker timeline, such as talk time or interruptions, outside the LLM.

  • Cold starts under load: The first connection to a service is often slower than the rest. Live-1's documentation notes that cold starts can delay the WebSocket connection by a few seconds, so open sessions before the user starts speaking. The harness prints session setup time separately for this reason.

Getting started

Run the harness on your own recordings, then repeat it at the concurrency you expect in production. Live-1 allows 10 concurrent streams per team, so plan your load test around that. Once you know which stage dominates, our follow-up tutorial, How to build a low-latency Voice AI stack, covers the fixes stage by stage.

To try streaming diarization, start with the streaming tutorial in our documentation, and share your numbers with us on Discord. For why speaker context matters beyond latency, see Why conversational context is the real performance driver for your Voice AI stack.

FAQ

What is a good latency target for a voice agent?

There is no single number, but conversation research gives a reference point: gaps between turns in human conversation are typically around 200 ms. Voice agents rarely reach that end-to-end. Set a budget per stage that adds up to a turn latency your users accept, and track it at p95.

Should I track p50 or p95?

Both. The p50 tells you what a typical turn feels like. The p95 tells you what users complain about. Once the p50 is acceptable, most of the remaining work is on the p95, and it only shows up under realistic load.

Does adding speaker diarization increase latency?

Not when it runs in parallel with ASR on the same audio. It adds delay only if you chain it in front of ASR, or if your application waits for a speaker label that arrives later than the transcript. The "first words minus first label" row shows whether the second case applies to you.

How do I measure the latency of speaker labels specifically?

For each diarization_speaker_start event, subtract its timestamp from its arrival time on the same audio clock. For a continuous view, enable heartbeats and track arrival time minus last_predicted_timestamp.

When is batch enough, and when do I need streaming?

Use batch when nobody needs the result during the conversation: meeting notes after the meeting, call analytics, quality reviews, evaluation. Batch models see the whole recording and are usually more accurate. Use streaming when the product has to act while people are still talking, as voice agents, live captions, and agent-assist tools do.

Speaker Intelligence Platform for developers

Detect, segment, label and separate speakers in any language.

Speaker Intelligence Platform for developers

Detect, segment, label and separate speakers in any language.

Make the most of conversational speech
with AI

Detect, segment, label and separate speakers in any language.