AiCredits
Streaming Ops

How to Handle Streaming and Cancellation in DeepSeek API Clients (Python)

Stop leaking connections and paying for tokens you never read. Runnable async Python patterns for streaming and cancellation in your own DeepSeek API clients.

Published 2026-10-03 Updated 2026-10-03 9 min

If you have shipped a chat UI on top of the DeepSeek API, you already know the happy path: open a stream, print deltas, done. The part that bites in production is everything that happens when the user hits Stop, closes the tab, or the network drops mid-sentence.

That matters more than it looks. A streaming response is an open HTTP connection plus an in-flight generation on the other side. If your client walks away without telling anyone, you leak sockets, you keep pulling tokens you will never read, and in async code you leave behind tasks that throw at shutdown. Cancellation is not an edge case — it is a first-class code path, and most clients get it wrong.

The Minimum Viable Streaming Loop

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": "Explain server-sent events in 3 sentences."}],
    stream=True,
    stream_options={"include_usage": True},  # final chunk carries token usage
)

for chunk in stream:
    if chunk.usage:                # the usage chunk has an empty choices list
        print("\n[tokens]", chunk.usage.total_tokens)
        continue
    delta = chunk.choices[0].delta
    if delta.content:
        print(delta.content, end="", flush=True)

Two details matter. First, stream_options={"include_usage": True} makes the API emit a final chunk carrying token usage — that chunk arrives with an empty choices list, so check for it before you index into choices. If your gateway does not return usage, drop the option and count locally, but know you lose the cache-hit breakdown, which is where the real savings live.

Second, iterate the stream object directly. The SDK decodes SSE frames lazily as bytes arrive, and it only notices a dead connection when you ask for the next frame.

Three Kinds of Cancellation, One Rule

  • Client-side early exit — your code decides it has enough (a stop condition, a length cap, the user pressing Stop). You must break the loop and close the stream.

  • Transport loss — the tab closes, a mobile network hands off, a proxy times out. Your process finds out on the next read or write that fails.

  • Deadline — you want the request to die after a fixed budget regardless of activity. Enforce that yourself instead of hoping the other side gives up.

  • The shared rule: always release the stream in a finally block. Every other design choice is downstream of that.

Sync Clients: Break, Then Close

import os
from openai import OpenAI

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


def stream_until(prompt: str, max_chars: int = 200) -> str:
    """Stop reading as soon as we have enough text, and release the socket."""
    stream = client.chat.completions.create(
        model="deepseek-v4-flash",
        messages=[{"role": "user", "content": prompt}],
        stream=True,
    )
    parts: list[str] = []
    try:
        for chunk in stream:
            if not chunk.choices:
                continue
            piece = chunk.choices[0].delta.content
            if not piece:
                continue
            parts.append(piece)
            if sum(len(p) for p in parts) >= max_chars:
                break
    finally:
        stream.close()      # returns the underlying httpx response to the pool
    return "".join(parts)


print(stream_until("List caching strategies, one per line."))

stream.close() is the line people forget. Without it, the underlying httpx response is only released when the object is garbage collected — under load that means connection-pool exhaustion long before your CPU is busy. The finally also guarantees cleanup when your own parsing code raises halfway through a response.

Async Clients: Let Cancellation Propagate

import asyncio
import os
from openai import AsyncOpenAI

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


async def stream_with_deadline(prompt: str, seconds: float) -> str:
    parts: list[str] = []
    stream = await aclient.chat.completions.create(
        model="deepseek-v4-flash",
        messages=[{"role": "user", "content": prompt}],
        stream=True,
    )
    try:
        # Python 3.11+. On older versions wrap the coroutine in asyncio.wait_for.
        async with asyncio.timeout(seconds):
            async for chunk in stream:
                if chunk.choices and chunk.choices[0].delta.content:
                    parts.append(chunk.choices[0].delta.content)
    except TimeoutError:
        parts.append("\n[deadline reached - partial answer]")
    finally:
        await stream.close()
    return "".join(parts)


async def main() -> None:
    task = asyncio.create_task(
        stream_with_deadline("Summarize HTTP/2 flow control.", 30)
    )
    await asyncio.sleep(1.0)
    task.cancel()             # simulates the user pressing Stop
    try:
        await task
    except asyncio.CancelledError:
        print("cancelled cleanly, stream closed in finally")


asyncio.run(main())

asyncio.timeout raises TimeoutError at the await inside the loop, and the finally still runs. When an outer task is cancelled, asyncio.CancelledError propagates through the async for, closing the async iterator, and your await stream.close() gets its chance to execute. Note that asyncio.timeout requires Python 3.11+; on older interpreters use asyncio.wait_for around the whole coroutine, accepting that you cannot distinguish a slow first token from a slow tail.

When You Are the Server: Detecting the Disconnect

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

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


@app.get("/chat")
async def chat(request: Request, q: str):
    async def event_source():
        stream = await aclient.chat.completions.create(
            model="deepseek-v4-flash",
            messages=[{"role": "user", "content": q}],
            stream=True,
        )
        try:
            async for chunk in stream:
                if await request.is_disconnected():
                    break              # browser is gone; stop relaying frames
                if chunk.choices and chunk.choices[0].delta.content:
                    yield "data: " + json.dumps(
                        {"text": chunk.choices[0].delta.content}
                    ) + "\n\n"
            yield "data: [DONE]\n\n"
        finally:
            await stream.close()

    return StreamingResponse(event_source(), media_type="text/event-stream")

Most teams write this proxy and forget that StreamingResponse keeps pulling frames from upstream long after the browser goes away. await request.is_disconnected() turns that into a clean break. You cannot un-generate tokens that have already left the provider, but you can stop relaying them and free your own socket immediately.

Frames, Buffers, and the Partial-Event Trap

  • SSE events are separated by a blank line, and a network read can split one anywhere — including mid-data: line. Buffer bytes and parse only on the full \n\n boundary.

  • A single event may carry multiple data: lines. Join them with \n before calling json.loads.

  • data: [DONE] is a sentinel, not JSON. Check for it before parsing.

  • Deltas are not cumulative. Each frame contains only the new fragment; concatenate, never replace.

Tool Calls Arrive in Fragments

from collections import defaultdict


def collect_tool_calls(stream) -> list[dict]:
    """Merge fragmented tool_call deltas into complete calls, keyed by index."""
    acc = defaultdict(lambda: {"id": None, "name": None, "arguments": ""})
    for chunk in stream:
        if not chunk.choices:
            continue
        for tc in chunk.choices[0].delta.tool_calls or []:
            slot = acc[tc.index]
            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
    return [acc[i] for i in sorted(acc)]

Every streamed tool call arrives as a series of deltas keyed by index, with the function name usually in one frame and the JSON arguments dribbling out across many. Buffer by index and concatenate before parsing. If you cancel mid-arguments you will hold a syntactically invalid JSON string — treat that as a signal to discard the call, not to repair it.

What Cancellation Actually Costs

Cancelling is neither free nor wasteful. Output tokens already generated are billed; tokens never generated are not. So the arithmetic is simple in shape: cancelling early always beats letting a runaway response finish, but it never beats not asking for a runaway response at all. Cap max_tokens on any call whose output you display incrementally.

Prompt caching shifts the picture too — a long, stable system prompt that hits the cache costs less than a fresh one, so re-sending context after a cancellation hurts less than you would expect. Off-peak requests cost less than peak ones, and the pro model costs more per token than flash. For current rates, see aicreditsapi.com/pricing.

ScenarioRecommended pattern
Interactive chat with a Stop buttonAsync stream + task.cancel() + close() in finally
Server-side SSE proxyStreamingResponse + request.is_disconnected() break
Batch summarization jobNon-streaming, max_tokens cap, hard deadline
Agent with tool callsStreaming + index-keyed accumulator, discard on cancel
Queue worker / webhookNon-streaming, retry with idempotency key

Pick the Cheapest Model That Solves the Task

For anything interactive, default to deepseek-v4-flash. It is the fast option and covers the overwhelming majority of chat, extraction, classification, and summarization work. Escalate to deepseek-v4-pro only when the task genuinely needs stronger reasoning and you can absorb the higher cost per token. Streaming a slow, expensive model to a user who is likely to cancel halfway is the worst of both worlds.

FAQ

Does breaking out of a stream stop generation on the server?

Not instantly and not guaranteed. Closing the connection is a signal the gateway may only notice when it next tries to write a chunk. Always close the stream explicitly so the socket is released and the following write fails fast.

Am I billed for tokens after I cancel?

Only for output tokens already produced before the cancellation took effect. Anything the model never generated is not billed. Cancelling early is always cheaper than letting a long response finish, but capping max_tokens is cheaper still.

Can I resume a cancelled stream where it stopped?

No. The chat completions streaming API has no resume cursor. If you need resumability, persist the partial output and issue a follow-up request that includes the partial text in the conversation, asking the model to continue from it.

Should I stream tool calls?

Yes when latency matters — you can show progress while arguments stream in. Buffer deltas by index and never parse half-finished JSON. If you cancel mid-call, discard the call entirely rather than trying to repair it.

How do I set a timeout without breaking legitimately long responses?

Separate concerns: use a short connect and first-byte timeout, plus a generous overall deadline you can extend when chunks keep arriving. The OpenAI SDK exposes per-request timeouts, and asyncio.timeout gives you a hard cap on top.

Which model should I stream?

deepseek-v4-flash for almost everything interactive. Use deepseek-v4-pro when the task needs deeper reasoning and the higher per-token cost is justified by the answer quality.

Streaming takes a dozen lines; making it survivable is the engineering. Wrap every stream in try/finally, give every call a deadline you control, propagate cancellation instead of swallowing it, and choose the least expensive model that actually solves the task.

AiCredits sells DeepSeek API credits to developers outside China — pay by card or PayPal, no Chinese phone number or bank account required — so you can wire up these streaming clients at aicreditsapi.com without fighting the signup flow.

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 ×