DeepSeek’s API supports an OpenAI-compatible chat-completions format. Point the OpenAI SDK to https://api.deepseek.com, supply a DeepSeek key and choose deepseek-v4-flash or deepseek-v4-pro. Compatibility reduces migration work, but DeepSeek-specific thinking controls and response behaviour still require testing.
Compatibility does not mean identical
The OpenAI SDK handles transport, authentication, streaming and typed response objects. DeepSeek implements compatible endpoints and parameters, not every OpenAI product feature. Model names, reasoning fields, limits, errors and beta endpoints differ.
Keep provider configuration separate from application logic. Do not assume an OpenAI Responses API feature exists in DeepSeek Chat Completions because the same SDK package can send the request.
Python configuration
import os
from openai import OpenAI, APIConnectionError, APIStatusError
key = os.getenv("DEEPSEEK_API_KEY")
if not key:
raise RuntimeError("Set DEEPSEEK_API_KEY")
client = OpenAI(
api_key=key,
base_url="https://api.deepseek.com",
timeout=30.0,
max_retries=2,
)
try:
result = client.chat.completions.create(
model="deepseek-v4-flash",
messages=[{"role": "user", "content": "Return two cache use cases."}],
max_tokens=200,
extra_body={"thinking": {"type": "disabled"}},
)
if result.choices[0].finish_reason != "stop":
raise RuntimeError(f"Unexpected finish reason: {result.choices[0].finish_reason}")
print(result.choices[0].message.content)
except APIConnectionError:
print("Network connection failed")
except APIStatusError as exc:
print(f"Provider returned HTTP {exc.status_code}")
Log a request ID where available, not the secret or full sensitive prompt.
JavaScript configuration
import OpenAI from "openai";
const key = process.env.DEEPSEEK_API_KEY;
if (!key) throw new Error("Set DEEPSEEK_API_KEY");
const client = new OpenAI({
apiKey: key,
baseURL: "https://api.deepseek.com",
timeout: 30_000,
maxRetries: 2,
});
try {
const result = await client.chat.completions.create({
model: "deepseek-v4-flash",
messages: [{ role: "user", content: "Return two cache use cases." }],
max_tokens: 200,
thinking: { type: "disabled" },
});
if (result.choices[0].finish_reason !== "stop") {
throw new Error(`Unexpected finish reason: ${result.choices[0].finish_reason}`);
}
console.log(result.choices[0].message.content);
} catch (error) {
console.error("DeepSeek request failed");
}
Keep detailed provider errors in restricted logs and return a generic message to untrusted clients.
DeepSeek-specific thinking controls
Official examples place thinking: {type: "enabled"} in Python’s extra_body and pass reasoning_effort as high or max. Current models default to thinking enabled. In thinking mode, temperature, top_p, presence_penalty and frequency_penalty do not take effect according to DeepSeek’s guide.
If a thinking turn performs tool calls, preserve reasoning_content in the subsequent tool sequence. This is a DeepSeek protocol detail that generic SDK examples may not cover.
Streaming
Set stream=True or stream: true and consume server-sent events. DeepSeek can send keep-alive comments during slow requests. Your parser should ignore keep-alives, append reasoning and content to separate buffers and handle [DONE].
Never assume every chunk contains content. Support cancelled clients and close the upstream connection. Set a total deadline even when keep-alives continue, otherwise an application can hold resources indefinitely.
JSON output
Set response_format={"type": "json_object"} and include the word “json” plus the target shape in the prompt. DeepSeek warns that JSON mode can occasionally return empty content and that insufficient max_tokens can truncate the object.
Parse inside a try/catch, validate against a schema and retry only with a bounded repair strategy. Valid syntax does not validate business meaning. See the JSON output guide.
Tool calls
The SDK exposes tool-call objects, but the arguments are model-generated strings. Parse JSON, validate the function name and schema and then apply authorisation. DeepSeek’s API reference warns that the model may generate invalid JSON or hallucinated parameters.
Map tool names to fixed functions. Never use eval, dynamic imports or raw shell interpolation. Cap tool rounds and require confirmation for writes, purchases, messages and deletions.
Error and retry policy
Let the SDK retry transient connection failures, but keep the count small. For 429, 500 and 503, use exponential backoff with jitter. For 400, 401, 402 and 422, change the request, credential or balance instead of repeating.
Idempotency matters. A retried read may be safe; a retried write tool can duplicate an action. Attach application idempotency keys where the downstream system supports them.
Version and migration tests
Pin a tested SDK major version and update deliberately. At startup or in CI, validate the configured model against DeepSeek’s current model list. Maintain tests for ordinary text, streaming, JSON, tool calls, timeouts and finish reasons.
DeepSeek retired older aliases in July 2026. A compatibility layer should fail with a clear migration message when obsolete configuration remains.
Security boundaries
The SDK belongs on a server or trusted local machine. An API key included in a mobile or browser bundle can be extracted. Authenticate your own users, enforce quotas and remove sensitive data before requests.
The API cornerstone guide covers budgets, privacy and model selection. Compatibility is a transport convenience, not a substitute for product security.
When an SDK call fails, work through the documented API error guide before changing libraries. Compatibility does not override authentication, billing, model availability or request-validation errors.
Conclusion
Using DeepSeek through the OpenAI SDK requires only a base URL and provider key at the simplest level. Production readiness comes from handling DeepSeek-specific thinking, streaming, JSON, tools, errors and model migrations explicitly.
Common questions
Frequently asked questions
Can I reuse all OpenAI API code unchanged?
Not safely. Chat-completions structure is compatible, but provider-specific models, fields and features differ.
Should I use `/v1` in the base URL?
Follow DeepSeek’s current example: https://api.deepseek.com. Verify if your SDK or proxy adds paths.
Where should the key be stored?
Use a server-side environment variable or managed secret store, not source code.
Why is temperature ignored?
DeepSeek’s thinking mode documentation says sampling parameters do not take effect in that mode.
Evidence
Sources
- Your First API Call — official external destination
DeepSeek · official API documentation · verified July 30, 2026
- Thinking Mode — official external destination
DeepSeek · official API documentation · verified July 30, 2026
- Error Codes — official external destination
DeepSeek · official API documentation · verified July 30, 2026
- Models & Pricing — official external destination
DeepSeek · official API pricing documentation · verified July 30, 2026
Practical guide