DeepSeek API streaming lets your application display an answer while it is being generated. For Chat Completions, send stream: true, then consume the incoming Server-Sent Events (SSE) instead of waiting for a complete response body.
A useful implementation also needs to handle chunks without visible text, collect token usage, recognize an interrupted answer, and close the connection. This guide walks through those decisions with cURL, Python, and Node.js examples, then explains how the separate Responses API changes the event format.
Last reviewed: November 15, 2026.
How DeepSeek API Streaming Works
With a non-streaming call, your application receives the completed response as one JSON object. With streaming, it reads a sequence of events over the HTTP response. Your interface can append answer fragments as they arrive.
The main examples below use the OpenAI-compatible Chat Completions route. DeepSeek’s official quickstart documents the base URL, API-key authentication, and current model identifiers.
| Setting | Value used here |
|---|---|
| HTTP endpoint | POST https://api.deepseek.com/chat/completions |
| SDK base URL | https://api.deepseek.com |
| Model | deepseek-flash |
| Alternative documented model | deepseek-v4-pro |
| Streaming switch | stream: true |
| Transport | Server-Sent Events over HTTP |

Streaming improves the experience of waiting when useful text reaches the screen sooner. It does not, by itself, demonstrate faster model generation or lower cost. Measure the first visible answer separately from the time needed to finish the response.
An SSE Event Is Not a Network Read
SSE uses UTF-8 text, with events separated by blank lines. A network read can contain part of an event or several events. The SSE standard also defines comments and multiline data fields.
This is why calling JSON.parse() on every raw network chunk fails unpredictably. The SDK examples handle the framing for you. If you write a parser, decode text incrementally, buffer unfinished events, and parse JSON only after assembling a complete event.
Make Your First Streaming Request with cURL
You need a DeepSeek API key and sufficient API balance. Obtain the key from the DeepSeek platform, then make it available to your terminal as DEEPSEEK_API_KEY. Replace the placeholder in the command for your shell.
macOS, Linux, or WSL:
export DEEPSEEK_API_KEY="your_deepseek_api_key"
Windows PowerShell:
$env:DEEPSEEK_API_KEY = "your_deepseek_api_key"
The following cURL command uses Bash syntax. On native Windows, use the Python or Node.js examples below, or run this command in WSL after setting the key in that shell. It requests a short answer with thinking disabled and an illustrative 512-token output cap:
curl --no-buffer --silent --show-error --fail-with-body \
--max-time 120 \
https://api.deepseek.com/chat/completions \
-H "Authorization: Bearer $DEEPSEEK_API_KEY" \
-H "Content-Type: application/json" \
--data '{
"model": "deepseek-flash",
"messages": [{"role": "user", "content": "Explain SSE in two sentences."}],
"thinking": {"type": "disabled"},
"max_tokens": 512,
"stream": true,
"stream_options": {"include_usage": true}
}'
--no-buffer, also written -N, disables cURL’s output buffering. It does not control buffering elsewhere in your deployment. --max-time 120 bounds this example’s transfer time; it is a demonstration setting, not a DeepSeek service limit. See the cURL option reference.
You should see data: records rather than one ordinary JSON response. Chat Completions uses data: [DONE] as its stream terminator. That marker is control data, so a raw parser must recognize it before attempting JSON decoding.

DeepSeek API Streaming in Python
This example requires Python 3.11 or later because it uses asyncio.timeout() to bound the entire request and reading loop. Install the OpenAI Python SDK in your project environment:
python -m pip install --upgrade openai
Save the following as stream_deepseek.py. It prints answer fragments immediately, stores reasoning separately, captures usage wherever it appears, and reports the finish reason.
import asyncio
import os
import sys
from openai import AsyncOpenAI
async def stream_reply(client, emit):
result = {"answer": "", "reasoning": "", "usage": None, "finish_reason": None}
async with asyncio.timeout(120):
stream = await client.chat.completions.create(
model="deepseek-flash",
messages=[{"role": "user", "content": "Explain SSE in two sentences."}],
max_tokens=512,
stream=True,
stream_options={"include_usage": True},
extra_body={"thinking": {"type": "disabled"}},
)
async with stream:
async for chunk in stream:
if chunk.usage is not None:
result["usage"] = chunk.usage.model_dump()
if not chunk.choices:
continue
choice = chunk.choices[0]
delta = choice.delta
result["reasoning"] += getattr(delta, "reasoning_content", None) or ""
text = delta.content or ""
result["answer"] += text
if text:
emit(text)
if choice.finish_reason is not None:
result["finish_reason"] = choice.finish_reason
return result
async def main():
async with AsyncOpenAI(
api_key=os.environ["DEEPSEEK_API_KEY"],
base_url="https://api.deepseek.com",
timeout=60.0,
max_retries=0,
) as client:
try:
result = await stream_reply(client, lambda text: print(text, end="", flush=True))
except Exception as error:
status = getattr(error, "status_code", None)
print(f"\nStream failed ({type(error).__name__}, HTTP {status}); displayed text is partial.", file=sys.stderr)
return 1
print(f"\nfinish_reason={result['finish_reason']}; usage={result['usage']}", file=sys.stderr)
if result["finish_reason"] != "stop":
print("No normal text completion; keep the result marked incomplete.", file=sys.stderr)
return 1
return 0
if __name__ == "__main__":
sys.exit(asyncio.run(main()))
Run it from the terminal where you set the API key:
python stream_deepseek.py
Answer text goes to standard output. Completion details and errors go to standard error, so redirecting the answer to a file does not mix it with diagnostic messages. flush=True prevents Python’s output buffering from hiding incremental progress.
The 120-second outer deadline covers both creating and consuming the stream. It serves a different purpose from the SDK’s timeout setting. A connection that keeps receiving activity can remain open even when no useful answer has arrived.
DeepSeek API Streaming in JavaScript and Node.js
Use a Node.js release supported by the official JavaScript SDK. In a new project directory, initialize the project and install the package:
npm init -y
npm install openai
Save this as stream-deepseek.mjs. The .mjs extension lets Node run the import syntax without changing your package configuration.
import OpenAI from "openai";
import { pathToFileURL } from "node:url";
export async function streamReply(client, emit) {
const result = { answer: "", reasoning: "", usage: null, finish_reason: null };
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), 120_000);
let stream;
try {
stream = await client.chat.completions.create({
model: "deepseek-flash",
messages: [{ role: "user", content: "Explain SSE in two sentences." }],
max_tokens: 512,
stream: true,
stream_options: { include_usage: true },
thinking: { type: "disabled" },
}, { signal: controller.signal });
for await (const chunk of stream) {
if (chunk.usage != null) result.usage = chunk.usage;
const choice = chunk.choices?.[0];
if (!choice) continue;
result.reasoning += choice.delta.reasoning_content ?? "";
const text = choice.delta.content ?? "";
result.answer += text;
if (text) emit(text);
if (choice.finish_reason != null) result.finish_reason = choice.finish_reason;
}
if (controller.signal.aborted) throw new Error("Stream deadline exceeded");
return result;
} finally {
clearTimeout(timer);
stream?.controller.abort();
}
}
async function main() {
const client = new OpenAI({
apiKey: process.env.DEEPSEEK_API_KEY,
baseURL: "https://api.deepseek.com",
timeout: 60_000,
maxRetries: 0,
});
try {
const result = await streamReply(client, text => process.stdout.write(text));
console.error("\nfinish_reason:", result.finish_reason, "usage:", result.usage);
if (result.finish_reason !== "stop") {
console.error("No normal text completion; keep the result marked incomplete.");
process.exitCode = 1;
}
} catch (error) {
console.error(`\nStream failed (${error.name}, HTTP ${error.status ?? "n/a"}); displayed text is partial.`);
process.exitCode = 1;
}
}
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
await main();
}
Run the file with the same environment variable available:
node stream-deepseek.mjs
This is server-side JavaScript. Do not move the reusable API key into a browser bundle. The exported function makes the stream consumer reusable, while the final condition runs the example when you launch the file directly.
Both examples disable automatic retries. If a response fails after showing partial text, they report the failure instead of silently appending a new generation to the old one. Their 512-token cap and timeout values are starting points for this small demonstration.
Handle Reasoning, Usage, and Completion Correctly
Keep Reasoning Separate from Answer Text
DeepSeek’s thinking mode is enabled by default. When active, it can return delta.reasoning_content before answer text appears in delta.content. The examples disable thinking for the first test but can collect either field.

To try thinking mode, change "disabled" to "enabled". Reconsider the small output cap and deadline for that workload. Keep the two buffers separate, and avoid treating an empty answer field as an error while reasoning is still arriving.
Preserve text exactly as received. Trimming each fragment can remove spaces between words, indentation in code, or meaningful line breaks. The examples append fragments without trimming them.
Read Usage from the Final Finish Chunk
The current Chat Completions reference specifies that the final JSON chunk carries aggregate usage and a choice with a non-null finish_reason. DeepSeek does not emit a separate usage-only chunk with empty choices.
With include_usage: true, earlier chunks have usage: null. When the option is false or omitted, earlier chunks omit that field; final usage still arrives. The examples check usage before processing choices and tolerate empty choices defensively.
If a connection fails before the final accounting information arrives, record usage as unavailable rather than zero. DeepSeek’s token usage guidance explains the accounting unit; counting network reads or displayed fragments is not an equivalent measurement.
Treat the Finish Reason as Application State
| Observed state | How the application should treat it |
|---|---|
stop | The model ended normally or reached a requested stop sequence. Validate the answer as needed. |
length | The output hit its limit. Keep it marked as truncated. |
tool_calls | The next step belongs to your tool workflow; it is not a finished text answer. |
content_filter, insufficient_system_resource, or aborted | Handle the specific condition without presenting the result as an ordinary completed answer. |
| No finish reason before the connection ends | Treat the output as incomplete and preserve the failure state. |

The SDK consumes the raw [DONE] marker internally, as shown in the Python SDK stream implementation. These examples check the model’s finish state; they do not independently inspect the wire-level terminator. A custom SSE parser should track both the expected transport ending and the response’s completion state.
Chat Completions vs. Responses API Streaming
DeepSeek also offers native Responses API streaming. It uses named semantic events, so the Chat Completions loops above cannot consume its objects unchanged.

| Concern | Chat Completions | Responses API |
|---|---|---|
| Endpoint | /chat/completions | /responses |
| Answer fragment | choices[0].delta.content | response.output_text.delta |
| Reasoning fragment | delta.reasoning_content | response.reasoning_text.delta |
| Completion signal | A finish reason, followed by [DONE] on the wire | response.completed, response.incomplete, or response.failed |
| Usage location | usage on the final JSON chunk | response.usage on the terminal event |
For Responses, dispatch on the SDK event’s type, append the text from output-text delta events, and inspect the final response status. There is no data: [DONE] message in this protocol. Read error or incomplete-response details when the terminal event is not response.completed.

Deliver the Stream to a Browser
For a web application, let the browser call your backend. The backend holds the DeepSeek key, creates the model request, and forwards incremental results to the page. This gives your application one place to manage access, cancellation, and request limits.
- Send the user’s prompt to your application endpoint using
fetch(). - Have the backend consume DeepSeek’s stream and forward answer fragments, plus explicit completion or failure information.
- Read the browser response incrementally and update the interface without waiting for the full body.
- When the user stops generation or leaves the page, cancel the browser request and propagate that cancellation to the upstream request.
The native EventSource interface does not provide a general POST-body and custom-header interface for calling DeepSeek directly. A streamed fetch() response from your own backend fits this request pattern. MDN’s readable streams guide explains incremental consumption and cancellation.
Decide what your backend sends. If it forwards raw SSE, the browser needs an SSE parser. If it transforms the response into your own events, document those events. A plain text stream also needs a way to distinguish a successful finish from an interrupted connection.
Check Buffering Through the Entire Delivery Path
If streaming works in your terminal but the page receives everything at once, inspect your backend, reverse proxy, and hosting configuration. For Nginx, proxy_buffering controls response buffering; X-Accel-Buffering: no can also control it when the configuration permits.

That header is not a universal instruction to every CDN or hosting platform. Test the deployed route itself. If the consumer reads more slowly than the producer writes, also respect your runtime’s backpressure mechanism instead of accumulating an unlimited queue; the Node.js stream documentation explains its buffering and flow controls.
Troubleshoot Empty, Slow, and Interrupted Streams
DeepSeek documents : keep-alive comments while a request is waiting. These comments are connection activity, not answer text. Its rate-limit and keep-alive documentation says the server closes a request if inference has not started after ten minutes. That is a waiting condition, not a universal maximum duration for every stream.

| Symptom | Likely check or next step |
|---|---|
| No visible text, but events arrive | Look for reasoning or metadata. Read delta.content for the answer and preserve reasoning separately. |
| Everything appears at the end | Check output flushing, full-body reads, backend buffering, and proxy behavior. |
| JSON parsing fails on random chunks | Separate network-read boundaries from SSE event boundaries. Handle comments and [DONE] before JSON parsing. |
usage is null during generation | Continue to the final chunk. If the stream is interrupted, usage may remain unavailable. |
| The answer ends abruptly | Inspect the finish reason, transport error, deadline, and hosting timeouts. Do not label the partial text complete. |
| Words or code formatting run together | Stop trimming fragments before concatenation. |
| The connection stays open without useful output | Distinguish keep-alive activity from answer progress and enforce an overall deadline. |
Handle HTTP Errors Before Assuming a Stream Exists
A rejected request may return an ordinary error response before streaming starts. Check the status rather than feeding that body into an SSE parser. DeepSeek’s error reference lists the relevant categories:
- 400 or 422: inspect the request body and unsupported or invalid parameters.
- 401: check the API key and authentication header.
- 402: check the DeepSeek account balance.
- 429: reduce request pressure and check the applicable concurrency limits.
- 500 or 503: consider a delayed, bounded retry for the server failure.
After partial output, make any retry a separate attempt. Keep the previous text marked as partial and give the replacement its own state. Reissuing the same prompt does not establish that the new generation will resume at the exact point where the old connection failed.
Test Your Stream Handler Before Deployment
The Python and Node.js consumers above were checked locally with synthetic SSE responses through the actual SDK parsers. The checks included split UTF-8 characters, comments, reasoning fragments, final usage, missing completion information, transport failures, and deadlines. These were simulated protocol checks, not live DeepSeek inference or performance measurements.
Use the following cases when adapting the examples to your application:
| Test input or condition | Expected behavior |
|---|---|
| A role-only chunk or empty content | No crash and no extra visible text. |
| Reasoning followed by answer fragments | Separate buffers with only the intended field rendered as the answer. |
| Spaces, line breaks, accented characters, and emoji split across reads | The reconstructed output matches the original text. |
| Usage on the final finish chunk | Usage is retained even though the chunk adds no answer text. |
| An empty choices array | Defensive handling without assuming this is DeepSeek’s normal usage format. |
A length finish or EOF before a finish reason | The text remains marked incomplete. |
| A stream error, disconnect, or expired deadline | The connection is cleaned up and partial output is not presented as success. |
Then test one small authenticated request through your deployed application. That separate check confirms your account, model access, network route, and hosting behavior—conditions a local fixture cannot verify.
Streaming Costs and Performance
Streaming changes how output is delivered. Normal model usage charges still apply under DeepSeek’s current pricing. Use the returned input, output, and applicable cache statistics when reviewing cost; do not equate one received chunk with one billable token.
For performance, record time to the first answer fragment and time to successful completion. If thinking is enabled, record reasoning activity separately. A keep-alive byte, a reasoning fragment, and the first useful answer are different milestones.
Cancellation can prevent your application from continuing to consume an unwanted response, but it does not justify assuming that earlier work was free. If final usage is unavailable, check the account’s usage records rather than substituting a zero-cost result.
Frequently Asked Questions
Does DeepSeek Streaming Require WebSockets?
No. The interfaces covered here stream over HTTP using SSE. Your application may use WebSockets elsewhere, but they are not required to receive these DeepSeek responses.
Can I Stream a JSON Response?
Yes, but the SSE envelope and the model’s JSON text are separate layers. Accumulate the answer, confirm an acceptable completion state, then parse and validate the completed JSON. Follow DeepSeek’s JSON Output instructions, including requesting JSON in the prompt and allowing enough output space. Handle blank or truncated output explicitly.
How Do Streaming Tool Calls Work?
Accumulate argument fragments for each tool-call index, then parse and validate the completed arguments before your application executes the function. DeepSeek’s tool-call guide explains the request-and-result cycle. The examples in this article are text-only consumers, not complete tool executors.
For thinking-mode requests that include tools, follow the documented requirement to pass prior reasoning_content back in subsequent requests. A blanket rule to discard all reasoning history would be incorrect for that workflow.
How Do I Stop a Streaming Response?
Cancel the active request and close its stream. The Node example already passes an AbortController signal; a web application can connect its Stop action to the same cancellation path. In Python, cancel the consuming task and allow the asynchronous context managers to close the resources. Keep cancellation distinct from successful completion in your interface.
Why Does a Stream End Without a Complete Answer?
A model can reach its output limit, a request can be interrupted, or the connection can fail. Inspect the finish reason and error state before deciding what happened. Preserve partial output, and offer a new attempt deliberately instead of silently labeling it complete.
