DeepSeek API Best Practices for deepseek-flash and V4-Pro

DeepSeek API best practices for deepseek-flash and deepseek-v4-pro: model choice, thinking mode, caching, JSON mode, costs and error handling, from the docs.

API·April 25, 2026·By DS Guide Editorial
DeepSeek API best practices title card: eyebrow 'API · Best practices', title 'API Best Practices', tagline 'Default to Flash, cache prefixes, retry 429 and 503.', and four stats: Flash default model, Half off-peak rates, 98% Flash cache saving, and 429 back off and retry, beside an open-manual illustration.

You shipped a prototype against deepseek-chat, traffic grew, and now the bills, the latency tail, and the occasional empty JSON response are real problems. This guide collects DeepSeek API best practices for the current models, based on DeepSeek’s own documentation. It assumes you have an API key and a working OpenAI SDK call, and focuses on the choices that move cost, reliability, and quality once you go past “hello world.” You will get a model-selection rubric, the parameter map for thinking mode, a worked cost calculation for both deepseek-flash and deepseek-v4-pro at peak and off-peak rates, caching tactics, JSON-mode caveats, and an error-handling pattern for throttling and overload.

What the DeepSeek API actually is in October 2026

Infographic checklist of DeepSeek API production best practices including retries, timeouts, caching, and secrets

The DeepSeek API is a stateless HTTP service that accepts OpenAI-compatible Chat Completions requests at POST /chat/completions against the base URL https://api.deepseek.com. DeepSeek’s Models & Pricing page lists two models: deepseek-flash, served by DeepSeek-V4.1-Flash-1017 (released 17 October 2026, and the only current model with image input), and deepseek-v4-pro, served by DeepSeek-V4-Pro-0813 (released 13 August 2026). Both publish their weights under the MIT license on Hugging Face, both have a 1M-token context, and both can produce up to 384K output tokens per response.

Two architectural facts shape every best practice that follows. First, the API speaks several formats: OpenAI Chat Completions, the OpenAI Responses API (same base URL) and the Anthropic API (base URL https://api.deepseek.com/anthropic), and both models support non-thinking and thinking mode, with thinking the default. Second, the API is stateless — DeepSeek does not retain conversation history for you. The web chat at chat.deepseek.com keeps your sessions; the API does not. You resend the full messages array on every call.

Legacy IDs and migration

If your codebase still references deepseek-chat or deepseek-reasoner, it is out of date: those IDs were scheduled for retirement on 2026-07-24 at 15:59 UTC (until then they pointed to deepseek-v4-flash non-thinking / thinking) and are no longer listed in DeepSeek’s documentation. The legacy names deepseek-v4-flash and deepseek-v4-flash-vision-exp are still accepted, but they are served by DeepSeek-V4.1-Flash-1017 and billed at the deepseek-flash price. The migration is a one-line change: keep base_url and set model to deepseek-flash or deepseek-v4-pro. Switch behind a feature flag, run for a day, delete the old ID. Our DeepSeek OpenAI SDK compatibility notes cover the exact import paths.

Quickstart: the call you should be making in 2026

Below is a minimal Python template. It targets deepseek-flash — the right default for chat, classification, summarisation, and most agent tool-calls — and explicitly disables thinking via extra_body={"thinking": {"type": "disabled"}} to keep latency and output tokens down (thinking is on by default). The key comes from an environment variable, never from source code.

import os
from openai import OpenAI

client = OpenAI(
    api_key=os.environ.get("DEEPSEEK_API_KEY"),
    base_url="https://api.deepseek.com",
)

resp = client.chat.completions.create(
    model="deepseek-flash",
    messages=[
        {"role": "system", "content": "You are a concise technical assistant."},
        {"role": "user", "content": "Explain context caching in two sentences."},
    ],
    temperature=1.3,                   # DeepSeek's recommendation for general conversation
    max_tokens=512,
    stream=False,
    extra_body={"thinking": {"type": "disabled"}},  # thinking is on by default
)
print(resp.choices[0].message.content)

The same call against POST /chat/completions in curl looks like this; useful for smoke-testing from CI without an SDK:

curl https://api.deepseek.com/chat/completions \
  -H "Authorization: Bearer $DEEPSEEK_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "deepseek-flash",
    "messages": [{"role": "user", "content": "ping"}],
    "thinking": {"type": "disabled"},
    "max_tokens": 32
  }'

For a guided walkthrough of authentication, billing setup, and your first call, see our DeepSeek API getting started tutorial and the page on how to get a DeepSeek API key.

Pick the right model — deepseek-flash or deepseek-v4-pro

The highest-leverage decision for a DeepSeek API deployment is which model you route to. deepseek-v4-pro costs 3.3× as much as deepseek-flash on output, 4.4× on cache-miss input and about 7.3× on cache-hit input, so the default should be Flash, with Pro reserved for tasks where your own evals show it pays off.

Dimension deepseek-flash deepseek-v4-pro
Model version DeepSeek-V4.1-Flash-1017 DeepSeek-V4-Pro-0813
Context window 1M tokens 1M tokens
Max output 384K tokens 384K tokens
Vision (image input) Supported Not supported
Input, cache hit ($/1M, peak / off-peak) $0.006 / $0.003 $0.044 / $0.022
Input, cache miss ($/1M, peak / off-peak) $0.30 / $0.15 $1.32 / $0.66
Output ($/1M, peak / off-peak) $1.20 / $0.60 $3.96 / $1.98
Concurrency limit (per account) 2,500 500
Typical use Chat, classification, summarisation, RAG, vision, most tool-calls Workloads where your evals show a gain worth the price

Rates are from DeepSeek’s official pricing page as of October 2026. Off-peak rates are half of peak; peak hours are 01:00–04:00 and 06:00–10:00 UTC, Monday through Friday, excluding Chinese public holidays, and all other hours (including weekends) are off-peak. Batch and background jobs that can wait should run off-peak. For your own numbers, see the DeepSeek pricing calculator.

A simple routing rule

  1. Start every new feature on deepseek-flash. Build evals.
  2. If your eval shows Flash failing on a category — for example agentic coding, multi-step tool use, or hard math — re-run that subset on deepseek-v4-pro.
  3. If Pro lifts the pass rate by enough to justify 3.3× the output cost on those calls, route only that category to Pro. Keep everything else on Flash.

Don’t assume Pro is the stronger model for your task: DeepSeek’s 10 September 2026 V4.1-Flash announcement says tests by multiple parties put V4.1-Flash ahead of V4-Pro on performance, cost, speed and total runtime. Let your own evals decide.

Use thinking mode deliberately, not by default

Thinking is a request parameter on either model, not a separate model ID, and it is on by default with effort high. Three settings:

  • Non-thinking — pass extra_body={"thinking": {"type": "disabled"}}. Fastest and cheapest. The right opt-out for chat, RAG, and structured extraction.
  • Thinking (high) — the default; set it explicitly with reasoning_effort="high" and extra_body={"thinking": {"type": "enabled"}}. Returns reasoning_content alongside the final content. Use for multi-step reasoning, planning, hard math. reasoning_effort="low" is the lighter option; DeepSeek’s guidance is low for simple tasks and high for daily agent tasks.
  • Thinking-max — reasoning_effort="max", for more complex scenarios. Per the API reference, max_tokens defaults to 64K in thinking mode and 128K at max effort (8K in non-thinking mode); you can set it up to 384K (393,216).

One trap: DeepSeek’s Thinking Mode guide says thinking mode does not support temperature, presence_penalty or frequency_penalty — setting them triggers no error but has no effect — and top_p behaves differently per model. (The API reference now lists the two penalties as no longer supported in either mode.) If your code carefully tunes temperature=0.0 for code generation and leaves thinking on, the temperature is silently ignored. Plan accordingly.

A thinking-mode call:

resp = client.chat.completions.create(
    model="deepseek-v4-pro",
    messages=[{"role": "user", "content": "Plan a zero-downtime DB migration."}],
    reasoning_effort="high",
    extra_body={"thinking": {"type": "enabled"}},
)
print(resp.choices[0].message.reasoning_content)  # the reasoning content
print(resp.choices[0].message.content)            # the final answer

Tune temperature to the task

DeepSeek publishes specific temperature recommendations — match them unless you have a reason not to. They apply in non-thinking mode only, since thinking mode ignores temperature.

Task Recommended temperature
Code generation, mathematics 0.0
Data analysis, data cleaning 1.0
General conversation, translation 1.3
Creative writing, poetry 1.5

If you find yourself at temperature=0.7 across the board, you are probably leaving determinism on the table for code paths and creativity for writing paths. More on prompt-side tuning lives in our DeepSeek prompt engineering guide.

Caching: a 98% discount on repeated input

Title card: eyebrow 'Caching · deepseek-flash', title 'Cached Input Cost', tagline 'Input cost at peak: 1M calls of 2,200 tokens, 2,000 cached.', and four stats: 660 USD input cost with no cache, 72 USD with caching, 89% of input cost saved, and half that cost off-peak, beside a balance-scale illustration.

Context caching is on by default: repeated prompt prefixes are served from a disk cache and billed at the cache-hit rate. On deepseek-flash the cache-hit rate is 2% of the cache-miss rate (a 98% reduction); on deepseek-v4-pro it is about 3.3% (about 96.7% less). Per DeepSeek’s Context Caching guide, a request hits only when it fully matches a persisted “cache prefix unit” — units are written at the end of each request’s input and output, at common prefixes the system detects across requests, and at fixed intervals in long inputs. The implications:

  • Put the long, stable content (system prompt, retrieval results that recur, few-shot examples) at the beginning of messages. Volatile content (the user’s new question) goes last.
  • Avoid timestamps, request IDs, or randomised greetings in your system prompt. Each one is a cache miss waiting to happen.
  • Expect the first requests with a new shared prefix to miss: the shared part only hits once it has been persisted as a unit. The cache is best-effort, so budget for misses.
  • Cache hits do not free you from paying for the user’s new tokens. The miss line in your bill is the new turn against the cached prefix.

For the hit rules, examples and the usage fields to log, see our deep dive on DeepSeek context caching.

A worked cost example for both tiers

Workload: 1,000,000 calls per day, each with a 2,000-token system prompt that the cache catches, a 200-token user message that does not, and a 300-token response. The totals assume every call runs in one period; a real day straddles both, so split your volume by the share you expect in each.

deepseek-flash (the default recommendation)

                                                    PEAK                   OFF-PEAK
Cached input :  2,000 × 1,000,000 = 2,000,000,000 tok × $0.006/M = $12.00    × $0.003/M = $6.00
Uncached in  :    200 × 1,000,000 =   200,000,000 tok × $0.30/M  = $60.00    × $0.15/M  = $30.00
Output       :    300 × 1,000,000 =   300,000,000 tok × $1.20/M  = $360.00   × $0.60/M  = $180.00
                                                                   -------               -------
Total                                                              $432.00               $216.00

deepseek-v4-pro (same workload)

                                       PEAK                       OFF-PEAK
Cached input :  2,000,000,000 tok × $0.044/M = $88.00       × $0.022/M = $44.00
Uncached in  :    200,000,000 tok × $1.32/M  = $264.00      × $0.66/M  = $132.00
Output       :    300,000,000 tok × $3.96/M  = $1,188.00    × $1.98/M  = $594.00
                                               ---------                --------
Total                                          $1,540.00                $770.00

Same traffic, about 3.6× the bill on deepseek-v4-pro in either period. If your eval does not show a meaningful win for Pro on the workload, the math is the answer. The DeepSeek cost estimator automates the same arithmetic against your own token volumes; the DeepSeek token counter helps you measure them in the first place.

JSON mode without the empty-string bug

JSON mode is set with response_format={"type": "json_object"}. It is designed to return valid JSON, but DeepSeek’s JSON Output guide notes that the API may occasionally return empty content. Three rules from that guide:

  1. Include the word “json” in the system or user prompt, plus a small example of the desired output. Without the instruction, the API reference warns, the model may stream whitespace until it reaches the token limit.
  2. Set max_tokens high enough to cover the worst-case output. A truncated JSON object is invalid JSON.
  3. Always handle the empty-content case: treat it like a transient error, retry once, and adjust the prompt if it recurs.

A defensive pattern (thinking is switched off so that temperature takes effect):

import json

def classify(review_text):
    resp = client.chat.completions.create(
        model="deepseek-flash",
        messages=[
            {"role": "system",
             "content": 'Reply only as json, for example {"sentiment": "pos"}. '
                        'Allowed values: pos, neg, neu.'},
            {"role": "user", "content": review_text},
        ],
        response_format={"type": "json_object"},
        max_tokens=128,
        temperature=0.0,
        extra_body={"thinking": {"type": "disabled"}},
    )
    raw = resp.choices[0].message.content or ""
    try:
        return json.loads(raw)
    except json.JSONDecodeError:
        return None  # retry once or fall back

Full request/response shapes and edge cases are catalogued in the DeepSeek JSON mode reference.

Streaming and tool calling

Set stream=True to receive server-sent-event chunks. With thinking enabled, reasoning_content streams before the final content — render them in separate UI surfaces or you will confuse end users. Token usage arrives on the last chunk. For implementation patterns including keep-alive comments and proxy timeouts, see our DeepSeek API streaming guide.

Tool calling uses the OpenAI-compatible tools array and works in both thinking and non-thinking modes. In thinking mode, a request that carries tools must pass back the reasoning_content of all previous turns, or the API returns a 400 error; and tool_choice values required or a named function are not supported in thinking mode. DeepSeek’s documentation includes integration guides for agents such as Claude Code, Codex, OpenCode and OpenClaw, helped by the OpenAI- and Anthropic-compatible surfaces — your existing tool definitions port cleanly. The function calling reference covers the exact JSON-schema requirements.

FIM and Chat Prefix Completion (Beta)

Both are useful — Fill-In-the-Middle for code editors, Chat Prefix Completion for continuation-style prompts where you need the model to extend a partial assistant message. Both need the Beta base URL https://api.deepseek.com/beta. FIM runs in non-thinking mode only and has a 4K maximum output; do not pass reasoning_effort in FIM calls.

Error handling that survives launch week

Treat the API as eventually reliable, not always reliable. The error envelope is OpenAI-shaped, so existing retry middleware works. Meanings below follow DeepSeek’s Error Codes page.

Status Meaning Action
400 Invalid format (request body) Do not retry. Fix the body using the hints in the error message.
401 Authentication fails (wrong API key) Surface to ops; do not retry.
402 Insufficient balance Page on-call; halt traffic and top up.
422 Invalid parameters Do not retry. Fix the parameters using the hints in the error message.
429 Rate limit reached (too fast, or over a concurrency limit) Exponential backoff with jitter; cap your own concurrency below 2,500 (Flash) / 500 (Pro).
500 / 503 Server error / server overloaded Retry after a brief wait, up to 3× with backoff; then fall back.

Two operational habits worth adopting:

  • Idempotency. Hash (model, messages, temperature) and cache successful responses for ~60 seconds. Cuts duplicate spend on retried client calls.
  • Model fallback. If deepseek-v4-pro returns 503, retry the request on deepseek-flash with the same body. Most traffic is fine on Flash; degraded mode beats outage.

The full status code map is in our DeepSeek API error codes reference, and rate-limit specifics live in DeepSeek API rate limits.

Observability and security checklist

Title card: eyebrow 'Observability · Usage', title 'Log Every Call', tagline 'Usage fields that explain your DeepSeek bill.', and four stats: Hit, cache-hit tokens; Miss, cache-miss input; Out, output tokens; and Think, reasoning tokens, beside a mainframe illustration.
  • Log usage.prompt_tokens, usage.completion_tokens, the cache split (prompt_cache_hit_tokens / prompt_cache_miss_tokens) and, in thinking mode, completion_tokens_details.reasoning_tokens on every response — plus whether the call ran at peak or off-peak. Without this, you cannot debug a bill.
  • Store API keys in your secrets manager, not in .env files committed by accident. Rotate quarterly.
  • Pass a user_id (an opaque ID, never personal data) if you serve many end users: DeepSeek uses it for content-safety handling, KV-cache isolation and scheduling isolation.
  • Consider data residency: requests go to DeepSeek-operated infrastructure subject to Chinese law. For regulated workloads, evaluate self-hosting the open weights — see our notes on running DeepSeek through DeepSeek Docker deployment.
  • Pin model strings; do not interpolate from user input.
  • Set per-tenant token budgets in your application layer. DeepSeek’s own limits are per-account concurrency caps, not per-tenant budgets.

For more on the broader ecosystem and where the API fits, see the DeepSeek API docs and guides hub.

Frequently asked questions

How do I migrate from deepseek-chat to V4 without breaking my app?

Change one line: model="deepseek-chat" becomes model="deepseek-flash" (or deepseek-v4-pro). The base URL, authentication, and request shape stay the same. The legacy IDs were scheduled for retirement on 2026-07-24 at 15:59 UTC and are no longer listed in DeepSeek’s docs. Note that thinking mode is now on by default, so disable it explicitly if your old code expected deepseek-chat’s non-thinking behaviour. Our DeepSeek API documentation page has the migration checklist.

What is the cheapest way to test the DeepSeek API?

Use deepseek-flash in non-thinking mode with short prompts, ideally off-peak. At $0.30 per million cache-miss input tokens and $1.20 per million output tokens at peak ($0.15 and $0.60 off-peak; cache hits $0.006 / $0.003), a thousand test calls with 500 input and 500 output tokens each cost $0.75 at peak and $0.375 off-peak. Avoid thinking mode while developing — it adds reasoning tokens to the output. Estimate spend before you run with the DeepSeek pricing calculator.

Does the DeepSeek API remember previous messages?

No. The API is stateless — DeepSeek does not retain conversation state between requests. Your client must resend the full messages array on each call to maintain a multi-turn conversation. The web chat at chat.deepseek.com behaves differently because session storage lives on the consumer surface, not in the API. The DeepSeek browser vs app guide covers the consumer side.

Can I use the OpenAI Python SDK with DeepSeek?

Yes. Install the openai package, instantiate OpenAI(base_url="https://api.deepseek.com", api_key=os.environ.get("DEEPSEEK_API_KEY")), and call client.chat.completions.create(...) as usual; DeepSeek-specific fields such as thinking go in extra_body. DeepSeek also exposes an Anthropic-compatible surface at https://api.deepseek.com/anthropic if you prefer that SDK. The DeepSeek OpenAI SDK compatibility page lists the parameters that behave identically and the few that differ.

Why does my JSON-mode call sometimes return an empty string?

JSON mode is designed to return valid JSON, and DeepSeek’s JSON Output guide notes that the API may occasionally return empty content; DeepSeek suggests adjusting the prompt to mitigate it. Three fixes: include the word “json” plus an example in the prompt, set max_tokens high enough to avoid truncation, and wrap the call in a single retry with a fallback. Full patterns in our DeepSeek JSON mode reference.

Sources & Methodology

Last source check: October 25, 2026

Primary sources

Methodology

Pricing figures were checked against the official DeepSeek pricing page and normalised into estimated monthly costs using sample token usage scenarios. Actual costs may vary depending on caching, input/output ratio, regional availability, and provider updates.

Data confidence

High — figures checked directly against the official pricing page on the review date.

Editorial note

The site's pricing dataset is fetched daily from DeepSeek's official pricing page; this article reflects the prices on the date shown above.

Leave a Reply

Your email address will not be published. Required fields are marked *