OpenAI Python SDK: Streaming bricht bei eigenem base_url ab
Wer das OpenAI Python SDK auf eine eigene base_url umleitet, sieht oft ein charakteristisches Muster: normale Aufrufe funktionieren, Streaming-Aufrufe hängen, werden mitten im Durchlauf abgeschnitten oder sterben mit einem IndexError beim letzten Event. Ein Artikel beschreibt eine systematische Diagnose-Reihenfolge für dieses Problem.

Veröffentlicht am 24. Nov • Ursprünglich veröffentlicht auf tokenaimodels.com
Du hast das OpenAI Python SDK auf eine neue base_url umgestellt. Der blockierende Aufruf funktioniert einwandfrei, also sind Schlüssel und Netzwerk nachgewiesen. Der Streaming-Aufruf hängt, bricht auf halbem Weg ab oder stirbt mit IndexError: list index out of range bei einem Event, das wie das letzte aussieht.
Dieser Artikel ist eine Diagnose-Reihenfolge rather als eine Liste von Tipps: Bestätige, welchen Host du tatsächlich erreichst, weise nach, dass der Transport nicht puffert, sichere den usage-Block ab, egal ob er auf dem finish-Chunk ankommt oder in einem eigenen Event mit leerem choices-Array, und trenne die SDK-eigenen Retries von deinen eigenen. Er liefert eine lauffähige Probe, die Time-to-first-token, Chunk-Anzahl und Token-Verbrauch ausgibt, drei konkrete Fehler mit exakten Fixes sowie die Prüfungen, die nur hinter einem Gateway relevant sind.
Ein Austausch der base_url ändert vier Dinge gleichzeitig, und nur eines davon ist ein Hostname. Der Request-Pfad bleibt /v1/chat/completions, aber die Maschinerie dahinter, also TLS-Terminator, HTTP-Server, Ingress, Proxy und die eigene Edge des Modell-Anbieters, ist ein anderer Stack mit anderen Puffer-Defaults, anderen Idle-Timeouts und einem anderen Error-Envelope. Wenn der blockierende Aufruf funktioniert und der Streaming-Aufruf nicht, hast du mit an Sicherheit grenzender Wahrscheinlichkeit den Vertrag bestätigt und den Transport gebrochen. Behandle das ab der ersten Minute als getrennte Probleme, sonst verbringst du einen Nachmittag damit, das SDK für einen Bug zu tunen, der in einer nginx-Konfiguration zwei Hops entfernt sitzt.
Zwei Umgebungsvariablen verursachen hier mehr Probleme als alles andere im Code. Das Python SDK liest OPENAI_API_KEY und OPENAI_BASE_URL aus der Umgebung, wenn du sie nicht explizit übergibst. Ein veralteter Export OPENAI_BASE_URL=https://api.openai.com/v1 in einem Shell-Profil gewinnt stillschweigend, dein Schlüssel wird an den falschen Dienst geschickt, und die 401 sieht wie ein Schlüssel-Problem aus. Gib die aufgelösten Werte aus, bevor du irgendetwas anderes debuggst.
import os print ( "key set:", bool ( os. environ. get ( "MODELRY_API_KEY" ) ) ) print ( "OPENAI_BASE_URL env:", os. environ. get ( "OPENAI_BASE_URL", "<unset>" ) ) Vollbildmodus öffnen Vollbildmodus verlassen Schritt 1: Nachweisen, welcher Host antwortet Hostnamen sind nicht austauschbar, selbst nicht auf derselben Domain. Eine Marketing-Apex ( tokenaimodels.com ) steht normalerweise vor einem CDN, das für HTML gebaut ist: Es kann eine Antwort puffern, bis ein Schwellenwert erreicht ist, und Bytes in einem Kompressions-Puffer halten, die auf weitere Eingabe warten. Ein API-Host ( api.tokenaimodels.com ) ist die direkte Verbindung.
Auf der Plattform, gegen die dieser Artikel geschrieben wurde, steht das explizit in der Dokumentation: Der Apex wird per CDN ausgeliefert und kann puffern, die api-Subdomain garantiert Token-für-Token-Streaming. Prüfe, ob die Bytes in Stücken bei dir ankommen, bevor du eine einzige Zeile Anwendungscode anfasst:
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 Vollbildmodus öffnen Vollbildmodus verlassen Ein ttfb nahe an total ist das Kennzeichen einer gepufferten Antwort: Das erste Byte kam erst an, als das letzte Byte kam. -N deaktiviert das eigene Puffern von curl, sodass du das Verhalten des Servers misst, nicht das des Clients.
Der folgende Client ist absichtlich gesprächig. Er setzt ein explizites Read-Timeout, deaktiviert die SDK-Retries, damit der erste echte Fehler sichtbar wird, fordert usage im Stream an, sichert das usage-only-Event ab und gibt Zeitmessungen aus, die zwischen „langsam beim Starten“ und „kommt als ein Klumpen an“ unterscheiden.
#!/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 ( ) ) Vollbildmodus öffnen Vollbildmodus verlassen export MODELRY_API_KEY = "sk-live-..." python3 stream_probe.py Vollbildmodus öffnen Vollbildmodus verlassen Die drei Zahlen lesen chunks=1 bedeutet, dass die gesamte Antwort in einem einzigen Event ankam. Nichts, was du im SDK änderst, behebt das; ein Proxy hat den Body gepuffert oder der Dienst hat überhaupt nicht gestreamt. chunks in den Hunderten mit ttft unter einer Sekunde ist ein gesunder Stream. max_gap im Bereich von Dutzenden Sekunden bei kleinem ttft ist eine Pause auf Modellseite, kein Transportproblem. Reasoning-Workloads werden vor dem ersten Delta legitimerweise still.
Usage kommt irgendwo am Ende des Streams an, und die Form hängt vom Gateway ab: Auf unserem eigenen Endpoint saß der usage-Block auf dem Chunk, der finish_reason: stop trug, während choices noch gefüllt war; andere OpenAI-kompatible Gateways senden ein separates usage-only-Event mit leerem choices-Array. Code, der eine Form annimmt, bricht auf der anderen. Ein bedingungsloses Indizieren von event.choices stirbt auf der Variante mit leerem Array, und zwar nachdem die gesamte Antwort bereits ausgegeben wurde, wodurch der Traceback wie ein Bug am Anfang der Antwort aussieht. Sichere den leeren Fall ab und speichere den usage-Block (genau das tut der Zweig if not event.choices oben).
Wenn du stream_options verwendest, beachte, dass manche Gateways {"include_usage": true} in deinem Namen injizieren, sodass das usage-Event erscheint, auch wenn du es nie angefordert hast.
Drei verschiedene Uhren sind im Spiel, und es ist nicht dieselbe Uhr. Das Read-Timeout des SDK bestimmt, wie lange es auf das nächste Byte wartet. Das Request-Timeout des Servers bestimmt den gesamten Aufruf, auf dieser Plattform 280 Sekunden, danach wird die Verbindung ungeachtet der Aktivität geschlossen.
Dein eigener Reverse-Proxy kann eine dritte haben, üblicherweise 60 Sekunden, geerbt aus einer Default-Konfiguration, die für HTML-Seiten geschrieben wurde. Lange Reasoning-Aufrufe sind das übliche Opfer: Ein einzelner Request kann minutenlang nachdenken, bevor das erste Token kommt. Fixes, in der Reihenfolge der Wahrscheinlichkeit: Selbst dann streamen, wenn du die gesamte Antwort willst, das Client-Idle-Timeout deutlich über deine erwartete Time-to-first-token anheben und proxy_buffering off (plus proxy_read_timeout) auf jedem nginx setzen, den du betreibst.
Setze max_retries nicht über null, solange du nicht weißt, welche der drei Uhren zugeschlagen hat. Retries verwandeln eine Diagnose in einen Timeout-Sturm.
Klassisches Puffern, und fast immer der Apex-Host oder ein CDN davor. Drei Prüfungen: der Hostname ( api. statt des Apex), die Response-Header ( Transfer-Encoding: chunked vorhanden, Content-Encoding abwesend) und deine eigene Proxy-Konfiguration. Die Dokumentation eines Gateways sagt dir, welcher Host direkt ist. Glaube der Dokumentation mehr als deiner DNS-Intuition, denn beide Hosts antworten üblicherweise mit 200, und nur einer von ihnen streamt.
Ein Gateway ist ein zweiter Hop, den du nicht kontrollierst, deshalb ändern sich vier Dinge in einer Weise, die das SDK nicht abbildet. Erstens ist der Error-Envelope normalisiert, aber die Codes sind die des Gateways: 402 insufficient_balance ist ein Fehler des Prepaid-Guthabens, kein Fehler eines Quota-Plans, und kein noch so häufiges Retry hebt ihn auf. Zweitens trägt jede Response einen x-request-id Header, der der einzige Anhaltspunkt ist, um einen Request durch das Gateway bis zum Anbieter zu verfolgen. Logge ihn bei Fehlern, sonst hast du nichts, das du in einem Support-Ticket zitieren kannst.
Drittens findet ein Failover nur vor dem ersten Token statt, und nur dann, wenn ein zweiter Kanal konfiguriert ist: Sobald die Ausgabe begonnen hat, ist die Antwort festgelegt, daher ist ein Abbruch mitten im Stream eine fehlgeschlagene Anfrage, und ein erneuter Versuch dupliziert Text, für den bereits bezahlt wurde. Viertens gibt es keine SSE-Keep-alive-Kommentarzeilen, sodass Schweigen der Normalzustand einer langen Generierung ist und der Idle-Timeout auf Basis von Messungen festgelegt werden sollte, nicht anhand einer Vorlage. Und wenn das Gateway Nutzungsdaten meldet, sollten diese Zahlen als maßgeblich behandelt werden: Gleichen Sie die eigene Abrechnung immer mit der Usage des letzten Ereignisses ab, niemals mit einer Token-Schätzung.
Erstellen Sie einen kostenlosen Schlüssel unter https://tokenaimodels.com, richten Sie den Probe auf https://api.tokenaimodels.com/v1, und Sie wissen binnen einer Minute, ob Ihr Stream echt, gepuffert oder tot ist.
Modelry ist ein unabhängiger Plattformbetreiber, der einen vorausbezahlten, nutzungsbasierten Endpunkt für die DeepSeek-Modelle betreibt, ohne dass bei der Registrierung eine Kreditkarte nötig ist, und mit einem Ausgabenlimit für jeden Schlüssel: https://tokenaimodels.com/signup?utm_source=devto&utm_medium=post&utm_campaign=why_your_openai
Automatisch übersetzt. Das Original auf Englisch ist unten aufklappbar.
Original (Englisch) anzeigen
Posted on Nov 24 • Originally published at tokenaimodels.com
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.
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>" ) ) Enter fullscreen mode Exit fullscreen mode 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 Enter fullscreen mode Exit fullscreen mode 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.
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 ( ) ) Enter fullscreen mode Exit fullscreen mode export MODELRY_API_KEY = "sk-live-..." python3 stream_probe.py Enter fullscreen mode Exit fullscreen mode 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.
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 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.
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.
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.
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 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