By Faheem R. Khattak | Facts checked 27 November 2026
DeepSeek API Tutorial: From First Key to a Working Reasoning App with Thinking Mode
The DeepSeek API is the cheapest way most developers will ever touch a frontier reasoning model — and the tutorials ranking for it are out of date. Most of them still tell you to call deepseek-reasoner, the R1 API model. That model ID was retired on 24 July 2026. If you copy that code today, it will not run. The live API has only two models, deepseek-flash and deepseek-v4-pro, and reasoning is no longer a model you pick. It is thinking mode, switched on by default, inside both of them. This tutorial takes you from zero to a working reasoning app in one sitting: get a key, make a first call, turn thinking on and off, read the reasoning trace correctly — including the one mistake that returns a 400 error — stream answers live, add tools, keep the bill tiny with cache hits and off-peak hours, and handle the ten errors the API actually returns. Everything here was checked against DeepSeek’s own documentation on 27 November 2026, and the code samples follow the official docs as they stand today.
Two warnings before you start, both dated. First, prices in this guide are as they stood on 27 November 2026, unchanged since our earlier DeepSeek explainer of 17 November — but DeepSeek says prices may vary and reserves the right to adjust them, so re-check the pricing page before you spend real money. Second, the console itself — platform.deepseek.com — could not be read directly while this guide was being checked, so the account and key steps below are presented as the flow the official docs describe, not as a tested walkthrough. No free-credit figure is stated anywhere in this guide, because none is verified. What is verified is the API itself: the endpoints, the two model IDs, the parameters, the prices, the limits and the error codes. That is what this tutorial teaches.

1. What the DeepSeek API Is (and What It Isn’t)
<img src="

” alt=”A single front door with two different keys hanging beside it on hooks, bright hallway light, minimalist. No readable text.”>
The DeepSeek API is a hosted HTTP API for DeepSeek’s open-weight models. You send it a request — a list of messages — and it returns the model’s response. You pay per token, per million tokens, with no subscription and no minimum that the docs state. The base URL in the OpenAI format is https://api.deepseek.com, and chat completions live at POST /chat/completions. There is also an Anthropic-format base URL, https://api.deepseek.com/anthropic. The important practical fact is compatibility: the API uses an API format compatible with OpenAI and Anthropic, so you can use the OpenAI or Anthropic SDK, or software compatible with the OpenAI API, by changing the configuration. There is no DeepSeek-specific SDK to learn. If you already know how to call the OpenAI API, you already know most of how to call this one — the differences are the model names, the thinking-mode parameters, and the reasoning field, and this guide covers all three in full.
What you get for that compatibility is two models and nothing else to choose between. The current lineup, as listed on DeepSeek’s pricing page, is deepseek-flash, served by DeepSeek-V4.1-Flash-1017, and deepseek-v4-pro, served by DeepSeek-V4-Pro-0813. Both have a 1-million-token context length and a maximum output of 384K tokens. Both support JSON output, tool calls, the Responses API, the Anthropic API and Chat Prefix Completion in beta, and both support thinking mode, which is on by default. The one capability difference that matters at the selection stage is vision: Flash supports image input, and V4-Pro does not. If your app needs to look at a picture, the choice is made for you.
What the API is not matters just as much. It is not the DeepSeek chatbot at chat.deepseek.com — that is the consumer app, and chatting there does not use your API key. It is not a hosted website or a user interface of any kind; you build the front end, and the API supplies the intelligence. It is not stateful: the API keeps no memory of your conversation between calls, so your code must resend the conversation history with every request, a point section 5 returns to in detail. And it is not the old API. The old model IDs deepseek-chat and deepseek-reasoner are gone from the current docs, and the legacy names deepseek-v4-flash and deepseek-v4-flash-vision-exp are still accepted only as aliases — the models behind them are retired, requests are served by V4.1-Flash-1017 and billed at the Flash price. If a tutorial, a forum post or an old code sample tells you to call deepseek-reasoner, it is describing an API that no longer exists.
This guide does not re-explain DeepSeek itself — the company, the model family, why its models are cheap, or its privacy story. That is a different question, and our DeepSeek explainer answers it in full. What this guide does is teach you to build with the API, and it picks one default model for the worked examples — Flash — and tells you exactly when to switch to Pro. The pattern will feel familiar if you have built with another provider’s API first: our Gemini API tutorial follows the same shape — key, first call, streaming, memory, structured output, tools, errors — and the two pieces are written to fit together, so what you learn in one transfers to the other.
One more scope note before the code starts. This tutorial covers the Chat Completions API, which is the core of the DeepSeek API and the route almost every app should start on. The docs also describe the Responses API, the Anthropic-format API, Chat Prefix Completion and FIM completion (both in beta, the latter in non-thinking mode only), plus standalone Search and Fetch APIs, file parsing and OCR, and speech APIs. Those are covered as capabilities in section 11, with their prices, so you know where they live — but the worked code in this guide is Chat Completions, because that is the API your app will actually call first.
2. Before You Write Code: Account, Key, and Balance

Everything starts at platform.deepseek.com, DeepSeek’s API open platform. The official docs say to apply for an API key there, and link to the platform from the quickstart. That is the documented flow, and it is stated here as the documented flow rather than a tested walkthrough: the platform site could not be read directly on 27 November 2026, returning an access-denied response, so the clicks, the billing screens and the top-up screens are not described here as verified fact. What the docs do state plainly is the shape of the system: fees are deducted from a topped-up balance or a granted balance, and when both exist, the granted balance is used first. No figure for any granted balance, no minimum top-up, and no payment method is stated in this guide, because none of those was verified on a primary source. If another guide quotes you a free-credit number — a token count, a dollar amount, an expiry — treat it as secondary reporting, not as a fact, and check the platform itself before you rely on it.
Once you have a key, the rule for it is simple and absolute: never hardcode it, never put it in client-side code, never commit it to a repository, and never paste it into a chat or a screenshot. Store it in an environment variable named DEEPSEEK_API_KEY, exactly as the official examples do, and let your code read it from the environment:
export DEEPSEEK_API_KEY="your-key-here"
Every code sample in this guide assumes that variable is set. In curl, it appears as ${DEEPSEEK_API_KEY} inside the Authorization header. In Python, the OpenAI SDK reads it with os.environ.get("DEEPSEEK_API_KEY"). If you ever see your key stop working, the first thing to check is not your code but the key itself — section 13 covers the 401 error in full — and if a key has leaked anywhere public, replace it rather than debugging it. A leaked key is a key someone else can spend money with, and the fix is rotation, not repair.
Key hygiene goes beyond the one variable. Keep separate keys for separate purposes where the platform allows it — one for development, one for production — so that rotating a development key never takes down a live app. Keep the production key on the server only, never in a front-end JavaScript file that a browser can read. If your app runs in the browser, the browser talks to your server and your server talks to DeepSeek; the key never leaves the server. And keep a note of which key is where: the most common “my key stopped working” story in any API is not a broken key but the wrong key in the wrong environment — the development key pasted into production, or an old key left in a shell profile after rotation. A thirty-second check of the environment variable saves an hour of debugging.
Before you write any code, understand the billing model at the level that matters for a first app. The API is pay-per-token: every request costs input tokens plus output tokens, priced per million tokens, with the exact prices in section 12. There is no per-request fee and no monthly fee stated in the docs. Your balance is the thing that runs out: when it does, the API returns a 402, insufficient balance, and your app stops until you top up. That is why the first thing a real app needs, after the key, is a way to watch the balance — and why section 12’s worked example and section 14’s checklist both treat cost controls as part of the build, not as an afterthought. Set a spending habit early: check the balance after your first few calls, note what a typical call costs, and only then scale up the volume.
One practical step worth taking now, before the first call, is to confirm your setup can reach the API at all. You do not need a full program for that — the curl command in section 4 is the test, and it takes seconds. If it returns a 200, your key, your network and the API are all fine, and everything after that is application logic. If it returns a 401, the key is wrong; if it returns a 402, the balance is empty; if it returns something else, section 13 maps it. Do that test first and you will never wonder, three sections later, whether the problem is your code or your account.
3. Pick Your Model: Flash vs V4-Pro

There are only two valid model values in the DeepSeek API today, and the choice between them is the first decision your app makes. This section is the whole decision in one place, with prices as they stood on 27 November 2026. Read it as a picker, not a ranking: there is no best model, only a best model for a given job and budget. For the wider method of choosing between models — the decision framework that applies across providers — our guide to choosing an AI model covers it in full, and the rule below is that framework applied to these two models.
DeepSeek Flash (deepseek-flash, served by DeepSeek-V4.1-Flash-1017) is the default. It is the cheaper model by a wide margin, it supports vision — image input — which Pro does not, and it carries the higher concurrency limit: 2,500 simultaneous connections per account against Pro’s 500. The homepage banner for the model behind it says its project-development capability is significantly improved, with lower cost and faster task completion; that is the banner’s own wording, not a measured speed claim, and this guide states no speed figure for either model because the official docs publish none. Flash is the model for everyday work: chat, drafting, coding assistance, summarising, extraction, and the reasoning app in section 14. Start here. Only move when Flash’s answers are not good enough for the hardest tasks in your app, not as a default.
DeepSeek V4-Pro (deepseek-v4-pro, served by DeepSeek-V4-Pro-0813) is the stronger reasoning model, and it costs accordingly. Its off-peak output price is $1.98 per million tokens against Flash’s $0.60 — roughly three times as much — and its cache-miss input is $0.66 off-peak against Flash’s $0.15. It has no vision support, so an app that needs to look at images cannot use it at all. What it offers in return is deeper reasoning on the hardest problems: the multi-step, high-stakes work where Flash’s answer falls short. Use it for the hardest calls in your app, not for every call — and section 14 shows exactly that pattern, with Flash as the default and Pro as a deliberate, per-question fallback.
| Model | Served by | Vision | Concurrency | Best for |
|---|---|---|---|---|
deepseek-flash | DeepSeek-V4.1-Flash-1017 | Yes | 2,500 | Default: everyday work, chat, coding, vision, high volume |
deepseek-v4-pro | DeepSeek-V4-Pro-0813 | No | 500 | Hardest reasoning, where Flash falls short |
The price preview below is the short version; the full table, with peak and off-peak, cache-hit and cache-miss, is in section 12. Per million tokens, off-peak: Flash costs $0.003 on a cache hit, $0.15 on a cache miss, and $0.60 for output. V4-Pro costs $0.022 on a cache hit, $0.66 on a cache miss, and $1.98 for output. Peak prices are exactly double the off-peak prices. The gap that matters most for a real app is the cache-hit line: a repeated system prompt served from the cache costs Flash $0.003 per million tokens — about fifty times cheaper than the same tokens on a cache miss. That single fact shapes how you write prompts, and section 12 returns to it.
Two traps to avoid. The first is the legacy IDs. deepseek-v4-flash and deepseek-v4-flash-vision-exp are still accepted by the API, but the models behind them are retired; requests sent under those names are served by V4.1-Flash-1017 and billed at the Flash price. Do not use them in new code — they are aliases for a retired generation, and the docs list only Flash and Pro as the current models. The second trap is the old IDs. deepseek-chat and deepseek-reasoner are not listed anywhere in the current docs. Do not use them at all; section 6 explains what happened to them. A model is a one-word change in your code — model="deepseek-v4-pro" instead of model="deepseek-flash" — so the cost of experimenting is nearly zero, and the right habit is to start on Flash, measure what your app actually spends and how good its answers are, and only then move up.
Why are these models so cheap? Part of the answer is that they are open-weight models, and the economics of open weights are different from the economics of closed models: the weights are public, the serving is a commodity, and the competition is on price and throughput rather than on exclusive capability. Our explainer on Llama and open models versus closed rivals covers that dynamic in depth, and our guide to Qwen covers the other cheap-API rival in the same space — Qwen is the model family most likely to be quoted against DeepSeek on price, and knowing both is what lets you judge a quote rather than accept it. None of that changes the choice in this section, which is between Flash and Pro; it explains why the choice is as cheap as it is.
4. Your First Call in Five Minutes

This is the official first call, exactly as DeepSeek’s own “Your First API Call” page teaches it. The page itself moved recently — the URL our earlier explainer cited now returns a 404, and the page lives at the docs root — so cite the root, not the old address. Set the environment variable first, then run the curl command:
export DEEPSEEK_API_KEY="your-key-here"
curl https://api.deepseek.com/chat/completions
-H "Content-Type: application/json"
-H "Authorization: Bearer ${DEEPSEEK_API_KEY}"
-d '{"model": "deepseek-flash", "messages": [{"role": "system", "content": "You are a helpful assistant."}, {"role": "user", "content": "Hello!"}], "thinking": {"type": "enabled"}, "reasoning_effort": "high", "stream": false}'
Read the command line by line, because every part of it reappears in the code that follows. The URL is https://api.deepseek.com/chat/completions — the OpenAI-format base URL plus the chat-completions path. The Content-Type: application/json header says the body is JSON. The Authorization: Bearer ${DEEPSEEK_API_KEY} header carries the key, taken from the environment, not pasted into the command. The body names the model (deepseek-flash), gives two messages (a system message setting the assistant’s role, and a user message saying “Hello!”), turns thinking on explicitly with "thinking": {"type": "enabled"}, sets the effort to "high", and sets "stream": false so the whole answer comes back at once. That is the entire first call. Nothing in it is optional except, strictly, the thinking fields — thinking is on by default — but including them makes the call explicit, and explicit is what a tutorial should be.
The same call in Python, via the OpenAI SDK, is the version your app will actually use. The docs say the API is compatible with the OpenAI SDK, so you install that SDK and point it at DeepSeek’s base URL:
pip install openai
import os
from openai import OpenAI
client = OpenAI(
api_key=os.environ.get("DEEPSEEK_API_KEY"),
base_url="https://api.deepseek.com",
)
response = client.chat.completions.create(
model="deepseek-flash",
messages=[
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "Hello!"},
],
extra_body={
"thinking": {"type": "enabled"},
},
reasoning_effort="high",
stream=False,
)
print(response.choices[0].message.content)
Two details in that sample deserve attention, because both are the kind of thing that breaks silently if you get them wrong. First, the base URL is https://api.deepseek.com — without it, the SDK talks to OpenAI, not DeepSeek, and the call fails with an authentication error that says nothing about the real problem. Second, thinking goes inside extra_body when you use the OpenAI SDK, because thinking is a DeepSeek extension field, not part of the OpenAI SDK’s own parameter list. In raw curl or raw HTTP it is a top-level field in the JSON body, as the curl example shows. Mix the two up — put thinking at the top level of the SDK call — and the SDK will reject it or drop it. This is the single most common setup mistake in DeepSeek code, and it is worth learning now rather than discovering it at midnight. reasoning_effort, by contrast, is passed as an ordinary parameter in the SDK call.
The Node.js version is the same shape, for the same reason — the OpenAI SDK exists for JavaScript too, and the configuration is identical:
npm install openai
import OpenAI from "openai";
const client = new OpenAI({
apiKey: process.env.DEEPSEEK_API_KEY,
baseURL: "https://api.deepseek.com",
});
const response = await client.chat.completions.create({
model: "deepseek-flash",
messages: [
{ role: "system", content: "You are a helpful assistant." },
{ role: "user", content: "Hello!" },
],
reasoning_effort: "high",
stream: false,
});
console.log(response.choices[0].message.content);
What comes back is a 200 response with a familiar shape, because it is the OpenAI shape: an id, a model field, a choices array with one element, and inside it a message with a role of assistant and a content field holding the answer, plus a finish_reason — normally stop — and a usage block with the token counts. In thinking mode there is one more field on the message, reasoning_content, sitting next to content, and section 7 is entirely about reading it correctly. For the “Hello!” round trip, the content is a greeting and the reasoning is short; the shape is what matters, not the words. If you see an error instead of a greeting, do not guess — section 13 maps the common ones to their fixes, and the most likely at this stage are 401 (wrong key) and 402 (empty balance).
That is the first call, and it is also the first version of your app: a program that takes a question and returns an answer. Everything from here on is an addition to this shape — the messages array changes how the model remembers, thinking changes how hard it reasons, streaming changes how the answer arrives, tools change what the model can do, and error handling changes what happens when things go wrong. None of them changes the call itself. Keep this program open while you read the rest; every section adds one argument or one loop to it. And note the format point, because it is the reason this whole tutorial is as portable as it is: the API mirrors the OpenAI format deliberately, so the shape you learn here is the shape of the industry’s most widely copied API. Our guide to the OpenAI API covers the format this API mirrors, and reading the two together is the fastest way to see which parts are shared and which parts — thinking, reasoning_content, the effort ladder — are DeepSeek’s own.
5. How Chat Completions Actually Works

Every call to the DeepSeek API is a chat completion: you send a messages array, and the model returns the next message in the conversation. The array must contain at least one item, and each item has a role and a content. The roles are system, user, assistant and tool, plus a “latest reminder message” role the docs list for a final nudge before the model answers. The system message sets the behaviour — “You are a helpful assistant” in the first call, or something far more specific in a real app: the tone, the format, the rules the model must follow. The user messages are the questions. The assistant messages are the model’s previous answers, sent back so the model can see what it already said. The tool messages are the results of function calls, sent back so the model can use them — section 9 covers those in full.
The fact that defines the whole API is statelessness. The API keeps no memory of your conversation between calls. Each request starts from zero, and the only history the model sees is the history you send in the messages array. Ask “I have 2 dogs in my house” in one call, then ask “How many paws are in my house?” in a new call with only that question, and the model has no idea what you are talking about. Send both messages — the first question and the first answer, then the second question — and it answers correctly. That is the entire mechanism of multi-turn conversation on this API: your code owns the history, appends each turn to the list, and resends the whole list every time. There is no session ID, no conversation object, no server-side memory to enable. The simplicity is a feature — your history lives in your database, under your control — but it is also a cost, because the history is re-sent and re-billed on every turn, and long conversations get expensive in input tokens. Keep the history trimmed: drop the oldest turns, summarise them, or cap the list, and do it deliberately rather than letting it grow without limit.
Three parameters sit alongside the messages on every call, and they are three separate choices, not one. The model is which model answers: deepseek-flash or deepseek-v4-pro, and nothing else. The thinking object is whether thinking mode is on: {"type": "enabled"} or {"type": "disabled"}. The reasoning_effort is how hard the model thinks when thinking is on: none, low, high or max. The docs’ rules for how they interact are precise, and they are worth stating exactly. When thinking is omitted or null, the mode follows reasoning_effort; if that is also omitted, thinking is enabled. When thinking is provided, its type is required and it takes precedence over reasoning_effort. The default effort is high. none disables thinking; low, high and max enable it. So there are two ways to turn thinking off — thinking: {"type": "disabled"}, or reasoning_effort: "none" — and one way to be explicit about turning it on, which is to say so in both fields, as the first-call example does. In a real app, pick one convention and use it everywhere; mixing the two is how a call ends up thinking when you meant it not to.
The fourth parameter that shapes every call is max_tokens, the cap on how many tokens the model may generate. It accepts 1 to 384K (393,216), and the total of input plus generated tokens is limited by the 1-million-token context length. The defaults are the thing to know: 8K when thinking is off, 64K when thinking is on, and 128K when the effort is max. Those defaults are generous for most work, and the usual mistake is to set the cap too low rather than too high — a cap that cuts the answer off mid-sentence produces a response with finish_reason: length, which is the API telling you the output was truncated, not that the model had nothing more to say. Set the cap deliberately for long-form work, and check finish_reason on every response: stop means the model finished, length means it hit your cap, and the fix for length is a bigger cap or a shorter task, not a retry of the same call.
Two more fields complete the basic shape. stop takes up to 16 sequences, each no more than 512 bytes of UTF-8, at which the model stops generating — useful when you want the answer to end at a marker rather than run on. And stream, a boolean defaulting to false, switches the response from one complete object to a stream of partial deltas — section 8 covers that in full. Around those sit the extensions and the safety controls: safety_check, a DeepSeek extension whose level: high turns on basic risk control reviewing input and output (the default is low); title, another extension, whose {"enabled": true} returns a short conversation title; and logprobs with top_logprobs (0 to 20, requiring logprobs: true) for the token probabilities, if your app needs them. None of those is needed for a first app, but knowing they exist saves you from reinventing them later.
Finally, the sampling parameters — and a warning about them. temperature runs from 0 to 2 with a default of 1, and the docs recommend altering temperature or top_p, not both. But in thinking mode, temperature has no effect at all, and neither do presence_penalty and frequency_penalty — setting them triggers no error, but they do nothing. More bluntly, frequency_penalty and presence_penalty are deprecated, no longer supported, and will not take effect in any mode. If you copy a code sample from an older tutorial that sets temperature=0.7 for deterministic output, delete that line when thinking is on: it does nothing, and the determinism you wanted has to come from somewhere else — from the prompt, from the effort level, from structured output. The top_p rules are model-specific and fiddly enough to state exactly: on Flash in thinking mode the default is 1.0 and values below 0.95 are treated as 0.95; on Flash without thinking it is fixed at 1.0 and any value you pass is ignored; on V4-Pro in thinking mode it is fixed at 0.95 when tool calling is enabled and 1.0 otherwise, and any value you pass is ignored; on V4-Pro without thinking, the value you pass is used, with a default of 1.0. For a first app, the practical rule is simple: leave both alone, and control the output with thinking effort and with your prompt.
6. Thinking Mode: The Reasoning Engine Inside Every Call

Thinking mode is the DeepSeek API’s reasoning engine, and it is not a model. That sentence is the whole of this section, and it is the correction this tutorial exists to make. Before the model outputs its final answer, it first outputs a chain-of-thought reasoning, to improve the accuracy of the final response — that is the docs’ own description. The reasoning happens inside both current models, Flash and Pro, on every call where thinking is enabled. And thinking is enabled by default, at the default effort of high. If you make the first call in section 4 and never touch a thinking parameter, you are already using a reasoning model. The old world, where you chose a reasoning model by its ID, is gone; the new world is a mode, and the mode is on unless you turn it off.
The controls are the toggle and the effort ladder. The toggle is thinking: {"type": "enabled"} or {"type": "disabled"} — in extra_body in the OpenAI SDK, top-level in raw HTTP, as section 4 showed. The effort ladder is reasoning_effort, with four live values: none, low, high and max. none disables thinking. low is the lightest reasoning — fast, cheap, enough for straightforward questions. high is the default, the balanced setting for most work. max is the deepest reasoning the API offers, and it raises the default output cap to 128K, because deep reasoning needs room. There are also legacy mappings, for code written against older parameter names: minimal maps to low, medium and xhigh map to high, and — new since our earlier explainer — ultra maps to max. If you inherit code that passes ultra, it still works; it simply means max now. The parameter shapes differ by format, for completeness: in the OpenAI format the fields are thinking plus reasoning_effort; in the Anthropic format the field is reasoning: {"effort": "none/low/high/max"}; in the Responses API it is output_config: {"effort": "low/high/max"}. This guide’s code is OpenAI-format throughout, because that is the format the worked examples use.
When should you turn thinking off? Whenever the answer does not need reasoning. A greeting, a format conversion, a simple extraction, a classification — these are fast, cheap, simple answers, and thinking mode spends tokens and time reasoning about them for no benefit. Turn it off with thinking: {"type": "disabled"} and the call gets faster and cheaper, with a default output cap of 8K instead of 64K. When should you turn the effort down to low? For the middle ground: questions that need a little thought but not the default’s full depth — a short summary, a straightforward explanation, a simple piece of code. And when should you raise it to max? For the genuinely hard problems: multi-step mathematics, a difficult debugging task, a proof, a plan with many constraints. The method is the same as with any dial: start at the default, and only move it when the task gives you a reason. A model that thinks at maximum effort about a greeting is not being thorough; it is wasting your money and your user’s time. The cost side of that waste is quantified in section 12, and the reasoning tokens behind it are the subject of section 7.
What happened to R1 — the retirement box. If you have followed DeepSeek at all, you will have heard of R1, the reasoning model that made the company’s name. R1 the model lives on as open weights — you can still download it, run it, and build with it yourself. But R1 the API model ID, deepseek-reasoner, was retired on DeepSeek’s own API on 24 July 2026, five days after V4 reached general availability, and it is not listed anywhere in the current docs. There is no R1 API any more, and there is no separate reasoning model to select. The reasoning went inside the two current models as thinking mode. That is why the title of this tutorial says “with Thinking Mode” and why no section of it is headed as an R1 API tutorial: a tutorial that teaches deepseek-reasoner today ships broken code. If you have old code that calls it, the migration is a one-line change of the model ID plus the thinking parameters in this section — and if you have old bookmarks, old forum answers or old videos that teach it, treat them as history, not as instructions. The stale keyword deepseek r1 api still appears in search suggestions, and it will keep appearing for a while; the answer to it is this box, not a tutorial.
One more thinking-mode rule, because it surprises people who come from other APIs: thinking mode does not support temperature, presence_penalty or frequency_penalty. Setting them triggers no error — the API accepts the request and ignores them — which is worse, in a way, than an error, because your code looks correct and does nothing. The last two are deprecated outright. If you want to change how the model answers in thinking mode, the levers are the effort level, the system prompt, and the output format — not the sampling knobs. And one rule that belongs here even though its full treatment is in section 9: tool_choice: required and named tool choices are not supported in thinking mode. The API returns a 400 error if you try. Disable thinking first if you need to force a tool call. That interaction between two features is the kind of thing that only shows up when you combine them, which is why this guide states it in both sections.
7. Reading the Reasoning: reasoning_content Done Right

In thinking mode, the model’s chain of thought is returned to you in a field called reasoning_content, at the same level as content on the message object. The final answer is in content; the reasoning that produced it is in reasoning_content. That separation is the whole design: your app can show the user the answer, show the reasoning separately, log the reasoning for debugging, or hide it entirely — but it must handle both fields, and it must handle them differently depending on whether tools are involved. This section is the core lesson of the tutorial, and the one most likely to save you a production incident.
Start with the simple case: reading both fields. The official docs’ sample asks the classic trick question — “9.11 and 9.8, which is greater?” — with reasoning_effort="high", and reads the two fields separately:
import os
from openai import OpenAI
client = OpenAI(
api_key=os.environ.get("DEEPSEEK_API_KEY"),
base_url="https://api.deepseek.com",
)
response = client.chat.completions.create(
model="deepseek-flash",
messages=[
{"role": "user", "content": "9.11 and 9.8, which is greater?"},
],
reasoning_effort="high",
)
message = response.choices[0].message
print("Reasoning:")
print(message.reasoning_content)
print("Answer:")
print(message.content)
The reasoning for that question works through the decimal places — 9.8 is 9.80, which is greater than 9.11 — and the answer states it plainly. The point of the example is not the arithmetic; it is the pattern. Read reasoning_content and content as two separate outputs from the same message, and never confuse them. The reasoning is the model’s working; the answer is its conclusion. In a user-facing app, show the answer prominently and the reasoning, if you show it at all, in a separate pane or behind a disclosure — never interleaved as if it were part of the answer. In a debugging log, keep both, because the reasoning is where a wrong answer’s cause usually lives.
Now the multi-turn rule, which splits into two cases. Without tools, the reasoning does not need to be passed back. If your next request carries no tools field, the reasoning_content from previous turns is ignored even if you do pass it back — it is not concatenated into the context, and the previous turn’s chain of thought is not carried forward. Your multi-turn code in that case is the simple pattern from section 5: append the assistant’s message and the next user message, and send the list. Nothing special is required, and nothing special happens if you include the reasoning anyway. It is simply ignored.
With tools, the rule reverses, and this is the 400 trap. When your request carries tools, the reasoning_content of all previous turns must be passed back, and it will be concatenated into the context. If you do not pass it back correctly, the API returns a 400 error — even for turns where the model did not call a tool. The failure mode is insidious: your first tool-using call works, the model calls a tool, you send the result back, and the second call fails with a 400, because the history you sent back was missing the reasoning from the first turn. The fix is the simplest correct pattern, and it is the one the docs teach: append the whole message object, not just its content. In Python, messages.append(response.choices[0].message) carries content, reasoning_content and tool_calls together, exactly as the API returned them. Do that on every turn, and the trap never fires. Rebuild the history by hand — extracting only content into a fresh {"role": "assistant", "content": ...} dict, as many tutorials teach for the OpenAI API — and it will fire the moment tools are involved. The difference between the two patterns is one line, and it is the difference between a working app and a 400 error on the second turn.
Why does the rule exist? Because in thinking mode with tools, the model’s reasoning and its tool calls are a single continuous process: it reasons, calls a tool, reads the result, reasons again, and only then answers. The reasoning is part of the conversation’s state, not a decoration on it. Without tools there is no such process to continue, so the reasoning can be dropped. With tools there is, so it cannot. You do not need to understand the internals to follow the rule — append the whole message object whenever tools are present — but understanding it helps you remember which case is which: tools present, pass the reasoning back; tools absent, it does not matter. Write that on a sticky note above your desk until it is habit.
One billing note belongs here, stated carefully, because the docs do not state it outright. The reasoning tokens appear in the usage object — the docs bill total input and output tokens and report the reasoning size in the usage details — but no official page read for this guide states verbatim whether reasoning tokens are billed as output tokens. Do not assume, and do not quote anyone who does. The safe practice is to budget for reasoning tokens as if they were output tokens until DeepSeek states otherwise, and to watch the usage object on your own calls: it tells you exactly how many tokens each call consumed, and that is the number your bill is built from. The worked cost example in section 12 counts only the 1,000-token final output per request and does not assume a reasoning-token charge, so its figures are a floor, not a promise.
8. Streaming: Showing Thinking and Answers Live

A non-streaming call waits for the whole answer before it returns anything. For a short answer that is fine. For a long answer — and a reasoning model thinking at high effort produces long answers — it feels broken: the user stares at a blank screen for ten seconds, wonders if the app crashed, and clicks away. Streaming fixes that. Instead of waiting for the complete response, your app receives the answer as it is generated, piece by piece, and displays each piece the moment it arrives. It is one argument in the call you already wrote: stream: true.
The mechanism is server-sent events, or SSE. With streaming on, the API returns a stream of data-only events, each carrying a partial delta of the response, and the stream ends with data: [DONE]. A minimal streaming loop in Python looks like this:
import os
from openai import OpenAI
client = OpenAI(
api_key=os.environ.get("DEEPSEEK_API_KEY"),
base_url="https://api.deepseek.com",
)
stream = client.chat.completions.create(
model="deepseek-flash",
messages=[
{"role": "user", "content": "Explain how rain forms, step by step."},
],
reasoning_effort="high",
stream=True,
)
for chunk in stream:
delta = chunk.choices[0].delta
if delta.reasoning_content:
print(delta.reasoning_content, end="", flush=True)
if delta.content:
print(delta.content, end="", flush=True)
Two details in that loop are specific to DeepSeek, and both matter. First, the deltas carry reasoning_content and content separately, exactly as the non-streaming message does — so a streaming app can show the reasoning in one pane and the answer in another, in real time, as the two streams arrive. That is the user interface the app in section 14 builds: two panes, one for thinking, one for the answer. Second, the deltas arrive in order — reasoning first, then the answer — because that is the order the model generates them. Your loop does not need to sort them; it needs only to route each delta to the right pane.
Token usage in a stream has a rule worth knowing exactly, because it is easy to get wrong. Set stream_options.include_usage to true and every chunk carries a usage field — null on all but the last. Either way, the last chunk before data: [DONE] carries the full token usage. There is no separate usage-only chunk: the usage rides on the last content chunk, whose choices array has exactly one element with no new content and a non-null finish_reason. If your code waits for a chunk that contains only usage and nothing else, it will wait forever. Read the usage off the last chunk, log it, and move on — section 14’s app logs exactly that number per call.
There is also a keep-alive mechanism, and it matters most for hand-rolled clients. While a request waits for inference to start, non-streaming requests return empty lines and streaming requests return SSE keep-alive comments — lines beginning with a colon, such as : keep-alive. These do not affect JSON parsing, but a hand-rolled parser must handle them: skip empty lines, skip colon lines, and parse only the data: lines. The SDKs handle this for you; raw HTTP clients do not. And there is a hard limit behind the keep-alive: if the request has not started inference after 10 minutes, the server closes the connection. A request that waits that long is not going to succeed by waiting longer; retry it, or check whether the API is overloaded — section 13 covers the 503 and 504 cases that go with that.
Two practical notes close the section. First, streaming does not change what you pay: the same tokens are generated and billed whether they arrive all at once or piece by piece. It changes only the experience — and for a reasoning model, where the thinking alone can take seconds, the experience is the difference between an app that feels alive and one that feels dead. Second, the deltas include the reasoning, so a streaming app must decide what to show. The default in section 14 is to show it, in its own pane, labelled as the model’s thinking — because a user who can see the reasoning understands the answer better, trusts it more, and spots its mistakes sooner. But if your app’s users should not see the raw chain of thought — a customer-facing support bot, for example — stream the reasoning to your logs and show only the answer. The choice is a product decision, not a technical one, and the API supports either.
9. Function Calling and Tools: Giving the Model Hands

A model on its own knows only what it was trained on, and its training has a cut-off date. Give it tools and it can do more: call your functions to reach your data, search the web for today’s facts, fetch a page and read it. The DeepSeek API has two kinds of tools — function tools, which you define, and DeepSeek web tools, which the API provides — and both are passed in the same tools argument. Both change the shape of the response, because the model may now answer in stages: reason, call a tool, read the result, reason again, then answer. That staging is exactly why section 7’s reasoning rule exists, and the two sections should be read together.
A function tool is a declaration: a name, a description, and a JSON Schema describing its parameters. The rules for the declaration are precise. Tool names must be unique within a call. A function name may contain letters, digits, underscores and dashes, and no more than 128 characters. Setting strict: true turns on strict-mode tool calls, which is in beta. The description is not decoration: it is what the model uses to decide when to call the function and what arguments to pass, so a vague description produces vague calls. Describe the function as if you were describing it to a careful colleague — what it does, when to use it, what each parameter means.
The tool-call loop is the part to learn carefully, and the docs’ own example is a weather app with two mocked functions, get_date and get_weather. The shape of the loop is the same in every app that uses tools, so learn it once. First, send the user’s question with the tools declared. If the model wants a tool, the response comes back with tool_calls on the message instead of a final answer — each call naming the function and carrying its arguments as JSON. Second, run the named function locally, with those arguments, in your own code. The model never executes your code and never sees your database; it only returns the call, and you decide what runs. Third, send the result back as a message with the role tool, carrying the tool_call_id from the call and the result as its content — and, crucially, append the whole assistant message object from the previous turn, reasoning included, as section 7 requires. Fourth, loop: send the updated history, and repeat until the response has no more tool calls. Then read the final content as the answer.
import json
# Your function, defined locally (the docs' sample mocks it the same way):
def get_weather(city):
return {"city": city, "condition": "Cloudy", "temperature": "7-13C"}
messages = [
{"role": "user", "content": "What is the weather like in Lahore today?"},
]
tools = [
{
"type": "function",
"function": {
"name": "get_weather",
"description": "Gets the current weather for a given city.",
"parameters": {
"type": "object",
"properties": {
"city": {
"type": "string",
"description": "The city name, e.g. Lahore",
},
},
"required": ["city"],
},
},
},
]
response = client.chat.completions.create(
model="deepseek-flash",
messages=messages,
tools=tools,
reasoning_effort="high",
)
message = response.choices[0].message
messages.append(message)
if message.tool_calls:
for call in message.tool_calls:
result = get_weather(**json.loads(call.function.arguments))
messages.append({
"role": "tool",
"tool_call_id": call.id,
"content": json.dumps(result),
})
final = client.chat.completions.create(
model="deepseek-flash",
messages=messages,
tools=tools,
reasoning_effort="high",
)
print(final.choices[0].message.content)
Three discipline points, all from the docs’ own pattern. First, validate the function arguments before your code acts on them, exactly as you would validate any user input — the model can pass a surprising value, and your function is the one that will run it. Second, resend the full tools array on every request in the loop; if you forget, the model may stop finding the tools. Third, and most important, append the whole message object — messages.append(message) — not a rebuilt dict of its content. That one line is what keeps the 400 error in section 7 from firing. The pattern in the sample above does it correctly; the pattern most tutorials teach for the OpenAI API, rebuilding the assistant message from its content alone, does not.
The tool_choice parameter controls whether the model must call a tool. Its values are none (the default when no tools are present), auto (the default when tools are present), required, and a named tool. Here is the rule that breaks apps: required and named tool choices are not supported in thinking mode, and the API returns a 400 error if you try them. If your app needs to force a tool call, disable thinking first. That is the only way to combine the two. There is one softening to the rule: when web tools are declared, required is treated as auto, so the call does not fail — but it does not force anything either. For a first app, leave tool_choice alone and let it default to auto; the model is good at deciding when a tool is needed, and the cases where you must force it are rarer than they look.
The web tools are DeepSeek’s own: deepseek_web_search and deepseek_read_url. Declare them like function tools, and the model can search the web and fetch pages from inside the call. There is a billing change here that postdates most existing guides, and it is dated precisely: starting at 12:00 on 18 November 2026, Beijing Time, the server-side search and web fetch tool calls triggered when calling the model are no longer billed per use. The results they return are appended to the model context and billed as model token usage — the same treatment applies whether the call is triggered through the web tools, the web_search tool in the Anthropic API, or the web_search tool in the Responses API. The standalone Search and Fetch APIs are still billed per use, at $0.75 per 1,000 successful requests each, as section 11 states. If you read a guide written before 18 November that prices in-model web tools per call, it is out of date; the current rule is that the search costs you context tokens, not a per-call fee.
Tools are also the bridge to agents, and the agent pattern is worth naming even though building one is beyond this tutorial. An agent is a loop like the one above — reason, call a tool, read the result, reason again — run for many turns toward a goal, with the model deciding each step. Our guide to AI agents explains what an agent is and when one is the right tool before you build with it, and our guide to Claude Skills, MCP and Projects covers the tool-use workspace on the Claude side, which is the closest comparison for how tool calling is organised elsewhere. The DeepSeek loop you have just learned is the substrate an agent runs on. Master the loop first; the agent is a loop with a goal and a budget.
10. JSON Output and Structured Answers

Prose is for humans; apps need data. If your app asks the model for a recipe and gets back a friendly paragraph, your code cannot reliably extract the ingredients, the quantities and the cooking time. Structured output solves that: you ask for JSON, and the model returns JSON your code can parse. On the DeepSeek API the mechanism is response_format, set to json_object, and the docs’ promise is that JSON output guarantees valid JSON. There is a rule attached to that promise, and it is not optional: you must also instruct the model to produce JSON via a system or user message. The format parameter alone is not enough. Tell the model, in words, to return JSON with the fields you want, and set the format parameter as well; the two together are what produce reliable structured output.
Here is a small structured-output example — extracting fields from a piece of text — in the pattern the docs teach:
import json
import os
from openai import OpenAI
client = OpenAI(
api_key=os.environ.get("DEEPSEEK_API_KEY"),
base_url="https://api.deepseek.com",
)
response = client.chat.completions.create(
model="deepseek-flash",
messages=[
{
"role": "system",
"content": "You extract information from text. Return only JSON with the keys name, city and topic. Do not add any other text.",
},
{
"role": "user",
"content": "Ayesha from Lahore wrote an essay about the Indus Waters Treaty.",
},
],
response_format={"type": "json_object"},
extra_body={"thinking": {"type": "disabled"}},
)
data = json.loads(response.choices[0].message.content)
print(data)
That sample disables thinking, and the reason is worth stating: for a simple extraction, reasoning adds tokens and time for no benefit, and a deterministic format task is exactly the case section 6 says to turn thinking off for. The expected result is a small object — {"name": "Ayesha", "city": "Lahore", "topic": "the Indus Waters Treaty"} — which your code can use directly: store it, display it in a table, pass it to another function. The json.loads call is the validation step, and it matters: parse defensively, and if parsing fails, retry the call or fall back to asking again with a clearer prompt. Structured output makes invalid JSON rare, but “rare” is not “never”, and a production app never feeds unvalidated model output straight into a database or a user interface.
There is one gotcha in the docs that no first app should discover by accident. If the output cannot be recognised as JSON, the API replaces the non-JSON content with spaces — the character U+0020 — so the message content may appear empty even with a finish_reason of stop. An empty-looking response with a stop finish reason, on a call that asked for JSON, usually means the model produced something the JSON parser could not recognise, and the API blanked it rather than returning it. The fix is not to retry the same prompt louder; it is to make the instruction clearer — a system message that names the exact keys, an example of the shape you want, and a short input that leaves no room for preamble. The other truncation case is finish_reason: length: the content may be partially cut off if the model hit the max_tokens cap, and a cut-off JSON object is not valid JSON, so check the finish reason before you parse, and treat a length finish as a signal to raise the cap or shorten the task.
When should you use structured output? Whenever your code needs to act on the answer rather than display it: extracting fields from a document, classifying a message, returning a list of items, filling a form, producing data for a chart. When the answer is for a human to read, leave the format alone and let the model write prose. A useful rule of thumb: if you find yourself writing a regular expression to pull a number out of the model’s reply, stop and use structured output instead. The model is better at filling a format than your regex is at parsing a paragraph, and the result is code you can maintain. And one combination to note: structured output and thinking mode work together — you can ask a reasoning model for JSON — but the reasoning itself is not JSON, it is in reasoning_content, and the JSON is in content. Keep the two fields separate, as section 7 teaches, and the combination is clean.
11. Vision, Files, Search, and Voice: The Rest of the API

Chat completions are the core of the DeepSeek API, but they are not the whole of it. Around the core sit four more capabilities — vision, file parsing, search and fetch, and voice — each with its own price and its own use. This section maps them, so you know what exists and what each is for in a real app. None of them needs a tutorial of its own here; each needs a paragraph, a price, and a pointer to where it fits.
Vision is the simplest: Flash supports image input, and V4-Pro does not. Send an image alongside your text and Flash can describe it, answer questions about it, or extract information from it — a photo of a broken appliance and the question “what is wrong with it”, a chart and the question “what does this show”, a handwritten note and the question “what does this say”. The image travels in the messages array with the text, and the model treats it as part of the conversation. If your app needs vision at all, it needs Flash, and the model choice in section 3 is already made for you. If your app needs the strongest reasoning and vision together, there is no single model in this API that offers both — that is a real limitation, and the honest answer is to split the work: Flash for the seeing, Pro for the hardest thinking, each called for the part it is good at.
File parsing and OCR is the document route: the API can parse files and read text from images of documents, priced at $0.225 per 1,000 pages. The use case is the document question-answerer: a user uploads a PDF, the API reads it, and the model answers questions about its contents. The error codes in section 13 give the limits a practical edge — a file that is too large returns a 413, a file that uploads too slowly returns a 408 — so a real app checks file size before it sends, and tells the user early rather than after a failed call. File parsing is also the route to the long-document app: instead of pasting a whole document into the messages array and paying cache-miss input prices on every turn, parse it once and work with the result.
Search and Fetch are the web route, and they come in two forms that must not be confused, because their billing differs. The standalone Search and Fetch APIs are separate endpoints you call directly: Search costs $0.75 per 1,000 successful requests, Fetch costs $0.75 per 1,000 successful requests, and you get the results back as data your code can use. The in-model web tools, deepseek_web_search and deepseek_read_url, are different: the model calls them from inside a chat completion, and since 12:00 on 18 November 2026 Beijing Time they are no longer billed per use — the results are appended to the model context and billed as model token usage, as section 9 states. Use the standalone APIs when your code needs search results as data. Use the in-model tools when the model needs live facts to answer. And if you want the news story behind the capability, our report on DeepSeek turning its app features into a developer API covers the 13 November release in news form; this section covers it as a capability, and does not re-report it. The same applies to the V4.1-Flash-1017 model behind Flash and its Search API opening — the news post on that release covers the announcement, and this tutorial covers the API it opened.
Voice is the newest of the four: text-to-speech at $0.45 per 10,000 characters, currently at a limited-time 50% discount of $0.225, and automatic speech recognition at $0.116 per hour of audio, currently at a limited-time 50% discount of $0.058. The use cases are the obvious ones — a voice assistant that speaks its answers, a transcription app that turns a lecture recording into text — and the discount matters enough to state plainly: it is described as limited-time, so do not build a budget that assumes it lasts forever. Re-check the pricing page before you commit a voice feature to production, exactly as you would for the model prices.
Two pointers close the section, because they are the natural next steps and neither needs a tutorial here. DeepSeek Harness is in developer preview for agent harness developers worldwide, with its guide hosted separately — it is the desktop app and harness for building agents on DeepSeek, and it is the route to take when the tool loop in section 9 grows into a full agent. And the API is supported by many popular AI agent and coding assistant tools: if you use Claude Code, GitHub Copilot or OpenCode, you can use DeepSeek as the backend model directly, with no code required. That last point is worth lingering on, because it is the fastest route of all for a developer who wants DeepSeek’s reasoning inside a tool they already use: change the backend model in the tool’s settings, and the tool does the rest. No code, no tutorial, no first call — just the model, where you already work.
12. What It Costs: Reading Your Bill Before It Arrives

Prices in this section are as they stood on 27 November 2026, checked against DeepSeek’s own pricing page that day, and unchanged since our explainer of 17 November. They are quoted per million tokens, in US dollars, for both models, at peak and off-peak, for cache-hit input, cache-miss input and output. DeepSeek says product prices may vary and reserves the right to adjust them, so treat this table as dated, not permanent — and re-check the pricing page before you spend. The habit to build is to check the pricing page before you commit to a model for a production app, because the numbers move, and the docs always carry the current figure.
| Model | Input, cache hit (off-peak / peak) | Input, cache miss (off-peak / peak) | Output (off-peak / peak) |
|---|---|---|---|
deepseek-flash | $0.003 / $0.006 | $0.15 / $0.30 | $0.60 / $1.20 |
deepseek-v4-pro | $0.022 / $0.044 | $0.66 / $1.32 | $1.98 / $3.96 |
Peak hours are 01:00–04:00 and 06:00–10:00 UTC, Monday to Friday, excluding Chinese public holidays. All other hours are off-peak, including weekends and Chinese public holidays in full. Off-peak is exactly half of peak on every line, so the table’s two columns are one rule, not two sets of numbers. In Pakistan time the peak windows are 06:00–09:00 and 11:00–15:00 PKT, Monday to Friday — which means a developer in Pakistan doing their heaviest work in the late morning is working in peak hours, and the same work done in the evening is off-peak. The saving from scheduling is real but small for a small app; it becomes real money only at volume, and the cache saving below is larger than the peak saving for almost every app.
The cache is the number that matters most. A cache hit on input costs about fifty times less than a cache miss: Flash at $0.003 against $0.15, Pro at $0.022 against $0.66. The mechanism is that repeated content — above all a repeated system prompt — is served from the cache rather than processed fresh. The strategy follows directly: put the long, stable part of your prompt in the system message, keep it identical across calls, and let the cache serve it. A long system prompt that changes on every call is billed at the cache-miss price every time; the same prompt repeated verbatim is billed at the cache-hit price. How often a given real app’s prompts actually hit the cache is not published, so no percentage saving is promised here — but the price gap is large enough that the habit is worth building regardless, and the arithmetic below shows how large the gap is when the cache does hit.
Here is the worked example, computed from the prices above — arithmetic, not a measured outcome, dated 27 November 2026. A small reasoning app: 100 requests a day, each with 2,000 input tokens on a cache miss and 1,000 output tokens, on deepseek-flash. Off-peak, the input costs 100 × 2,000 = 200,000 tokens at $0.15 per million, which is $0.03; the output costs 100 × 1,000 = 100,000 tokens at $0.60 per million, which is $0.06; the total is $0.09 a day, or about $2.70 a month over 30 days. At peak, the same shape doubles: $0.06 of input and $0.12 of output, $0.18 a day, about $5.40 a month. The same shape on deepseek-v4-pro off-peak costs $0.132 of input and $0.198 of output, about $0.33 a day or $9.90 a month; at peak, about $0.66 a day or $19.80 a month. And the cache illustration: if the 2,000-token input is mostly a repeated system prompt served from the cache, the off-peak input line falls to 200,000 tokens at $0.003 per million — $0.0006 — and the input cost effectively disappears, leaving the output as almost the whole bill. That is the shape of a well-built DeepSeek app: the input is nearly free, and you pay for the answers.
Two comparisons put those numbers in context. First, the token-volume context: DeepSeek now moves more tokens through its API than some of its largest rivals, and our report on DeepSeek’s token dominance covers that volume in news form — the cheap prices in this section are part of why the volume is that high. Second, the model comparison: Pro costs roughly three times Flash on output and roughly four times on cache-miss input, so an app that defaults to Pro pays three to four times as much for every call. That is the price of the hardest reasoning, and it is worth paying when the task needs it and wasteful when it does not. The cost controls follow from all of this, and they are short enough to list: turn thinking off for simple calls, where section 6 says it adds nothing; cap max_tokens so a runaway answer cannot bill you for 64K tokens; keep the system prompt stable so the cache can serve it; schedule bulk work outside the peak windows where you can; and watch the balance, because a 402 is the API telling you the money ran out, not that the code broke.
One warning about the worked example, because it is the kind of thing that gets misquoted. It counts only the 1,000-token final output per request and does not assume any charge for reasoning tokens, because the docs do not state the billing treatment of reasoning tokens verbatim — section 7 states that gap plainly. If reasoning tokens are billed as output, a reasoning-heavy app costs more than the example shows, and the difference grows with the effort level. Budget for the reasoning as output until DeepSeek states otherwise, watch the usage object on your own calls, and treat the $0.09-a-day figure as a floor for a reasoning app, not as a promise. The prices are real; the example is arithmetic on them; your app’s real bill is what the usage object says it is.
13. Errors, Limits, and Retries: The Ten Codes You’ll Actually Meet

Every app breaks. The difference between a demo and a product is that the product knows what broke and what to do about it. The DeepSeek API documents exactly ten error codes, no more, and this section maps each one to its fix. Learn the map now; you will use it on the first day your app has real users. The retry rule comes first, because it is the one developers get backwards most often: retry 408, 429 and the 5xx codes after waiting; top up on 402 first; and never blind-retry the other 4xx codes without changing the request, because the same request will fail the same way a hundred times.
| Code | Name | Cause (official) | Fix (official) |
|---|---|---|---|
| 400 | Invalid Format | Invalid request body format | Modify the body per the hints in the error message |
| 401 | Authentication Fails | Wrong API key | Check the key; create one first if you have none |
| 402 | Insufficient Balance | Out of balance | Check balance, top up |
| 408 | Request Timeout | File upload too slow (e.g. OCR / speech-to-text) | Check network, retry; see that API’s limits |
| 413 | Request Too Large | Uploaded file too large (e.g. OCR / speech-to-text) | Reduce file size |
| 422 | Invalid Parameters | Request contains invalid parameters | Modify parameters per the error-message hints |
| 429 | Rate Limit Reached | Sending too fast, or concurrency / QPS limit exceeded | Pace requests reasonably; see Rate Limit & Isolation |
| 500 | Server Error | DeepSeek’s server issue | Retry after a brief wait; contact support if it persists |
| 503 | Server Overloaded | Server overloaded due to high traffic | Retry after a brief wait |
| 504 | Gateway Timeout | Request did not finish in time (e.g. OCR / document upload) | Retry later, or send a smaller file |
Three of those codes deserve more than a row in the table, because they are the ones a first app meets most often and misunderstands most easily. The 400 is the most common, and it has two distinct causes in this API. The first is a malformed request body — a missing field, a wrong type, a parameter the API does not recognise — and the fix is to read the error message, which carries hints about what is wrong, and modify the body accordingly. The second is the thinking-mode trap from sections 6 and 9: a tool_choice of required or a named tool while thinking is on, or a multi-turn history with tools that is missing the previous turns’ reasoning_content. Both return a 400, and both are fixed by changing the request, not by retrying it. A 400 that survives a retry is a 400 that was never going to be fixed by retrying.
The 401 is the simplest code in the table and the most commonly misdiagnosed: the API key is wrong. Check the key, and create one first if you have none. In practice the causes are mundane — the environment variable is not set in the shell that ran the code, the key in the variable is an old one left over from a rotation, the key was copied with a trailing space or a missing character, or the base URL points at the wrong provider and the key is being checked against the wrong service. Check the variable with a print, check the base URL, and check that the key you think you set is the key the process actually sees. The 402 is equally simple and equally worth stating plainly: the balance is empty. Check the balance and top it up. Do not retry a 402, do not change the code, do not regenerate the key — the money ran out, and the fix is money.
The 429 is the limit code, and the limit it reports is concurrency, not a per-minute rate. DeepSeek publishes concurrency limits per account, regardless of which API key makes the call: Flash allows 2,500 simultaneous connections, V4-Pro allows 500. A request counts as one concurrent connection from the moment it is sent until the response completes, so a long reasoning call holds its slot for longer than a short one, and a burst of long calls exhausts the limit faster than the same number of short ones. Exceeding the limit returns a 429. The fix is to pace requests reasonably — queue them, spread them out, and do not fire a thousand parallel calls at an API that allows five hundred — or to request a free capacity expansion, which DeepSeek offers through a form linked from the rate-limit page, matched to your actual business needs at no additional cost. The form itself was not opened or tested for this guide, so its fields and approval time are not described here. What the docs do not publish, and this guide does not invent, is any per-key or per-minute limit: there are no requests-per-minute or tokens-per-minute caps stated anywhere in the official docs, so do not code against numbers that do not exist.
There is one more lever on limits, and it is user_id. Pass a custom ID — a string of ASCII letters, digits, underscores and hyphens, no more than 512 bytes of UTF-8, containing no private user information — and the API uses it for content-safety isolation, KVCache isolation for privacy, and scheduling isolation. For regular users, all user_id values combine for the concurrency calculation. For users with increased quotas, each user_id also gets its own limit: Flash 2,500 and V4-Pro 500 per user_id, with an empty ID counting as a special user_id of its own. In the OpenAI Chat Completions format the field goes at the top level of the HTTP body — inside extra_body when you use the OpenAI SDK — and in the Anthropic format it goes inside metadata. For a first app, the practical use is simple: give each of your end users their own user_id, and one user’s burst cannot consume another user’s share of your concurrency.
When you do retry, do it properly: wait a short time before the first retry, increase the delay exponentially — a second, then two, then four, then eight — add a random jitter so all your clients do not retry at the same instant, and set a maximum number of attempts so a retry loop can never run forever. The Search and Fetch APIs have their own error table, and its retry rule is the same shape: retry 408, 429 and 5xx after waiting; top up on 402 first; do not retry other 4xx codes without changing the request. That table was read only through a search excerpt of the official guide, not in full, so it is cited here for its retry rule and not reproduced as a table. The pattern across all of it is the same: read the code, find the bucket it belongs to, and apply that bucket’s fix. Guessing wastes the hour that the map saves.
14. Putting It Together: A Working Reasoning App

You now have every piece. This section assembles them into one working program: a small reasoning app that takes a hard question, calls Flash with thinking on, streams the reasoning trace to one pane and the answer to another, falls back to Pro on demand, logs the token usage of every call, and handles the 401, 402 and 429 errors. It is a single Python file, built only from the patterns this guide has already taught, and it is deliberately small — the skeleton of a real app, not a framework.
The app’s shape is three functions and a loop. The first function makes a reasoning call and streams it, routing the reasoning deltas to one place and the answer deltas to another. The second function runs the tool loop from section 9, for questions that need a tool. The third is the fallback: the same question, asked of Pro, when the user asks for the strongest reasoning or when Flash’s answer is not good enough. The loop around them is the user interface: read a question, call Flash, print the thinking and the answer as they arrive, log the usage from the last chunk, and repeat. The fallback is a flag, not a default — --pro on the command line, or a “use Pro” button in a real interface — because Pro costs three times as much, and the default should be the cheap model.
import json
import os
import sys
import time
from openai import OpenAI
client = OpenAI(
api_key=os.environ.get("DEEPSEEK_API_KEY"),
base_url="https://api.deepseek.com",
)
MODEL_DEFAULT = "deepseek-flash"
MODEL_STRONG = "deepseek-v4-pro"
def ask(question, model=MODEL_DEFAULT, effort="high", tools=None):
messages = [
{"role": "system", "content": "You are a careful reasoning assistant. Think step by step, then give a clear final answer."},
{"role": "user", "content": question},
]
stream = client.chat.completions.create(
model=model,
messages=messages,
tools=tools,
extra_body={"thinking": {"type": "enabled"}},
reasoning_effort=effort,
stream=True,
stream_options={"include_usage": True},
)
print("--- Thinking ---")
usage = None
for chunk in stream:
if chunk.usage is not None:
usage = chunk.usage
delta = chunk.choices[0].delta
if getattr(delta, "reasoning_content", None):
print(delta.reasoning_content, end="", flush=True)
if delta.content:
print(delta.content, end="", flush=True)
print("n--- Usage ---")
print(usage)
return usage
That function is the whole app in miniature, and every line in it comes from an earlier section: the system message and user message from section 5, the extra_body thinking toggle from section 4, the high default effort from section 6, the streaming loop with its two panes from section 8, and the usage read off the last chunk from section 8’s rule that there is no separate usage-only chunk. The usage print is not decoration: it is the cost control. Log it per call, with the model and the question, and you will know what your app spends before the bill tells you. A production version would write it to a file or a database; this version prints it, and the habit is the same either way.
The error handling wraps that function, and it follows section 13’s map exactly. A 401 means the key is wrong: stop and say so, because retrying a wrong key changes nothing. A 402 means the balance is empty: stop and say so, because the fix is a top-up, not code. A 429 means the concurrency limit was hit: wait and retry, with exponential backoff and a cap on attempts. A 500 or 503 means the server had a problem: wait briefly and retry. Anything else in the 4xx range means the request itself is wrong — most often, in this app, the 400 from a missing reasoning_content in a tool-using history — and the fix is to change the request, not to retry it:
def ask_with_retries(question, model=MODEL_DEFAULT, effort="high"):
delay = 1
for attempt in range(4):
try:
return ask(question, model=model, effort=effort)
except Exception as exc:
status = getattr(getattr(exc, "response", None), "status_code", None)
if status in (401, 402):
print(f"Stopped: HTTP {status}. Check the key (401) or top up the balance (402).")
raise
if status in (429, 500, 503):
print(f"HTTP {status}; retrying in {delay}s (attempt {attempt + 1}/4).")
time.sleep(delay)
delay *= 2
continue
raise
print("Gave up after 4 attempts.")
return None
if __name__ == "__main__":
model = MODEL_STRONG if "--pro" in sys.argv else MODEL_DEFAULT
question = " ".join(a for a in sys.argv[1:] if a != "--pro")
if not question:
question = "9.11 and 9.8, which is greater, and why?"
ask_with_retries(question, model=model)
Run it with a question — python app.py "Why is the sky blue?" — and it streams the thinking, then the answer, then the usage. Run it with --pro and the same question goes to V4-Pro. The tool loop from section 9 bolts onto the same shape: pass a tools list into ask, append the whole message object to the history on every turn, and send tool results back with their tool_call_id — the 400 trap is the one thing the bolt-on must not forget, and the sample in section 9 shows the correct pattern. The vision capability from section 11 bolts on the same way, with Flash as the model, and the JSON output from section 10 bolts on by adding response_format and the instruction to return JSON — with thinking disabled for the simple extractions, as section 10’s sample does.
Before you ship it, run the pre-launch checklist. The key is in the environment variable, not in the code, and the production key is not the development key. The thinking default is chosen deliberately — on at high for hard questions, off for simple ones — and not left to accident. The reasoning pass-back is correct: the history appends the whole message object whenever tools are present, and the 400 trap has been tested with a two-turn tool call, not merely read about. The cost caps are set: a max_tokens cap on long-form calls, a stable system prompt so the cache can serve it, and a usage log that records the model, the tokens and the cost of every call. The error handling has been exercised, not just written: a wrong key produces a clean 401 message, an empty balance a clean 402, and a burst of parallel calls a 429 with a retry rather than a crash. And the prices have been re-checked on the day you ship, because the figures in section 12 are dated 27 November 2026 and DeepSeek reserves the right to change them.
Where to go next is short, because the next steps are all one line each. DeepSeek Harness is in developer preview for agent harness developers worldwide — the route to take when the tool loop grows into a full agent. Claude Code, GitHub Copilot and OpenCode can all use DeepSeek as their backend model directly, with no code required — the fastest way to put DeepSeek’s reasoning inside a tool you already use. And the model picker in our guide to choosing an AI model is the framework for the next decision, when a new model appears or a new app needs a different trade-off. The app you have built is small on purpose: one program, one key, two models, thinking on by default, the reasoning visible, the bill visible, and the errors handled. That is not a toy. Those abilities — a first call, thinking, streaming, tools, structured output, cost control and error handling — are the skeleton of almost every AI app in production. Build one real thing on top of it, ship it behind a back end that holds your key, and you will have gone from first key to working reasoning app.
The DeepSeek API rewards the developer who reads the docs over the one who copies a tutorial — and this guide was written to be the docs, in order, with the working code attached. The API you learned here is the DeepSeek API as it stands on 27 November 2026: two models, thinking mode on by default, the reasoning in reasoning_content, the 400 trap and its one-line fix, streaming with usage on the last chunk, tools with a forced-call ban in thinking mode, prices dated and warned about, and ten error codes with their fixes. The models and the prices will move, and the docs will move with them. Re-check the pricing page when you ship, keep your key on the server, pass the reasoning back when tools are present, and build the next thing. Checked 27 November 2026.
Sources
- DeepSeek — “Pricing” (api-docs.deepseek.com/quick_start/pricing): the current lineup — deepseek-flash (served by DeepSeek-V4.1-Flash-1017) and deepseek-v4-pro (served by DeepSeek-V4-Pro-0813); 1M context, 384K max output; prices per 1M tokens, peak and off-peak, cache-hit and cache-miss; peak hours 01:00–04:00 and 06:00–10:00 UTC Mon–Fri excluding Chinese public holidays; concurrency Flash 2,500 / V4-Pro 500; Search & Fetch $0.75/1,000, file parsing & OCR $0.225/1,000 pages, TTS $0.45/10,000 chars (50% off), ASR $0.116/hour (50% off); the 18 Nov 2026 change ending per-use billing for in-model server-side search/fetch tool calls. Read in full, 27 November 2026.
- DeepSeek — “Chat Completions” (api-docs.deepseek.com/api/create-chat-completion): the only two valid model values; messages array and roles; thinking object and reasoning_effort (none / low / high / max, default high); max_tokens 1–384K, defaults 8K non-thinking / 64K thinking / 128K with max effort; response_format json_object and the must-instruct rule; stream and stream_options.include_usage; temperature no effect in thinking mode; top_p model-specific rules; tools, tool_choice and the thinking-mode ban on required/named tools; frequency_penalty / presence_penalty deprecated; safety_check, title, logprobs, user_id. Read in full, 27 November 2026.
- DeepSeek — “Thinking Mode” (api-docs.deepseek.com/guides/thinking_mode/): thinking enabled by default, default effort high; effort mappings including ultra → max; thinking in extra_body for the OpenAI SDK; reasoning_content next to content; the pass-back rule — required every turn when tools are present (400 otherwise), ignored when tools are absent; the 9.11 vs 9.8 Python sample and the weather tool-call sample. Read in full, 27 November 2026.
- DeepSeek — “Your First API Call” (api-docs.deepseek.com/ — docs root): OpenAI/Anthropic-compatible format; base URLs https://api.deepseek.com and https://api.deepseek.com/anthropic; the official curl first call; DeepSeek Harness in developer preview; Claude Code, GitHub Copilot and OpenCode as backends. Read in full, 27 November 2026. Note: the page formerly at /news/news250917 now returns 404; the page lives at the docs root.
- DeepSeek — “Rate Limit & Isolation” (api-docs.deepseek.com/quick_start/rate_limit): concurrency per account, Flash 2,500 / V4-Pro 500; 429 on exceeding; free capacity-expansion requests; user_id isolation (content-safety, KVCache, scheduling); keep-alive empty lines and : keep-alive comments; 10-minute close if inference has not started. Read in full, 27 November 2026.
- DeepSeek — “Error Codes” (api-docs.deepseek.com/quick_start/error_codes/): the ten documented codes — 400, 401, 402, 408, 413, 422, 429, 500, 503, 504 — with official causes and fixes. Read in full, 27 November 2026. The Search & Fetch error table and its retry rule were read via a search excerpt of the official guide, not in full.
- DeepSeek — homepage (deepseek.com): banner on DeepSeek V4.1 Flash updated to V4.1-Flash-1017; entry points chat.deepseek.com, platform.deepseek.com, Harness. Read 27 November 2026. The homepage states no pricing or specs and is not cited for those.
- Internal research base: C11 brief (DeepSeek explainer, 17 Nov 2026) — prices re-verified live against DeepSeek’s pricing page on 27 November 2026 and confirmed unchanged; R1 / deepseek-reasoner retirement 24 Jul 2026 as established in C11.
- Site sources linked in the article: the DeepSeek explainer (post 5899); the Gemini API tutorial (D6); the OpenAI API explainer; the Llama open-models vs closed-rivals explainer; the AI agents explainer (post 6248); the Claude Skills, MCP and Projects guide; the Qwen models explainer; the DeepSeek full-app-API news post (post 5714); the DeepSeek OpenRouter token-dominance report (post 5107); the AI model picker guide. All verified HTTP 200 on 27 November 2026 (see COUNTS.txt).
Prices checked 27 November 2026 — re-check the DeepSeek pricing page before you spend. The platform.deepseek.com console steps in this guide are presented as the documented flow; the console could not be read directly on 27 November 2026, and no granted-balance or free-credit figure is stated in this guide.


0 Comments