AiCredits
SSE in Practice

DeepSeek API Streaming Responses: Server-Sent Events in Practice

Learn DeepSeek API streaming responses with SSE: runnable OpenAI SDK code, chunk parsing pitfalls, FastAPI and Node.js patterns, and production hardening.

Published 2026-09-22 Updated 2026-09-22 8 min

Streaming Is a Latency Decision, Not a Feature Flag

Most teams bolt streaming on at the end of a project, treat it as a UI nicety, and then discover it quietly rewires their architecture: partial state, mid-stream failures, cancellation semantics, and token accounting that only shows up after the last byte. The payoff is real — the user starts reading the first sentence while the model is still writing the fifth — but it only arrives if you handle the framing correctly.

This post is about that framing: Server-Sent Events as the DeepSeek chat completions endpoint exposes them, what the chunks actually contain, and the handful of parsing and infrastructure mistakes that make streaming look broken when it is working fine.

What SSE Actually Looks Like on the Wire

SSE is a plain-text protocol riding on a long-lived HTTP response. The server answers with text/event-stream and writes frames separated by a blank line; each frame is one or more field: value lines. DeepSeek's OpenAI-compatible endpoint emits exactly one JSON object per data: line and closes with a literal data: [DONE] sentinel.

HTTP/1.1 200 OK
Content-Type: text/event-stream

data: {"id":"cmpl_1","choices":[{"index":0,"delta":{"role":"assistant","content":""},"finish_reason":null}]}

data: {"id":"cmpl_1","choices":[{"index":0,"delta":{"content":"Server-Sent"},"finish_reason":null}]}

data: {"id":"cmpl_1","choices":[{"index":0,"delta":{"content":" Events"},"finish_reason":null}]}

data: {"id":"cmpl_1","choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}

data: [DONE]

Three consequences fall out of that shape, and they cause nearly every streaming bug:

  • The first frame carries the assistant role with an empty content string, and the last carries finish_reason with no content at all. Code that assumes every chunk contains text will throw.

  • Token metadata is not attached to every chunk. You must opt in, and read it from a final frame whose choices array is empty.

  • A chunk is not a message boundary. A word, an emoji, or an escape sequence can be split across two frames — concatenate first, render second.

A Minimal Streaming Client with the OpenAI SDK

AiCredits exposes an OpenAI-compatible endpoint, so you don't need a bespoke SDK or a proxy layer just to stream. Point the standard client at the base URL, turn on streaming, and iterate.

from openai import OpenAI

client = OpenAI(
    api_key="YOUR_AICREDITS_KEY",
    base_url="https://api.aicreditsapi.com/v1",
)

stream = client.chat.completions.create(
    model="deepseek-v4-flash",
    messages=[
        {"role": "system", "content": "You are a concise technical assistant."},
        {"role": "user", "content": "Explain SSE chunk framing in five bullets."},
    ],
    stream=True,
    stream_options={"include_usage": True},
)

for chunk in stream:
    if not chunk.choices:
        continue  # the final usage frame has no choices
    delta = chunk.choices[0].delta
    if delta and delta.content:
        print(delta.content, end="", flush=True)

print()

Passing stream_options={"include_usage": True} is what makes the final chunk useful: it arrives with an empty choices array and a populated usage field carrying prompt and completion token counts. Skip it and usage is None for the whole stream — an easy oversight to discover weeks later when you try to reconcile a bill against your logs.

Accumulating Text Without Breaking on Edge Chunks

When you need both incremental output and the complete string — for logging, moderation, or persistence — accumulate inside the same loop rather than issuing a second request. Guard every level of the chunk, because any of them can be absent.

from collections.abc import Iterator

from openai import OpenAI

client = OpenAI(
    api_key="YOUR_AICREDITS_KEY",
    base_url="https://api.aicreditsapi.com/v1",
)


def stream_text(
    prompt: str,
    sink: list[str] | None = None,
    model: str = "deepseek-v4-flash",
) -> Iterator[str]:
    """Yield text deltas, optionally accumulating the full reply in `sink`."""
    with client.chat.completions.create(
        model=model,
        messages=[{"role": "user", "content": prompt}],
        stream=True,
        stream_options={"include_usage": True},
    ) as stream:
        for chunk in stream:
            choice = chunk.choices[0] if chunk.choices else None
            if choice is None or choice.delta is None:
                continue
            text = getattr(choice.delta, "content", None)
            if not text:
                continue
            if sink is not None:
                sink.append(text)
            yield text


parts: list[str] = []
for piece in stream_text("Summarize SSE backpressure in two sentences.", sink=parts):
    print(piece, end="", flush=True)

print("\n--- full reply ---")
print("".join(parts))

Note the defensive getattr on the delta. Deployments can attach extra delta fields beyond content — reasoning traces, tool-call fragments, refusal text. Reading only delta.content keeps your code working when those appear, and tolerating unknown keys is far safer than assuming a frozen schema.

Serving SSE from Your Own Backend

In a browser app you rarely expose your AiCredits key to the client. You proxy through your own endpoint and re-emit SSE. The subtle part is that the frames are now yours to construct — and raw model text is not safe to drop into a data: line verbatim. A newline in the completion would terminate the frame early and corrupt the stream for every chunk that follows.

import json

from fastapi import FastAPI
from fastapi.responses import StreamingResponse
from openai import OpenAI

app = FastAPI()

client = OpenAI(
    api_key="YOUR_AICREDITS_KEY",
    base_url="https://api.aicreditsapi.com/v1",
)


def sse(data: str, event: str = "delta") -> str:
    # json.dumps keeps newlines and control characters from breaking the frame
    return f"event: {event}\ndata: {json.dumps(data)}\n\n"


@app.get("/chat")
def chat(q: str):
    def generate():
        stream = client.chat.completions.create(
            model="deepseek-v4-flash",
            messages=[{"role": "user", "content": q}],
            stream=True,
        )
        try:
            for chunk in stream:
                if not chunk.choices:
                    continue
                delta = chunk.choices[0].delta
                if delta and delta.content:
                    yield sse(delta.content)
            yield sse("[DONE]", event="done")
        except Exception as exc:
            yield sse(f"upstream error: {exc}", event="error")
        finally:
            stream.close()

    return StreamingResponse(
        generate(),
        media_type="text/event-stream",
        headers={
            "Cache-Control": "no-cache, no-transform",
            "Connection": "keep-alive",
            "X-Accel-Buffering": "no",
        },
    )

The json.dumps call is not decoration: it escapes newlines and control characters so each frame stays on one logical line. The X-Accel-Buffering: no header stops Nginx and similar reverse proxies from holding the response until completion, and media_type must be text/event-stream or the browser's EventSource will refuse the connection outright.

Close the upstream stream in a finally block. Without it, a user who navigates away leaves the upstream generation running to completion — you pay for tokens nobody will ever read.

Node.js Equivalent

import OpenAI from "openai";

const client = new OpenAI({
  apiKey: process.env.AICREDITS_API_KEY,
  baseURL: "https://api.aicreditsapi.com/v1",
});

const stream = await client.chat.completions.create({
  model: "deepseek-v4-flash",
  messages: [{ role: "user", content: "List three SSE failure modes." }],
  stream: true,
  stream_options: { include_usage: true },
});

let full = "";
for await (const chunk of stream) {
  const text = chunk.choices?.[0]?.delta?.content;
  if (text) {
    full += text;
    process.stdout.write(text);
  }
  if (chunk.usage) {
    console.error("usage:", chunk.usage);
  }
}

Production Gotchas and Their Fixes

SymptomLikely causeFix
Nothing renders until the whole response is doneReverse proxy or framework buffers the bodyDisable proxy buffering, send X-Accel-Buffering: no, flush after each frame
TypeError on NoneType.contentFirst frame is role-only; last frame has no contentGuard delta and delta.content before reading
Client parser errors on a chunk containing a newlineRaw text placed into a data: line verbatimJSON-encode the payload, decode on the client
usage is None for every requestinclude_usage was never requestedPass stream_options={"include_usage": True} and read the final frame
Upstream keeps generating after the user leavesStream never closed on disconnectClose in a finally block and break the loop when the client drops
Stream hangs with no error mid-responseUpstream exception swallowed by the iteratorCatch around the loop and emit an explicit error event before closing

Token Accounting, Cache Hits, and What Streaming Actually Costs

Streaming itself costs nothing extra. You pay for tokens, not transport. What changes is the shape of the bill: prompt tokens are re-sent on every turn of a conversation, cache hits on repeated prefixes are cheaper than fresh input, and off-peak traffic costs less than peak. If you are streaming into a chat UI, cache-friendly prompt layout — stable system prompt first, volatile user content last — is the biggest lever you control.

  • Log usage.completion_tokens per request; the final SSE frame is the only place it appears.

  • Keep the system prompt byte-identical across turns so prefix caching can apply.

  • Reserve deepseek-v4-pro for requests where a wrong answer is expensive; pro costs more than flash.

  • Interactive streaming should default to deepseek-v4-flash; batch non-urgent work off-peak where rates are lower.

  • Current rates for flash, pro, off-peak windows, and cache pricing are at aicreditsapi.com/pricing.

  • Lint your SSE handler like any other code — unawaited streams and missing close calls are exactly the kind of thing static checks catch before review.

AiCredits sells DeepSeek API credits to international developers — pay by card or PayPal, no Chinese phone number or bank account required — and the endpoint used throughout this article is the same one you would run in production.

Flash or Pro for Streaming Workloads?

deepseek-v4-flash is the default for anything user-facing and latency-sensitive. It is the fast, inexpensive option and covers the vast majority of interactive streaming: chat, summarization, extraction, code explanation. deepseek-v4-pro costs more and belongs where a wrong answer is genuinely expensive — long multi-step reasoning, tricky refactors, analysis across large context.

The two are drop-in interchangeable at the API level: change the model string, keep the streaming loop. A practical pattern is to route by request class rather than by trial and error — flash by default, pro behind an explicit flag or an escalation path when the user asks for a deeper pass. Because the streaming shape is the same, your front end never needs to know which one answered.

FAQ

Does streaming change what I pay for DeepSeek API calls?

No. You are billed for prompt and completion tokens, not for the transport. Off-peak requests cost less, cache hits on repeated prefixes are cheaper than fresh input, and deepseek-v4-pro costs more than deepseek-v4-flash. Current rates are at aicreditsapi.com/pricing.

How do I get token usage from a streamed response?

Set stream_options={'include_usage': True}. The API then sends a final chunk with an empty choices array and a populated usage field. Read it after the loop finishes, not inside it.

Can I use the OpenAI SDK with DeepSeek on AiCredits?

Yes. Set base_url to https://api.aicreditsapi.com/v1, use your AiCredits key, and pick model='deepseek-v4-flash' or 'deepseek-v4-pro'. No other SDK change is required.

Do I need a Chinese phone number or bank account?

No. AiCredits is built for international developers: pay by card or PayPal and start calling the API from anywhere.

Should I stream with deepseek-v4-pro?

Only where a wrong answer is expensive. Pro costs more than flash, so reserve it for long reasoning or high-stakes analysis and keep flash as the default for interactive streaming.

Does the [DONE] sentinel matter?

Yes, if you parse raw SSE yourself — it is how you distinguish a normal end of stream from a truncated connection. With the OpenAI SDK the iterator simply stops, so you never handle it directly.

Ship the Contract, Not Just the Feature

Streaming is a contract about partial data: some chunks have text, some do not, the last one may carry nothing but a finish reason, and the whole thing can be cut off by a proxy that decided to buffer. Handle the empty deltas, encode your frames, close your streams, and read your usage from the final frame. Everything after that is just UX.

A stream that renders instantly but leaks upstream tokens on every abandoned request is not faster — it is just more expensive. Close the loop.

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 ×