Sub topic 9
Building a turn-based voice loop
This chapter connects the three stages you have used separately: transcription, a chat model, and speech synthesis. It assumes you can call the transcription and speech endpoints, have used a chat completions API, and keep your API key in the OPENAI_API_KEY environment variable.
What "turn-based" means
In a turn-based loop, the user finishes speaking, the app processes the whole recording, and then it plays a reply. Only one side talks at a time. This is simpler than a live conversation because there is no interruption handling and no continuous audio stream. Each turn is a complete round trip.
One turn as a function
The function below runs one turn. It transcribes the recording, appends the text to the history, asks the chat model for a reply, appends that reply, and writes the spoken reply to a file.
from openai import OpenAI
client = OpenAI()
def voice_turn(input_path, history, output_path="reply.mp3"):
with open(input_path, "rb") as f:
user_text = client.audio.transcriptions.create(model="whisper-1", file=f).text
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})
with client.audio.speech.with_streaming_response.create(
model="tts-1", voice="alloy", input=reply_text
) as response:
response.stream_to_file(output_path)
return user_text, reply_textTo run several turns, create one history list and pass the same list into every call:
history = []
user_text, reply_text = voice_turn("turn1.mp3", history)
print("You said:", user_text)
print("Reply:", reply_text)Design choices in the loop
- The system prompt shapes the reply for the ear. Spoken answers should be short. Lists, tables, and markdown symbols sound wrong when read aloud, so tell the model to avoid them.
- The history holds text, not audio. Only the transcript and the reply text are stored. This keeps the chat request small and lets you reuse your normal chat code.
- The speech call receives the reply text, not the whole completion. Pass
completion.choices[0].message.contentas a plain string. - The function returns both texts. You can log them, show captions, or measure transcription quality later.
Common errors
- Empty or silent recordings. The transcript may be empty or contain a guess. Check
user_text.strip()before calling the chat model, and ask the user to repeat. - Unbounded history. Each turn adds two messages, so cost and latency grow. Keep the last several turns, or summarize older ones.
- A failure after a partial update. If the chat call fails after you appended the user message, the history ends with an unanswered user turn. Append the message only once you can complete the turn, or remove it on failure.
- Missing retries. Any of the three calls can hit a rate limit or timeout. Wrap them with the retry pattern from the errors chapter.
- Overwritten output. Writing every reply to
reply.mp3replaces the previous file. Pass a uniqueoutput_pathper turn if you need to keep them.
Where the delay comes from
The user waits for three calls in sequence: transcription, the chat completion, and the start of speech output. Streaming the speech response helps only with the last stage. The latency chapter shows how to measure each stage.
Exercise
In voice_turn, why should you check for an empty transcript before appending it to history and calling the chat model?
Show answer
A silent or unintelligible recording can produce an empty or meaningless transcript. Sending it to the chat model wastes a call, adds a useless message to the history, and may produce a confusing reply. Checking first lets you ask the user to repeat without changing the history.