Sub topic 11
Errors, rate limits, retries, and cost
This chapter assumes you can call the transcription and speech endpoints from Python, that you have an API key in an environment variable, and that you have built the chunking step from the long-audio chapter. Here you will make those calls survive real traffic: classify failures, retry the right ones, respect rate limits, and estimate what a voice app costs.
Why speech calls fail more often than text calls
Speech requests are heavier than chat requests. A transcription call uploads a file, which can be several megabytes. A synthesis call returns binary audio. Both take longer than a short chat completion, so they are more exposed to timeouts, dropped connections, and rate limits. A voice loop also chains three calls, so a failure in any one of them breaks the whole turn.
Errors fall into two groups.
- Transient errors may succeed if you try again: rate limits, timeouts, connection resets, and server errors.
- Permanent errors will fail every time until you change the request: a bad key, an unsupported file format, a file over the size limit, or an invalid parameter.
Retrying a permanent error wastes time and, on some providers, money. The first job of error handling is to tell the two groups apart.
Common errors and what they mean
The table uses HTTP status codes as most hosted APIs return them. The OpenAI Python SDK maps each one to an exception class.
| Status | SDK exception | Typical cause | Retry? |
|---|---|---|---|
| 400 | `BadRequestError` | Unsupported format, corrupt file, invalid voice or parameter | No. Fix the request. |
| 401 | `AuthenticationError` | Missing or wrong API key | No. Fix the key. |
| 413 | `APIStatusError` | File larger than the size limit | No. Chunk the audio. |
| 429 | `RateLimitError` | Too many requests or tokens per minute, or quota exhausted | Usually yes, with backoff. |
| 500, 502, 503 | `InternalServerError` | Provider-side fault or overload | Yes, with backoff. |
| none | `APITimeoutError`, `APIConnectionError` | Slow upload, network drop | Yes, with backoff. |
A 429 needs a closer look, because it covers two different situations. A rate limit means you sent too much too fast, and waiting fixes it. An exhausted quota or billing limit also arrives as a 429 on some providers, and waiting never fixes it. Read the error message body before you decide. If it mentions billing or quota, stop retrying and alert a person.
Retrying with exponential backoff
Exponential backoff waits longer after each failure: 1 second, then 2, then 4. Longer waits give a rate limit window time to reset and stop your clients from hammering a struggling server.
The version below adds two refinements. It adds jitter, a small random amount, so many clients that failed together do not retry at the same instant. It also honors the server's Retry-After header when one is present.
import random
import time
from openai import (
APIConnectionError,
APITimeoutError,
InternalServerError,
OpenAI,
RateLimitError,
)
client = OpenAI(timeout=60.0, max_retries=0) # we handle retries ourselves
RETRYABLE = (RateLimitError, APITimeoutError, APIConnectionError, InternalServerError)
def delay_for(error, attempt):
retry_after = None
response = getattr(error, "response", None)
if response is not None:
retry_after = response.headers.get("retry-after")
if retry_after is not None:
try:
return float(retry_after)
except ValueError:
pass
return min(30.0, 2 ** attempt) + random.uniform(0, 0.5)
def transcribe_with_retry(path, attempts=4):
for attempt in range(attempts):
try:
with open(path, "rb") as f:
return client.audio.transcriptions.create(model="whisper-1", file=f).text
except RETRYABLE as error:
if attempt == attempts - 1:
raise
time.sleep(delay_for(error, attempt))Three details matter here.
- The file is reopened on every attempt. A file object that was partly read by a failed upload is positioned at the wrong place, so reusing it can send a truncated file.
max_retries=0turns off the SDK's built-in retries. The SDK retries some errors by default. Leaving both layers on multiplies the attempts, so you get up to four times the retries you intended. Pick one layer.- The delay is capped at 30 seconds. Without a cap, a long outage would put a user waiting minutes for one turn.
Do not catch Exception broadly. That would retry a 401 or a 400 four times and hide the real problem.
Timeouts
A timeout bounds how long you wait for a response. Set one explicitly, since a hung request in a voice app is a silent, dead conversation.
The right value depends on the call. A 10-minute chunk of audio takes longer to upload and transcribe than a 5-second clip. A fixed 60 seconds is a reasonable start for chunked transcription. For short synthesis calls, a tighter limit such as 20 seconds is usually enough. You can set different clients for different jobs, or pass a per-request timeout with client.with_options(timeout=20.0).
A timeout does not guarantee the server stopped working. The provider may have finished the request and billed it even though you never saw the result. For transcription this is harmless apart from cost. Keep it in mind for any call with side effects.
Rate limits
Providers cap usage over a time window. Common dimensions are requests per minute, tokens per minute for chat models, and audio seconds or requests per minute for speech models. Exact numbers depend on your account tier, so read the limits page for your account instead of copying numbers from a tutorial.
Backoff reacts to limits after you hit them. Better is to avoid hitting them.
- Limit concurrency. When you transcribe 40 chunks, do not start 40 requests at once. A pool of 3 to 5 workers is usually enough.
- Check the rate limit headers in responses, if the provider sends them. They show how many requests remain in the window.
- Spread batch work over time. A nightly job has no reason to run at full speed.
The example below transcribes chunks in parallel with a fixed worker count and keeps the results in order. It uses transcribe_with_retry from the previous section.
from concurrent.futures import ThreadPoolExecutor
def transcribe_chunks(chunk_paths, workers=4):
with ThreadPoolExecutor(max_workers=workers) as pool:
texts = list(pool.map(transcribe_with_retry, chunk_paths))
return " ".join(texts)pool.map returns results in the order of the input list, which is what you need to rebuild the transcript. If one chunk still fails after its retries, the exception surfaces when you read that result and the whole call fails. For long jobs, wrap each chunk so you can save the finished ones and redo only the failed ones.
Failures inside a voice loop
In a turn-based voice loop, each stage needs its own plan, because the user is waiting.
- Transcription fails: retry once or twice quickly, then ask the user to repeat. Do not call the LLM with empty text.
- The chat call fails: retry, and if it still fails, play a short pre-recorded apology instead of silence.
- Synthesis fails: fall back to showing the reply as text, if the interface has a screen.
Also handle a successful call that returns nothing useful. Silence, background noise, or a very short clip can return an empty string. Check len(text.strip()) == 0 before sending it onward. The loop should treat that as "no speech heard" and not as a question.
A pre-recorded fallback clip is worth generating once, ahead of time, and storing as a file. It keeps working when the synthesis service is the thing that is down.
Cost
Speech APIs bill by different units than chat APIs, and the units are easy to confuse.
| Call | Billed by | Practical consequence |
|---|---|---|
| Transcription (`whisper-1`) | Minutes of audio sent | Trimming silence and cutting the recording to what matters saves money. |
| Speech synthesis (`tts-1`) | Characters of input text | Long LLM replies cost more. Short spoken answers are cheaper and faster. |
| Chat completion | Input and output tokens | The growing history in a voice loop raises the cost of each later turn. |
Prices change, so check the provider's pricing page. The structure above is what stays stable, and it tells you where to look for savings.
A rough cost model for one voice turn is:
def estimate_turn_cost(audio_seconds, reply_chars, stt_per_minute, tts_per_million_chars, chat_cost=0.0):
stt = (audio_seconds / 60) * stt_per_minute
tts = (reply_chars / 1_000_000) * tts_per_million_chars
return stt + tts + chat_cost
# Placeholder prices for illustration only. Replace with current values.
print(round(estimate_turn_cost(8, 160, stt_per_minute=0.006, tts_per_million_chars=15.0), 5))With these placeholder prices, an 8-second question and a 160-character answer cost well under a cent for the speech parts. The cost grows with volume, not with any single turn, so multiply by expected turns per day before you decide it is negligible.
Several habits keep costs down:
- Ask the chat model for short replies. This lowers synthesis cost and also lowers latency.
- Cache synthesized audio for text that repeats, such as greetings and error messages. Key the cache on the text, voice, and format.
- Do not retry permanent errors, and cap attempts. A retry loop with no cap can multiply your bill during an outage that returns timeouts after the work is done.
- Chunk with care. Overlapping chunks to avoid cutting words mid-sentence means you pay for the overlap twice.
- Log audio seconds and characters per request, so you can see which feature drives the bill.
Logging what you need to debug
When a call fails at 2 a.m., you need enough detail to understand why. Record, for each call, the stage (transcription, chat, synthesis), the attempt number, the exception class, the status code, the provider's request ID if present, the audio duration or character count, and the elapsed time. The request ID is what the provider's support team asks for first. The SDK exposes it on error.request_id for API status errors.
Common mistakes
- Retrying every exception, including 400 and 401 errors.
- Leaving the SDK's built-in retries on while also writing your own loop.
- Reusing an open file object across retry attempts.
- Setting no timeout, so one stuck request freezes the turn.
- Starting unbounded parallel requests and then being surprised by 429 responses.
- Treating an empty transcript as a valid user message.
- Estimating cost from a single request instead of from daily volume.
Exercise
Your batch job transcribes 60 chunks with 20 parallel workers and keeps getting 429 errors, even though each call uses retry with backoff. Give two changes that reduce the errors, and say why backoff alone was not enough.
Show answer
Lower the worker count (for example to 3 to 5) and spread the requests over time, or read the rate limit headers and slow down when few requests remain. Backoff only reacts after the limit is hit, and 20 workers that fail together also retry together, so they keep exceeding the limit. Adding jitter helps desynchronize the retries. Also check the error body, since a 429 caused by an exhausted quota is not fixed by waiting.
Exercise
A transcription call returns a 400 error saying the file format is unsupported. Should your retry wrapper retry it? What should happen instead?
Show answer
No. A 400 is a permanent error, so the same request will fail again. The wrapper should raise it immediately. Fix the cause by converting the file to a supported format such as MP3 or WAV, then submit it again.