Single logo
  • Courses
  • Blog
  • About
Join free on SkoolJoin free on Skool

In this topic

AI Engineering
  • The AI Stack in One Picture: Six Layers Every AI Product Is Built From
  • Tokenization: What an LLM Actually Sees When You Type
  • LLM Tokens, Context Windows and Cost: What One Question Really Costs
  • What an LLM Can and Cannot Do: One Prediction Loop, Its Strengths and Its Gaps
  • Structured LLM Output with Pydantic: Describe the Shape Once, Check Every Reply
  • Temperature, Top-p and Sampling: Why the Same Prompt Gives a Different Answer
  • Open vs Closed LLMs: Cost, Control, Privacy and Capability, Decided per Workload
  • Streaming and Error Handling for LLM Calls: Show the First Word Early, Retry Politely, Fail Calmly
  • Practice: Build a CLI Chat Tool with Memory, Commands, Error Handling and a History Cap
  • Explicit Criteria vs Vague Prompts: Turn Every Adjective Into a Check a Script Can Run
  • Few-Shot Prompting Done Right: How Many Examples, How Different, What Order, and the Leak That Lies
  • Prompt Caching: Keep the Start of Every Request Identical and Pay for the Long Part Once
  • Prompt Versioning and Testing in a Repo: Prompt Files, a Registry, a Hash per Answer and Tests That Gate
  • Context Engineering: What Belongs in the Context Window, Turn by Turn
  • Context Engineering for a Long-Running Agent: Clear, Compact, Take Notes, Prove It
  • What an Embedding Actually Is: Meaning as Numbers, Search by Closeness, and Where Hand-Made Numbers Break
  • The RAG Pipeline Explained: 7 Stages From Documents to a Cited Answer
  • Similarity Search: Finding the Closest Vectors with NumPy and NearestNeighbors
  • Why RAG Exists: The Problem It Solves, Compared With Pasting Everything and Fine-Tuning
  • Real Embedding Models: an Open Model or a Provider API, Then Search, Duplicates and Recommendations
  • Chunking Strategies for RAG: Fixed Size, Sentences or Headings, Measured on One Handbook
  • Vector Databases Hands-On: The Same Search in Chroma and pgvector
  • RAG Prompt Assembly and Citations: Number the Blocks, Fit a Token Budget, Check Every Claim
  • Hybrid Search: BM25 Plus Dense Embeddings, Merged With Reciprocal Rank Fusion
  • Reranking With a Cross-Encoder: When the Second Pass Helps, and When It Doesn't
  • Retrieval Evals: Score the Retriever With Recall@K, MRR and nDCG Before Blaming the Model
  • Choosing a Vector Index: Flat, HNSW or IVF-PQ, a Memory Estimate, and Filters That Starve Small Customers
  • Citations and Abstention in RAG: What a Citation Proves, and When the Right Answer Is "It's Not in the Documents"
  • Embedding Migration With Zero Downtime: Two Indexes, a Dual-Write Backfill, a Shadow Check and a Flag
  • Cosine, Dot Product or Euclidean Distance: Why Three Measures Pick Three Winners, and the One Fix
  • Choosing an Embedding Model: Dimension, Context Length, Domain and Cost, Tested on Your Own Questions
  • Loading and Parsing Real Documents for RAG: PDF Headers, Wrapped Lines, Tables and HTML Chrome, Scored
  • Where Naive RAG Fails: Five Ways the Simplest Retriever Hands the Model the Wrong Pages
  • RAG Generation Metrics: Faithfulness, Groundedness and Relevance, One Claim at a Time
  • Context Engineering for a Long-Running Agent: Clear, Compact, Take Notes, Prove It
  • What LangChain Is For, and When to Skip It: Five Standard Parts, One Pipe, and a Decision Table
  • Why Chains Break: No Branch, No Retry, No Pause, and the Same Refund Assistant as a LangGraph Graph
  • LangGraph Nodes, Edges and State: Build Your First Graph, Route With a Conditional Edge, and Read the Run Three Ways
  • Human-in-the-Loop and Checkpointing in LangGraph: interrupt, a SQLite Save Slot and Command(resume=...)
  • Multi-Agent Patterns: Hub and Spoke in LangGraph, With Short Briefs, Owned Tools and a Retry the Hub Decides
  • A Research Agent in LangGraph: Plan, Search, Read, Write, and a Check Node That Rejects Citations Nobody Read
  • Workflow or Agent: Decide Who Picks the Next Step, Then Let the Constraints Choose the Design
  • Custom Agent Loops and Harnesses: A Dispatch Table, an Approval Hold, Error Results and a Turn Budget
  • Building an MCP Server: Tools, Resources and Prompts in Python and TypeScript
  • MCP Transports: stdio or Streamable HTTP, and Who Starts the Server
  • Deploying and Authenticating an MCP Server: Environment Keys for stdio, Bearer Tokens and Scopes for HTTP
  • From ML Metrics to LLM Evals: Same Ruler, New Targets
  • Why You Cannot Ship an LLM Feature Without an Eval: Five Parts, Three Graders, One Tiny Eval
  • Building a Golden Dataset for LLM Evals: Cases, a Schema, a Coverage Table and a Seeded Split
  • Retrieval Evals: Score the Retriever With Recall@K, MRR and nDCG Before Blaming the Model
  • Regression Testing an LLM Bot in CI: A Golden Set, Two pytest Gates and GitHub Actions
  • Testing a RAG Bot Before It Ships: Slices, a Release Gate per Slice, and the Week After
  • RAG Generation Metrics: Faithfulness, Groundedness and Relevance, One Claim at a Time
  • LLM-as-Judge: Write a Rubric, Check Every Verdict, and Trust the Grader Only After Kappa Says So
  • RAGAS and Custom Evals: Framework Faithfulness Plus Your Own Citation and Required-Fact Checks, Behind One Gate
  • Which Test Layer Owns the Failure? Unit, Functional, Integration and End-to-End Tests for a Claude App
  • Six Ways a 200 Can Still Be Wrong: Hallucination, Refusal, Under-Acting, Context Loss, Format Drift and Inconsistency
  • Proving a Model Upgrade Is Ready: A Frozen Golden Set, a Calibrated Judge, the Right Layer and a Release Gate
  • Fallback Models for an LLM App: A Chain That Checks Region and Fit, Flags Degraded Answers and Gets Rehearsed
  • Back Pressure for LLM Traffic: Bound the Queue, Give Chat Its Own Lane, Count Tokens, Cancel When the Caller Leaves
  • Load Balancing LLM Traffic: Count the Work, Weigh the Prefix Cache, Check Real Health, Drain Before Deploys
  • A Message Queue for Document Ingestion: At Least Once, Leases, an Idempotent Consumer and a Dead Letter Queue
  • Caching for AI Apps: Four Layers, What Goes in Each Key, and How a Delete Travels
  • Semantic Caching: Why a Similarity Threshold Can't Stop Confident Wrong Answers
  • LLM Model Routing: Rules, a Classifier or a Cascade, Judged on Cost per Win and Every Topic
  • Cutting p95 and Cost in Half for an LLM App: Read the Bill, Match the Lever, Guard Success
  • Observability and Tracing for LLM Apps: A Span per Stage, Redaction First, Bad Traces Become Tests
  • Guardrails for an LLM Agent: Check What Comes In, What It Wants to Do, and What Goes Out
  • Embedding Migration With Zero Downtime: Two Indexes, a Dual-Write Backfill, a Shadow Check and a Flag
  • Design a Multi-Tenant RAG Assistant, Part 1: Requirements, Rough Numbers and a Contract
  • Design a Multi-Tenant RAG Assistant, Part 2: Tenant Isolation, a Scoped Cache and Walking an Outage
  • A 500 MB PDF Takes 50 s to Answer, Get It to 2 s: Measure First, Then Promise Per Path
  • A 500 MB PDF From 50 s to 2 s, the Fast Path: Queue, Status, Streaming and an Acceptance Test That Fails
  • Guardrails for an LLM Agent: Check What Comes In, What It Wants to Do, and What Goes Out
  • Prompt Injection, Jailbreaks and Untrusted Input: Label What Comes In, Gate What Goes Out
  • Injection Exposure Review for an Agent: Map Inputs, Data and Effects, Layer Every Path, Retest the Job
  • Data Leakage and PII in LLM Apps: Redact, Minimize, Log Safely and Count Every Place
  • Hooks That Block Destructive Actions: a PreToolUse Gate That Allows, Asks or Denies
  • Claude API Keys: Keep the Key on a Server Proxy, One Key per Environment, Rotate and Scope It
  1. Blog
  2. /
  3. AI Engineering
  4. /
  5. LLM Fundamentals

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.

Chaand Sheikh

·27 November 2026LLM Fundamentals

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.

Plain call against stream=True plain call nothing on screen whole reply, 1.32 s stream=True first word, 0.14 s done, 1.35 s 0 s 0.5 s 1.0 s 1.5 s
Same question, two ways, from the run below. The total time is about the same; what the customer feels is the first word.

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:

  1. stream=True is 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.
  2. Print each text piece. That's the for loop. Each chunk carries a small bit of text in chunk.choices[0].delta.content. Some chunks carry no text (the last one only says the reply has stopped), so if text: skips them.
  3. Seconds since the request started. start notes 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.

Retries with a growing wait, then the fallback Busy model: 429, 500, then ok call 1 429 call 2 500 call 3 ok, reply 0.2 s 0.4 s Model down: no answer in 5 s, every time call 1 timeout call 2 timeout call 3 timeout call 4 timeout 0.2 s 0.4 s 0.8 s give up after 4 tries; the customer sees one calm sentence: "Sorry, our assistant is busy. Please try again in a minute."
Retry only what can pass later, double the wait each time, and stop after four tries with a polite fallback.

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
  1. 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.
  2. At most four attempts, exponential wait from 0.2 seconds. That's the @retry decorator: stop_after_attempt(4) and wait_exponential(multiplier=0.2, max=2). Exponential just means the wait doubles every time, and max=2 caps it at 2 seconds.
  3. A line before each wait. before_sleep=log_retry, so you can see what's going on.
  4. The polite fallback. reraise=True hands the last error back after the fourth attempt, and safe_ask catches it and returns FALLBACK instead 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 forThen check
stream=True, print pieces as they arriveempty pieces are skipped
which errors to retry: 429, 500, timeoutonly those errors are retried
max attempts and a growing waitSDK max_retries=0, so one layer retries
a timeout on every callno call can wait forever
a polite fallback messagethe user never sees a stack trace

Common mistakes

  • Printing every chunk without if text:. Some chunks carry no text, and you print None.
  • 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_retries plus 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

JobCodeIn the run
Show the first word earlystream=True, loop, delta.contentfirst word 0.14 s, done 1.35 s; plain call 1.32 s
Retry what can passretry_if_exception_type(RETRY_ON)429 and 500, then ok
Wait longer each timewait_exponential(multiplier=0.2, max=2)0.2, 0.4, 0.8 s
Don't wait forevertimeout=5, stop_after_attempt(4)gives up after the fourth timeout
One retry layermax_retries=0not 3 x 4 = 12 calls
Fail politelysafe_ask returns FALLBACK"Sorry, our assistant is busy..."

Try it yourself

  1. Run the demos and the offline tests: python demo.py stream, python demo.py resilient, then python demo.py tests.
  2. Break something: change a scene's script to ("500", "500", "ok") and read the log.
  3. 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.

Tried the exercise? Share your answer or ask a question.

The StudyEasy AI Community is free to join, with the lesson files, notebooks and code.

Join free on Skool

Keep going in AI Engineering · 8 of 79

Previous
Open vs Closed LLMs: Cost, Control, Privacy and Capability, Decided per Workload
Next post
Practice: Build a CLI Chat Tool with Memory, Commands, Error Handling and a History Cap

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.

On this page

  • How streaming works
  • Stream a reply in code
  • Retry, and wait longer each time
  • And when nobody answers?
  • Retries with tenacity
  • What the log tells you
  • Your prompt checklist
  • Common mistakes
  • Quick recap
  • Try it yourself
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

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)

Single logo

Empowering Education, One Course at a Time

About
About usContact usFAQs
Legal
Terms of ServicePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.