DeepSeek API Function Calling & JSON Mode Guide
Use OpenAI-compatible tool schemas and json_object output with DeepSeek API in Python and Node.js, with multi-turn message handling and validation checks.
On this page
1. Model capability and support
deepseek-chat is the standard model for low-latency Function Calling and structured JSON extraction via OpenAI-compatible tools schemas. If you test tool loops on deepseek-reasoner, ensure your client strips reasoning_content before sending follow-up tool results, or keep tool dispatch on deepseek-chat.
2. Standard 4-step tool calling workflow
- Define tool schemas: Provide the
toolsarray containing function names, descriptions, and JSON Schema parameters. - Model decision: The API returns
tool_callswith parsed arguments. - Execute locally: Your application invokes the corresponding local function with the provided arguments.
- Return result: Append the tool output (with
role: "tool") tomessagesand request the final synthesized answer.
3. Complete executable Python example
import json
from openai import OpenAI
client = OpenAI(
api_key="sk-your_deepseek_api_key",
base_url="https://api.deepseek.com"
)
# 1. Local implementation
def get_weather(location: str, unit: str = "celsius"):
return json.dumps({"location": location, "temperature": 22, "condition": "Sunny", "unit": unit})
# 2. Tool schema
tools = [{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get current weather for a specified location",
"parameters": {
"type": "object",
"properties": {
"location": {"type": "string", "description": "City name, e.g. London"},
"unit": {"type": "string", "enum": ["celsius", "fahrenheit"]}
},
"required": ["location"]
}
}
}]
messages = [{"role": "user", "content": "What is the weather in London today?"}]
# 3. Initial request triggering tool call
response = client.chat.completions.create(
model="deepseek-chat",
messages=messages,
tools=tools
)
message = response.choices[0].message
if message.tool_calls:
messages.append(message)
for tool_call in message.tool_calls:
if tool_call.function.name == "get_weather":
args = json.loads(tool_call.function.arguments)
tool_result = get_weather(**args)
# 4. Append tool execution output
messages.append({
"role": "tool",
"tool_call_id": tool_call.id,
"content": tool_result
})
# 5. Second request producing final answer
final_response = client.chat.completions.create(
model="deepseek-chat",
messages=messages
)
print("Final answer:", final_response.choices[0].message.content)Equivalent tool-call loop in Node.js (npm install openai):
import OpenAI from "openai";
const client = new OpenAI({
apiKey: process.env.DEEPSEEK_API_KEY,
baseURL: "https://api.deepseek.com",
});
const tools = [{
type: "function",
function: {
name: "get_weather",
description: "Get current weather for a city",
parameters: {
type: "object",
properties: { location: { type: "string" } },
required: ["location"],
},
},
}];
const messages = [{ role: "user", content: "What is the weather in London?" }];
const first = await client.chat.completions.create({ model: "deepseek-chat", messages, tools });
const msg = first.choices[0].message;
if (msg.tool_calls?.length) {
messages.push(msg);
for (const call of msg.tool_calls) {
const { location } = JSON.parse(call.function.arguments);
messages.push({
role: "tool",
tool_call_id: call.id,
content: JSON.stringify({ location, temperature: 22, condition: "Sunny" }),
});
}
const finalRes = await client.chat.completions.create({ model: "deepseek-chat", messages });
console.log(finalRes.choices[0].message.content);
}4. Structured JSON Object output mode
When you need valid JSON output without external tool calls, set response_format={'type': 'json_object'}. Per DeepSeek's JSON Mode contract, your system or user message must explicitly include the word json (along with an example schema), and max_tokens must be high enough to avoid mid-object truncation:
response = client.chat.completions.create(
model="deepseek-chat",
messages=[
{"role": "system", "content": "Extract user fields and return json with keys: name, age, role, city."},
{"role": "user", "content": "John Doe, 29, Software Engineer in Seattle"}
],
response_format={"type": "json_object"},
max_tokens=1024
)
print(response.choices[0].message.content)5. Troubleshooting and retry tips
JSON decode error when parsing arguments
Wrap json.loads() in a try...except block. If arguments are malformed, append the error message back to the conversation for auto-repair.
Model fails to trigger tool execution
Ensure the function description clearly matches the user prompt intent, or pass tool_choice="auto" explicitly.