DeepSeek API Integration: Python Requests, Streaming, and Errors
- Authors

- Name
- Geeks Kai
- @KaiGeeks

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.
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.
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.
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.
Use the provider’s error-code table rather than catching an undefined custom exception or retrying every failure.
| Status | What to check | Retry policy |
|---|---|---|
| 400 / 422 | Request format or unsupported parameters | Correct the request first |
| 401 | API key and authentication | Correct credentials; do not loop |
| 402 | Account balance | Resolve the account issue first |
| 429 | Request rate and concurrency | Reduce pressure; use bounded backoff |
| 500 / 503 | Provider error or overload | A 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.
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.