Streaming and Error Handling for LLM Calls: Show the First Word Early, Retry Politely, Fail Calmly
A support chat that shows nothing for 1.32 seconds, then crashes on a 429. Stream the reply so the first word lands at 0.14 s, retry 429, 500 and timeouts with tenacity (waits 0.2, 0.4, 0.8 s), and end with one calm sentence.
What you will learn
- Stream a reply with stream=True and print each piece from delta.content as it arrives
- Explain why streaming changes the first word, not the total time
- Retry only 429, 500 and timeouts with tenacity and an exponential wait
- Set a timeout, turn off the SDK's own retries and return a polite fallback instead of a stack trace
Before you start
- Basic Python
- The Claude Messages API: Your First Call, Field by Field
Picture a small online shop with a support chat. A customer types Where is my order? Our app sends it to the model and waits.
Problem one: the screen shows nothing. Just three dots, for more than a second. For a long answer it can be much longer, and the customer thinks the app is stuck.
Problem two is worse: the model is busy and sends back an error, a 429 Too Many Requests. If we don't handle it, the app crashes right in front of the customer.
So the LLM call has two jobs: show the first words early, and when things go wrong, fail politely. Three words to hold on to: stream, retry, fallback.
No key needed. The code here runs against a stand-in test model that speaks the same wire format as the OpenAI API, answers from mock orders and can be told to fail on purpose. Put your own key in .env (OPENAI_API_KEY=your-key-here) and the same code calls the real model.
How streaming works
Same question, same model. The only thing that changes is when the text reaches the screen.
- Plain call: the model writes the whole answer first. We wait, and at 1.32 seconds the full sentence lands in one piece.
- stream=True: the model sends each small piece the moment it is written. Your... order... left... The first word is on screen at 0.14 seconds, and the rest keeps dropping in until the sentence is complete.
Think of a waiter who brings each dish as soon as it is ready, instead of holding everything back for the end. The total time is about the same, but the customer sees something almost ten times sooner.
Stream a reply in code
Here is the prompt you might give your AI assistant for this, and the code that matters from what it gives back:
Write a Python script using the OpenAI SDK that asks 'Where is my order?' with stream=True, prints each text piece with the seconds since the request started, and then does the same call without streaming so I can compare.
import time
# client and MODEL come from the project's make_client(): the stand-in
# test model without a key, the real OpenAI client with one.
messages = [{"role": "user", "content": "Where is my order?"}]
def show_stream():
start = time.perf_counter()
stream = client.chat.completions.create(model=MODEL, messages=messages, stream=True)
for chunk in stream:
text = chunk.choices[0].delta.content
if text:
print(f" {time.perf_counter() - start:4.2f}s {text!r}")
print(f" done at {time.perf_counter() - start:4.2f}s")
def show_whole():
start = time.perf_counter()
reply = client.chat.completions.create(model=MODEL, messages=messages)
print(f" {time.perf_counter() - start:4.2f}s {reply.choices[0].message.content!r}")
if __name__ == "__main__":
print("warm-up call (the SDK's one-time setup, not timed)")
client.chat.completions.create(model=MODEL, messages=messages)
print("stream=True")
show_stream()
print("stream=False")
show_whole()
Match the prompt to the code:
stream=Trueis two words in the prompt and one argument in the code. That one argument changes the call: you get back a stream, not a finished answer.- Print each text piece. That's the
forloop. Each chunk carries a small bit of text inchunk.choices[0].delta.content. Some chunks carry no text (the last one only says the reply has stopped), soif text:skips them. - Seconds since the request started.
startnotes the time, and every print subtracts it.
Read it like this: ask with stream=True, loop over the pieces, print the ones that carry text. The rest is the plain call, for comparison. The run:
warm-up call (the SDK's one-time setup, not timed)
[test model] call 1 -> ok
stream=True
[test model] call 2 -> ok
0.14s 'Your '
0.26s 'order '
0.38s 'left '
0.50s 'the '
0.62s 'warehouse '
0.74s 'today '
0.86s 'and '
0.98s 'arrives '
1.11s 'on '
1.23s 'Friday.'
done at 1.35s
stream=False
[test model] call 3 -> ok
1.32s 'Your order left the warehouse today and arrives on Friday.'
The [test model] lines are the stand-in reporting each call it gets. The stream starts at 0.14 seconds and finishes at 1.35. The plain call shows nothing at all until 1.32. Nearly the same total, and that first word is the whole reason we stream.
Retry, and wait longer each time
Now the second job, errors. For this run the test model is scripted to fail twice and then answer:
- Call 1 comes back with a 429, too many requests. We don't give up; we wait 0.2 seconds.
- Call 2 gets a 500, a server error. This time we wait a little longer, 0.4 seconds.
- Call 3 works. The reply arrives, and the customer never knew.
It's like calling a busy phone line: wait a bit, redial, wait a bit longer each time. But only retry what can actually pass later. A busy server, yes. A wrong API key will not fix itself, so retrying it is useless.
And when nobody answers?
What if the model never answers? Every call gets a 5-second timeout. No answer, so we wait and try again: 0.2, then 0.4. After the third failure we wait 0.8, try one last time, and then stop. Waiting forever is also a failure.
And the customer sees one calm sentence: Sorry, our assistant is busy. Please try again in a minute. No crash, no stack trace.
Only one layer retries. The OpenAI SDK also retries on its own, with a setting called max_retries. If both layers retry, they multiply: three tries inside, four outside, and that's twelve calls for one question. So set the SDK's max_retries to 0 and let your own rule do the work.
from openai import OpenAI
client = OpenAI(max_retries=0, timeout=5) # our rule retries, not the SDK; 5 s per call
Retries with tenacity
The prompt for this part:
Wrap an OpenAI chat call with tenacity: retry on RateLimitError, InternalServerError and APITimeoutError, at most four attempts, exponential wait starting at 0.2 s, and print a line before each wait. If it still fails, return a polite fallback message instead of raising.
And the code that matters, using a small library called tenacity:
import openai
from dotenv import load_dotenv
from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential
load_dotenv()
RETRY_ON = (openai.RateLimitError, openai.InternalServerError, openai.APITimeoutError)
MODEL = "gpt-4o-mini"
FALLBACK = "Sorry, our assistant is busy. Please try again in a minute."
def log_retry(state):
error = type(state.outcome.exception()).__name__
print(f" attempt {state.attempt_number} failed: {error}, waiting {state.next_action.sleep:.1f}s")
def ask_once(client, question):
messages = [{"role": "user", "content": question}]
reply = client.chat.completions.create(model=MODEL, messages=messages)
return reply.choices[0].message.content
@retry(retry=retry_if_exception_type(RETRY_ON), stop=stop_after_attempt(4),
wait=wait_exponential(multiplier=0.2, max=2),
before_sleep=log_retry, reraise=True)
def ask_with_backoff(client, question):
return ask_once(client, question)
def safe_ask(client, question):
try:
return ask_with_backoff(client, question)
except RETRY_ON as error:
print(f" giving up after {type(error).__name__}")
return FALLBACK
- Which errors to retry.
RETRY_ON: the rate limit error (429), the server error (500) and the timeout. Nothing else, so a bad key or a bad request fails at once. - At most four attempts, exponential wait from 0.2 seconds. That's the
@retrydecorator:stop_after_attempt(4)andwait_exponential(multiplier=0.2, max=2). Exponential just means the wait doubles every time, andmax=2caps it at 2 seconds. - A line before each wait.
before_sleep=log_retry, so you can see what's going on. - The polite fallback.
reraise=Truehands the last error back after the fourth attempt, andsafe_askcatches it and returnsFALLBACKinstead of crashing.
What the log tells you
The run has three scenes. Scene 1 leaves the SDK's own retries on (max_retries=2) with no tenacity, scene 2 is our rule with the SDK's retries off, and scene 3 is the bad day:
1. SDK retries only (max_retries=2)
[test model] call 1 -> 429
[test model] call 2 -> 500
[test model] call 3 -> ok
reply: Your order left the warehouse today and arrives on Friday.
2. Our backoff (SDK retries off)
[test model] call 1 -> 429
attempt 1 failed: RateLimitError, waiting 0.2s
[test model] call 2 -> 500
attempt 2 failed: InternalServerError, waiting 0.4s
[test model] call 3 -> ok
reply: Your order left the warehouse today and arrives on Friday.
3. Timeouts, then the fallback
[test model] call 1 -> timeout
attempt 1 failed: APITimeoutError, waiting 0.2s
[test model] call 2 -> timeout
attempt 2 failed: APITimeoutError, waiting 0.4s
[test model] call 3 -> timeout
attempt 3 failed: APITimeoutError, waiting 0.8s
[test model] call 4 -> timeout
giving up after APITimeoutError
reply: Sorry, our assistant is busy. Please try again in a minute.
Scene 1 shows the SDK quietly retrying a 429 and a 500 by itself, which is exactly why two layers would multiply. In scene 2 the waits double, 0.2 then 0.4, and call 3 works. In scene 3, after the fourth timeout, the customer gets one calm sentence, not a stack trace.
This is the retry around a single LLM call. Retrying whole background jobs, with jitter so many jobs don't retry at the same moment, is in Retries and Backoff for Reliable Tasks. And when the fallback should be another model rather than a sentence, see Fallback Models for an LLM App.
Your prompt checklist
AI writes this code well, but only if you ask for the right things and then check what comes back.
| Ask for | Then check |
|---|---|
stream=True, print pieces as they arrive | empty pieces are skipped |
| which errors to retry: 429, 500, timeout | only those errors are retried |
| max attempts and a growing wait | SDK max_retries=0, so one layer retries |
| a timeout on every call | no call can wait forever |
| a polite fallback message | the user never sees a stack trace |
Common mistakes
- Printing every chunk without
if text:. Some chunks carry no text, and you printNone. - Retrying every exception. A wrong key or a bad request fails the same way four times, only slower.
- Two retry layers. The SDK's
max_retriesplus your own rule turns one question into twelve calls. - No timeout. A call that never answers holds the customer forever.
- Letting the last error escape to the page instead of returning a fallback.
- Expecting streaming to make the model faster. The total time stays about the same; the first word comes sooner.
Quick recap
| Job | Code | In the run |
|---|---|---|
| Show the first word early | stream=True, loop, delta.content | first word 0.14 s, done 1.35 s; plain call 1.32 s |
| Retry what can pass | retry_if_exception_type(RETRY_ON) | 429 and 500, then ok |
| Wait longer each time | wait_exponential(multiplier=0.2, max=2) | 0.2, 0.4, 0.8 s |
| Don't wait forever | timeout=5, stop_after_attempt(4) | gives up after the fourth timeout |
| One retry layer | max_retries=0 | not 3 x 4 = 12 calls |
| Fail politely | safe_ask returns FALLBACK | "Sorry, our assistant is busy..." |
Try it yourself
- Run the demos and the offline tests:
python demo.py stream,python demo.py resilient, thenpython demo.py tests. - Break something: change a scene's script to
("500", "500", "ok")and read the log. - Take the sample prompt from
PROMPT.md, give it to your own AI assistant, and compare what you get with this code against the checklist above.
The project, with the stand-in model, the demos and the tests, is in the StudyEasy AI Community, free to join.
Related course on Udemy
Become an AI Engineer: LLMs, RAG, Agents and MCP
Build real AI systems in Python: LLM APIs, RAG, evals, agents and MCP.View on Udemy ↗: Become an AI Engineer: LLMs, RAG, Agents and MCP (paid course, opens in a new tab)Related posts
The AI Stack in One Picture: Six Layers Every AI Product Is Built From
Every AI product is built from six layers: data, model, retrieval, orchestration, serving and ops, with evals and security across all of them. A restaurant analogy, one request traced through all six, and what an AI engineer actually builds around the model call.
Tokenization: What an LLM Actually Sees When You Type
A language model never sees letters, only token ids. Use tiktoken to watch strawberry become three ids, see a space or a capital change them, fix the letter-counting problem, and compare English, German and Hindi token counts.
LLM Tokens, Context Windows and Cost: What One Question Really Costs
Follow one four-word help desk question that becomes 911 input tokens. Learn what fills the context window, why chat memory grows every turn, how max_tokens cuts a reply, and how to price a call.
What an LLM Can and Cannot Do: One Prediction Loop, Its Strengths and Its Gaps
A large language model predicts the next token, over and over. That one loop makes it strong at drafting, summarising and classifying, and weak at fresh facts, exact maths, memory and guaranteed truth. See why with a three-line tiktoken script, and learn the fix for each gap.