DeepSeek Tool Calls: A Complete Python Function Calling Guide

DeepSeek tool calls let a model request a function your application provides. You describe the function and its arguments, receive a structured request, execute the approved operation, and return its result so the model can continue. For these custom functions, your application supplies the implementation, as explained in DeepSeek’s Tool Calls guide.

This tutorial builds that complete loop with the hosted DeepSeek Chat Completions API and the OpenAI Python SDK. The example uses fictional inventory data, so you can understand the integration without connecting a database or another paid service. Later sections cover tool selection, thinking history, strict schemas, streaming, and troubleshooting.

Last reviewed: November 21, 2026. The examples’ control flow and validation were checked locally with the real SDK and mocked HTTP responses. They were not run against a live DeepSeek account.

How DeepSeek Tool Calls Work

For custom function calling, your application manages a conversation that alternates between model responses and tool results. The tool definition describes an operation; the function in your code performs it.

StageMessage or actionWhat your application keeps
User requestA user asks for information that requires a lookup.The user message and available function definitions.
Assistant tool requestThe assistant returns one or more calls.The complete assistant message, including each call’s ID and arguments.
Tool executionYour code validates and runs the requested functions.One result message per call, linked by its exact ID.
Assistant continuationYou send the updated history back.The next assistant message, which may answer or request more tools.

The history is the connection between those stages. If you send a result without the assistant request that created it, or attach it to the wrong ID, the model cannot reliably associate the result with the requested operation.

DeepSeek function calling workflow showing model tool requests, application-side function execution and returned results

For example, one item inside message.tool_calls could look like this. This is an illustrative payload:

{
  "id": "call_inventory_1",
  "type": "function",
  "function": {
    "name": "lookup_inventory",
    "arguments": "{\"sku\":\"LAMP-01\"}"
  }
}

Notice that arguments is a JSON string. Parse it before using it, then validate the resulting object. In Python, json.loads() decodes JSON and json.dumps() produces a JSON string for the result you send back.

Choose a Model and Set Up the SDK

DeepSeek’s current quick start lists deepseek-flash and deepseek-v4-pro. Both appear with Tool Calls support in the model table. The example below uses deepseek-flash and explicitly disables thinking for the first implementation.

You need Python, the openai package, and a DeepSeek API key. The SDK sends this example’s requests to DeepSeek, using DeepSeek credentials and billing.

python -m pip install --upgrade openai

Set the key in the terminal where you will run the script. On macOS or Linux:

export DEEPSEEK_API_KEY="your_deepseek_api_key"

In Windows PowerShell:

$env:DEEPSEEK_API_KEY = "your_deepseek_api_key"

Keep the key in your application’s server environment. The local inventory function below uses no network service, but the model requests are billable API calls. Check the official pricing page for current rates.

Complete Python Example: Look Up Sample Inventory

Save the following as deepseek_tool_calls.py. Its fictional catalog contains seven units of LAMP-01 and zero units of DESK-02. Unknown SKUs return a clear error instead of a made-up quantity.

The example separates the tool schema, local execution, and conversation loop. It handles every returned call and keeps the complete assistant messages in history.

"""Read-only tool-calling example with explicitly fictional inventory data."""

import json
import os

from openai import OpenAI

MAX_MODEL_ROUNDS = 4  # Application limits, not DeepSeek service limits.
MAX_TOOL_CALLS = 8
INVENTORY = {"LAMP-01": 7, "DESK-02": 0}

TOOLS = [{
    "type": "function",
    "function": {
        "name": "lookup_inventory",
        "description": "Look up a SKU in the fictional demo inventory.",
        "parameters": {
            "type": "object",
            "properties": {
                "sku": {"type": "string", "description": "Product SKU, such as LAMP-01."}
            },
            "required": ["sku"],
            "additionalProperties": False,
        },
    },
}]


def lookup_inventory(sku):
    if sku not in INVENTORY:
        return {"error": "unknown_sku", "sku": sku}
    return {"sku": sku, "quantity": INVENTORY[sku], "source": "fictional_demo_data"}


def execute_tool(call):
    if call.function.name != "lookup_inventory":
        return {"error": "unknown_tool"}
    if not isinstance(call.function.arguments, str):
        return {"error": "arguments_must_be_a_JSON_string"}
    try:
        arguments = json.loads(call.function.arguments)
    except json.JSONDecodeError:
        return {"error": "invalid_JSON"}
    if not isinstance(arguments, dict) or set(arguments) != {"sku"}:
        return {"error": "expected_exactly_one_argument_named_sku"}
    sku = arguments["sku"]
    if not isinstance(sku, str) or not sku.strip() or len(sku) > 32:
        return {"error": "sku_must_be_a_nonempty_string_of_at_most_32_characters"}
    return lookup_inventory(sku.strip())


def run_turn(client, messages):
    seen_call_ids = set()
    calls_used = 0
    for round_number in range(1, MAX_MODEL_ROUNDS + 1):
        response = client.chat.completions.create(
            model="deepseek-flash",
            messages=messages,
            tools=TOOLS,
            tool_choice="auto",
            extra_body={"thinking": {"type": "disabled"}},
        )
        if not response.choices:
            raise RuntimeError("The API returned no choices.")
        choice = response.choices[0]
        message = choice.message
        calls = message.tool_calls or []

        if choice.finish_reason not in {"stop", "tool_calls"}:
            raise RuntimeError(f"Incomplete response: {choice.finish_reason}")
        if bool(calls) != (choice.finish_reason == "tool_calls"):
            raise RuntimeError("The finish reason and tool calls disagree.")
        if not calls:
            if not isinstance(message.content, str) or not message.content.strip():
                raise RuntimeError("The model stopped without an answer.")
            messages.append(message)  # Retain the complete final assistant turn.
            return message.content

        if round_number == MAX_MODEL_ROUNDS:
            raise RuntimeError("Model-round limit reached; no further tools executed.")
        if calls_used + len(calls) > MAX_TOOL_CALLS:
            raise RuntimeError("Tool-call limit reached; this batch was not executed.")
        batch_ids = set()
        for call in calls:
            if call.type != "function":
                raise RuntimeError("Unexpected tool-call type.")
            if not isinstance(call.id, str) or not call.id.strip():
                raise RuntimeError("A tool call is missing its ID.")
            if call.id in batch_ids or call.id in seen_call_ids:
                raise RuntimeError("Duplicate or reused tool-call ID.")
            batch_ids.add(call.id)

        # Keep tool_calls and provider fields, including any reasoning_content.
        messages.append(message)
        for call in calls:
            result = execute_tool(call)
            messages.append({
                "role": "tool",
                "tool_call_id": call.id,
                "content": json.dumps(result),
            })
        seen_call_ids.update(batch_ids)
        calls_used += len(calls)
    raise RuntimeError("Model-round limit reached.")


def main():
    messages = [
        {"role": "system", "content": "Use lookup_inventory for stock questions. "
         "Describe its results as fictional demo data; do not invent quantities."},
        {"role": "user", "content": "Check stock for LAMP-01 and DESK-02."},
    ]
    with OpenAI(
        api_key=os.environ["DEEPSEEK_API_KEY"],
        base_url="https://api.deepseek.com",
        max_retries=0,
        timeout=60.0,
    ) as client:
        print(run_turn(client, messages))


if __name__ == "__main__":
    main()

Run it from the same terminal:

python deepseek_tool_calls.py

When the model uses the lookup tool, its answer should reflect the sample quantities: LAMP-01 has 7 units; DESK-02 has 0. The exact wording and number of requested tool calls can vary. Because the example uses auto, a tool call is not guaranteed on every response.

The four-round limit, eight-call budget, 32-character SKU check, and 60-second request timeout are choices made for this example. The round and call budgets reset for each run_turn() invocation; they are not DeepSeek service limits. Automatic SDK retries are disabled so failures remain visible.

The loop reserves a model round to consume tool results. If its final available round requests another tool, the code stops before executing that batch. This avoids doing additional work when the example cannot ask the model to interpret its result.

Local checks covered multiple calls, result-ID matching, malformed arguments, unknown functions, incomplete responses, loop limits, and history preservation. Mocked responses verify those application behaviors; live testing is still needed to evaluate a model’s tool selection with your own prompts.

Control Tool Selection With tool_choice

The Chat Completions reference defines these selection options:

SettingBehaviorThinking mode
autoThe model may answer directly or request tools.Supported.
noneThe model generates a response without calling tools.Supported.
requiredThe model must request at least one tool.Disable thinking first.
A named functionThe model must request the selected function.Disable thinking first.
DeepSeek API tool_choice documentation showing auto, none, required and named function selection with thinking mode restrictions

For a forced inventory lookup, the Chat Completions parameter is:

tool_choice={"type": "function", "function": {"name": "lookup_inventory"}}

Apply forcing only where your workflow needs it. After returning a result, allow the model to finish with auto, or choose none when further tools are inappropriate. Forcing a tool on every iteration can prevent a final answer.

Also distinguish multiple requested calls from concurrent execution. The example processes calls sequentially. Your application may execute independent lookups concurrently, but a later action that depends on an earlier result must wait. Always handle the complete returned batch.

Use Thinking Mode Without Losing Conversation History

Thinking is enabled by default in the current hosted API. To enable it explicitly in the example, change the request’s extra_body value and optionally set its effort:

extra_body={"thinking": {"type": "enabled"}},
reasoning_effort="high",

With tools present, DeepSeek requires the previous assistant reasoning_content to be carried into subsequent requests. This includes earlier user turns and assistant turns that did not call a tool. Missing reasoning history can cause HTTP 400. See the current Thinking Mode rules.

DeepSeek Thinking Mode tool calling diagram showing how reasoning history and tool results are passed between requests

The example uses messages.append(message) for both tool-request and final-answer turns. Keep that complete API history when adding another user message. Inside the existing client block, a follow-up can use:

messages.append({
    "role": "user",
    "content": "Which of those sample products is unavailable?"
})
print(run_turn(client, messages))

Store the full API conversation separately from the transcript you display to users. A display containing only visible text is insufficient to reconstruct a tool-enabled thinking conversation.

Keep tool_choice="auto" for this variation. The current Chat Completions API rejects required and named forcing while thinking is enabled. Depending on the task, you may also need a longer request timeout than the sample’s 60 seconds.

Enable Strict Mode for Tool Arguments

Strict mode constrains generated arguments to a supported schema. DeepSeek documents it as a beta feature for thinking and non-thinking modes.

  1. Use https://api.deepseek.com/beta as the client’s base URL.
  2. Set strict: true inside every function definition.
  3. List every object property in required and set additionalProperties: false on each object.
  4. Use the supported JSON Schema subset; unsupported keywords can cause rejection.
DeepSeek Tool Calls strict mode beta configuration showing JSON schema requirements and function argument validation

The sample’s simple schema already declares its only property as required and forbids extra properties. Inside main(), replace the existing client block with the following, keeping it indented inside the function:

    for tool in TOOLS:
        tool["function"]["strict"] = True

    with OpenAI(
        api_key=os.environ["DEEPSEEK_API_KEY"],
        base_url="https://api.deepseek.com/beta",
        max_retries=0,
        timeout=60.0,
    ) as client:
        print(run_turn(client, messages))

The documented subset excludes string minLength/maxLength and array minItems/maxItems. The sample therefore checks SKU length locally.

A correctly shaped SKU still may not exist in your database. Similarly, a valid account ID does not establish that the current user may access it. Keep business checks and authorization in application code even when strict mode is enabled.

Handle Streaming Tool Calls Without Parsing Partial JSON

Streaming returns argument fragments in delta.tool_calls. Accumulate them by call index, retain their metadata, and wait for a completed response before parsing or executing. Text and reasoning need separate buffers. These fields are documented in the streaming response schema.

Add this helper above run_turn() in the same file. It reconstructs a completion choice for custom function tools, allowing the existing validation and execution loop to remain in place.

from openai.types.chat import ChatCompletionMessage
from openai.types.chat.chat_completion import Choice


def collect_assistant(stream):
    """Collect one choice containing text and custom function calls, without execution.

    Require a completed, accepted finish reason. The SDK iterator does not expose
    the raw SSE [DONE] marker. JSON/schema validation belongs in the dispatcher.
    """
    content, reasoning, saw_reasoning = "", "", False
    pending, finish = {}, None
    for chunk in stream:
        if not chunk.choices:
            continue
        if len(chunk.choices) != 1 or chunk.choices[0].index != 0:
            raise ValueError("Expected exactly one completion choice")
        if finish is not None:
            raise ValueError("Received another choice after the terminal chunk")
        choice = chunk.choices[0]
        delta = choice.delta
        if getattr(delta, "server_tool_calls", None) or getattr(choice, "server_tool_event", None):
            raise ValueError("This collector supports custom function tools only")
        content += delta.content or ""
        has_reasoning = "reasoning_content" in (delta.model_extra or {})
        if has_reasoning or "reasoning_content" in delta.model_fields_set:
            saw_reasoning = True
            reasoning += getattr(delta, "reasoning_content", None) or ""
        for part in delta.tool_calls or []:
            if part.index < 0:
                raise ValueError("Invalid tool-call index")
            call = pending.setdefault(part.index, {
                "id": None, "type": None, "name": None, "arguments": ""
            })
            metadata = (("id", part.id), ("type", part.type),
                        ("name", part.function.name if part.function else None))
            for key, value in metadata:
                if value is not None:
                    if call[key] is not None and call[key] != value:
                        raise ValueError("Tool-call metadata changed during streaming")
                    call[key] = value
            if part.function:
                call["arguments"] += part.function.arguments or ""
        if choice.finish_reason is not None:
            finish = choice.finish_reason
    if finish not in {"stop", "tool_calls"}:
        raise ValueError(f"Incomplete or unsuccessful generation: {finish!r}")
    if bool(pending) != (finish == "tool_calls"):
        raise ValueError("Tool calls and finish reason disagree")
    calls, ids = [], set()
    for index in sorted(pending):
        call = pending[index]
        if not call["id"] or not call["name"] or call["type"] != "function":
            raise ValueError("Incomplete function-call metadata")
        if call["id"] in ids:
            raise ValueError("Duplicate tool-call ID")
        ids.add(call["id"])
        calls.append({"id": call["id"], "type": "function", "function": {
            "name": call["name"], "arguments": call["arguments"]
        }})
    message = {"role": "assistant", "content": content, "tool_calls": calls or None}
    if saw_reasoning:
        message["reasoning_content"] = reasoning
    return Choice(index=0, message=ChatCompletionMessage(**message), finish_reason=finish)

Inside run_turn(), replace the request, empty-choice check, and choice = response.choices[0] assignment with the following. Continue with the existing message = choice.message line and the rest of the function:

with client.chat.completions.create(
    model="deepseek-flash",
    messages=messages,
    tools=TOOLS,
    tool_choice="auto",
    stream=True,
    extra_body={"thinking": {"type": "disabled"}},
) as stream:
    choice = collect_assistant(stream)

Keep the original indentation inside the loop. The collector checks for an accepted finish reason and complete call metadata. The dispatcher still parses and validates the reconstructed arguments. A transport exception propagates instead of triggering tool execution.

The helper does not inspect the raw SSE [DONE] marker, which the SDK iterator does not expose. It also deliberately rejects server web-tool events because those require different handling.

Local streaming fixtures covered interleaved calls, fragmented JSON, Unicode, empty fragments, separate reasoning, missing completion, rejected finish states, and serialization into the next SDK request. This is what protects the boundary between receiving fragments and executing a complete request.

Keep API Formats and Server Web Tools Separate

The runnable example uses Chat Completions. DeepSeek also supports the Responses API, whose function-tool payloads use different fields:

Part of the exchangeChat CompletionsResponses
Tool definitionFunction fields nested under function.Function fields such as name and parameters at the top level.
Requested callAn item in message.tool_calls.A function_call output item.
Returned resultA role: "tool" message with tool_call_id.A function_call_output input item with call_id.

DeepSeek’s Responses implementation is stateless: send the required conversation history instead of relying on previous_response_id. Check the compatibility guide before adapting code from another provider.

There is also a separate server-executed workflow. DeepSeek’s Web Tools guide documents deepseek_web_search and deepseek_read_url with deepseek-flash. DeepSeek performs those operations, and Chat Completions carries their history in server_tool_calls. They do not belong in the local inventory dispatcher.

Official DeepSeek server-side web tools documentation showing web search, deep thinking search and URL reading capabilities

When using a gateway or a locally hosted model, verify that provider’s supported model, tool parser, and protocol. The behavior of DeepSeek’s hosted endpoint does not automatically establish compatibility elsewhere.

Troubleshoot DeepSeek Tool Calls

Read the exact error and inspect the most recent assistant/tool exchange. The table combines the protocol rules above with checks for mistakes in your application’s loop.

SymptomWhat to checkNext step
HTTP 400 after enabling thinkingWas reasoning history lost?Preserve full assistant messages across requests and user turns.
HTTP 400 when forcing a functionIs thinking still enabled?Disable thinking or use auto.
Strict schema rejectedBeta URL, function-level strict flags, and schema keywords.Reduce to a supported schema and keep remaining validation locally.
Empty text with tool callsThe assistant is requesting an operation.Process the calls instead of treating empty text as the final answer.
JSON parsing failsIncomplete arguments, invalid JSON, or interrupted generation.Reject the incomplete response; return an argument error for a complete but invalid call.
A result is ignored or history is rejectedMissing assistant call or mismatched result ID.Retain the call message and attach each result to its original ID.
The model keeps calling toolsRepeated forcing, vague descriptions, or errors it cannot resolve.Allow a final response and enforce a bounded loop.
Only one requested result appearsCode that reads only the first call.Process every call and supply one matching result per call.

For general transport errors, DeepSeek’s error-code guide distinguishes authentication failures (401), insufficient API balance (402), rate limits (429), and server errors (500/503). Fix credentials or request structure before retrying those failures blindly.

Adapt the Example to Real Tools

Replace lookup_inventory() with a backend lookup only after the message loop works. Keep the boundary between generated input and application decisions explicit.

  • Expose specific functions. A function such as get_available_stock(sku) is easier to validate than a tool accepting arbitrary SQL or shell commands.
  • Use authenticated application context. Determine the user or tenant from your own session, then check access before returning records. Do not grant access because the model supplied an account ID.
  • Return useful, bounded results. Send the fields needed for the answer rather than an entire database record or document collection.
  • Handle tool failures explicitly. Return a concise failure result for expected problems. Add timeouts around real network tools; the model-request timeout does not cover your backend function.
  • Protect operations that change state. For purchases, messages, or updates, enforce your confirmation rules and deduplicate retries. A repeated request must not accidentally repeat the action.

Tool descriptions should explain when a function is useful and what its result means. For a real inventory tool, specify whether the quantity is available-to-sell stock, physical stock, or a cached estimate. Precise semantics help the model avoid turning a technically valid result into a misleading answer.

Treat text returned by a search or database as data. It should not become permission to call unrelated tools or override the application’s access rules.

Track Cost and Latency Across the Whole Loop

A custom-tool round trip commonly includes one model request to choose the tool and another to interpret its result. Additional tool rounds add model requests and backend work. Measure the complete interaction, including tool execution, rather than timing only the first response.

Record request count, finish reason, tool duration, and token usage. DeepSeek’s token-usage guide points to the returned usage data for actual consumption; current rates are on the pricing page.

Keep schemas focused and results concise. If you compact a long conversation, preserve the call/result relationships and the thinking history required for the requests you keep. Test the reconstructed history before relying on it.

Frequently Asked Questions

Are DeepSeek Tool Calls and Function Calling the Same Thing?

For the custom function workflow in this guide, yes. Function calling describes the interaction; tool_calls is the Chat Completions field containing the requested operations. Server-executed web tools use a separate workflow.

Do I Need an Agent Framework?

No. The example uses the OpenAI SDK plus ordinary Python functions. A framework can organize tools and state, but you still need to understand argument validation, message history, execution limits, and provider-specific fields.

Does JSON Output Enable Tool Calling?

No. JSON Output controls the format of the assistant’s text response. Function calling supplies a tool definition and an execution round trip. An answer that happens to contain a function name in JSON does not execute your function.

Can I Use the Same Example With deepseek-v4-pro?

DeepSeek’s model table lists Tool Calls support for both current hosted model IDs. You can change the example’s model to deepseek-v4-pro, keep its explicit mode setting, and test your prompts and tools. Similar API support does not guarantee identical tool choices or timing.

Why Did DeepSeek Answer Without Calling My Tool?

The example uses auto, which permits a direct answer. Improve the tool’s description and make the need for current application data clear. If your workflow requires a call, use a supported forced-choice setting with thinking disabled, then allow a final answer after returning the result.