{"slug": "openai-python-sdk-stream-hangs-on-base-url-switch", "title": "OpenAI Python SDK stream hangs on base_url switch", "summary": "A developer published a diagnostic guide for debugging OpenAI Python SDK streaming failures that appear after switching base_url, arguing that a working blocking call proves the API contract but not the transport. The guide provides a runnable probe that prints time-to-first-token, chunk count and token usage, plus fixes for three concrete failures: stale OPENAI_BASE_URL environment variables, CDN-buffered apex hostnames versus direct api subdomains, and usage blocks arriving in a separate event with an empty choices array.", "body_md": "You repointed the OpenAI Python SDK at a new base_url. The blocking call returns fine, so the key and the network are proven. The streaming call hangs, truncates halfway, or dies with `IndexError: list index out of range` on what looks like the last event. This article is a diagnosis order rather than a list of tips: confirm which host you are actually hitting, prove the transport is not buffering, guard the usage block whether it arrives on the finish chunk or in its own event with an empty `choices` array, and separate SDK-level retries from your own. It ships one runnable probe that prints time-to-first-token, chunk count and token usage, three concrete failures with exact fixes, and the checks that only apply behind a gateway.\n\nSwapping `base_url` changes four things at once, and only one of them is a hostname. The request path stays `/v1/chat/completions`, but the machinery behind it — TLS terminator, HTTP server, ingress, proxy, the model provider's own edge — is a different stack with different buffering defaults, different idle timeouts and a different error envelope. When the blocking call works and the streaming call does not, you have almost certainly proved the *contract* and broken the *transport*. Treat those as separate problems from the first minute, or you will spend an afternoon tuning the SDK for a bug sitting in an nginx config two hops away.\n\nTwo environment variables bite here more than anything in the code. The Python SDK reads `OPENAI_API_KEY` and `OPENAI_BASE_URL` from the environment when you do not pass them explicitly. A stale `export OPENAI_BASE_URL=https://api.openai.com/v1` in a shell profile will silently win, your key will be sent to the wrong service, and the 401 will look like a key problem. Print the resolved values before you debug anything else.\n\n``` python\nimport os\nprint(\"key set:\", bool(os.environ.get(\"MODELRY_API_KEY\")))\nprint(\"OPENAI_BASE_URL env:\", os.environ.get(\"OPENAI_BASE_URL\", \"<unset>\"))\n```\n\nHostnames are not interchangeable, even on the same domain. A marketing apex (`tokenaimodels.com`) is normally fronted by a CDN built for HTML: it may buffer a response until a threshold size is reached, and it may hold bytes in a compression buffer waiting for more input. An API host (`api.tokenaimodels.com`) is the direct connection. On the platform this article was written against, the documentation states this explicitly — the apex is CDN-served and may buffer, the `api` subdomain guarantees token-by-token streaming. Verify the bytes reach you in pieces before you touch a single line of application code:\n\n```\ncurl -sS -N -o /dev/null -w 'connect=%{time_connect}s ttfb=%{time_starttransfer}s total=%{time_total}s\\n' \\\\\n  -H \"Authorization: Bearer $MODELRY_API_KEY\" \\\\\n  -H \"Content-Type: application/json\" \\\\\n  -d '{\"model\":\"deepseek-chat\",\"messages\":[{\"role\":\"user\",\"content\":\"Count from 1 to 60.\"}],\"stream\":true,\"max_tokens\":300}' \\\\\n  https://api.tokenaimodels.com/v1/chat/completions\n```\n\nA `ttfb` close to `total` is the signature of a buffered response: the first byte arrived only when the last byte did. `-N` disables curl's own buffering, so what you measure is the server's behaviour, not the client's.\n\nThe client below is deliberately noisy. It sets an explicit read timeout, disables SDK retries so the first real failure is visible, asks for usage in the stream, guards the usage-only event, and prints timing statistics that distinguish \"slow to start\" from \"arrives in one lump\".\n\n``` bash\n#!/usr/bin/env python3\n\"\"\"stream_probe.py — show whether a base_url really streams, and where it breaks.\"\"\"\nimport os, sys, time\nfrom openai import OpenAI, APIStatusError, APITimeoutError\n\nBASE_URL = os.environ.get(\"BASE_URL\", \"https://api.tokenaimodels.com/v1\")\nMODEL = os.environ.get(\"MODEL\", \"deepseek-chat\")\n\nclient = OpenAI(\n    api_key=os.environ[\"MODELRY_API_KEY\"],\n    base_url=BASE_URL,\n    timeout=180.0,   # read timeout, not just connect timeout\n    max_retries=0,   # we want failure #1, not failure #3\n)\n\ndef main() -> int:\n    started = time.monotonic()\n    ttft = None\n    marks: list[float] = []\n    parts: list[str] = []\n    usage = None\n    try:\n        stream = client.chat.completions.create(\n            model=MODEL,\n            messages=[{\"role\": \"user\",\n                       \"content\": \"List five causes of TCP retransmission, one line each.\"}],\n            stream=True,\n            stream_options={\"include_usage\": True},\n            max_tokens=400,\n        )\n        for event in stream:\n            if not event.choices:            # usage-only event, sent before [DONE]\n                usage = event.usage\n                continue\n            delta = event.choices[0].delta\n            chunk = getattr(delta, \"content\", None)\n            if not chunk:\n                continue\n            now = time.monotonic()\n            if ttft is None:\n                ttft = now - started\n            marks.append(now)\n            parts.append(chunk)\n            print(chunk, end=\"\", flush=True)\n    except APITimeoutError as exc:\n        print(f\"\\nTIMEOUT after {time.monotonic() - started:.1f}s: {exc}\", file=sys.stderr)\n        return 2\n    except APIStatusError as exc:\n        rid = exc.response.headers.get(\"x-request-id\", \"-\")\n        print(f\"\\nHTTP {exc.status_code} x-request-id={rid}: {exc.message}\", file=sys.stderr)\n        return 3\n\n    total = time.monotonic() - started\n    gaps = [b - a for a, b in zip(marks, marks[1:])] or [0.0]\n    print()\n    print(f\"chunks={len(marks)} chars={sum(len(p) for p in parts)}\")\n    print(f\"ttft={ttft or 0:.2f}s total={total:.2f}s max_gap={max(gaps):.2f}s\")\n    if usage is not None:\n        details = getattr(usage, \"prompt_tokens_details\", None)\n        cached = getattr(details, \"cached_tokens\", 0) or 0\n        print(f\"tokens in={usage.prompt_tokens} cached={cached} out={usage.completion_tokens}\")\n    return 0 if ttft is not None else 1\n\nif __name__ == \"__main__\":\n    sys.exit(main())\nexport MODELRY_API_KEY=\"sk-live-...\"\npython3 stream_probe.py\n```\n\n`chunks=1` means the whole answer arrived in a single event. Nothing you change in the SDK will fix that; a proxy buffered the body or the service did not stream at all. `chunks` in the hundreds with `ttft` under a second is a healthy stream. `max_gap` in the tens of seconds with a small `ttft` is a model-side pause, not a transport problem — reasoning workloads legitimately go quiet before the first delta.\n\n`IndexError: list index out of range` on the final event\nUsage arrives somewhere in the tail of the stream, and the shape depends on the gateway: on our own endpoint the usage block rode on the chunk that carried `finish_reason: stop`, with `choices` still populated, while other OpenAI-compatible gateways send a separate usage-only event with an **empty** `choices` array. Code that assumes one shape breaks on the other — indexing `event.choices[0]` unconditionally dies on the empty-array variant — after having printed the entire answer, which makes the traceback look like a bug at the beginning of the response. Guard the empty case and store the usage block (that is what the `if not event.choices` branch above does). If you are on `stream_options`, note that some gateways inject `{\"include_usage\": true}` on your behalf, so the usage event appears even when you never asked for it.\n\n`APITimeoutError`\nThree different clocks are in play and they are not the same clock. The SDK's read timeout governs how long it waits for the *next* byte. The server's request timeout governs the whole call — on this platform 280 seconds, after which the connection is closed regardless of activity. Your own reverse proxy may have a third, usually 60 seconds, inherited from a default config written for HTML pages. Long reasoning calls are the usual victim: a single request can think for minutes before the first token. Fixes, in order of likelihood: stream even when you want the whole answer, raise the client idle timeout well above your expected time-to-first-token, and set `proxy_buffering off` (plus `proxy_read_timeout`) on any nginx you own. Do not set `max_retries` above zero until you know which of the three clocks fired — retries turn a diagnosis into a timeout storm.\n\nClassic buffering, and almost always the apex host or a CDN in front of it. Three checks: the hostname (`api.` not the apex), the response headers (`Transfer-Encoding: chunked` present, `Content-Encoding` absent), and your own proxy config. A gateway's own docs will tell you which host is direct — believe the docs over your DNS intuition, because both hosts usually answer `200` and only one of them streams.\n\nA gateway is a second hop that you do not control, so four things change in ways the SDK does not model. **First**, the error envelope is normalised but the *codes* are the gateway's: `402 insufficient_balance` is a prepaid-balance failure, not a quota-plan failure, and no amount of retrying will clear it. **Second**, every response carries an `x-request-id` header that is the only handle for tracing a request through the gateway to the provider — log it on failure or you will have nothing to quote in a support ticket. **Third**, failover happens only *before* the first token, and only where a second channel is configured: once output has started the response is committed, so a mid-stream disconnect is a failed request and retrying it duplicates text you already paid for. **Fourth**, there are no SSE keep-alive comment lines, so \"silence\" is the normal state of a long generation and your idle timeout must be set from measurement, not from a template. And when the gateway reports usage, treat its numbers as authoritative: settle your own accounting against the last event's `usage`, never against a token estimate.\n\nCreate a free key at [https://tokenaimodels.com](https://tokenaimodels.com), point the probe at `https://api.tokenaimodels.com/v1`, and you will know inside a minute whether your stream is real, buffered, or dead.\n\n*Modelry is an independent platform operator running a prepaid, metered endpoint for the DeepSeek models — no card to sign up, and a spend cap on every key: [https://tokenaimodels.com/signup?utm_source=devto&utm_medium=post&utm_campaign=why_your_openai](https://tokenaimodels.com/signup?utm_source=devto&utm_medium=post&utm_campaign=why_your_openai)*", "url": "https://wpnews.pro/news/openai-python-sdk-stream-hangs-on-base-url-switch", "canonical_source": "https://dev.to/paipizze/openai-python-sdk-stream-hangs-on-baseurl-switch-333j", "published_at": "2026-11-24 05:42:24+00:00", "updated_at": "2026-11-24 05:46:03.431509+00:00", "lang": "en", "topics": ["ai-tools", "developer-tools", "large-language-models"], "entities": ["OpenAI", "Python", "tokenaimodels.com", "deepseek-chat"], "also_reported_by": [], "takeaway": "When a blocking call succeeds but streaming hangs after a base_url switch, curl with -N and compare ttfb to total to detect buffering, and guard the usage-only stream event that carries an empty choices array.", "recommendation": {"advice": "Before debugging SDK code, print the resolved OPENAI_BASE_URL and run a curl -N probe comparing ttfb to total to confirm the new host actually streams token by token.", "playbook": "production-ops", "playbook_url": "https://wpnews.pro/playbooks/production-ops"}, "alternates": {"html": "https://wpnews.pro/news/openai-python-sdk-stream-hangs-on-base-url-switch", "markdown": "https://wpnews.pro/news/openai-python-sdk-stream-hangs-on-base-url-switch.md", "text": "https://wpnews.pro/news/openai-python-sdk-stream-hangs-on-base-url-switch.txt", "jsonld": "https://wpnews.pro/news/openai-python-sdk-stream-hangs-on-base-url-switch.jsonld"}}