DeepSeek API Guide: Python, JavaScript and Integrations
The
DeepSeek API lets developers use DeepSeek’s hosted models inside applications, internal tools and AI agents. Its main advantage is compatibility: developers can use familiar OpenAI-style or Anthropic-style SDKs while sending requests to DeepSeek’s endpoints.
As of August 7, 2026, DeepSeek’s
official model and pricing table lists the current model IDs as deepseek-v4-flash and deepseek-v4-pro. Both support Chat Completions, thinking and non-thinking modes, JSON output, tool calls and an Anthropic-compatible interface. The Responses API currently supports Flash but not Pro.
This guide focuses on implementation. Read the
complete DeepSeek AI guide for the product map and the
DeepSeek pricing guide before estimating production cost.
DeepSeek API at a glance
| Item | Current value |
| OpenAI-compatible base URL | https://api.deepseek.com |
| Anthropic-compatible base URL | https://api.deepseek.com/anthropic |
| Current model IDs | deepseek-v4-flash, deepseek-v4-pro |
| Context window | 1M tokens |
| Maximum output | 384K tokens |
| Thinking mode | Supported on both models |
| JSON output | Supported on both models |
| Tool calls | Supported on both models |
| Responses API | Flash only at the cut-off date |
| Legacy aliases | deepseek-chat and deepseek-reasoner retired July 24, 2026 |
The official starting point is the
DeepSeek API documentation. The code below adds safeguards that minimal quick-start examples often omit.
1. Create and protect an API key
Create a key in the DeepSeek Open Platform account. Treat it like a password with financial consequences.
Do not:
- paste the key into source code;
- commit it to Git;
- expose it in browser-side JavaScript;
- place it in a mobile application bundle;
- share one unrestricted key across unrelated teams;
- or print it in logs.
Use an environment variable named DEEPSEEK_API_KEY in the examples below. In production, use a managed secret store and rotate the key after suspected exposure.
DeepSeek’s Open Platform terms make the developer responsible for fees and losses caused by sharing or leaking the key. They also require downstream developers to create appropriate privacy notices, legal bases and technical safeguards for end users.
2. Install the OpenAI SDK
DeepSeek’s OpenAI-compatible interface works with the OpenAI SDK after changing the base URL.
Python:
python -m pip install --upgrade openai
JavaScript or TypeScript:
npm install openai Copy Raw HTMLRich Code
Compatibility reduces integration effort, but it does not make DeepSeek behavior identical to OpenAI. Test model-specific parameters, tool calls, output shape and errors.
3. Make a DeepSeek request with Python
This example validates the environment variable, applies a timeout and catches common failures.
import os
import sys
from openai import APIConnectionError, APIStatusError, APITimeoutError, OpenAI
api_key = os.getenv("DEEPSEEK_API_KEY")
if not api_key:
raise RuntimeError("DEEPSEEK_API_KEY is not set")
client = OpenAI(
api_key=api_key,
base_url="https://api.deepseek.com",
timeout=60.0,
max_retries=2,
)
try:
response = client.chat.completions.create(
model="deepseek-v4-flash",
messages=[
{
"role": "system",
"content": "Answer clearly. State uncertainty and never invent sources.",
},
{
"role": "user",
"content": "Explain context caching in 120 words.",
},
],
stream=False,
max_tokens=500,
extra_body={"thinking": {"type": "disabled"}},
)
except APITimeoutError as exc:
print(f"DeepSeek request timed out: {exc}", file=sys.stderr)
raise
except APIConnectionError as exc:
print(f"Could not reach the DeepSeek API: {exc}", file=sys.stderr)
raise
except APIStatusError as exc:
print(
f"DeepSeek returned HTTP {exc.status_code}: {exc.response.text}",
file=sys.stderr,
)
raise
message = response.choices[0].message.content
if not message:
raise RuntimeError("DeepSeek returned an empty response")
print(message)
Parameter names can differ across SDK versions. Pin and test the SDK version used by your application rather than copying an example indefinitely.
4. Make a DeepSeek request with JavaScript
Server-side JavaScript should read the key from the environment and set request limits.
import OpenAI from "openai";
const apiKey = process.env.DEEPSEEK_API_KEY;
if (!apiKey) {
throw new Error("DEEPSEEK_API_KEY is not set");
}
const client = new OpenAI({
apiKey,
baseURL: "https://api.deepseek.com",
timeout: 60_000,
maxRetries: 2,
});
async function main() {
try {
const response = await client.chat.completions.create({
model: "deepseek-v4-flash",
messages: [
{
role: "system",
content: "Answer clearly. State uncertainty and never invent sources.",
},
{
role: "user",
content: "Explain context caching in 120 words.",
},
],
max_tokens: 500,
stream: false,
thinking: { type: "disabled" },
});
const text = response.choices[0]?.message?.content;
if (!text) {
throw new Error("DeepSeek returned an empty response");
}
console.log(text);
} catch (error) {
if (error instanceof OpenAI.APIError) {
console.error("DeepSeek API error", {
status: error.status,
name: error.name,
message: error.message,
});
} else {
console.error("Unexpected DeepSeek client error", error);
}
process.exitCode = 1;
}
}
main();
Never run this code directly in a public browser bundle. A browser user could inspect the network request or packaged JavaScript and steal the key. Put the model call behind your own authenticated server endpoint.
5. Choose V4 Flash or V4 Pro
Start with deepseek-v4-flash for most workloads. It is much cheaper and the current 0731 version was post-trained for stronger agentic behavior.
Use deepseek-v4-pro when representative tests show that the larger model materially improves:
- difficult reasoning;
- complex code changes;
- long-document synthesis;
- planning across many dependencies;
- or tool selection in consequential agents.
A production router can send ordinary tasks to Flash and escalate only failures or high-risk cases to Pro. The
DeepSeek models guide explains the model families and current lifecycle.
6. Enable thinking mode
DeepSeek V4 supports thinking and non-thinking modes. Thinking is enabled by default in parts of the current
thinking-mode documentation, so applications should set the desired behavior explicitly rather than rely on defaults.
Python example:
response = client.chat.completions.create(
model="deepseek-v4-pro",
messages=[
{"role": "user", "content": "Design a safe migration plan for this database."}
],
reasoning_effort="high",
extra_body={"thinking": {"type": "enabled"}},
max_tokens=4000,
)
print(response.choices[0].message.content)
Use thinking for difficult work. Disable it for simple extraction, classification or formatting where extra output and latency add little value.
At the current snapshot, effort mappings are not perfectly symmetrical between Flash and Pro. DeepSeek’s thinking-mode documentation says Pro temporarily maps some requested levels to higher effort. Measure actual latency and token usage.
Do not store or expose hidden reasoning as if it were an audit trail. For verification, preserve the final answer, input evidence, tool calls, tool results, model ID and application decisions.
DeepSeek added a Responses-compatible endpoint for agent and Codex integrations. At the cut-off date, only deepseek-v4-flash is supported.
from openai import OpenAI
import os
client = OpenAI(
api_key=os.environ["DEEPSEEK_API_KEY"],
base_url="https://api.deepseek.com",
timeout=60.0,
)
response = client.responses.create(
model="deepseek-v4-flash",
instructions="Return a concise, evidence-aware answer.",
input="List the migration risks when changing an API model alias.",
max_output_tokens=800,
)
print(response.output_text)
Copy Raw HTMLRich Code
Do not switch the model name to Pro until DeepSeek’s documentation shows Responses support is live and your tests confirm it. “Expected in early August” is not the same as available.
8. Use the Anthropic-compatible API
DeepSeek also documents an
Anthropic-compatible interface with this base URL:
https://api.deepseek.com/anthropic
Copy Raw HTMLRich Code
This can help applications or agent tools built around the Anthropic Messages API. It does not turn DeepSeek into Claude. The model, provider, terms, data handling and safety behavior remain DeepSeek’s.
A configuration may require:
- ANTHROPIC_BASE_URL=https://api.deepseek.com/anthropic;
- a DeepSeek API key supplied through the environment variable expected by the tool;
- a DeepSeek model name;
- and provider-specific testing.
The official documentation includes a
Claude Code integration guide. Using DeepSeek as a backend in Claude Code means the interface or harness is Claude Code while the model inference comes from DeepSeek. Do not describe the result as “Claude powered by DeepSeek” without explaining that distinction.
Structured output is useful for extraction and application workflows. A model’s JSON mode improves formatting but does not validate the business meaning of the fields.
import json
response = client.chat.completions.create(
model="deepseek-v4-flash",
messages=[
{
"role": "system",
"content": (
"Extract the contract fields as JSON with keys: "
"party_names, effective_date, renewal_term, termination_notice_days. "
"Use null when the source does not state a value."
),
},
{"role": "user", "content": "Contract text goes here."},
],
response_format={"type": "json_object"},
extra_body={"thinking": {"type": "disabled"}},
max_tokens=1000,
)
raw = response.choices[0].message.content
try:
data = json.loads(raw)
except (TypeError, json.JSONDecodeError) as exc:
raise RuntimeError(f"Invalid JSON from DeepSeek: {raw!r}") from exc
required = {
"party_names",
"effective_date",
"renewal_term",
"termination_notice_days",
}
missing = required.difference(data)
if missing:
raise RuntimeError(f"Missing required fields: {sorted(missing)}")
print(data)
Copy Raw HTMLRich Code
For production:
- validate against a JSON schema;
- reject unknown fields where appropriate;
- enforce types and ranges;
- preserve the source passage for review;
- and define what happens when a value is absent.
Tool calling allows a model to request an operation such as looking up an order, querying a database or creating a support ticket. The model should propose a tool call; your application remains responsible for validating and executing it.
A safe tool layer should:
- expose only necessary functions;
- use strict schemas;
- authenticate the end user independently of the model;
- check authorization for every action;
- validate arguments;
- require confirmation for consequential writes;
- cap the number of iterations;
- isolate code execution;
- and log calls and results without leaking secrets.
Never allow free-form model text to become a shell command or SQL statement without a constrained intermediary. Prompt injection in a retrieved webpage or document can try to manipulate an agent into using its tools incorrectly.
11. Stream responses
Streaming returns output incrementally and can improve perceived latency. It also changes error handling: a request may begin successfully and fail before completion.
Applications should:
- distinguish partial from completed output;
- avoid acting on an incomplete tool argument;
- handle disconnects;
- store the final completion status;
- and provide a retry path that does not duplicate irreversible actions.
For an ordinary chat interface, stream text to the user. For structured extraction or tool calls, waiting for a complete validated response may be safer.
12. Manage long context
V4 supports a one-million-token context window, but sending the maximum on every request is usually inefficient.
Use:
- retrieval to select relevant evidence;
- stable prompt prefixes for cache reuse;
- conversation summarization;
- tool-result compression;
- document identifiers and provenance;
- and explicit instructions that the model must say when evidence is missing.
Large context can create new failure modes. The model may miss a passage, combine incompatible versions or overweight a late document. Test with adversarial ordering and contradictory sources.
13. Handle rate limits and failures
DeepSeek lists concurrency limits rather than a simple requests-per-minute number in the current
pricing table. Actual behavior can depend on model, account and service conditions.
Production code should recognize:
- authentication failures;
- insufficient balance;
- invalid parameters;
- rate or concurrency limits;
- server errors;
- network timeouts;
- malformed output;
- content refusals;
- and tool failures.
Use exponential backoff with jitter for retryable failures. Do not retry invalid credentials or malformed requests indefinitely. Cap retries and surface a clear failure state.
For write actions, make the application idempotent. The model call itself may be repeated after a timeout even when the first attempt succeeded. Use your own operation IDs and check whether an action has already been completed.
14. Record usage and cost
Capture the provider’s usage fields for each request. Store at least:
- timestamp;
- application and user or service account;
- model ID;
- input, cached input and output tokens;
- latency;
- retry count;
- success or failure;
- tool calls;
- and estimated cost.
Do not log full prompts by default when they can contain personal, confidential or regulated data. Use data classification, redaction and retention rules.
Monitor cost per successful task rather than cost per request. A cheap model with a high correction rate can be expensive operationally.
15. Migrate from old DeepSeek model IDs
Any application still using deepseek-chat or deepseek-reasoner needs an explicit migration. Those aliases were retired on July 24, 2026.
Migration steps:
- search code, configuration, infrastructure templates and secrets for the old IDs;
- choose V4 Flash or Pro by workload;
- set thinking behavior explicitly;
- rerun regression tests;
- inspect JSON and tool-call differences;
- update cost assumptions;
- monitor error rates after release;
- remove compatibility branches after the migration is stable.
Do not perform a blind string replacement in a consequential application. The old aliases may have implied thinking or non-thinking behavior that the new configuration must recreate deliberately.
16. Integrate DeepSeek with Codex and coding agents
DeepSeek’s official documentation provides integration instructions for Codex, Claude Code, OpenCode and other agent tools.
At the August 7 snapshot:
- Codex integration uses the Responses API;
- only V4 Flash is supported through that route;
- V4 Pro support was described as expected but was not yet listed as available;
- V4 Flash 0731 was specifically adapted for coding-agent use.
Agent integrations increase risk because the model can inspect files, run commands or modify repositories. Use:
- a disposable branch or worktree;
- least-privilege credentials;
- sandboxed execution;
- command allowlists or confirmation;
- tests and static analysis;
- review of every diff;
- and a clean rollback path.
A strong benchmark does not justify giving an agent unrestricted production access.
17. Protect user data
DeepSeek’s consumer privacy policy says covered personal data is processed and stored in
China. The Open Platform terms place downstream privacy and security responsibilities on the developer.
Before sending production data, align the implementation with the procurement and governance controls in
DeepSeek for business:
- classify the data;
- identify the legal basis and contractual role;
- review current terms and privacy documents;
- minimize prompts;
- remove secrets and unnecessary identifiers;
- decide whether model-training opt-out settings apply to the relevant service;
- define retention and deletion;
- and consider a third-party or self-hosted route when the official service is not approved.
Read
Is DeepSeek safe? for the full deployment-specific analysis.
Production checklist
Application
- Current model IDs are configured centrally.
- Timeouts and capped retries are set.
- Output and context limits exist.
- JSON is schema-validated.
- Tool arguments are validated and authorized.
- Consequential actions require confirmation.
- Fallback behavior is defined.
Security
- API keys are in a managed secret store.
- Keys are not exposed to browsers or mobile clients.
- Prompt and response logging is minimized.
- Retrieved content is treated as untrusted.
- Code execution is sandboxed.
- Incident and key-rotation procedures exist.
Quality
- Representative evaluation cases exist.
- Hallucination and refusal behavior is measured.
- Model changes trigger regression tests.
- Human review is assigned for high-impact outputs.
- Source evidence is preserved where needed.
Operations
- Token use and cost are monitored.
- Concurrency behavior is load-tested.
- Alerts cover errors, latency and balance.
- Model-provider abstraction is documented.
- A rollback or alternate provider is available.
Frequently asked questions
What is the DeepSeek API base URL?
Use https://api.deepseek.com for the OpenAI-compatible interface and https://api.deepseek.com/anthropic for the Anthropic-compatible interface.
Which DeepSeek API model should I use?
Start with deepseek-v4-flash. Use deepseek-v4-pro when evaluation shows a meaningful quality gain on difficult work.
Does the DeepSeek API work with the OpenAI SDK?
Yes. Change the base URL, API key and model name. Compatibility does not remove the need to test DeepSeek-specific parameters and behavior.
Does DeepSeek support the Anthropic API?
DeepSeek provides an Anthropic-compatible endpoint. It uses DeepSeek models and terms, not Anthropic models or safeguards.
Does DeepSeek support the Responses API?
At the August 7, 2026 snapshot, Responses supports V4 Flash only. Pro support should not be assumed until the official documentation changes.
How do I enable DeepSeek thinking mode?
Use the thinking parameter and a supported reasoning-effort value. Set the behavior explicitly because defaults and effort mappings can change.
Can I use DeepSeek in Claude Code?
Yes, through DeepSeek’s Anthropic-compatible endpoint according to its official integration guide. Claude Code is the harness; DeepSeek supplies the model inference.
Can I put a DeepSeek key in frontend JavaScript?
No. A public frontend cannot protect a provider key. Call DeepSeek from an authenticated server you control.
Is the DeepSeek API free?
No. It is token-metered. Consumer chat access and API billing are separate.
What happened to deepseek-chat and deepseek-reasoner?
DeepSeek’s
changelog records the retirement of both legacy aliases in July 2026. Migrate to V4 Flash or Pro and re-test thinking behavior.
The bottom line
The DeepSeek API is easy to prototype because it supports familiar SDK formats and extremely low current token rates. A production integration still needs deliberate model selection, explicit thinking settings, schema validation, safe tool execution, key protection, usage monitoring and a migration path.
Use V4 Flash as the baseline, route only difficult work to Pro, and never confuse API compatibility with identical provider behavior. DeepSeek can reduce inference cost dramatically; the application remains responsible for security, privacy, correctness and every action taken on the model’s output.