AiCredits
Streaming Guide

Streaming Responses With the OpenAI SDK Against Third-Party Endpoints

Streaming with the OpenAI SDK against OpenAI-compatible third-party endpoints: runnable code, retry safety, tool-call deltas, and buffering fixes in Python.

Published 2026-10-16 Updated 2026-10-16 9 min

Why Streaming Matters More on a Third-Party Endpoint

Against a first-party API you are talking to one well-known edge. Against an OpenAI-compatible gateway such as AiCredits, your request travels a different network path, so first-token latency is the number that moves around — sometimes by a lot. Streaming turns that variance into a non-issue: the user sees words almost immediately and the slow tail happens behind text they can already read.

When streaming works, it looks identical to the first-party experience. When it breaks, it breaks in boring, fixable ways: a proxy buffers the whole response, your code indexes chunk.choices[0] on a usage-only chunk, or a retry quietly duplicates half an answer. The patterns below survive all three.

1. The Minimal Streaming Client

import os
from openai import OpenAI

client = OpenAI(
    api_key=os.environ["AICREDITS_API_KEY"],
    base_url="https://api.aicreditsapi.com/v1",
)

stream = client.chat.completions.create(
    model="deepseek-v4-flash",
    messages=[{"role": "user", "content": "Summarize server-sent events in two sentences."}],
    stream=True,
    timeout=90,
)

for chunk in stream:
    # A usage-only final chunk (and some gateway keep-alives) have no choices.
    if not chunk.choices:
        continue
    delta = chunk.choices[0].delta
    if delta.content:
        print(delta.content, end="", flush=True)  # flush keeps the UI live
print()

Three details in that loop do real work. if not chunk.choices guards the final usage chunk that many compatible gateways send with an empty choices list — indexing blindly raises an IndexError at the worst possible moment. delta.content is None on the role chunk and on tool-call chunks, so check before printing. And flush=True stops Python from batching output when you pipe through Docker, systemd, or a shell redirect, which is a very common reason a working stream "looks broken".

If you want token accounting, many compatible endpoints accept stream_options={"include_usage": True} and then emit a last chunk where choices is empty and usage is populated. Support varies between providers, so treat usage as optional rather than assuming it.

2. Accumulating Tool Calls From Deltas

import os
from collections import OrderedDict
from openai import OpenAI

client = OpenAI(
    api_key=os.environ["AICREDITS_API_KEY"],
    base_url="https://api.aicreditsapi.com/v1",
)

stream = client.chat.completions.create(
    model="deepseek-v4-flash",
    messages=[{"role": "user", "content": "What is the weather in Lisbon right now?"}],
    tools=[{
        "type": "function",
        "function": {
            "name": "get_weather",
            "description": "Get the current weather for a city",
            "parameters": {
                "type": "object",
                "properties": {"city": {"type": "string"}},
                "required": ["city"],
            },
        },
    }],
    stream=True,
)

calls = OrderedDict()
finish = None

for chunk in stream:
    if not chunk.choices:
        continue
    choice = chunk.choices[0]
    if choice.finish_reason:
        finish = choice.finish_reason
    for tc in choice.delta.tool_calls or []:
        slot = calls.setdefault(tc.index, {"id": None, "name": "", "arguments": ""})
        if tc.id:
            slot["id"] = tc.id
        if tc.function:
            if tc.function.name:
                slot["name"] += tc.function.name
            if tc.function.arguments:
                slot["arguments"] += tc.function.arguments

for slot in calls.values():
    print(slot["name"], slot["arguments"], finish)

Tool calls arrive as fragments keyed by tc.index. The function name usually lands in the first fragment while the JSON arguments string drips in across many, so you concatenate strings and only parse at the end. Use += rather than a plain assignment for the name too — a gateway is allowed to split a long identifier across chunks, and silently keeping the last fragment is a subtle bug that only shows up in production.

3. Retries, Timeouts, and the Duplicate-Text Trap

import os
import time
from openai import APIConnectionError, APIStatusError, OpenAI

client = OpenAI(
    api_key=os.environ["AICREDITS_API_KEY"],
    base_url="https://api.aicreditsapi.com/v1",
)

def stream_text(prompt, model="deepseek-v4-flash", attempts=3):
    """Yield text deltas, retrying only while zero tokens have been emitted."""
    last_error = None
    for attempt in range(attempts):
        emitted = False
        try:
            stream = client.chat.completions.create(
                model=model,
                messages=[{"role": "user", "content": prompt}],
                stream=True,
                timeout=120,
            )
            for chunk in stream:
                if not chunk.choices:
                    continue
                piece = chunk.choices[0].delta.content
                if piece:
                    emitted = True
                    yield piece
            return
        except (APIConnectionError, APIStatusError) as exc:
            if emitted:
                # The user already saw text. A retry would duplicate it.
                raise
            last_error = exc
            time.sleep(1.5 * (attempt + 1))
    raise last_error

if __name__ == "__main__":
    for token in stream_text("List three practical uses for SSE."):
        print(token, end="", flush=True)

The rule is simple and easy to get wrong: retry only while emitted is False. Once a single delta has reached the user, a retry re-sends the whole prompt and the user watches the first sentence appear twice. Better to raise and let the UI show a truncated answer with a manual retry button.

Also note that for streaming responses the SDK's timeout covers reads between chunks, not just the initial connection. A generous read timeout is safer than a tight total timeout, because a model that pauses to think is not a model that has failed.

4. Re-Streaming to a Browser Without Buffering

import json
import os
from fastapi import FastAPI
from fastapi.responses import StreamingResponse
from openai import AsyncOpenAI

app = FastAPI()
client = AsyncOpenAI(
    api_key=os.environ["AICREDITS_API_KEY"],
    base_url="https://api.aicreditsapi.com/v1",
)

@app.get("/chat")
async def chat(q: str):
    async def events():
        stream = await client.chat.completions.create(
            model="deepseek-v4-flash",
            messages=[{"role": "user", "content": q}],
            stream=True,
        )
        try:
            async for chunk in stream:
                if not chunk.choices:
                    continue
                piece = chunk.choices[0].delta.content
                if piece:
                    yield "data: " + json.dumps({"delta": piece}) + "\n\n"
            yield "data: [DONE]\n\n"
        finally:
            await stream.close()

    return StreamingResponse(
        events(),
        media_type="text/event-stream",
        headers={
            "Cache-Control": "no-cache",
            "Connection": "keep-alive",
            "X-Accel-Buffering": "no",  # stops nginx from buffering the SSE body
        },
    )

Two failure modes appear once you put your own web layer in front of the gateway. First, nginx buffers proxied responses by default, so the whole SSE body lands at once — X-Accel-Buffering: no disables that for the route. Second, raw model text injected into a data: line breaks the protocol the instant the model emits a newline; wrapping each delta in json.dumps keeps every event on exactly one line.

While you are there: do not gzip text/event-stream, and if a CDN or WAF sits in front, check that it is not set to buffer responses. If a stream stalls in production but works on your laptop, the buffering layer is almost always the culprit.

What Actually Differs Between Providers

AreaWhat differsSafe handling
Final chunkSome gateways send a usage-only chunk with an empty choices list after finish_reason; others just stop.Skip chunks with an empty choices list; never index choices[0] without checking.
Keep-alivesComment or empty events may arrive during a long pause before the first token.The SDK filters them, but your own SSE proxy must not assume every event carries a delta.
Mid-stream errorsThe connection can drop after headers are sent, leaving no HTTP status to read.Treat an early end without finish_reason as a failure and surface it in the UI.
Usage reportingusage may be absent, or only sent when stream_options is supported.Read chunk.usage when it appears; fall back to your own accounting when it does not.
Proxy bufferingnginx and gzip can hold the entire stream until the response completes.Disable compression on the SSE route and send X-Accel-Buffering: no.
First-token latencyVariance is wider than against a first-party endpoint.Stream the output and use a generous read timeout instead of a tight total timeout.

Choosing a Model When Someone Is Watching

Streaming changes the model calculus. Because progress is visible, users tolerate a slower model far better than they tolerate a blank spinner — which makes deepseek-v4-pro a reasonable default for tasks where answer quality matters and a few extra seconds are acceptable. Keep deepseek-v4-flash as the default for anything interactive and short: chat turns, inline helpers, quick classification, drafting steps.

Cost behaves the same way either way: billing is per token whether or not you stream, cached input costs less than fresh input, off-peak traffic costs less than peak, and pro costs more than flash. A broken retry loop is the easiest way to pay twice for one answer, which is why the emitted guard above is a cost control as much as a UX control. Current rates live at aicreditsapi.com/pricing.

AiCredits exists for developers outside China who want DeepSeek models behind a plain OpenAI-compatible endpoint — pay by card or PayPal, no Chinese phone number or bank account required. Drop your key into the code above and it runs as written.

Quick Checklist

  • Iterate the stream object; never treat the return value as a string.

  • Guard chunk.choices and delta.content, and read finish_reason to detect truncation.

  • Retry only before the first delta reaches the user.

  • Disable proxy buffering and gzip on your SSE route; send X-Accel-Buffering: no.

  • JSON-encode every delta inside your data: line so newlines cannot break the protocol.

  • Treat usage as optional, but log it when present so you can reconcile spend.

  • Test with a deliberately long prompt — short answers hide inter-token gaps.

FAQ

Does streaming cost more than a normal request?

No. You are billed for tokens, not for transport, so the same prompt and the same answer cost the same streamed or not. What does cost extra is a retry after a partial answer: it re-sends the prompt and produces a second billed completion. Cache hits and off-peak traffic are cheaper, and pro costs more than flash. See aicreditsapi.com/pricing for current rates.

Can I use the official OpenAI SDK with a third-party endpoint?

Yes. Point base_url at the gateway and supply its key; the chat completions surface is the same REST shape the SDK already knows. Features beyond that — files, fine-tuning, assistants-style APIs — may not exist or may behave differently on any compatible provider, so verify per feature rather than assuming parity.

Why does my stream arrive as one giant chunk?

Almost always buffering: nginx proxy_buffering, a gzip layer, a CDN rule, or your own print without flush. Confirm the endpoint itself streams first with a no-buffer request in curl, then work outward through your stack. If curl streams and your app does not, the buffering is on your side.

Can I resume a stream that dropped halfway?

No. SSE has no resume semantics and the completion is already in flight server-side, so nothing is replayable. Show the partial text, mark it visibly as incomplete, and offer a fresh request instead of silently retrying behind the user's back.

Should I use deepseek-v4-flash or deepseek-v4-pro for a streaming UI?

Flash by default — it keeps perceived latency low, which is what a streaming interface is for. Switch to pro for reasoning-heavy answers where the user expects to wait a little, since streaming makes that wait feel productive rather than frozen.

Try Lint in 2 seconds

Wrote something? Paste it here for a free grammar check. No account needed.

More Tools →

Related Tools

💻Code Explainer

Was this article helpful?

| Share on X Reddit Copy link

服务器宕机了?别等用户告诉你

Wakeless 梦哨 帮你 30 秒监控网站 / API / SSL 证书,宕机秒级告警到邮箱、飞书、Slack。免费档 30 个监控,永久免费,无需信用卡。

免费开始监控 →
💬
反馈意见 / Feedback ×