# DeepSeek Streaming in Python: Handle Chunks and Incomplete Replies

> Stream a DeepSeek answer without treating every event as text, and detect interruptions before saving a partial reply as a completed result.

Canonical article: https://modelrovia.com/guides/deepseek-streaming-python/
Author: Modelrovia Editorial
Published: 2026-11-01
Updated: 2026-11-01

**Streaming delivers a response in pieces; it does not make each event a complete message.** In Python, read text from each choice's delta, tolerate events without choices, and keep track of whether the response actually finished.

This extends our [first DeepSeek request](/guides/deepseek-api-python-quickstart/). It assumes your key and balance already work. The example follows official documentation checked November 1, 2026; it has not been run against a live API.

## Separate display from completion

There are two different jobs: show text as it arrives, and decide whether the accumulated answer is usable. A network failure can happen after several readable paragraphs. Printing those paragraphs does not turn them into a complete answer.

The following terminal example collects answer text while displaying it. It reports a completion reason separately and exits if the stream ends without a normal stop. It does not print a reasoning field as if it were the final answer.

```python
import getpass
from openai import OpenAI

client = OpenAI(api_key=getpass.getpass("DeepSeek key: "),
                base_url="https://api.deepseek.com",
                timeout=60.0, max_retries=0)
parts = []
finish_reason = None
try:
    stream = client.chat.completions.create(
        model="deepseek-flash",
        messages=[{"role": "user", "content": (
            "Give three numbered checks before sending a newsletter."
        )}],
        stream=True,
    )
    with stream:
        for event in stream:
            if not event.choices:
                continue
            choice = event.choices[0]
            text = choice.delta.content or ""
            parts.append(text)
            print(text, end="", flush=True)
            if choice.finish_reason is not None:
                finish_reason = choice.finish_reason
except Exception as error:
    print("\nStream interrupted:", type(error).__name__)
    raise SystemExit("Partial answer was not accepted.")
print()
answer = "".join(parts)
if finish_reason != "stop" or not answer.strip():
    raise SystemExit(f"Answer not accepted: {finish_reason!r}")
print("Completed answer received; check its contents before use.")
```

Install `openai` in your Python environment before running the file. Actual wording varies. Check that there are three relevant items after transport-level completion succeeds.

## Handle the edge cases explicitly

An event may carry metadata, an empty delta, or a completion reason rather than visible text. Do not assume a fixed number of events, one word per event, or that the final event contains content. Concatenate the returned text as supplied instead of inserting spaces between chunks.

If you later add tool calls, this text-only acceptance rule is insufficient. Tool arguments have their own incremental representation and completion path. Keep that implementation separate rather than executing whatever text happens to arrive.

## Make retries visible

A retry starts a new request. It can produce a different answer and may add usage cost. For a terminal demo, fail clearly and let the user decide to rerun. For a product, distinguish an interrupted draft from a completed message in both storage and the interface.

Avoid logging API keys or dumping sensitive prompts when reporting failures. Save redacted request metadata, completion state, and your application's request ID instead.

## Measure the right thing

If you evaluate streaming responsiveness, record time to first **answer text**, total completion time, model ID, and input size. Time to any network event may measure something else. This guide reports none of those timings: a code example is not a benchmark.

## Sources & references

- [DeepSeek chat-completions API](https://api-docs.deepseek.com/api/create-chat-completion/)
- [DeepSeek first API call](https://api-docs.deepseek.com/)

[Editorial standards](https://modelrovia.com/methodology/)
