Notizen / 01

OpenAI Python SDK stream hangs on base_url switch

2026-11-17Modelry-Notizen

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.

The change that is never a one-line change

Swapping 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.

Two 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.

import os
print("key set:", bool(os.environ.get("MODELRY_API_KEY")))
print("OPENAI_BASE_URL env:", os.environ.get("OPENAI_BASE_URL", "<unset>"))

Step 1: prove which host is answering

Hostnames 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:

curl -sS -N -o /dev/null -w 'connect=%{time_connect}s ttfb=%{time_starttransfer}s total=%{time_total}s\n' \\
  -H "Authorization: Bearer $MODELRY_API_KEY" \\
  -H "Content-Type: application/json" \\
  -d '{"model":"deepseek-chat","messages":[{"role":"user","content":"Count from 1 to 60."}],"stream":true,"max_tokens":300}' \\
  https://api.tokenaimodels.com/v1/chat/completions

A 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.

Step 2: run a probe that reports instead of guessing

The 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".

#!/usr/bin/env python3
"""stream_probe.py — show whether a base_url really streams, and where it breaks."""
import os, sys, time
from openai import OpenAI, APIStatusError, APITimeoutError

BASE_URL = os.environ.get("BASE_URL", "https://api.tokenaimodels.com/v1")
MODEL = os.environ.get("MODEL", "deepseek-chat")

client = OpenAI(
    api_key=os.environ["MODELRY_API_KEY"],
    base_url=BASE_URL,
    timeout=180.0,   # read timeout, not just connect timeout
    max_retries=0,   # we want failure #1, not failure #3
)

def main() -> int:
    started = time.monotonic()
    ttft = None
    marks: list[float] = []
    parts: list[str] = []
    usage = None
    try:
        stream = client.chat.completions.create(
            model=MODEL,
            messages=[{"role": "user",
                       "content": "List five causes of TCP retransmission, one line each."}],
            stream=True,
            stream_options={"include_usage": True},
            max_tokens=400,
        )
        for event in stream:
            if not event.choices:            # usage-only event, sent before [DONE]
                usage = event.usage
                continue
            delta = event.choices[0].delta
            chunk = getattr(delta, "content", None)
            if not chunk:
                continue
            now = time.monotonic()
            if ttft is None:
                ttft = now - started
            marks.append(now)
            parts.append(chunk)
            print(chunk, end="", flush=True)
    except APITimeoutError as exc:
        print(f"\nTIMEOUT after {time.monotonic() - started:.1f}s: {exc}", file=sys.stderr)
        return 2
    except APIStatusError as exc:
        rid = exc.response.headers.get("x-request-id", "-")
        print(f"\nHTTP {exc.status_code} x-request-id={rid}: {exc.message}", file=sys.stderr)
        return 3

    total = time.monotonic() - started
    gaps = [b - a for a, b in zip(marks, marks[1:])] or [0.0]
    print()
    print(f"chunks={len(marks)} chars={sum(len(p) for p in parts)}")
    print(f"ttft={ttft or 0:.2f}s total={total:.2f}s max_gap={max(gaps):.2f}s")
    if usage is not None:
        details = getattr(usage, "prompt_tokens_details", None)
        cached = getattr(details, "cached_tokens", 0) or 0
        print(f"tokens in={usage.prompt_tokens} cached={cached} out={usage.completion_tokens}")
    return 0 if ttft is not None else 1

if __name__ == "__main__":
    sys.exit(main())
export MODELRY_API_KEY="sk-live-..."
python3 stream_probe.py

Reading the three numbers

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.

Failure 1: IndexError: list index out of range on the final event

Usage 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.

Failure 2: the stream stalls, then raises APITimeoutError

Three 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.

Failure 3: tokens arrive, but all at the end

Classic 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.

What to watch when you speak to a gateway instead of OpenAI

A 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.

Create a free key at 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.

Modelry betreibt eine Plattform, die DeepSeek-Modelle hinter einem HTTP-Endpoint bereitstellt; vorausbezahlte Credits und Steuern werden beim Kauf vom Merchant of Record abgewickelt, und die Datenaufbewahrung ist dokumentiert. Starten Sie mit $0.50 Testguthaben: Schlüssel erstellen.

Alle Notizen

OpenAI Python SDK stream hangs on base_url switch — Modelry