Timeouts, retries and streaming with the OpenAI Python SDK: the defaults that surprised me

●3 ●5
calendar_today • schedule2 min read

I run the same code against several OpenAI-compatible endpoints: hosted ones, a gateway, and a local server. Three SDK defaults caused most of my production issues.

1. The default read timeout is 10 minutes. openai.DEFAULT_TIMEOUT is Timeout(connect=5.0, read=600, write=600, pool=600). A hung upstream keeps a worker busy for up to 10 minutes. Set it explicitly:

import os
from openai import OpenAI, Timeout

client = OpenAI(
    base_url=os.environ.get("LLM_BASE_URL", "https://api.china-aiapi.com/v1"),
    api_key=os.environ["LLM_API_KEY"],
    timeout=Timeout(60.0, connect=5.0),  # 60 s read/write/pool, 5 s connect
    max_retries=2,                       # the default; shown so it's visible
)

2. Retries multiply. The SDK retries on connection errors, 408, 409, 429 and 5xx, with backoff, and honours Retry-After. If your gateway or proxy also retries, one slow request can turn into 3 × N upstream attempts. Pick one layer to own retries. If the server side already does it, use max_retries=0 in the client, or set it per call:

quick = client.with_options(max_retries=0, timeout=20.0)

3. Streams are only retried before the first byte. Once tokens are flowing, a dropped connection raises in the middle of your loop, and replaying the request would duplicate output the user has already seen. Handle that case yourself:

from openai import APIConnectionError, APITimeoutError

def stream_answer(prompt: str) -> str:
    parts = []
    try:
        stream = client.chat.completions.create(
            model="MODEL_ID",
            messages=[{"role": "user", "content": prompt}],
            stream=True,
            stream_options={"include_usage": True},
        )
        for chunk in stream:
            if chunk.choices and chunk.choices[0].delta.content:
                parts.append(chunk.choices[0].delta.content)
                print(chunk.choices[0].delta.content, end="", flush=True)
            if chunk.usage:  # final chunk: choices is empty, usage is set
                print(f"\n[{chunk.usage.total_tokens} tokens]")
    except (APIConnectionError, APITimeoutError):
        if parts:
            parts.append(" [connection lost, answer incomplete]")
        else:
            raise  # nothing shown yet: safe to retry at a higher level
    return "".join(parts)

Note the if chunk.choices check. With include_usage, the last chunk has an empty choices list, and chunk.choices[0] throws IndexError at the very end of an otherwise good answer.

I'd like to hear how others split retries between client and gateway.

Disclosure: I work on the APIGOTO team; APIGOTO is independent of OpenAI, Anthropic and Google. The default base URL above is ours (www.china-aiapi.com), but everything here applies to any OpenAI-compatible endpoint.

Want more #python & #llm deep dives?

Join 6,183+ developers sharing real benchmarks, code breakdowns, and projects. Free forever.

2 Comments

0 votes
0

More Posts

The Zero-Net-Loss Fleet & The Mercenary Squad: A Live AI Economy

DEVPlank - Aug 4

Sovereign Intelligence: The Complete 25,000 Word Blueprint (Download)

Pocket Portfolio - Apr 1

Dashboard Operasional Armada Rental Mobil dengan Python + FastAPI

Masbadar - Mar 12

The Privacy Gap: Why sending financial ledgers to OpenAI is broken

Pocket Portfolio - Feb 23

When One Python Process Fails, You Need to See All of Them

Tom Smithverified - Nov 23
chevron_left
162 Points • 8 Badges
2Posts
2Comments

Related Jobs

View all jobs →

Commenters (This Week)

1 comment
1 comment

Contribute meaningful comments to climb the leaderboard and earn badges!