Building a Zero-Latency Voice Agent: WebSockets, Local Whisper, and Ollama in Python

Building a Zero-Latency Voice Agent: WebSockets, Local Whisper, and Ollama in Python

Leader ●1 ●4 ●8
calendar_today • schedule7 min read

Building a Zero-Latency Voice Agent: WebSockets, Local Whisper, and Ollama in Python

Most voice AI architectures rely on third-party managed APIs chained together over standard HTTPS REST endpoints. The typical sequence is familiar: record client audio, ship an HTTP POST to a cloud Speech-to-Text (STT) endpoint, wait for text, POST that prompt to a proprietary LLM API, wait for a completion token stream, and finally POST that text to a Text-to-Speech (TTS) cloud service.

By the time the audio packet bounces across three external vendors, network round-trip overhead and serialization latency guarantee a delay of anywhere from 1,800ms to 3,500ms. In conversational audio, anything over 600ms breaks conversational pacing and feels robotic.

To build responsive, deterministic voice infrastructure, you need three core elements:

  1. Persistent full-duplex transport (bi-directional WebSockets) to avoid connection renegotiation overhead.
  2. Local, in-memory model execution using quantized weights on GPU/VRAM to eliminate external network hops.
  3. Speculative pipelined execution, running transcription concurrently alongside turn-taking detection rather than buffering full silence blocks sequentially.

Here is a complete, production-grade guide to building a self-hosted, streaming voice-to-voice agent backend using Python, faster-whisper, ollama, and native in-memory piper-tts.


Architecture Overview

[ Client / Browser / SIP Bridge ]
        │ Audio Stream (PCM 16-bit 16kHz via WebSocket)
        ▼
[ Python Async Engine ]
   ├── Voice Activity Detection (Silero VAD)
   ├── Speculative STT (faster-whisper on CUDA / CTranslate2 via ThreadPool)
   ├── Inference Queue (Async Ollama streaming generation)
   └── Fast Audio Synthesis (Piper In-Memory ONNX)
        │
        ▼ Audio Output Stream (Raw PCM over WebSocket)
[ Client Playback / Telephony Host ]


1. Environment & Dependency Setup

Ensure you have your CUDA environment configured (CUDA 12.x recommended).

Install the core libraries:

pip install fastapi uvicorn websockets faster-whisper ollama torch torchaudio numpy piper-tts

Download a Piper voice model and its corresponding config JSON (for example, the Lessac medium-quality voice):

wget https://huggingface.co/rhasspy/piper-voices/resolve/main/en/en_US/lessac/medium/en_US-lessac-medium.onnx
wget https://huggingface.co/rhasspy/piper-voices/resolve/main/en/en_US/lessac/medium/en_US-lessac-medium.onnx.json

Make sure your local Ollama daemon is running with an instruction-tuned model loaded:

ollama run mistral-nemo


2. Low-Latency Voice Activity Detection (VAD)

Before feeding audio frames to the Whisper transcription pipeline, raw audio must pass through an ultra-lightweight VAD model. This prevents Whisper from hallucinating over room tone, static, or background noise.

Silero VAD operates on tiny 512-sample frames (~32ms chunks at 16kHz) with negligible CPU overhead:

import numpy as np
import torch

class VADDetector:
    def __init__(self, sample_rate: int = 16000, threshold: float = 0.5):
        self.model, _ = torch.hub.load(
            repo_or_dir="snakers4/silero-vad",
            model="silero_vad",
            force_reload=False,
            onnx=False
        )
        self.model.eval()
        self.sample_rate = sample_rate
        self.threshold = threshold

    def is_speech(self, audio_chunk: bytes) -> bool:
        """Evaluates whether raw 16-bit PCM bytes contain human speech."""
        audio_int16 = np.frombuffer(audio_chunk, dtype=np.int16)
        audio_float32 = audio_int16.astype(np.float32) / 32768.0
        tensor = torch.from_numpy(audio_float32)

        with torch.no_grad():
            confidence = self.model(tensor, self.sample_rate).item()
        
        return confidence > self.threshold


3. Direct Streaming Transcription with faster-whisper

Standard openai-whisper running vanilla PyTorch introduces unnecessary memory copying and execution overhead. faster-whisper relies on CTranslate2, a custom inference engine that utilizes 8-bit quantization (int8_float16) to speed up execution by roughly 4x while slashing VRAM footprint.

To avoid memory allocations and filesystem bottlenecks, convert raw PCM directly to a NumPy float32 array rather than wrapping it in an in-memory .wav container:

import numpy as np
from faster_whisper import WhisperModel

class TranscriptionEngine:
    def __init__(self, model_size: str = "base.en", device: str = "cuda", compute_type: str = "float16"):
        # Use 'int8_float16' for lower-memory GPUs (e.g., 4GB-6GB VRAM)
        self.model = WhisperModel(model_size, device=device, compute_type=compute_type)

    def transcribe_pcm(self, pcm_bytes: bytes) -> str:
        """Directly transcribes 16-bit PCM buffer without intermediate WAV wrapping."""
        if not pcm_bytes:
            return ""

        audio_int16 = np.frombuffer(pcm_bytes, dtype=np.int16)
        audio_float32 = audio_int16.astype(np.float32) / 32768.0

        segments, _ = self.model.transcribe(
            audio_float32,
            beam_size=1,        # Greedy decoding for minimal latency
            best_of=1,
            temperature=0.0,
            vad_filter=False    # Pre-filtered by Silero VAD
        )

        return " ".join([segment.text for segment in segments]).strip()


4. Local LLM Streaming via Ollama

When generating conversational responses, never wait for the complete completion to finish. We capture tokens as they exit the LLM stream, aggregate them into phrase chunks (delimited by commas, periods, or question marks), and forward them directly to the TTS engine:

from typing import AsyncGenerator
import ollama

SYSTEM_PROMPT = """You are a high-speed voice assistant. 
Respond tersely, clearly, and conversationally in 1 to 2 sentences maximum. 
Never use markdown, lists, code blocks, or emojis."""

async def stream_llm_response(prompt: str, model: str = "mistral-nemo") -> AsyncGenerator[str, None]:
    client = ollama.AsyncClient()
    
    stream = await client.chat(
        model=model,
        messages=[
            {"role": "system", "content": SYSTEM_PROMPT},
            {"role": "user", "content": prompt}
        ],
        stream=True,
    )

    buffer = ""
    sentence_delimiters = {".", "!", "?", ",", ";"}

    async for chunk in stream:
        token = chunk["message"]["content"]
        buffer += token
        
        # Dispatch sub-clauses to TTS immediately
        if any(punct in token for punct in sentence_delimiters) and len(buffer.strip()) > 15:
            yield buffer.strip()
            buffer = ""

    if buffer.strip():
        yield buffer.strip()


5. Sub-50ms Speech Synthesis with Native Piper

Instead of spawning shell subprocesses with subprocess.Popen—which incurs process initialization latency and reloads the ONNX model from disk on every clause—load the model into memory once using the native PiperVoice bindings:

from piper.voice import PiperVoice

class NativeTTS:
    def __init__(self, model_path: str = "en_US-lessac-medium.onnx"):
        self.voice = PiperVoice.load(model_path)

    def synthesize(self, text: str) -> bytes:
        """Synthesizes raw 16-bit PCM bytes directly from in-memory ONNX session."""
        return self.voice.synthesize_stream_raw(text)


6. The Speculative Async WebSocket Server

In standard voice servers, silence detection is sequential: the server buffers 400ms–800ms of silence, then calls Whisper, and then queries the LLM.

To break below 400ms end-to-end, this implementation uses speculative background transcription. As soon as 2 frames (~64ms) of silence are detected, Whisper begins transcribing an audio snapshot in a background thread. If the user speaks again, the task is discarded. If silence persists to frame 8 (~256ms), the transcript is already done, immediately launching the LLM generation.

import asyncio
from concurrent.futures import ThreadPoolExecutor
from fastapi import FastAPI, WebSocket, WebSocketDisconnect
import uvicorn

app = FastAPI()

# Single-worker thread executor prevents concurrent GPU scheduling clashes
inference_executor = ThreadPoolExecutor(max_workers=1)

vad = VADDetector()
stt = TranscriptionEngine(model_size="base.en", device="cuda", compute_type="float16")
tts = NativeTTS(model_path="en_US-lessac-medium.onnx")

FRAME_SIZE = 1024               # 512 samples @ 16-bit 16kHz = 1024 bytes (32ms)
SILENCE_FRAMES_THRESHOLD = 8    # ~256ms silence window for completion
SPECULATIVE_TRIGGER_FRAME = 2   # Launch background STT at ~64ms of silence

@app.websocket("/ws/voice")
async def voice_endpoint(websocket: WebSocket):
    await websocket.accept()
    loop = asyncio.get_running_loop()
    
    audio_buffer = bytearray()
    silence_counter = 0
    is_speaking = False
    speculative_task: asyncio.Task | None = None

    try:
        while True:
            chunk = await websocket.receive_bytes()
            speech_present = await loop.run_in_executor(None, vad.is_speech, chunk[:FRAME_SIZE])
            
            if speech_present:
                is_speaking = True
                silence_counter = 0
                audio_buffer.extend(chunk)

                # User resumed speaking: invalidate speculative job
                if speculative_task and not speculative_task.done():
                    speculative_task.cancel()
                    speculative_task = None

            elif is_speaking:
                audio_buffer.extend(chunk)
                silence_counter += 1
                
                # Step 1: Speculative transcription trigger
                if silence_counter == SPECULATIVE_TRIGGER_FRAME and speculative_task is None:
                    cutoff = SPECULATIVE_TRIGGER_FRAME * FRAME_SIZE
                    snapshot_bytes = bytes(audio_buffer[:-cutoff]) if len(audio_buffer) > cutoff else bytes(audio_buffer)
                    
                    if len(snapshot_bytes) > FRAME_SIZE * 4:  # Speech > 128ms
                        speculative_task = asyncio.create_task(
                            loop.run_in_executor(inference_executor, stt.transcribe_pcm, snapshot_bytes)
                        )

                # Step 2: Confirmed turn boundary
                if silence_counter > SILENCE_FRAMES_THRESHOLD:
                    user_text = ""

                    if speculative_task:
                        try:
                            user_text = await speculative_task
                        except asyncio.CancelledError:
                            user_text = ""
                        finally:
                            speculative_task = None
                    else:
                        cutoff = SILENCE_FRAMES_THRESHOLD * FRAME_SIZE
                        active_audio = bytes(audio_buffer[:-cutoff]) if len(audio_buffer) > cutoff else bytes(audio_buffer)
                        user_text = await loop.run_in_executor(inference_executor, stt.transcribe_pcm, active_audio)

                    audio_buffer.clear()
                    is_speaking = False
                    silence_counter = 0

                    if not user_text.strip():
                        continue

                    # Step 3: Stream LLM text and synthesize audio chunks concurrently
                    async for text_clause in stream_llm_response(user_text):
                        audio_response_pcm = await loop.run_in_executor(inference_executor, tts.synthesize, text_clause)
                        
                        # Step 4: Stream audio back to client
                        await websocket.send_bytes(audio_response_pcm)

    except WebSocketDisconnect:
        if speculative_task and not speculative_task.done():
            speculative_task.cancel()

if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=8000)


Performance Benchmark

Running this speculative architecture locally on a modern dedicated mid-range GPU (e.g., RTX 3050 Ti Laptop or desktop RTX 3060/4060):

Stage Mechanism Delay Cumulative Timeline
Silence Detection User stops; 2 frames pass 64ms $t = 64\text{ms}$
Speculative STT Whisper runs in parallel with silence 120ms Finishes at $t = 184\text{ms}$
Endpoint Confirmed Frame 8 reached (256ms total silence) 0ms added (STT ready) $t = 256\text{ms}$
First Token (LLM) Ollama mistral-nemo (Q4_K_M) 90ms $t = 346\text{ms}$
First Chunk (TTS) Piper Native in-memory 35ms $t = 381\text{ms}$
Time-to-First-Audio Caller Silence $\to$ Speaker Output — ~380ms

Operational Takeaways

  1. Overlap Endpointing with Inference: Do not wait for silence confirmation to start transcribing. Speculatively transcribing audio as soon as a pause begins masks 100% of Whisper's latency behind the user's natural conversational gap.
  2. Keep Models In-Memory: Avoid invoking command-line binaries via subprocess.Popen in the request path. Persistent native ONNX sessions eliminate repeated runtime initialization and file descriptor overhead.
  3. Pipeline Clauses Immediately: Never wait for the complete LLM response string before kicking off TTS. Splitting output tokens on punctuation boundary rules drops perceived Time-To-First-Audio (TTFA) by over 60%.
  4. Buffer Raw PCM: Avoid sending compressed WebM or MP3 over local WebSockets. Transmitting uncompressed 16-bit 16kHz PCM avoids encoder spin-up overhead and keeps thread utilization low.
  5. Control Prompt Entropy: Force your local LLM system prompt to prohibit lists, backticks, and markdown formatting. TTS engines trip over unpronounceable characters, creating jarring synthetic audio bugs.

Want more #python deep dives?

Join 6,013+ developers sharing real benchmarks, code breakdowns, and projects. Free forever.

2 Comments

1 vote
0

More Posts

Dashboard Operasional Armada Rental Mobil dengan Python + FastAPI

Masbadar - Mar 12

The Zero-Net-Loss Fleet & The Mercenary Squad: A Live AI Economy

DEVPlank - Aug 4

When One Python Process Fails, You Need to See All of Them

Tom Smithverified - Nov 23

Local-First: The Browser as the Vault

Pocket Portfolio - Apr 20

Python for commerce students, from a former bio kid

rahuldk1105 - Oct 30
chevron_left
1.6k Points • 13 Badges
canada • prophetdice.tech
3Posts
8Comments
4Connections
Senior full-stack engineer and open-source contributor with 20 years in the trenches building scalab... Show more

Related Jobs

Commenters (This Week)

5 comments
1 comment

Contribute meaningful comments to climb the leaderboard and earn badges!