You can use the OpenAI SDK with DeepSeek by installing the openai package, providing a DeepSeek API key, setting the base URL to https://api.deepseek.com, and choosing a DeepSeek model. The same Python and JavaScript clients can then call DeepSeek’s documented Chat Completions and Responses endpoints.
This guide takes you from a first request to streaming, structured data, and a complete function-calling workflow. It also explains the compatibility details that matter when moving an existing application. DeepSeek’s official quickstart is the reference for the initial connection settings.
Documentation reviewed November 21, 2026. Examples were checked with the SDK versions listed below using local simulated HTTP responses. Live DeepSeek inference, latency, and billing were not tested.
Quick configuration: OpenAI SDK with DeepSeek
| Setting | Python | JavaScript / Node.js |
|---|---|---|
| Package | openai | openai |
| API key option | api_key | apiKey |
| Base URL option | base_url | baseURL |
| Base URL value | https://api.deepseek.com | https://api.deepseek.com |
| Model used in this guide | deepseek-flash | deepseek-flash |
| Chat method | client.chat.completions.create() | client.chat.completions.create() |
Pass the API root as the base URL. The SDK adds /chat/completions or /responses when you call the corresponding method. Supplying the entire endpoint as the base URL can produce an incorrect request path.
DeepSeek’s current model table recommends deepseek-flash and also lists deepseek-v4-pro. Older Flash aliases may still route to the current Flash model. However, the retirement deadline for deepseek-chat and deepseek-reasoner was July 24, 2026, according to the V4 release notice. Replace those older names when updating tutorials or application settings.
Jump to: Python · Node.js · Responses API · Streaming · JSON · Tool calls · Troubleshooting
Before you start: credentials and supported runtimes
Create an API key in the DeepSeek platform and check that the account has API balance. These examples read the key from DEEPSEEK_API_KEY. That variable name belongs to your application: you must pass its value explicitly to the SDK.
For the package versions used here, use Python 3.10 or later, or Node.js 22 or later. The reproducible installation commands pin Python openai==3.57.0 and npm [email protected]. See the Python package metadata and Node package metadata for runtime requirements.
Set the key in the terminal session that will run your script. Replace the placeholder with your DeepSeek key. On macOS or Linux:
export DEEPSEEK_API_KEY="your_deepseek_api_key"
On Windows PowerShell:
$env:DEEPSEEK_API_KEY="your_deepseek_api_key"
Keep credentials in your backend environment or a secrets manager. A frontend JavaScript bundle exposes its contents to visitors, so route browser requests through your own server. If you use a .env file instead, configure a loader; simply creating the file does not make every Python or Node process read it.
Use the OpenAI Python SDK with DeepSeek
In a new project directory, create a virtual environment and install the pinned package. The following activation command is for macOS or Linux:
python -m venv .venv
source .venv/bin/activate
python -m pip install "openai==3.57.0"
In PowerShell, activate the environment with .venv\Scripts\Activate.ps1 before running the installation command. If your system names its Python interpreter python3, use that command when creating the environment.
Save the following as deepseek_example.py. This first request explicitly disables thinking so its small output budget is available for the short answer.
import os
from openai import OpenAI
client = OpenAI(
api_key=os.environ["DEEPSEEK_API_KEY"],
base_url="https://api.deepseek.com",
timeout=60.0,
max_retries=0,
)
result = client.chat.completions.create(
model="deepseek-flash",
messages=[
{"role": "system", "content": "You are a concise assistant."},
{"role": "user", "content": "Reply with exactly: DeepSeek connection works."},
],
max_tokens=256,
extra_body={"thinking": {"type": "disabled"}},
)
choice = result.choices[0]
print(choice.message.content or "[No final text returned]")
print("Finish reason:", choice.finish_reason)
Run it in the same terminal:
python deepseek_example.py
A successful run should produce a short confirmation followed by Finish reason: stop. Generated wording can vary. If the reason is length, the output reached its limit; treat it as incomplete even if the printed text looks plausible.
The 60-second timeout and disabled retries make the first diagnostic request easier to understand. They are tutorial settings. Later, choose timeout and retry behavior for your workload. The constructor and request interfaces are documented in the OpenAI Python SDK.

For the Python extension examples below: retain the imports and client = OpenAI(...) setup above, then replace the initial request and print statements with the relevant snippet. Each extension performs its own model request.
Use the OpenAI SDK with DeepSeek in Node.js
In a new Node project, install the same npm package used for OpenAI integrations:
npm init -y
npm install --save-exact [email protected]
Save this as deepseek-example.mjs. The .mjs extension makes this an ES module, so the import statement and top-level await work together.
import OpenAI from "openai";
const apiKey = process.env.DEEPSEEK_API_KEY;
if (!apiKey) throw new Error("Set DEEPSEEK_API_KEY before running this file.");
const client = new OpenAI({
apiKey,
baseURL: "https://api.deepseek.com",
timeout: 60_000,
maxRetries: 0,
});
const result = await client.chat.completions.create({
model: "deepseek-flash",
messages: [
{ role: "system", content: "You are a concise assistant." },
{ role: "user", content: "Reply with exactly: DeepSeek connection works." },
],
max_tokens: 256,
thinking: { type: "disabled" },
});
const choice = result.choices[0];
console.log(choice.message.content ?? "[No final text returned]");
console.log("Finish reason:", choice.finish_reason);
node deepseek-example.mjs
Notice the language-specific spelling: JavaScript uses baseURL, and its timeout is in milliseconds. Also, thinking belongs directly in the JavaScript request object. Python’s extra_body is a client-side extension mechanism; copying that wrapper into JavaScript would send a different JSON shape. Compare the official DeepSeek Node.js example.

What changes for TypeScript?
The SDK’s types describe OpenAI’s API, so a DeepSeek-specific property may trigger an excess-property error. In a TypeScript file with the same import and configured client, replace the request with an explicitly extended parameter type:
const params: OpenAI.Chat.Completions.ChatCompletionCreateParamsNonStreaming & {
thinking: { type: "disabled" };
} = {
model: "deepseek-flash",
messages: [{ role: "user", content: "Say hello in one sentence." }],
max_tokens: 256,
thinking: { type: "disabled" },
};
const result = await client.chat.completions.create(params);
console.log(result.choices[0].message.content);
This keeps the normal Chat Completions fields typed while declaring the additional provider field. The official JavaScript/TypeScript SDK documents support for sending additional request properties; those properties still need to be supported by the destination API.
Chat Completions vs. Responses: choose the right request shape
DeepSeek supports both API formats. Keep Chat Completions for an existing messages-based integration. Use Responses when your application already handles its input and output items. The formats have different field names and stream events, so adapt the response parser along with the request.
| Task | Chat Completions | Responses |
|---|---|---|
| SDK method | client.chat.completions.create() | client.responses.create() |
| Conversation input | messages | input and optional instructions |
| Output limit | max_tokens | max_output_tokens |
| Final text | choices[0].message.content | output_text |
| Completion check | finish_reason | status |
| Streamed text | choices[0].delta.content | response.output_text.delta events |
This example uses the existing Python client and disables thinking through the Responses reasoning field:
response = client.responses.create(
model="deepseek-flash",
instructions="You are a concise assistant.",
input="Explain what an API client does in one sentence.",
reasoning={"effort": "none"},
max_output_tokens=256,
)
if response.status != "completed":
raise RuntimeError(f"Response did not complete: {response.status}")
if not response.output_text.strip():
raise RuntimeError("Response completed without usable text.")
print(response.output_text)
DeepSeek’s Responses API reference defines these fields. Its max_output_tokens budget includes reasoning as well as visible output when thinking is enabled.
Keep conversation history in your application
DeepSeek’s Responses implementation is stateless: send the required conversation history in each input request. previous_response_id does not provide stored conversation continuation, and store remains false. See the Responses compatibility guide.

For a simple text conversation, retain the user and assistant turns in order and add the next user turn. For tools or richer output, preserve the relevant output items rather than reducing every response to a single text string. The same application-owned history principle applies to Chat Completions: DeepSeek’s multi-round conversation guide sends the accumulated messages again.
Keep separate histories for separate users. A shared global message list can accidentally mix conversations. Decide how much history each task needs, and handle context limits explicitly instead of assuming the provider will trim the conversation for you.
Stream DeepSeek output with the OpenAI SDK
Streaming lets your interface display fragments while generation continues. In a Chat Completions stream, read delta.content. Some chunks contain control information rather than printable text, so check the fields before using them.
finish_reason = None
parts = []
with client.chat.completions.create(
model="deepseek-flash",
messages=[{"role": "user", "content": "Explain APIs in three short sentences."}],
max_tokens=256,
extra_body={"thinking": {"type": "disabled"}},
stream=True,
) as stream:
for chunk in stream:
if not chunk.choices:
continue
choice = chunk.choices[0]
if choice.delta.content:
parts.append(choice.delta.content)
print(choice.delta.content, end="", flush=True)
if choice.finish_reason:
finish_reason = choice.finish_reason
print()
if finish_reason != "stop" or not "".join(parts).strip():
raise RuntimeError(f"Stream did not finish normally: {finish_reason}")
This text-only example keeps the displayed answer provisional until it receives a normal finish reason and nonblank text. A transport error may raise an exception. A stream that ends without a normal finish reason is incomplete, and any displayed fragments should remain marked as partial. For a user interface, replace print() with your application’s incremental rendering or server-streaming mechanism.
DeepSeek’s Chat Completions reference documents the terminal finish reason and usage behavior. The empty-choices guard above is defensive client code; it does not assume DeepSeek sends a separate usage-only chunk.
Responses streaming requires a different loop: consume events whose type is response.output_text.delta, read event.delta, and handle completion, incomplete, and failure events. Its stream does not use Chat’s [DONE] terminator. Use the event contract in the Responses guide.

Control thinking mode without losing conversation state
Thinking is enabled by default in DeepSeek’s current API. The quickstarts disable it explicitly. To enable it in Chat Completions, change the extension to {"thinking": {"type": "enabled"}} and, if needed, set reasoning_effort="high". Allocate a suitable output budget for the task.
The final answer arrives in content; reasoning arrives separately in reasoning_content. In thinking mode, temperature, presence_penalty, and frequency_penalty do not affect generation. These behaviors are documented in Thinking Mode.
History handling depends on the request. When a thinking request includes tools, preserve the complete reasoning_content from earlier assistant turns, including turns that did not call a tool. Dropping it can cause a 400 error. Without tools, earlier reasoning does not need to be returned. Avoid a blanket rule that strips reasoning from every conversation.
For an application that switches modes, record the mode with each request and keep the returned assistant message intact in the internal conversation record. Display the final answer field in the ordinary answer area, and treat any reasoning display as a separate interface decision.
Request JSON output and validate the result
For Chat Completions, set response_format={"type": "json_object"} and explicitly ask for JSON in the prompt. A concrete example makes your intended fields easier to follow. DeepSeek’s JSON Output guide also notes that empty or whitespace-only output can occur.
import json
result = client.chat.completions.create(
model="deepseek-flash",
messages=[{
"role": "user",
"content": 'Return JSON only, with this shape: {"status":"ok","items":["a"]}.',
}],
response_format={"type": "json_object"},
max_tokens=256,
extra_body={"thinking": {"type": "disabled"}},
)
choice = result.choices[0]
text = choice.message.content or ""
if choice.finish_reason != "stop" or not text.strip():
raise ValueError("Expected a complete, nonempty JSON response.")
data = json.loads(text)
if (
not isinstance(data, dict)
or set(data) != {"status", "items"}
or data["status"] != "ok"
or not isinstance(data["items"], list)
or not all(isinstance(item, str) for item in data["items"])
):
raise ValueError("JSON does not match the application's expected fields.")
print(data)
The checks serve different purposes: completion status catches truncation, json.loads() checks syntax, and the remaining conditions check your application’s data contract. A parseable object with the wrong fields is still unusable for the intended workflow.

For schema-based text output, DeepSeek’s Responses endpoint also documents text.format with type: "json_schema", a schema name, and a schema object. That is a separate capability from Chat’s JSON-object mode. Match the request to the endpoint, and validate returned data before storing or acting on it.
Complete a function-calling round trip
A custom function tool gives the model a way to request application data. Your code receives the tool name and arguments, runs the permitted function, and returns its result with the original tool_call_id. Then another model request can produce the answer.
The following example uses a fictional order lookup with fixed local data. It allows at most three model requests, checks the requested function and argument shape, and rejects incomplete tool output before processing it. Reuse the configured Python client.
import json
tools = [{
"type": "function",
"function": {
"name": "lookup_demo_order",
"description": "Look up the status of a fictional demo order.",
"parameters": {
"type": "object",
"properties": {"order_id": {"type": "string"}},
"required": ["order_id"],
"additionalProperties": False,
},
},
}]
messages = [{"role": "user", "content": "Use the tool to check demo order DEMO-42."}]
for _ in range(3):
result = client.chat.completions.create(
model="deepseek-flash",
messages=messages,
tools=tools,
max_tokens=512,
extra_body={"thinking": {"type": "disabled"}},
)
choice = result.choices[0]
message = choice.message
messages.append(message.model_dump(exclude_unset=True))
if not message.tool_calls:
if choice.finish_reason != "stop" or not (message.content or "").strip():
raise RuntimeError("Expected a complete final answer.")
print(message.content)
break
if choice.finish_reason != "tool_calls":
raise RuntimeError("Tool request was incomplete.")
for call in message.tool_calls:
if call.type != "function" or call.function.name != "lookup_demo_order":
raise ValueError("Unknown tool requested.")
args = json.loads(call.function.arguments)
if (
not isinstance(args, dict)
or set(args) != {"order_id"}
or not isinstance(args["order_id"], str)
):
raise ValueError("Invalid tool arguments.")
status = "shipped" if args["order_id"] == "DEMO-42" else "not_found"
messages.append({
"role": "tool",
"tool_call_id": call.id,
"content": json.dumps({"order_id": args["order_id"], "status": status}),
})
else:
raise RuntimeError("Stopped after three model requests without a final answer.")
The local lookup has no external side effects. In a real order system, also check the signed-in user’s access to that order before returning data. Persist completed tool results when recovering from failures so a retry does not repeat a real-world action.
Appending message.model_dump(exclude_unset=True) preserves returned fields, including explicit content: null, tool calls, and any additional reasoning field. Keep these fields when replaying the assistant turn. DeepSeek’s Tool Calls guide describes the request-and-result sequence.

If you need DeepSeek’s beta strict function schemas, follow that guide’s separate beta endpoint and schema requirements. The basic example above validates arguments locally. A JSON Schema inside a tool definition does not, by itself, establish every strict-mode guarantee.
Use AsyncOpenAI in an asynchronous Python application
For async request handlers, use AsyncOpenAI and await the API request. The provider key, base URL, and request fields remain the same. This complete script demonstrates the lifecycle:
import asyncio
import os
from openai import AsyncOpenAI
async def main():
async with AsyncOpenAI(
api_key=os.environ["DEEPSEEK_API_KEY"],
base_url="https://api.deepseek.com",
timeout=60.0,
max_retries=0,
) as client:
result = await client.chat.completions.create(
model="deepseek-flash",
messages=[{"role": "user", "content": "Say hello in one sentence."}],
max_tokens=256,
extra_body={"thinking": {"type": "disabled"}},
)
print(result.choices[0].message.content)
asyncio.run(main())
The Python SDK provides synchronous and asynchronous clients. In a running web service, reuse an appropriately scoped client and close it during shutdown. Apply a concurrency limit when dispatching many requests; async code alone does not control your account’s request volume.
Which other OpenAI features work with DeepSeek?
Check support at the endpoint and model level. A method appearing in the installed SDK does not establish that the destination server implements its behavior.
| Capability | What to check before migrating |
|---|---|
| Vision | deepseek-flash supports image input. Chat and Responses use different image content shapes; the current model table does not list vision support for Pro. |
| Files | DeepSeek documents SDK-compatible file operations for Flash. Upload purpose and parsing rules depend on file type. |
| Stored Responses conversations | Keep history in your application; do not rely on previous_response_id. |
| Built-in tools | The Responses guide lists OpenAI-shaped file_search, code_interpreter, computer_use, and mcp tools as ignored. |
| Other SDK resources | Verify a matching DeepSeek endpoint before porting embeddings, fine-tuning, batch jobs, or other resource calls. A working chat request is insufficient evidence. |
Use the official Vision guide, Files API guide, model capability table, and Responses support matrix for these distinctions. Some unsupported Responses parameters are ignored, so a successful HTTP status alone does not prove that a requested feature ran.

For each feature your application needs, define an observable check. If the task requires document content, verify that the response actually used the uploaded document. If it requires a tool, inspect the returned tool records. Keep a small migration test set covering the outputs your application depends on.
Troubleshoot OpenAI SDK and DeepSeek errors
| Error or symptom | What to inspect | Next step |
|---|---|---|
| 401 authentication error | Wrong, missing, or invalid DeepSeek key | Pass the DeepSeek credential explicitly; check the environment used by the running process. |
| 402 insufficient balance | DeepSeek account balance | Resolve the balance issue before repeating requests. |
| 400 or 422 | Request fields, values, history, and endpoint shape | Read the provider’s error message and reduce the request to the working quickstart. |
| 429 | Rate, concurrency, or QPS limits | Reduce concurrent work and use bounded retry delays. |
| 500 or 503 | Provider failure or overload | Retry transient failures with a delay and a fixed attempt limit. |
| Model or route not found | Model ID and constructed URL | Check current model names and pass the API root as the base URL. Inspect any gateway configuration. |
| Python import or attribute error | Installed package, interpreter, and local filenames | Run python -m pip show openai; avoid naming your script openai.py. |
TypeScript rejects thinking | SDK type definition | Use the typed extension shown above, then confirm the field is supported by DeepSeek. |
| Blank text or incomplete output | Finish reason, response status, reasoning fields, and token budget | Distinguish incomplete generation from a transport error before retrying. |
| Timeout | Network access, workload duration, and client timeout | Check connectivity and increase the budget only when the workload justifies it. |
The HTTP meanings above follow DeepSeek’s Error Codes reference. For 400 and 422 errors, changing credentials will not repair an invalid request body. For 402, repeated retries will not add account balance.
When catching SDK exceptions, inspect the HTTP status as well as the class. In Python, a 402 response is an APIStatusError; in JavaScript it is an APIError. Check for status 402 to distinguish a balance problem from other failures handled by those classes. See the Python exception definitions and JavaScript error handling.
Log enough context to reproduce the failure: SDK version, chosen model, endpoint, status, completion state, and a request identifier when available. Keep API keys and sensitive prompt contents out of routine logs. Separate transport failures from valid HTTP responses whose generation ended incompletely.
Prepare the integration for production
- Keep provider clients explicit. Create a dedicated DeepSeek client so its key, model, and URL cannot be confused with another provider’s configuration.
- Pin and review dependencies. Upgrade the SDK deliberately and rerun representative request and response checks.
- Set a timeout and retry budget. The examples disable automatic retries for diagnosis. Enable a bounded policy for transient failures and avoid stacking it with another unbounded retry loop.
- Validate completion before using output. Handle truncated text, blank JSON, malformed tool arguments, and interrupted streams as distinct cases.
- Measure your actual workload. Record latency, successful completion rate, tool rounds, and token usage on representative prompts.
- Keep conversations isolated. Store history per user or session and apply the reasoning-history rules when tools are enabled.
Monitor costs through DeepSeek’s account and usage records. Current pricing distinguishes input, output, and cached input, and can vary by time period. Link your budgeting assumptions to the current pricing page instead of copying an old model’s rate into a permanent estimate. For parallel workloads, review DeepSeek’s account-level limits.
Frequently asked questions
Do I need an OpenAI API key to use DeepSeek through this SDK?
Use a DeepSeek API key for requests sent to DeepSeek. The openai package supplies the client code; your explicit base URL and credentials determine the provider used by these examples. You can create the key in the DeepSeek platform.
Can one application use both OpenAI and DeepSeek?
Yes. Maintain separate configured clients and select the appropriate client and model for each task. Prefer explicit constructor settings over changing a process-wide base URL while requests are running. Keep provider-specific request features behind clear application interfaces.
Does using the OpenAI SDK make DeepSeek API calls free?
DeepSeek API usage follows DeepSeek’s pricing. Installing a client package does not supply API balance. Check usage and charges in the provider account associated with the key used for the request.
Why do older examples use openai.ChatCompletion.create?
Those examples use an older Python interface. The code in this guide creates an OpenAI client and calls client.chat.completions.create(). Check the installed package version before combining code from different generations of the SDK; the current Python repository documents the supported interface.
How these examples were checked
The examples were exercised with OpenAI Python 3.57.0 and OpenAI Node.js 7.62.0 using locally intercepted HTTP requests and simulated responses. Checks covered request URLs and JSON serialization, response parsing, streaming, structured-data validation, and the bounded tool workflow. This validates client behavior and example logic; it does not establish live DeepSeek availability, answer quality, or production performance.
