Overview of Tool Calls

DeepSeek V4 fully supports OpenAI-compatible Function Calling (now referred to as Tool Calls), enabling AI to autonomously decide to call external tools to fulfill user requests. The model itself does not execute tools; instead, it generates structured call requests, which are actually executed by developer code, and the results are returned.

Basic Tool Call Example

from openai import OpenAI
import json
import os

client = OpenAI(
    api_key=os.environ.get('DEEPSEEK_API_KEY'),
    base_url='https://api.deepseek.com'
)

# Define tools
tools = [{
    "type": "function",
    "function": {
        "name": "get_weather",
        "description": "Get real-time weather information for a specified city",
        "parameters": {
            "type": "object",
            "properties": {
                "city": {"type": "string", "description": "City name"},
                "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]}
            },
            "required": ["city"]
        }
    }
}, {
    "type": "function",
    "function": {
        "name": "get_stock_price",
        "description": "Get real-time stock price",
        "parameters": {
            "type": "object",
            "properties": {
                "symbol": {"type": "string", "description": "Stock symbol"}
            },
            "required": ["symbol"]
        }
    }
}]

# Send request
response = client.chat.completions.create(
    model='deepseek-v4-flash',
    messages=[{"role": "user", "content": "What's the weather in Beijing today? Also check the AAPL stock price"}],
    tools=tools,
    tool_choice="auto"
)

# Process tool calls
msg = response.choices[0].message
if msg.tool_calls:
    for tool_call in msg.tool_calls:
        func_name = tool_call.function.name
        func_args = json.loads(tool_call.function.arguments)
        print(f"Calling: {func_name}({func_args})")

Parallel Tool Calls

When a user request involves multiple independent tools, DeepSeek V4 automatically calls all tools in parallel, significantly reducing round-trip latency. In the example above, the weather query and stock price query will be executed simultaneously. Advantages of parallel calls:

  • Only one API call is needed when requesting multiple tools
  • Total latency = max(single tool latency), not sum
  • Dependencies are handled automatically—dependent tools remain serial

Strict Mode

DeepSeek V4 supports the tool_choice parameter to precisely control tool calling behavior:

tool_choice valueBehavior
"auto" (default)The model decides autonomously whether to call tools
"required"Forces tool calling
"none"Prohibits tool calling, only text replies
{"type":"function","function":{"name":"xxx"}}Forces calling the specified function

Complete Node.js Example

import OpenAI from 'openai';

const openai = new OpenAI({
  baseURL: 'https://api.deepseek.com',
  apiKey: process.env.DEEPSEEK_API_KEY,
});

async function runWithTools(prompt) {
  const messages = [{ role: 'user', content: prompt }];

  const response = await openai.chat.completions.create({
    model: 'deepseek-v4-pro',
    messages,
    tools: [/* tool definitions */],
    tool_choice: 'auto',
  });

  const msg = response.choices[0].message;

  if (msg.tool_calls) {
    // Execute all tool calls
    for (const tc of msg.tool_calls) {
      const result = await executeTool(tc.function.name, JSON.parse(tc.function.arguments));
      messages.push({ role: 'tool', tool_call_id: tc.id, content: JSON.stringify(result) });
    }

    // Return results to the model to generate final reply
    const final = await openai.chat.completions.create({
      model: 'deepseek-v4-pro',
      messages,
    });
    return final.choices[0].message.content;
  }

  return msg.content;
}

Error Handling Best Practices

  • Tool execution failure: Return a clear error message (non-empty string) so the model knows the failure reason and can try alternative approaches
  • Timeout control: Set a timeout for each tool (recommended 30s), and return a timeout error after timeout
  • Result simplification: Results returned to the model should be concise, containing only necessary information to avoid exceeding context
  • Retry mechanism: Automatically retry once if tool execution fails

Multi-Tool Orchestration Patterns

PatternDescriptionUse Cases
Parallel CallsMultiple independent tools called simultaneouslyCheck weather + stock price + news
Serial DependencyTool B depends on the result of Tool AFirst search documents, then analyze results
Conditional BranchingChoose different tools based on user inputCustomer service: query order or query refund
Loop IterationCall repeatedly until condition is metPaginate to fetch full data