Sub topic 10
Where the time goes: a latency budget
A voice app feels fast or slow based on one number: the gap between the moment the user stops talking and the moment they hear the first word of the reply. This chapter breaks that gap into stages, shows how to measure each one, and covers the changes that shorten it most.
This chapter assumes you can call the transcription, chat, and speech endpoints from Python, and that you have read the chapters on the turn-based voice loop and on streaming audio output.
The latency you are budgeting
The number to optimize is time to first audio. It starts when the user finishes speaking and ends when the first audio byte plays. Total turn time matters less, because a user who hears a reply starting after one second does not mind that it runs for ten.
In the cascaded pipeline (speech-to-text, then LLM, then text-to-speech) the stages run one after another. Each stage waits for the previous one, so their delays add up.
The stages
The following table lists the stages and the levers that act on each. The ranges are illustrative. Real values depend on provider, model, region, and load, so measure your own.
| Stage | What takes the time | Typical order of magnitude | Main levers |
|---|---|---|---|
| End-of-speech detection | Waiting to be sure the user stopped | 0.3 to 1 s | Tune the silence threshold |
| Upload | File size over your connection | 0.1 to 1 s | Compress audio, lower the sample rate, trim silence |
| Transcription | Processing time grows with audio length | 0.5 to 3 s | Shorter turns, a faster model |
| LLM | Time to first token plus generation | 0.5 to 3 s | Smaller model, shorter prompt, short replies, streaming |
| Speech synthesis | Time to first audio byte | 0.3 to 1.5 s | Streaming, sentence-sized inputs, a faster model |
| Playback start | Buffering in the player | 0.05 to 0.3 s | Smaller buffers, a format the player decodes quickly |
Add the middle values and a naive pipeline lands around four to eight seconds. That feels sluggish in conversation, which is why the rest of the chapter focuses on overlapping stages instead of only speeding up each one.
Measure first
Do not tune from intuition. Record a timestamp at each stage boundary and log it per turn. The function below is a variant of the voice loop that times every stage. It also records time to first audio byte by consuming the synthesized audio as a stream.
import time
from openai import OpenAI
client = OpenAI()
def timed_voice_turn(input_path, history, output_path="reply.mp3"):
timings = {}
start = time.perf_counter()
with open(input_path, "rb") as f:
user_text = client.audio.transcriptions.create(model="whisper-1", file=f).text
after_stt = time.perf_counter()
timings["stt"] = after_stt - start
history.append({"role": "user", "content": user_text})
completion = client.chat.completions.create(
model="gpt-4o-mini",
messages=[{"role": "system", "content": "Answer in one or two short spoken sentences."}] + history,
)
reply_text = completion.choices[0].message.content
history.append({"role": "assistant", "content": reply_text})
after_llm = time.perf_counter()
timings["llm"] = after_llm - after_stt
first_byte_seen = False
with client.audio.speech.with_streaming_response.create(
model="tts-1", voice="alloy", input=reply_text, response_format="mp3"
) as response:
with open(output_path, "wb") as out:
for chunk in response.iter_bytes(chunk_size=4096):
if not first_byte_seen:
timings["tts_first_byte"] = time.perf_counter() - after_llm
first_byte_seen = True
out.write(chunk)
timings["tts_total"] = time.perf_counter() - after_llm
timings["time_to_first_audio"] = (
timings["stt"] + timings["llm"] + timings["tts_first_byte"]
)
return user_text, reply_text, timingsRun it on a set of real recordings, not one. Latency has a long tail, so look at the median and the 95th percentile. A median of two seconds with a 95th percentile of nine seconds is a different problem from a steady four seconds.
Optimizing each stage
Before transcription
The audio you send determines both upload time and, for some providers, processing time.
- Send mono audio at 16 kHz. Speech models do not benefit from stereo or from sample rates above what they resample to internally.
- Use a compressed format such as MP3 or Opus instead of WAV. A minute of 16 kHz mono WAV is about 1.9 MB, while the same minute as MP3 is a fraction of that.
- Trim leading and trailing silence. Silence adds upload bytes and can make transcribers hallucinate text.
- Keep turns short. Transcription of a file starts only after the full file arrives, so a 30-second turn costs more than a 5-second one.
During the LLM call
The LLM often dominates the budget, and its cost has two parts: time to first token and generation speed.
- Tell the model to answer briefly. A system prompt asking for one or two spoken sentences cuts generation time directly, because speech is slow to listen to and long replies are bad voice design anyway.
- Keep the prompt and history small. Long context raises time to first token. Summarize or drop old turns.
- Use a smaller, faster model for routine turns and reserve a larger one for hard queries.
- Stream the response with
stream=Trueso you can act on tokens as they arrive.
During synthesis
Speech synthesis returns audio faster per character than people speak it, but a long input still delays the first byte if you wait for the whole file. Two habits fix that: stream the audio bytes into the player as they arrive, and feed synthesis in sentence-sized pieces.
Overlap the stages
The largest gain comes from not waiting for the LLM to finish before starting speech. Stream the LLM output, cut it at sentence boundaries, and send the first sentence to speech synthesis while the model writes the second. The helper below turns a streamed chat completion into whole sentences.
import re
from openai import OpenAI
client = OpenAI()
def sentences(stream):
buffer = ""
for event in stream:
if not event.choices:
continue
buffer += event.choices[0].delta.content or ""
while True:
match = re.search(r"[.!?]\s", buffer)
if not match:
break
yield buffer[:match.end()].strip()
buffer = buffer[match.end():]
if buffer.strip():
yield buffer.strip()
stream = client.chat.completions.create(
model="gpt-4o-mini",
messages=[{"role": "user", "content": "Explain DNS in three short sentences."}],
stream=True,
)
for index, sentence in enumerate(sentences(stream)):
with client.audio.speech.with_streaming_response.create(
model="tts-1", voice="alloy", input=sentence, response_format="mp3"
) as response:
response.stream_to_file(f"sentence_{index:02d}.mp3")
print(index, sentence)This version writes one file per sentence to keep the example self-contained. In a real app you would hand each synthesized chunk to a playback queue and start playing the first one immediately.
With this change, the reply starts after the first sentence is generated and synthesized instead of after the whole reply. For a five-sentence answer, that can save several seconds.
Edge cases and trade-offs
- Short chunks sound choppy. Synthesizing very small pieces can change intonation between pieces and add per-request overhead. Sentences are a good minimum size.
- Parallel requests hit rate limits sooner. Overlapping stages increases the number of simultaneous calls per user. Check your limits before you scale.
- Retries add to the tail. A retry with backoff can add seconds to one turn. Keep timeouts tight in voice apps, since a user will not wait the way a batch job does.
- Cold connections cost time. Reuse the client object so HTTP connections stay open. Creating a new client per turn adds connection setup to every request.
- End-of-speech detection is a trade-off. A short silence threshold responds sooner but cuts users off mid-thought. A long one feels slow. Start near 700 ms and adjust from user testing.
- Filler can mask delay. Playing a short acknowledgment while the pipeline works reduces perceived wait, but it does not reduce the real time and can feel repetitive.
If the budget still cannot reach about one second to first audio, a cascaded pipeline may be the wrong tool. The final chapter compares it with realtime speech-to-speech models, which skip the text round trip.
Putting a budget in writing
Pick a target for time to first audio, for example 1.5 seconds at the median. Assign each stage a share, such as 0.3 s for upload and detection, 0.4 s for transcription, 0.4 s for the first LLM sentence, and 0.4 s for synthesis. Log the measured values and alert when a stage exceeds its share. A written budget tells you which stage to work on next and stops you from optimizing one that is already small.
Exercise
Your timing logs show a median of 0.6 s for transcription, 2.4 s for a full LLM reply, and 0.7 s for time to first synthesis byte. The reply has four sentences, and the first sentence is complete about 0.5 s after the LLM starts generating. About how long is time to first audio now, and about how long after streaming the LLM into sentence-sized synthesis calls (assume synthesis of the first sentence takes the same 0.7 s)?
Show answer
Now: 0.6 + 2.4 + 0.7 = 3.7 s. With sentence streaming: 0.6 + 0.5 + 0.7 = 1.8 s. The saving comes from starting synthesis once the first sentence exists instead of waiting for the full 2.4 s reply.
Exercise
Why should you track the 95th percentile of time to first audio and not only the median?
Show answer
Latency has a long tail from retries, rate limiting, and slow network calls. A good median can hide turns that take many seconds, and those slow turns are the ones users remember and complain about.