← All articles

DeepSeek API: The Complete Guide for AI Engineers (2026)

Everything you need to start building with the DeepSeek API — signup, API key, first call in 3 minutes. We cover V4-Flash and V4-Pro, thinking mode, streaming, tool calls, pricing, rate limits, common errors, and how to route DeepSeek as a primary or backup provider.

· TheRouter

The DeepSeek API is an OpenAI-compatible endpoint that gives you access to DeepSeek's V4 model family — including V4-Pro, their strongest reasoning model, and V4-Flash, their fast and extremely affordable workhorse. Both models support 1 million tokens of context, optional thinking mode, tool calls, and JSON output. You sign up at platform.deepseek.com, grab an API key, point your existing OpenAI SDK at https://api.deepseek.com, and your code works.

We wrote this guide because DeepSeek's pricing is among the lowest in the industry, but the V4 model line introduced new model names, thinking mode defaults, and a deprecation timeline for legacy names that can trip you up if you're not paying attention. This is the single reference we wanted when we first integrated DeepSeek into our routing layer.

Getting Started in 3 Minutes

Step 1: Create an account. Go to platform.deepseek.com and sign up. DeepSeek supports email registration and Google OAuth login.

Step 2: Get your API key. Navigate to API Keys and click "Create API Key." Copy it — you'll need it in a moment. Keys are shown once; store them securely.

Step 3: Make your first call. Install the OpenAI Python SDK if you haven't already:

pip install --upgrade openai

Then run:

from openai import OpenAI

client = OpenAI(
    api_key="YOUR_DEEPSEEK_KEY",
    base_url="https://api.deepseek.com",
)

response = client.chat.completions.create(
    model="deepseek-v4-flash",
    messages=[{"role": "user", "content": "What is DeepSeek V4?"}],
)

print(response.choices[0].message.content)

That's it. No credit card required for the initial free balance. DeepSeek periodically tops up accounts with promotional credits — check your account balance to see what's available.

DeepSeek Model Families: V4-Flash and V4-Pro

DeepSeek currently offers two models via their API, both launched as a preview on April 24, 2026:

ModelModel IDContextMax OutputBest For
V4-Flashdeepseek-v4-flash1M tokens384KFast chat, code generation, high-throughput workloads
V4-Prodeepseek-v4-pro1M tokens384KComplex reasoning, multi-step analysis, tool-heavy agent workflows

Both models support both thinking and non-thinking modes. Thinking mode is enabled by default — the model emits chain-of-thought reasoning before the final answer.

Legacy Model Names (Deprecated)

DeepSeek is deprecating two older model IDs on July 24, 2026 (15:59 UTC):

Legacy IDMaps ToNote
deepseek-chatdeepseek-v4-flash (non-thinking mode)Will stop working after deprecation
deepseek-reasonerdeepseek-v4-flash (thinking mode)Will stop working after deprecation

If your codebase still uses deepseek-chat or deepseek-reasoner, switch to deepseek-v4-flash now. We recommend setting the thinking toggle explicitly rather than relying on implicit mode selection.

What Changed from V3 to V4

The V4 line is DeepSeek's fourth-generation architecture. Key differences from V3.x:

  • Unified thinking mode: V4 replaces the separate R1 reasoning line — V4's optional thinking mode covers what R1 was used for. If you were routing to deepseek-r1 for reasoning tasks, switch to deepseek-v4-pro with thinking enabled.
  • 1M context window: V3.x topped out at 128K; V4 supports 1M tokens on both Flash and Pro.
  • Anthropic API compatibility: V4 added an Anthropic-format endpoint at https://api.deepseek.com/anthropic, in addition to the existing OpenAI format.
  • FIM completion: Fill-in-the-middle completion is supported in non-thinking mode on both models, useful for code completion workflows.

Source: DeepSeek V4 Preview Release, retrieved 2026-06-07.

OpenAI SDK Setup: Python, Node.js, and Streaming

DeepSeek implements the OpenAI ChatCompletions specification. No special SDK required — use the official OpenAI SDK and change base_url.

Python

from openai import OpenAI

client = OpenAI(
    api_key="YOUR_DEEPSEEK_KEY",
    base_url="https://api.deepseek.com",
)

# Non-streaming
response = client.chat.completions.create(
    model="deepseek-v4-flash",
    messages=[{"role": "user", "content": "Explain the CAP theorem."}],
)
print(response.choices[0].message.content)

# Streaming
stream = client.chat.completions.create(
    model="deepseek-v4-flash",
    messages=[{"role": "user", "content": "Explain the CAP theorem."}],
    stream=True,
)
for chunk in stream:
    if chunk.choices[0].delta.content:
        print(chunk.choices[0].delta.content, end="")

Node.js

import OpenAI from "openai";

const client = new OpenAI({
    apiKey: process.env.DEEPSEEK_API_KEY,
    baseURL: "https://api.deepseek.com",
});

const completion = await client.chat.completions.create({
    model: "deepseek-v4-flash",
    messages: [{ role: "user", content: "Explain the CAP theorem." }],
});

console.log(completion.choices[0].message.content);

curl

curl https://api.deepseek.com/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer ${DEEPSEEK_API_KEY}" \
  -d '{
    "model": "deepseek-v4-flash",
    "messages": [{"role": "user", "content": "Hello!"}],
    "stream": false
  }'

Source: DeepSeek API Docs — Your First API Call, retrieved 2026-06-07.

Thinking Mode: When and How to Use It

Both V4 models support thinking mode — the model generates chain-of-thought reasoning before producing the final answer. Thinking mode is enabled by default on both models.

Toggle Thinking Mode

# Enable thinking (default)
response = client.chat.completions.create(
    model="deepseek-v4-pro",
    messages=[{"role": "user", "content": "Prove that sqrt(2) is irrational."}],
    extra_body={"thinking": {"type": "enabled"}},
    reasoning_effort="high",
)

# Disable thinking
response = client.chat.completions.create(
    model="deepseek-v4-flash",
    messages=[{"role": "user", "content": "What is 2+2?"}],
    extra_body={"thinking": {"type": "disabled"}},
)

Effort Levels

  • high — default for regular requests
  • max — automatically used by some agent tools (Claude Code, OpenCode); gives deeper reasoning at higher latency

Accessing Reasoning Content

In thinking mode, the reasoning chain is returned in a reasoning_content field alongside the regular content:

response = client.chat.completions.create(
    model="deepseek-v4-pro",
    messages=[{"role": "user", "content": "9.11 vs 9.8, which is greater?"}],
    reasoning_effort="high",
    extra_body={"thinking": {"type": "enabled"}},
)

reasoning = response.choices[0].message.reasoning_content  # chain of thought
answer = response.choices[0].message.content               # final answer

Multi-Turn Conversations with Thinking

When there are no tool calls between turns, the reasoning_content from previous turns does not need to be included in subsequent requests. DeepSeek's API ignores it automatically. However, when tool calls are involved, reasoning_content must be passed back in all subsequent turns — failure to do so results in a 400 error.

When to Disable Thinking

  • Simple factual queries — thinking adds latency for no quality gain
  • High-throughput chat — disable thinking to maximize V4-Flash's concurrency advantage
  • Cost-sensitive workloads — thinking tokens count toward output pricing

Source: DeepSeek API Docs — Thinking Mode, retrieved 2026-06-07.

Tool Calls and JSON Output

Both V4 models support function/tool calling and structured JSON output, compatible with OpenAI's specification.

Tool Calls

import json

tools = [
    {
        "type": "function",
        "function": {
            "name": "get_weather",
            "description": "Get current weather for a city",
            "parameters": {
                "type": "object",
                "properties": {
                    "city": {"type": "string", "description": "City name"},
                },
                "required": ["city"],
            },
        },
    }
]

response = client.chat.completions.create(
    model="deepseek-v4-pro",
    messages=[{"role": "user", "content": "What's the weather in Beijing?"}],
    tools=tools,
    tool_choice="auto",
)

# Check if the model wants to call a tool
if response.choices[0].message.tool_calls:
    call = response.choices[0].message.tool_calls[0]
    print(f"Function: {call.function.name}")
    print(f"Arguments: {json.loads(call.function.arguments)}")

JSON Output

response = client.chat.completions.create(
    model="deepseek-v4-flash",
    messages=[
        {"role": "system", "content": "Respond in JSON format."},
        {"role": "user", "content": "List 3 programming languages with their years of creation."},
    ],
    response_format={"type": "json_object"},
)
print(json.loads(response.choices[0].message.content))

FIM Completion (Code Completion)

Both models support fill-in-the-middle in non-thinking mode, useful for code editors:

response = client.completions.create(
    model="deepseek-v4-flash",
    prompt="def fibonacci(n):\n    ",
    suffix="    return fib",
)
print(response.choices[0].text)

Source: DeepSeek API Docs — Tool Calls, retrieved 2026-06-07.

Pricing and Rate Limits

Pricing (Per 1M Tokens)

ModelInput (Cache Hit)Input (Cache Miss)Output
V4-Flash$0.0028$0.14$0.28
V4-Pro$0.003625$0.435$0.87

Source: DeepSeek API Docs — Models & Pricing, retrieved 2026-06-07. Prices subject to change.

Cache hit pricing is ~50× cheaper than cache miss. This makes DeepSeek especially cost-effective for workloads that reuse the same system prompt or long context — like RAG pipelines, agent loops, or code analysis tools that share a codebase prefix.

Rate Limits (Concurrency)

ModelConcurrency Limit
V4-Pro500 concurrent requests
V4-Flash2,500 concurrent requests

DeepSeek measures concurrency at the account level — a request counts from the moment it's sent until the response completes. Exceeding the limit returns HTTP 429. There are no token-per-minute or requests-per-minute rate limits beyond concurrency.

If you need higher concurrency, DeepSeek offers a capacity expansion request form at no additional cost.

Source: DeepSeek API Docs — Rate Limit & Isolation, retrieved 2026-06-07.

Billing

DeepSeek bills from a prepaid balance (topped-up or granted). Promotional credits are used first. Prices may be adjusted — DeepSeek recommends topping up based on actual usage and checking pricing regularly.

Cost Comparison

To put the pricing in context: V4-Flash at $0.14/$0.28 per 1M tokens is significantly cheaper than most alternatives. It's a fraction of what you'd pay for comparable models from Western providers, while still supporting 1M context and tool calls.

Common Errors and Fixes

CodeMeaningFix
400Bad request — invalid parametersCheck model name, message format, and that reasoning_content is passed back when tool calls are involved in thinking mode
401Authentication failedVerify your API key at platform.deepseek.com
402Insufficient balanceTop up your account balance
422Invalid request bodyEnsure your JSON body matches the OpenAI ChatCompletions schema
429Concurrency limit exceededWait for in-flight requests to complete, or use user_id to isolate traffic
500Server errorRetry with exponential backoff; check DeepSeek status if persistent

Thinking Mode Pitfalls

  • temperature / top_p ignored in thinking mode: Setting these parameters won't cause an error, but they have no effect when thinking is enabled. Don't rely on them to control output randomness.
  • Missing reasoning_content in tool-call turns: If the model performed a tool call, you must include reasoning_content in subsequent requests. Omitting it returns a 400 error.
  • reasoning_effort compatibility: low and medium are silently mapped to high; xhigh is mapped to max. Don't use these as distinct levels.

Keep-Alive Behavior

When a request is waiting for inference, DeepSeek's API sends periodic keep-alive signals (empty lines for non-streaming, SSE comments for streaming). If parsing HTTP responses manually, handle these gracefully. If inference hasn't started within 10 minutes, the server closes the connection.

Source: DeepSeek API Docs — FAQ, retrieved 2026-06-07.

Routing DeepSeek with Backup Providers

If you're building a production application, relying on a single provider is risky. Here's how we'd approach routing DeepSeek as a primary provider with a fallback:

With TheRouter

If you use TheRouter, you can configure DeepSeek as a provider alongside others. TheRouter routes OpenAI-compatible requests through configured providers and supports provider/model fallback when live product paths support it. This means you can set DeepSeek as primary and another provider as backup — without changing your application code.

Manual Fallback Pattern

If you're handling fallback yourself:

import openai
import time

providers = [
    {"name": "deepseek", "base_url": "https://api.deepseek.com", "model": "deepseek-v4-flash", "key": "DS_KEY"},
    {"name": "siliconflow", "base_url": "https://api.siliconflow.cn/v1", "model": "deepseek-v4-flash", "key": "SF_KEY"},
    {"name": "other", "base_url": "https://api.other-provider.com/v1", "model": "deepseek-v4-flash", "key": "OTHER_KEY"},
]

for provider in providers:
    try:
        client = openai.OpenAI(api_key=provider["key"], base_url=provider["base_url"])
        response = client.chat.completions.create(
            model=provider["model"],
            messages=[{"role": "user", "content": "Hello!"}],
            timeout=30,
        )
        print(f"Success via {provider['name']}")
        break
    except Exception as e:
        print(f"{provider['name']} failed: {e}")
        time.sleep(1)

DeepSeek models are widely available through third-party aggregators like SiliconFlow, giving you geographic redundancy if DeepSeek's own API has regional issues.

Production Checklist

Before shipping DeepSeek to production:

  • Switch from legacy model names — if using deepseek-chat or deepseek-reasoner, migrate to deepseek-v4-flash before July 24, 2026
  • Set thinking mode explicitly — don't rely on defaults; pass {"thinking": {"type": "enabled"}} or {"type": "disabled"} based on your use case
  • Handle reasoning_content in tool-call turns — pass it back in subsequent requests to avoid 400 errors
  • Monitor concurrency — V4-Flash has a 2,500 concurrent request limit; V4-Pro has 500
  • Set up a fallback provider — don't depend on a single API endpoint for production traffic
  • Preload your context prefix — DeepSeek's disk-based cache makes repeated system prompts extremely cheap ($0.0028/1M for V4-Flash cache hits)
  • Use user_id for multi-tenant isolation — pass the user_id parameter for content safety, KVCache, and scheduling isolation across your users
  • Set timeouts — set a reasonable timeout (e.g., 60s) to avoid hanging connections on long-running thinking requests
  • Top up proactively — DeepSeek is prepaid; check balance regularly and top up before you run out

FAQ

Q: Can I use DeepSeek with Claude Code or GitHub Copilot? A: Yes. DeepSeek supports direct integration with agent tools like Claude Code, GitHub Copilot, and OpenCode. See the Agent Integrations Guide for setup details.

Q: What's the difference between V4-Flash and V4-Pro? A: V4-Pro is the stronger reasoning model — it scores higher on complex benchmarks and handles multi-step analysis better. V4-Flash is faster, cheaper, and has 5× higher concurrency (2,500 vs 500). Use V4-Flash for most production workloads; use V4-Pro when you need deeper reasoning or complex tool-call chains.

Q: Do thinking tokens cost extra? A: Yes. Thinking tokens (the reasoning_content output) are billed at output token rates. If you don't need deep reasoning, disable thinking mode to reduce costs.

Q: Is the DeepSeek API really OpenAI-compatible? A: Yes — the endpoint implements the OpenAI ChatCompletions specification. Any tool, SDK, or code that speaks OpenAI's format works with DeepSeek by changing the base_url and API key. DeepSeek also supports an Anthropic-format endpoint at https://api.deepseek.com/anthropic.

Q: How does context caching work? A: DeepSeek uses disk-based context caching. When multiple requests share the same prefix (system prompt, shared context), only the first request pays the full input price. Subsequent requests with the same prefix pay the cache-hit price — $0.0028/1M for V4-Flash vs. $0.14/1M without cache. This happens automatically; no configuration needed.

Q: Can I run DeepSeek models locally? A: Yes. Both V4-Flash and V4-Pro weights are available on HuggingFace under the MIT License. However, local deployment requires significant GPU resources. For production use, the API is simpler and more cost-effective.

Q: What happened to DeepSeek-R1? A: V4's thinking mode effectively replaces the R1 reasoning line. If you were using deepseek-r1 for complex reasoning, switch to deepseek-v4-pro with thinking enabled. R1 is still available through some third-party providers like SiliconFlow, but DeepSeek's own API is focusing on the V4 line going forward.


Last updated: June 7, 2026. Pricing and model availability sourced from DeepSeek API Docs. All pricing may change — verify current rates at platform.deepseek.com before budgeting.

Help & contact