DeepSeek API Function Call: Tools, JSON Mode, Streaming
A deepseek api function call here uses the standard OpenAI tools format: you describe functions, the model returns tool_calls, your code runs them and sends the results back. This guide shows the full loop, JSON mode and streaming.
Updated

Key points
- Pass functions in tools, control them with tool_choice.
- Run the function yourself and reply with a message of role tool.
- JSON mode uses response_format with type json_object.
- Streamed tool_calls arrive in fragments you must concatenate.
How the loop works
The model never executes anything. It only decides that a function should be called and writes the arguments. Your program does the real work. One round trip has four steps:
- You send
messagesplus atoolslist that describes each function with a JSON Schema. - The model replies with an assistant message holding
tool_calls, each with anid, a function name and an arguments string. - You run the function and append a message with
role: "tool", the matchingtool_call_idand the result as text. - You call the API again. The model reads the result and writes the final answer.
This API follows that format with the model ID uncensored. It is an independent hosted model, not the official DeepSeek service, so expect the OpenAI-style fields shown here rather than any vendor-specific extras.
A complete working example
The script below defines one function, lets the model ask for it, and finishes the conversation. Swap the stub for a real lookup in your own project.
import json, os
from openai import OpenAI
client = OpenAI(base_url="https://api.deepseeknsfw.top/v1", api_key=os.environ["API_KEY"])
def get_stock(item: str) -> dict:
data = {"iron sword": 4, "oak shield": 0}
return {"item": item, "in_stock": data.get(item.lower(), 0)}
tools = [{
"type": "function",
"function": {
"name": "get_stock",
"description": "Return how many units of an item are in stock.",
"parameters": {
"type": "object",
"properties": {"item": {"type": "string"}},
"required": ["item"],
},
},
}]
messages = [{"role": "user", "content": "Do you have an oak shield?"}]
first = client.chat.completions.create(
model="uncensored", messages=messages, tools=tools, tool_choice="auto"
)
msg = first.choices[0].message
messages.append(msg)
for call in msg.tool_calls or []:
args = json.loads(call.function.arguments)
result = get_stock(**args)
messages.append({
"role": "tool",
"tool_call_id": call.id,
"content": json.dumps(result),
})
final = client.chat.completions.create(
model="uncensored", messages=messages, tools=tools
)
print(final.choices[0].message.content)
Keep the tools list on the second call too. Some clients drop it, and then the model may try to write a function call as plain text.
Controlling when a tool is called
tool_choice decides how much freedom the model has:
"auto"lets the model answer directly or call a tool. This is the default when tools are present."none"blocks tool calls for that turn, useful when you want a plain summary.- An object naming a function, such as
{"type": "function", "function": {"name": "get_stock"}}, forces that specific call.
Forcing a call is the simplest way to get structured extraction: define a function whose parameters are the fields you want, force it, and read the arguments. The function never has to exist in your code.
Models can return several calls in one message. Run all of them and append one tool message per id before the next request. A missing result for one id is a common cause of confusing follow-up answers.
JSON mode
If you only need valid JSON and no function at all, set response_format to {"type": "json_object"}. Also say in the prompt that you want JSON and describe the keys. The setting makes the output parseable, but it does not guarantee your exact schema, so validate the result.
curl https://api.deepseeknsfw.top/v1/chat/completions \
-H "Authorization: Bearer $API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "uncensored",
"response_format": {"type": "json_object"},
"messages": [
{"role": "system", "content": "Reply with JSON: {\"title\": string, \"tags\": string[]}"},
{"role": "user", "content": "Summarize: a lighthouse keeper finds a message in a bottle."}
]
}'
Use JSON mode for fixed-shape output and tools when the model must choose between actions. For a mix, forced tool calls are usually the more reliable option.
Writing tool schemas the model can follow
The quality of tool calls depends mostly on the schema, not on tricks in the prompt. These rules work well in practice:
- Give each function a name that says what it does, such as
get_stockorcreate_ticket, nothelper1. - Describe every parameter in plain words, with units and formats. "Date as YYYY-MM-DD" prevents a lot of bad arguments.
- Use
enumfor fixed choices so the model cannot invent values. - Mark required fields in
required, and keep optional ones few. - Return small, clean results. A tool message with 5,000 tokens of raw data costs input money on every later round.
It also helps to say in the system prompt when tools should be used and when the model should answer directly. For a roleplay or story bot, for example, a tool that reads character sheets can be called at the start of a scene and ignored afterwards.
Validate arguments on your side even when the schema looks strict. Check types, ranges and permissions before running anything that changes data or spends money. The model suggests the call; your code decides whether it is allowed.
Forced tool call for data extraction
Here is a compact pattern that avoids a second round trip. Define a function whose parameters are the fields you want, force the model to call it, and read the arguments as your result. Nothing is executed.
tools = [{
"type": "function",
"function": {
"name": "save_character",
"description": "Record a story character.",
"parameters": {
"type": "object",
"properties": {
"name": {"type": "string"},
"age": {"type": "integer"},
"role": {"type": "string", "enum": ["hero", "villain", "ally"]},
},
"required": ["name", "role"],
},
},
}]
r = client.chat.completions.create(
model="uncensored",
messages=[{"role": "user", "content": "Mara, a 34-year-old smuggler who helps the crew."}],
tools=tools,
tool_choice={"type": "function", "function": {"name": "save_character"}},
)
print(r.choices[0].message.tool_calls[0].function.arguments)
The printed string is JSON that follows your schema, with role limited to the three allowed values. Lower temperature to 0.2 or so for extraction work, since you want consistency rather than variety.
Streaming tool calls
With stream: true, a tool call does not arrive in one piece. The function name appears in the first fragment of a call, and the arguments string is delivered in small slices across many chunks. Each fragment carries an index that tells you which call it belongs to.
calls = {}
stream = client.chat.completions.create(
model="uncensored", messages=messages, tools=tools, stream=True
)
for chunk in stream:
if not chunk.choices:
continue
for tc in chunk.choices[0].delta.tool_calls or []:
slot = calls.setdefault(tc.index, {"id": "", "name": "", "args": ""})
if tc.id:
slot["id"] = tc.id
if tc.function and tc.function.name:
slot["name"] = tc.function.name
if tc.function and tc.function.arguments:
slot["args"] += tc.function.arguments
Parse args with json.loads only after the stream finishes. A half-received string is not valid JSON. Remember that a streamed request keeps one concurrency slot until the stream ends, which matters if your agent runs several tools in parallel against the limit of 8 on a full key.
Pitfalls and fixes
- Invalid JSON in arguments. Wrap
json.loadsin try/except. On failure, send the error back as the tool result and let the model retry. - Wrong or missing
tool_call_id. The id in your tool message must match the call exactly. - Vague descriptions. The model chooses functions by reading names and descriptions. Write one clear sentence per function and per parameter.
- Endless loops. Cap the number of rounds, for example five, and stop with a message if the cap is hit.
- Too many tools. Send only the functions relevant to the current task. A short list gives cleaner choices and fewer tokens.
- 429 responses. Back off on
rate_limitedorconcurrency, and wait 5 seconds when aRetry-After: 5header shows up.
Tool definitions count as input tokens at $0.15 per 1M, and every round re-sends the history. A ten-round agent with a 3,000-token history sends about 30,000 input tokens, or $0.0045. Failed or refused requests are not charged.
Where to go next
The docs cover the base URL and headers. You can test everything above with the trial credit from the API key page, and compare costs on the pricing page. The service is for lawful adult use, text only, and never allows sexual content involving minors. For an overview of access and keys on this site, see the DeepSeek API key page.
More guides
Questions and answers
Does this API support function calling?
Yes. Use the tools and tool_choice fields, read tool_calls from the reply and send results back as messages with role tool.
Can I get structured JSON without defining a function?
Yes. Set response_format to {"type": "json_object"} and describe the keys in the prompt. Validate the output in your code.
Does streaming work with tools?
Yes. Tool calls arrive as fragments with an index. Join the pieces and parse the arguments after the stream ends.
Is this the official DeepSeek function calling?
No. It is an independent hosted model using the OpenAI-compatible tools format, with the model ID uncensored.
Who runs the functions?
Your own code. The model only chooses a function and writes the arguments.
Your key is one form away
Create an account, copy the key, change the base URL. That is the whole setup.