Sub topic 1
How speech fits around an LLM
A text LLM reads text and writes text. Speech APIs add two converters around it: one turns audio into text, the other turns text back into audio. This chapter explains that three-stage design, what each stage contributes, and where it can go wrong. Later chapters cover each stage in detail.
Prerequisites
This chapter assumes you have:
- Basic Python, including functions and file handling.
- Experience calling an LLM chat API through an SDK or plain HTTP.
- An API key stored in an environment variable, such as
OPENAI_API_KEY. - A rough idea of what an audio file is, for example an MP3 or WAV file.
You do not need any signal-processing background. The next chapter covers the audio basics you need before calling an API.
The pipeline in one picture
A cascaded speech pipeline has three stages that run one after another:
- Speech-to-text (STT), also called transcription. It takes recorded audio and returns text.
- LLM. It takes the text, plus any conversation history, and returns a text reply.
- Text-to-speech (TTS), also called speech synthesis. It takes the reply text and returns audio.
The LLM never touches audio in this design. Both converters sit at the edges and the model stays unchanged. You can swap the chat model, the voice, or the transcription provider without touching the other stages.
What each stage does
Each stage has different inputs, outputs, and limits. Keeping them straight helps you debug later.
| Stage | Input | Output | Typical limit or cost driver |
|---|---|---|---|
| STT | Audio file in a supported format | Transcript, optionally with timestamps | File size, audio duration billed per minute |
| LLM | Messages (text) | Reply text | Context window, tokens in and out |
| TTS | Text string | Audio bytes | Maximum input length, characters billed |
The units differ. STT is typically billed by audio duration, the LLM by tokens, and TTS by input characters. A cost estimate has to cover all three. The chapter on errors, rate limits, and cost works through this.
A minimal three-function skeleton
The code below wires the stages together for a single turn. It also times each stage. Its structure is the same for any provider: one function per stage, with plain strings and file paths passed between them. The example uses the OpenAI Python SDK.
import time
from openai import OpenAI
client = OpenAI() # reads OPENAI_API_KEY from the environment
def speech_to_text(path: str) -> str:
with open(path, "rb") as audio_file:
result = client.audio.transcriptions.create(
model="whisper-1",
file=audio_file,
)
return result.text
def think(user_text: str) -> str:
completion = client.chat.completions.create(
model="gpt-4o-mini",
messages=[
{"role": "system", "content": "Answer in one or two short spoken sentences."},
{"role": "user", "content": user_text},
],
)
return completion.choices[0].message.content
def text_to_speech(text: str, path: str) -> None:
with client.audio.speech.with_streaming_response.create(
model="tts-1",
voice="alloy",
input=text,
) as response:
response.stream_to_file(path)
def run_turn(input_path: str, output_path: str = "reply.mp3") -> None:
t0 = time.perf_counter()
user_text = speech_to_text(input_path)
t1 = time.perf_counter()
reply_text = think(user_text)
t2 = time.perf_counter()
text_to_speech(reply_text, output_path)
t3 = time.perf_counter()
print(f"Heard: {user_text}")
print(f"Said: {reply_text}")
print(f"STT {t1 - t0:.2f}s | LLM {t2 - t1:.2f}s | TTS {t3 - t2:.2f}s")
if __name__ == "__main__":
run_turn("question.mp3")Run it with a short recording named question.mp3. The last line prints how long each stage took. Those three numbers drive most of the design decisions in this tutorial.
Why latency adds up
The stages run in sequence, so their delays add. The user hears nothing until all three have finished, unless you overlap them. The total wait before the first sound is roughly:
- the time to upload and transcribe the audio, plus
- the time for the LLM to produce its reply, plus
- the time for TTS to produce the first audio.
Each term grows in a different way:
- STT time grows with the length of the recording and with network upload time.
- LLM time grows with the length of the reply, because the model generates it token by token.
- TTS time grows with the length of the text, unless you stream the audio and play it as it arrives.
Short spoken replies help in two places at once. The system prompt in the skeleton asks for one or two sentences for this reason. A long reply makes the LLM slower and also gives TTS more to synthesize. The chapters on streaming audio and on the latency budget cover techniques such as starting playback before synthesis finishes.
What the pipeline loses
Converting speech to text throws information away. The transcript holds the words and little else. The LLM cannot hear:
- tone, such as sarcasm, hesitation, or urgency;
- who is speaking, when several people share one recording;
- background sounds, such as an alarm or a barking dog;
- how the speaker pronounced a word, which matters for names and for language learning.
Some of this can be recovered. Timestamps from the transcription API tell you about pauses. Separate recordings per speaker solve speaker identification. Anything else, such as emotion, is simply absent from the text the model sees. If your product depends on it, the cascaded design is a poor fit. The last chapter of this tutorial returns to that choice.
The same loss happens on the way out. The LLM writes words, and the TTS stage decides how to say them. The model cannot directly control pacing or emphasis. You influence the result through the choice of voice and speed, and through the text itself. Short sentences and spelled-out numbers tend to sound better than long sentences with symbols.
Errors compound across stages
Every stage can make mistakes, and each stage trusts the one before it.
- If STT hears "mourning" instead of "morning", the LLM answers a question the user never asked, and TTS reads that answer aloud confidently.
- If the LLM returns Markdown, such as bullet points or asterisks, TTS may read the symbols out loud or pause strangely. Ask the model for plain spoken prose.
- If the reply is very long, TTS may reject it for exceeding its input limit.
Two habits help from the start. First, log the transcript and the reply text for each turn, so you can tell which stage caused a bad result. Second, treat the transcript as data that came from outside your system. Anyone who can speak into the microphone, or play a recording near it, controls the text sent to your LLM. A later chapter covers this risk.
Deciding where this design fits
A cascaded pipeline is a good default when:
- you want to reuse an existing text LLM app and add voice at the edges;
- you need the transcript for logs, search, captions, or compliance review;
- you want to pick the best provider for each stage independently;
- the conversation is turn-based, where the user finishes speaking and then waits for a reply.
It is a weaker fit when the conversation needs natural interruptions and very low delay, or when tone of voice matters to the task. Models that take audio in and produce audio out directly exist for those cases, and the last chapter compares them with the cascaded design.
Where the rest of the tutorial goes
The remaining chapters follow the stages in order. They start with audio formats, then transcription calls and options, handling long files, speech synthesis, and streaming. After that you build a voice loop, analyze latency, handle errors and cost, measure accuracy with word error rate, and cover privacy and untrusted input.
Exercises
Exercise
In a cascaded pipeline, a user says "cancel my order" in a noisy room and the transcript reads "counsel my border". Which stage caused the error, and which later stages are affected?
Show answer
The speech-to-text stage caused the error. The LLM receives the wrong text and replies to it, and the text-to-speech stage reads that reply aloud. The later stages work correctly on bad input, so logging the transcript separately is the quickest way to find the cause.
Exercise
Using the skeleton in this chapter, a run prints "STT 1.10s | LLM 0.90s | TTS 1.40s". What is the approximate wait before the user hears any reply, and which single change in the prompt would most reduce both the LLM and TTS times?
Show answer
The stages run in sequence, so the wait is about 3.4 seconds (1.10 + 0.90 + 1.40). Asking the LLM for shorter replies reduces both the LLM time and the TTS time, because a shorter text is generated faster and is also quicker to synthesize.
Exercise
Name two kinds of information the LLM cannot use in a cascaded pipeline, and say what you could do for one of them.
Show answer
Examples are tone of voice, speaker identity, background sounds, and pronunciation. For speaker identity, you can record each speaker on a separate channel or file and label the transcripts. For pauses, you can use timestamps from the transcription response.