Tutorial
Build a voice agent you can talk to
Stream your microphone to a realtime speech model, call a tool mid-conversation, measure latency and let the user interrupt it.
Bookmark
Bookmarks are kept in your free account, so you can find this page again on any device.
Sign in to bookmarkOn this page
A voice agent listens, thinks and talks back quickly enough that a conversation feels natural, and stops talking when you interrupt it. This tutorial builds one in about 160 lines of Python. Your microphone audio streams over a WebSocket to OpenAI’s Realtime API, a speech-to-speech model decides when you have finished, answers in audio, and calls a tool to look up an order when it needs to. You will measure how long each reply takes to start and handle barge-in, the moment the user talks over the agent.
It follows on from transcribing audio locally with faster-whisper, which turned recordings into text after the fact. Here everything happens while the person is still talking. It was written on 25 November 2026 against gpt-realtime-2.1, websockets 17.4 and sounddevice 0.5.6, with event names checked against OpenAI’s Realtime conversations guide.
Two ways to build a voice agent
| Cascade | Speech-to-speech | |
|---|---|---|
| Pipeline | Speech-to-text, then a text model, then text-to-speech | One model takes audio in and gives audio out |
| Example parts | faster-whisper, any chat model, a TTS voice | OpenAI Realtime API, Gemini Live API |
| Latency | Three stages add up; you can stream each | One stage; usually faster to first audio |
| Control | You see and can edit the text between stages | Less visibility; transcripts are a side output |
| Tone of voice | Lost in transcription | The model hears hesitation and emphasis |
| Swap parts | Any model, any voice, local options | Tied to one provider’s model and voices |
A cascade is easier to debug and can run entirely on your own hardware, which matters for private data. Speech-to-speech is the quickest way to a conversation that feels natural. This tutorial uses speech-to-speech; the last section shows where a cascade fits.
The latency budget
Users judge a voice agent by how long the silence lasts after they stop talking. Every stage between their last word and the agent’s first sound adds to it:
| Stage | What sets it | Your lever |
|---|---|---|
| Microphone chunk | Block size you send (20 ms here) | Smaller blocks, more messages |
| Network to the API | Distance to the provider’s region | Run close to the API; WebRTC for browsers |
| End-of-turn detection | How long the server waits in silence before deciding you finished (silence_duration_ms, 500 ms here) |
Shorter silence, or semantic turn detection |
| Model to first audio | Model size, instructions, tool calls | A smaller model, shorter instructions, fast tools |
| Network back and playback buffer | Distance and your audio device’s buffer | Play chunks as they arrive |
Notice that end-of-turn detection is usually the biggest deliberate delay, and it trades against interrupting people who pause mid-sentence. Set a budget for the whole chain before you tune any one part, measure it on real calls, and spend your effort on the largest stage. The agent below prints the time from the server deciding you stopped to the first audio arriving, which covers the middle three stages.
1. Set up
mkdir voice-agent && cd voice-agent
python3 -m venv .venv && source .venv/bin/activate
pip install websockets==17.4 sounddevice==0.5.6
export OPENAI_API_KEY=sk-...
sounddevice needs the PortAudio library. It is bundled with the macOS and Windows wheels; on Linux, install it from your package manager (sudo apt install libportaudio2 on Debian and Ubuntu). Use headphones: with speakers, the microphone hears the agent and it starts interrupting itself.
2. Configure the session
Create voice_agent.py and start with the configuration. The Realtime API is configured by sending a session.update event after connecting:
"""A voice agent over the OpenAI Realtime API: microphone in, speech out, one tool, barge-in."""
import asyncio
import base64
import json
import os
import threading
import time
import websockets
MODEL = "gpt-realtime-2.1"
URL = f"wss://api.openai.com/v1/realtime?model={MODEL}"
RATE = 24_000 # 24 kHz, 16-bit mono PCM in both directions
BLOCK_MS = 20 # microphone chunk size
BYTES_PER_MS = RATE * 2 // 1000
ORDERS = {"5001": "shipped on 22 November, arriving tomorrow", "5002": "still being packed"}
SESSION = {
"type": "session.update",
"session": {
"type": "realtime",
"model": MODEL,
"output_modalities": ["audio"],
"instructions": (
"You are the voice assistant for a small online shop. Keep answers to one or two short sentences. "
"If the caller asks about an order, ask for the order number, then use get_order_status."
),
"audio": {
"input": {
"format": {"type": "audio/pcm", "rate": RATE},
"turn_detection": {"type": "server_vad", "silence_duration_ms": 500, "prefix_padding_ms": 300},
},
"output": {"format": {"type": "audio/pcm", "rate": RATE}, "voice": "marin"},
},
"tools": [
{
"type": "function",
"name": "get_order_status",
"description": "Look up the delivery status of an order by its four-digit order number.",
"parameters": {
"type": "object",
"properties": {"order_number": {"type": "string", "description": "For example 5001"}},
"required": ["order_number"],
},
}
],
"tool_choice": "auto",
},
}
The parts that matter:
- Audio format. 24 kHz, 16-bit mono PCM in and out, which the guide recommends for PCM. Your microphone and speaker streams must use the same.
- Turn detection.
server_vaddecides you have finished after 500 ms of silence and keeps 300 ms of audio from before you started, so the first word is not clipped. These are the values from OpenAI’s voice activity detection guide. The alternative,semantic_vad, judges from your words whether you have finished, which suits people who pause to think. - Instructions. Short replies matter more in voice than in text: every extra sentence is seconds of audio the user must sit through or interrupt.
- Tools. Defined in the session, as in any tool-calling API. The same design rules apply; design tools an AI agent can use well covers them.
3. Play audio and remember what was heard
When the user interrupts, the server needs to know how much of the reply they actually heard, so it can drop the rest from the conversation. With a WebSocket connection your code plays the audio, so your code must keep count. Add a small player:
class Player:
"""Plays model audio and remembers how much of the current item the user has heard."""
def __init__(self):
self.buf = bytearray()
self.lock = threading.Lock()
self.item_id = None
self.played_bytes = 0
def add(self, item_id: str, pcm: bytes) -> None:
with self.lock:
if item_id != self.item_id:
self.item_id, self.played_bytes = item_id, 0
self.buf.extend(pcm)
def take(self, n: int) -> bytes:
"""Called by the audio device for the next n bytes; pads with silence."""
with self.lock:
chunk = bytes(self.buf[:n])
del self.buf[:n]
self.played_bytes += len(chunk)
return chunk + b"\x00" * (n - len(chunk))
def interrupt(self):
"""Stop at once. Returns (item_id, ms heard) if something was playing."""
with self.lock:
if not self.buf or self.item_id is None:
return None
self.buf.clear()
return self.item_id, self.played_bytes // BYTES_PER_MS
The audio device calls take from its own thread every 20 ms, hence the lock. At 24,000 samples a second and 2 bytes a sample, 48 bytes is one millisecond, which is how interrupt turns bytes played into milliseconds heard.
4. Handle the conversation events
Add the tool and the event loop:
def tool(name: str, args: dict) -> str:
if name == "get_order_status":
status = ORDERS.get(args.get("order_number", "").strip())
return json.dumps({"status": status} if status else {"error": "No order with that number."})
return json.dumps({"error": f"Unknown tool {name}"})
async def run(ws, mic_chunks: asyncio.Queue, player: Player, log=print) -> None:
await ws.send(json.dumps(SESSION))
async def send_mic():
while True:
pcm = await mic_chunks.get()
await ws.send(json.dumps({"type": "input_audio_buffer.append", "audio": base64.b64encode(pcm).decode()}))
sender = asyncio.create_task(send_mic())
user_stopped = None
try:
async for raw in ws:
ev = json.loads(raw)
kind = ev["type"]
if kind == "input_audio_buffer.speech_started":
# Barge-in: the user talks over the agent. Stop playback and tell the server what was heard.
heard = player.interrupt()
if heard:
item_id, ms = heard
await ws.send(json.dumps({"type": "conversation.item.truncate", "item_id": item_id,
"content_index": 0, "audio_end_ms": ms}))
log(f"[interrupted after {ms} ms]")
elif kind == "input_audio_buffer.speech_stopped":
user_stopped = time.monotonic()
elif kind == "response.output_audio.delta":
if user_stopped is not None:
log(f"[first audio {1000 * (time.monotonic() - user_stopped):.0f} ms after you stopped]")
user_stopped = None
player.add(ev["item_id"], base64.b64decode(ev["delta"]))
elif kind == "response.output_audio_transcript.done":
log(f"agent: {ev['transcript']}")
elif kind == "response.done":
for item in ev["response"].get("output", []):
if item.get("type") == "function_call":
result = tool(item["name"], json.loads(item["arguments"]))
log(f"[tool {item['name']}({item['arguments']}) -> {result}]")
await ws.send(json.dumps({"type": "conversation.item.create", "item": {
"type": "function_call_output", "call_id": item["call_id"], "output": result}}))
await ws.send(json.dumps({"type": "response.create"}))
elif kind == "error":
log(f"[error] {ev['error'].get('message')}")
finally:
sender.cancel()
Each branch is one rule from the Realtime guide:
input_audio_buffer.speech_startedmeans the server heard the user start talking. With turn detection on, the server cancels its own reply; the guide says the client should “immediately stop playback” and sendconversation.item.truncatewith the item’s id and the milliseconds actually played. Without the truncate, the model believes the user heard the whole answer.input_audio_buffer.speech_stoppedstarts the latency clock.response.output_audio.deltacarries base64 audio. Play it as it arrives; do not wait for the whole reply.response.donecarries any function calls with theircall_idand arguments. You run the tool, send the result as afunction_call_outputitem, thenresponse.createso the model speaks the answer.
The log parameter is there so you can test the loop without a microphone, which is how we checked it.
5. Connect the microphone and speaker
Finish the file:
async def main() -> None:
import sounddevice as sd
loop = asyncio.get_running_loop()
mic_chunks: asyncio.Queue = asyncio.Queue()
player = Player()
frames = RATE * BLOCK_MS // 1000
def on_mic(indata, n, t, status):
loop.call_soon_threadsafe(mic_chunks.put_nowait, bytes(indata))
def on_speaker(outdata, n, t, status):
outdata[:] = player.take(len(outdata))
headers = {"Authorization": f"Bearer {os.environ['OPENAI_API_KEY']}"}
with sd.RawInputStream(samplerate=RATE, channels=1, dtype="int16", blocksize=frames, callback=on_mic), \
sd.RawOutputStream(samplerate=RATE, channels=1, dtype="int16", blocksize=frames, callback=on_speaker):
async with websockets.connect(URL, additional_headers=headers, max_size=None) as ws:
print("Listening. Use headphones, speak, and press Ctrl+C to stop.")
await run(ws, mic_chunks, player)
if __name__ == "__main__":
try:
asyncio.run(main())
except KeyboardInterrupt:
pass
The microphone callback runs on the audio thread, so it hands each 20 ms chunk to the asyncio loop with call_soon_threadsafe. The speaker callback asks the player for exactly as many bytes as the device wants. max_size=None lifts the websockets default message size limit, since audio events can be large.
6. Talk to it
python voice_agent.py
Try this sequence and watch the log lines:
- Say “Hi, where’s my order?” The agent should ask for the order number.
- Say “It’s five thousand and one.” You should see a
[tool get_order_status(...)]line, then hear the status. - Ask an open question (“What can you help with?”) and start talking again halfway through the answer. You should see
[interrupted after ... ms], and the agent should stop at once and respond to what you said. - Note the
[first audio ... ms after you stopped]numbers across ten turns. That is your baseline for tuning.
To tune, change one thing at a time: silence_duration_ms from 500 to 300 (faster, but it may cut you off when you pause), semantic_vad instead of server_vad, a shorter instruction, or the smaller gpt-realtime-2.1-mini model. Re-measure after each change.
When to use a cascade instead
A cascade (speech-to-text, a text model, text-to-speech) is the better choice when:
- Audio must stay on your hardware. faster-whisper for transcription, a local model and a local voice keep everything private, at the cost of latency on modest machines. The faster-whisper tutorial covers the first stage.
- You need to inspect or filter the text. Compliance rules, redaction and logging are simpler when there is a transcript you control between stages.
- You want a specific model or voice. Any text model with tools, any TTS voice.
To keep a cascade fast, stream every stage: transcribe in short chunks, start the text model as soon as the turn ends, and start speaking the first sentence while the model is still writing the second.
Pitfalls
Speakers instead of headphones. The agent hears itself, the server detects “speech” and the agent keeps interrupting itself. Use headphones, or echo cancellation in a browser via WebRTC.
Not truncating on interruption. The model then believes the user heard everything, and answers questions like “what was the last thing you said?” wrongly.
Waiting for the whole reply before playing. That throws away the point of streaming and adds seconds of silence.
Slow tools. The user hears silence while the tool runs. Keep voice tools fast, or have the agent say “let me check” first.
Long instructions and long answers. Both add latency, and long spoken answers are hard to follow. Ask for one or two sentences.
Putting the API key in a browser. For web clients, use WebRTC with an ephemeral token minted by your server, as OpenAI’s WebRTC guide describes. Never ship a standard key to a browser.
Next steps
- Turn recordings into text and notes offline with faster-whisper.
- Make the agent’s tools faster and harder to misuse with design tools an AI agent can use well.
- Learn the streaming patterns behind responsive interfaces in stream LLM responses to a web page.
- Check how well the agent handles real requests with evaluate AI agents.
Covers
Check your understanding
Build a voice agent quiz
Cascade versus speech-to-speech, the latency budget, turn detection, truncating on barge-in, streaming playback, tool calls and the usual voice agent pitfalls.
8 questions · pass mark 70%
Review
Related
- Transcribe and summarise audio locally with faster-whisper
Transcribe audio locally with faster-whisper in Python, fix misheard names, then summarise the transcript with a local model through Ollama, all offline.
- Design tools an AI agent can use well
Take one badly designed agent tool, fix its names, descriptions, arguments, errors and output size, and measure the difference with a small eval you can rerun.
- Stream LLM responses to a web page with server-sent events
A Node server relays tokens as server-sent events, the page renders them as they arrive, and a Stop button cancels.
- Speech-to-text (STT)
A model that converts spoken audio into written words, used for transcripts, captions, voice commands and meeting notes.
- Text-to-speech (TTS)
A model that turns written text into spoken audio in a chosen voice, used for voice assistants, narration, audiobooks and accessibility.