geekskai Logogeekskai
ToolsBlogPricing
Sign in
Sign in
ToolsBlogSign in
Wednesday, February 5, 2025|5.055Mins Read

DeepSeek API Integration: Python Requests, Streaming, and Errors

Authors
  • avatar
    Name
    Geeks Kai
    Twitter
    @KaiGeeks
Discuss on Twitter • View on GitHub

Tags

apideepseekaiintegrationdevelopment

Previous Article

JS Express Tracking: Ultimate Guide for Package Monitoring

Next Article

AI Image Reader: Complete 2025 Guide to Financial Data Extraction
← Back to the blog
geekskai Logo
geekskai

Public tools for developers and creators, plus optional Geekskai Audio Toolkit plans. Built with care.

Popular Tools

SoundCloud DownloaderSoundCloud to MP3SoundCloud to WAVSoundCloud PlaylistSoundCloud Artwork
View All Tools

Resources

BlogAbout MePricingTagsProjectsPrivacy PolicyTerms of ServiceRefund Policy

Connect With Us

mailMail
githubGitHub
twitterTwitter
linkedinLinkedin
© 2026 geekskai • All rights reserved
DeepSeek API integration

Which endpoint and model should I use?

Use POST https://api.deepseek.com/chat/completions with a server-side API key. At this revision, the official quick start lists deepseek-flash and deepseek-v4-pro; the examples below use deepseek-flash. An R1 research/model name is not evidence that deepseek-r1 is an accepted current API identifier.

The official quick start owns the current endpoint and model names. Its Flash alias may point to a newer underlying release over time. Check that page and the change log when maintaining an integration; do not copy an old model name or an unofficial look-alike hostname into production.

Before running the examples

Use Python 3.10 or later. These examples use the standard library and require no third-party HTTP or SSE package. Create your key through the DeepSeek platform, then set DEEPSEEK_API_KEY in the environment of the process running the code. Keep the key out of browser bundles, source control and screenshots.

Requests can incur API charges. Check your account balance and the current model pricing. This guide does not promise a free allowance, a particular latency or a benchmark advantage over another provider.

1. Send a non-streaming request

Save this complete file as deepseek_client.py, set the environment variable, then run python3 deepseek_client.py. It explicitly disables thinking for a simple text response, uses a 90-second socket timeout and checks the completion reason before returning text.

import json
import os
import sys
from urllib.error import HTTPError, URLError
from urllib.request import Request, urlopen

API_URL = "https://api.deepseek.com/chat/completions"
MODEL = "deepseek-flash"


def build_request(payload):
    api_key = os.environ["DEEPSEEK_API_KEY"]
    return Request(
        API_URL,
        data=json.dumps(payload).encode("utf-8"),
        headers={"Authorization": f"Bearer {api_key}", "Content-Type": "application/json"},
        method="POST",
    )


def require_complete(finish_reason):
    if finish_reason != "stop":
        raise RuntimeError(f"Completion is not complete: {finish_reason!r}")


def complete(prompt):
    request = build_request({
        "model": MODEL,
        "messages": [{"role": "user", "content": prompt}],
        "thinking": {"type": "disabled"},
        "stream": False,
    })
    with urlopen(request, timeout=90) as response:
        completion = json.load(response)
    choice = completion["choices"][0]
    require_complete(choice.get("finish_reason"))
    answer = choice["message"].get("content")
    if not isinstance(answer, str):
        raise ValueError("Expected a text completion.")
    return answer


if __name__ == "__main__":
    try:
        answer = complete("Reply with a short greeting.")
        print(answer)
    except HTTPError as api_error:
        print(f"DeepSeek HTTP {api_error.code}; see the error table below.", file=sys.stderr)
        raise SystemExit(1) from None
    except (URLError, TimeoutError, ValueError, RuntimeError) as request_error:
        print(f"DeepSeek request failed: {type(request_error).__name__}", file=sys.stderr)
        raise SystemExit(1) from None

A missing environment variable raises KeyError before a request is sent. HTTP failures exit with a nonzero status; the script does not treat a JSON error response as a successful answer. Extend the response handling if you deliberately request tools or another output mode.

2. Read streamed text and detect interruption

Save the next file as deepseek_stream.py beside deepseek_client.py, then run python3 deepseek_stream.py. It imports the request builder from the first file; it is not a standalone fragment.

import json
import sys
from urllib.error import HTTPError, URLError
from urllib.request import urlopen
from deepseek_client import MODEL, build_request, require_complete


def sse_payloads(response):
    payload_lines = []
    for raw_line in response:
        line = raw_line.decode("utf-8").rstrip("\r\n")
        if line.startswith("data:"):
            payload_lines.append(line[5:].removeprefix(" "))
            continue
        if line or not payload_lines:
            continue
        yield "\n".join(payload_lines)
        payload_lines = []
    if payload_lines:
        yield "\n".join(payload_lines)


def stream_text(response):
    finish_reason = None
    for payload in sse_payloads(response):
        if payload == "[DONE]":
            require_complete(finish_reason)
            return
        chunk = json.loads(payload)
        if chunk.get("error"):
            raise RuntimeError("The provider returned a streamed error.")
        choices = chunk.get("choices", [])
        if not choices:
            continue
        choice = choices[0]
        finish_reason = choice.get("finish_reason") or finish_reason
        content = choice.get("delta", {}).get("content")
        if content:
            yield content
    raise RuntimeError("Stream ended without [DONE]; treat displayed text as partial.")


if __name__ == "__main__":
    request = build_request({
        "model": MODEL,
        "messages": [{"role": "user", "content": "Reply with a short greeting."}],
        "thinking": {"type": "disabled"},
        "stream": True,
    })
    request.add_header("Accept", "text/event-stream")
    try:
        with urlopen(request, timeout=90) as response:
            for text in stream_text(response):
                print(text, end="", flush=True)
        print()
    except (HTTPError, URLError, TimeoutError, ValueError, RuntimeError) as stream_error:
        print(f"\nDeepSeek stream failed: {type(stream_error).__name__}", file=sys.stderr)
        raise SystemExit(1) from None

The Chat Completions reference specifies SSE data: events, delta.content and the terminating [DONE] event. The parser respects event boundaries and ignores comments/keep-alive fields. It requires both a normal stop reason and the termination marker. A network failure, truncation (length) or another completion reason must not be presented as a finished answer.

Text already printed before an error is partial. In an application, keep it visibly marked as incomplete until the stream finishes successfully. If you enable thinking, reasoning deltas use reasoning_content; they are separate from final answer text and are not displayed by this example. Tool-call deltas also need their own handler.

3. Handle errors by category

Use the provider’s error-code table rather than catching an undefined custom exception or retrying every failure.

StatusWhat to checkRetry policy
400 / 422Request format or unsupported parametersCorrect the request first
401API key and authenticationCorrect credentials; do not loop
402Account balanceResolve the account issue first
429Request rate and concurrencyReduce pressure; use bounded backoff
500 / 503Provider error or overloadA bounded delayed retry may help

A timeout or broken stream does not prove the provider never accepted the request. Avoid unlimited retries and duplicate application actions. These examples deliberately leave automatic retries out; add explicit attempt limits and cancellation behavior appropriate to your application.

The rate-limit guide also describes waiting and keep-alive behavior. Receiving HTTP 200 or a keep-alive is not proof that generation has completed. Tune timeouts to your service requirements and observe actual failures rather than promising an upgrade will solve them.

Integration checklist

  • Confirm the official hostname, accepted model identifier and current account conditions.
  • Keep API calls and credentials on a trusted server.
  • Test authentication, balance and invalid-parameter failures before adding retries.
  • Check normal completion, token-limit truncation and a stream that ends early.
  • Keep prompts, keys and full provider responses out of routine error logs.
  • Record the model, status, completion reason and application outcome without claiming unmeasured performance.

These are reference integration examples. Offline protocol checks can verify request construction and parsing; they do not establish live API availability, account eligibility or generated-answer quality.