DeepSeek’s API can call your own Python functions and return clean JSON, and both features now work on the current models, deepseek-flash and deepseek-v4-pro. The rules changed a lot in 2026, so old snippets with deepseek-chat break.
This guide shows the full setup in Python: the tools schema, a working multi-turn tool loop, strict mode, JSON Output, and how thinking mode changes everything.
I checked every model id, parameter, price and error against the official DeepSeek API docs on 5 December 2026, using the openai Python SDK 3.65.0.
- Models: use
deepseek-flash(served by DeepSeek-V4.1-Flash-1017) ordeepseek-v4-pro. Both support tool calls and JSON Output. - Format: OpenAI-compatible. Base URL
https://api.deepseek.com, sametoolsarray as OpenAI. - Strict mode: still Beta. It needs
https://api.deepseek.com/betaand"strict": trueon every function. - Thinking mode: on by default. With tools you must send
reasoning_contentback on every turn, or you get a 400 error. - Price: deepseek-flash costs $0.30 input / $1.20 output per 1M tokens at peak, and half that off-peak.
What Function Calling and JSON Output Do
Function calling (DeepSeek calls it Tool Calls) lets the model ask your code to run a function. The model never runs anything itself. It returns a function name plus JSON arguments, your code runs the function, and you send the result back.
JSON Output is simpler. It forces the reply to be a valid JSON string, so you can parse it with json.loads() without regex hacks.
Here is when to use each one:
- Tool calls: the model needs live data or actions, such as weather, a database lookup, sending an email or running a search.
- Strict tool calls: you need the arguments to always match your schema, for example in a payment or booking flow.
- JSON Output: you only want structured data back, such as extracting fields from text. No functions are involved.
If you are new to the DeepSeek API, start with my DeepSeek API Python tutorial first, then come back here.
Current DeepSeek Model IDs (December 2026)
DeepSeek now has just two chat model ids. The old names are gone, so this is the first thing to fix in older code.
| Model id | Served by | Tool calls | JSON Output | Vision |
|---|---|---|---|---|
deepseek-flash |
DeepSeek-V4.1-Flash-1017 | Yes | Yes | Yes |
deepseek-v4-pro |
DeepSeek-V4-Pro-0813 | Yes | Yes | No |
deepseek-v4-flash (legacy) |
Routed to V4.1-Flash-1017, billed at Flash price | Yes | Yes | Yes |
Both current models have a 1M token context and up to 384K output tokens. Thinking mode is on by default for both.
Warning: the old deepseek-chat and deepseek-reasoner names were scheduled to be discontinued on 24 July 2026, per DeepSeek’s change log. If your code still uses them, switch to deepseek-flash now.
Setup: Key, SDK and Environment
DeepSeek uses the OpenAI API format, so you install the normal openai package. There is no separate DeepSeek SDK to learn.
- Create an API key. Sign in at platform.deepseek.com, top up a small balance, and create a key. My DeepSeek API key guide shows each screen.
- Install the SDK. Run
pip install -U openai. I checked this guide with version 3.65.0, which needs Python 3.10 or newer. - Store the key safely. On macOS or Linux run
export DEEPSEEK_API_KEY="sk-...". On Windows PowerShell run$env:DEEPSEEK_API_KEY="sk-...". - Point the client at DeepSeek. Set
base_url="https://api.deepseek.com". For strict mode only, usehttps://api.deepseek.com/beta. - Run a test call. Copy Example 1 below. If it prints a weather answer, your setup works.
The Tools Schema Explained
You describe each function in a tools list. The format is the same as OpenAI’s Chat Completions format, so most existing tool code ports over directly.
tools = [
{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get the current weather for a city.",
"parameters": {
"type": "object",
"properties": {
"city": {"type": "string", "description": "City name, e.g. Hangzhou"},
"unit": {"type": "string", "enum": ["celsius", "fahrenheit"]}
},
"required": ["city"]
}
}
}
]
The key fields from the API reference:
- name: letters, digits, underscores and dashes only, up to 128 characters. Names must be unique.
- description: tells the model when to use the tool. Write it like an instruction, not a label.
- parameters: a JSON Schema object. Leave it out for a function with no inputs.
- strict: optional, default
false. Set it totruefor strict mode (Beta).
tool_choice options
The tool_choice parameter controls whether the model must call a tool:
- auto: the default when tools are present. The model decides.
- none: the model answers in text and calls nothing.
- required: the model must call one or more tools.
- Named tool:
{"type": "function", "function": {"name": "get_weather"}}forces that one tool.
Note: required and named tool choices are not supported in thinking mode. The API returns a 400 error. Turn thinking off first if you need to force a tool.
Example 1: Your First Tool Call
This example runs in non-thinking mode, which is the simplest way to learn the flow. It asks for the weather, runs a fake get_weather function and sends the result back.
import os
import json
from openai import OpenAI
client = OpenAI(
api_key=os.environ["DEEPSEEK_API_KEY"],
base_url="https://api.deepseek.com",
)
tools = [{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get the current weather for a city.",
"parameters": {
"type": "object",
"properties": {"city": {"type": "string"}},
"required": ["city"],
},
},
}]
def get_weather(city):
# Replace with a real weather API call
return {"city": city, "temp_c": 24, "sky": "cloudy"}
messages = [{"role": "user", "content": "How's the weather in Hangzhou?"}]
response = client.chat.completions.create(
model="deepseek-flash",
messages=messages,
tools=tools,
extra_body={"thinking": {"type": "disabled"}},
)
msg = response.choices[0].message
messages.append(msg)
for call in msg.tool_calls or []:
args = json.loads(call.function.arguments)
result = get_weather(**args)
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,
extra_body={"thinking": {"type": "disabled"}},
)
print(final.choices[0].message.content)
Three details matter here. The thinking switch goes inside extra_body, because the OpenAI SDK does not know that field. The tool result must be a string, so wrap dicts in json.dumps().
Also, every tool_call_id must match an id from the assistant message right before it. DeepSeek validates this pairing and rejects duplicate ids.
Example 2: Multi-Turn Tool Loop in Thinking Mode
Real agents need a loop. The model may call one tool, read the result, then call another before it answers. In thinking mode it also reasons between each call.
The big rule from DeepSeek’s thinking mode guide: when a request carries tools, you must pass back the reasoning_content of all previous turns. That includes turns where no tool was called. If you skip it, the API returns a 400 error.
import os
import json
from datetime import date
from openai import OpenAI
client = OpenAI(
api_key=os.environ["DEEPSEEK_API_KEY"],
base_url="https://api.deepseek.com",
)
tools = [
{"type": "function", "function": {
"name": "get_date",
"description": "Get today's date.",
"parameters": {"type": "object", "properties": {}},
}},
{"type": "function", "function": {
"name": "get_weather",
"description": "Get the weather for a city on a date (YYYY-MM-DD).",
"parameters": {
"type": "object",
"properties": {
"city": {"type": "string"},
"day": {"type": "string"},
},
"required": ["city", "day"],
},
}},
]
def get_date():
return date.today().isoformat()
def get_weather(city, day):
return f"{city} on {day}: cloudy, 7 to 13 C"
TOOLS = {"get_date": get_date, "get_weather": get_weather}
def run_agent(messages, max_steps=8):
for step in range(max_steps):
resp = client.chat.completions.create(
model="deepseek-flash",
messages=messages,
tools=tools,
reasoning_effort="high",
extra_body={"thinking": {"type": "enabled"}},
)
msg = resp.choices[0].message
# Append the whole message: it keeps content,
# reasoning_content and tool_calls together
messages.append(msg)
if not msg.tool_calls:
return msg.content
for call in msg.tool_calls:
fn = TOOLS.get(call.function.name)
try:
args = json.loads(call.function.arguments or "{}")
result = fn(**args) if fn else "Unknown tool"
except Exception as e:
result = f"Tool error: {e}"
messages.append({
"role": "tool",
"tool_call_id": call.id,
"content": str(result),
})
return "Stopped: too many tool steps"
history = [{"role": "user", "content": "What's the weather in Hangzhou tomorrow?"}]
print(run_agent(history))
# Second question in the same chat: keep the full history
history.append({"role": "user", "content": "And in Guangzhou?"})
print(run_agent(history))
The line messages.append(msg) does the heavy lifting. DeepSeek’s docs say it equals appending a dict with content, reasoning_content and tool_calls.
Tip: if you save history as plain dicts (for a database or a web app), copy reasoning_content into each assistant dict yourself. If you drop it, you get the 400 error described above.
Thinking mode settings that change with tools
- Effort:
reasoning_effortaccepts low, high or max. Default is high. Values like medium map to high. - Ignored params:
temperature,presence_penaltyandfrequency_penaltydo nothing in thinking mode. They do not raise an error. - top_p on v4-pro: in thinking mode it is fixed at 0.95 when tool calling is on, and your value is ignored.
- Without tools: you do not need to send
reasoning_contentback. The API ignores it.
Example 3: Strict Mode (Beta)
Normal tool calls usually follow your schema, but not always. Strict mode makes the model’s arguments follow your JSON Schema exactly. DeepSeek still labels it Beta, and it works in both thinking and non-thinking mode.

To turn it on you need three things:
- Use the Beta base URL. Set
base_url="https://api.deepseek.com/beta". - Mark every function strict. All functions in
toolsneed"strict": true, not just one. - Write a strict-friendly schema. Every object must list all its properties in
requiredand set"additionalProperties": false.
import os
import json
from openai import OpenAI
client = OpenAI(
api_key=os.environ["DEEPSEEK_API_KEY"],
base_url="https://api.deepseek.com/beta",
)
tools = [{
"type": "function",
"function": {
"name": "create_order",
"strict": True,
"description": "Create a shop order for the customer.",
"parameters": {
"type": "object",
"properties": {
"customer_email": {"type": "string", "format": "email"},
"quantity": {"type": "integer", "minimum": 1, "maximum": 10},
"status": {"type": "string",
"enum": ["pending", "processing", "shipped"]},
},
"required": ["customer_email", "quantity", "status"],
"additionalProperties": False,
},
},
}]
resp = client.chat.completions.create(
model="deepseek-flash",
messages=[{"role": "user",
"content": "Order 3 units for jo@example.com, status pending."}],
tools=tools,
extra_body={"thinking": {"type": "disabled"}},
)
call = resp.choices[0].message.tool_calls[0]
print(call.function.name, json.loads(call.function.arguments))
The server checks your schema before it runs. If the schema uses something strict mode does not support, you get an error message back instead of a reply.
What JSON Schema features strict mode supports
| Type | Supported | Not supported |
|---|---|---|
| object | properties, required (all keys), additionalProperties: false | Optional keys |
| string | pattern, format (email, hostname, ipv4, ipv6, uuid) | minLength, maxLength |
| number / integer | const, default, minimum, maximum, exclusiveMinimum, exclusiveMaximum, multipleOf | None listed |
| array | items | minItems, maxItems |
| Other | enum, anyOf, $ref with $def (including recursion) | Anything not listed |
Tip: send one test request as soon as you write a strict schema. The server rejects unsupported keywords up front, so schema mistakes show up on the very first call.
Example 4: JSON Output Mode
JSON Output works on both models with the normal base URL. You set response_format to {"type": "json_object"}. The API reference lists only two values: text and json_object. There is no json_schema option on DeepSeek.
DeepSeek’s JSON guide asks for three things: put the word “json” in a prompt, show an example of the shape you want, and set max_tokens high enough so the JSON is not cut off.
import os
import json
from openai import OpenAI
client = OpenAI(
api_key=os.environ["DEEPSEEK_API_KEY"],
base_url="https://api.deepseek.com",
)
SYSTEM = """Extract the product and price from the user's text.
Reply in json only, using this shape:
{"product": "Laptop stand", "price_usd": 51.25}"""
def extract(text, retries=2):
for attempt in range(retries + 1):
resp = client.chat.completions.create(
model="deepseek-flash",
messages=[{"role": "system", "content": SYSTEM},
{"role": "user", "content": text}],
response_format={"type": "json_object"},
max_tokens=2000,
)
content = resp.choices[0].message.content or ""
if content.strip():
return json.loads(content)
raise ValueError("Empty JSON reply after retries")
print(extract("I bought a USB-C hub for 39 dollars yesterday."))
Why the retry loop? If the model’s text cannot be read as JSON, DeepSeek replaces the non-JSON part with spaces. You can get a blank reply even when finish_reason is stop, so check for it.
For a side-by-side view of how DeepSeek’s JSON mode compares with schema-based outputs elsewhere, see my structured outputs guide for Claude, OpenAI and Gemini.
The Same Tool Call With curl
This is handy for testing a schema before you write Python. It sends one tool and lets the model decide.
curl https://api.deepseek.com/chat/completions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer ${DEEPSEEK_API_KEY}" \
-d '{
"model": "deepseek-flash",
"thinking": {"type": "disabled"},
"messages": [{"role": "user", "content": "Weather in Hangzhou?"}],
"tools": [{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get the current weather for a city.",
"parameters": {
"type": "object",
"properties": {"city": {"type": "string"}},
"required": ["city"]
}
}
}]
}'
Look for "finish_reason": "tool_calls" and a tool_calls array in the reply. In raw JSON the thinking field sits at the top level, not inside extra_body.
Prices and a Worked Cost Example
Tool calls have no extra fee. You pay normal token prices, but tool loops send the full history each time, so input tokens add up fast.

| Per 1M tokens | deepseek-flash peak | deepseek-flash off-peak | deepseek-v4-pro peak | deepseek-v4-pro off-peak |
|---|---|---|---|---|
| Input, cache hit | $0.006 | $0.003 | $0.044 | $0.022 |
| Input, cache miss | $0.30 | $0.15 | $1.32 | $0.66 |
| Output | $1.20 | $0.60 | $3.96 | $1.98 |
Peak hours are 01:00 to 04:00 and 06:00 to 10:00 UTC, Monday to Friday, excluding Chinese public holidays. Every other hour, including weekends, is off-peak at half price.
Worked example: 1,000 agent tasks
Say each task takes 3 requests in a tool loop. Across those requests it sends 20,000 input tokens (12,000 cached, 8,000 new) and gets 1,500 output tokens back. For 1,000 tasks:
- deepseek-flash, peak: 8M x $0.30 + 12M x $0.006 + 1.5M x $1.20 = about $4.27.
- deepseek-flash, off-peak: half of that, about $2.14.
- deepseek-v4-pro, peak: 8M x $1.32 + 12M x $0.044 + 1.5M x $3.96 = about $17.03.
Thinking mode makes replies longer, so expect more output tokens than in non-thinking mode. For every price detail and the cache rules, see my full DeepSeek API pricing guide.
Limits You Should Know
| Limit | Value |
|---|---|
| Context length | 1M tokens (both models) |
Max output (max_tokens) |
Up to 384K (393,216) |
Default max_tokens |
8K non-thinking, 64K thinking, 128K with effort max |
| Concurrency per account | 2,500 (deepseek-flash), 500 (deepseek-v4-pro) |
| Function name | a-z, A-Z, 0-9, underscore, dash; max 128 characters |
| Forced tool choice | Non-thinking mode only |
| Deferred tool loading | Not in Chat Completions (Anthropic and Responses formats only, deepseek-flash only) |
| Strict mode | Beta base URL only |
Concurrency counts each open request at the account level, no matter which key sends it. Going over returns a 429.
Troubleshooting DeepSeek Tool Call Errors
These are common problems with tools and JSON on DeepSeek, with the fix for each. Error codes come from DeepSeek’s official error page.
| Symptom | Cause | Fix |
|---|---|---|
| 400 on the second tool request in thinking mode | reasoning_content was not passed back |
Append the full assistant message, or copy reasoning_content into your dict |
400 when using tool_choice="required" |
Forced tool choice in thinking mode | Disable thinking with extra_body={"thinking": {"type": "disabled"}} |
| 400 Invalid Format | Bad request body, unpaired or duplicate tool_call_id |
Follow each assistant tool_calls message with one tool message per id |
| Error back when using strict mode | Schema uses an unsupported keyword, a missing required key, or no additionalProperties: false |
Check the strict support table above; use the /beta base URL |
Blank JSON reply with finish_reason: stop |
Output could not be read as JSON, so it was replaced with spaces | Add “json” and an example to the prompt; retry on blank |
Cut-off JSON, finish_reason: length |
max_tokens too low |
Raise max_tokens |
| 401 Authentication Fails | Wrong or missing API key | Check DEEPSEEK_API_KEY |
| 402 Insufficient Balance | Account is out of credit | Top up on the platform |
| 422 Invalid Parameters | A parameter value is not allowed | Read the hint in the error message |
| 429 Rate Limit Reached | Over the concurrency limit | Add backoff, or ask DeepSeek for more capacity (free) |
| 500 or 503 | Server error or overload | Retry after a short wait |
| Model keeps calling tools | No stop condition in your loop | Cap steps, as max_steps does in Example 2 |
For the full list of DeepSeek API errors beyond tools, including network and timeout issues, see my DeepSeek API errors fix guide.
Frequently Asked Questions
Does DeepSeek support function calling?
Yes. Both deepseek-flash and deepseek-v4-pro support tool calls through the OpenAI-compatible Chat Completions API, plus the Responses and Anthropic formats.
Is DeepSeek strict mode still in beta?
Yes. As of 5 December 2026 the docs still label it “strict Mode (Beta)”. You must call https://api.deepseek.com/beta and set strict to true on every function.
Can I use tools with thinking mode on?
Yes, thinking mode supports tool calls. You must send back the reasoning_content from all earlier turns, and you cannot force a tool with required or a named choice.
Does DeepSeek support json_schema in response_format?
No. The API reference lists only text and json_object. For schema-level control, use a strict tool call instead and read its arguments.
Do I still use deepseek-chat or deepseek-reasoner?
No. Those names were set to be discontinued on 24 July 2026. Use deepseek-flash and control thinking with the thinking parameter.
Do tool calls cost extra on DeepSeek?
No. You pay normal token prices. Tool schemas, history and tool results all count as input tokens, so caching and off-peak hours help keep agent costs low.
Sources
- DeepSeek API Docs: Tool Calls (strict mode Beta)
- DeepSeek API Docs: Thinking Mode
- DeepSeek API Docs: JSON Output
- DeepSeek API Reference: Chat Completions
- DeepSeek API Docs: Models & Pricing
- DeepSeek API Docs: Error Codes
- DeepSeek API Docs: Rate Limit & Isolation
- DeepSeek API Change Log
- openai on PyPI




