Tool Calls 概述

DeepSeek V4 完整支持 OpenAI 兼容的 Function Calling(现称 Tool Calls),让 AI 能够自主决定调用外部工具来完成用户请求。模型本身不执行工具,而是生成结构化的调用请求,由开发者代码实际执行并将结果返回。

基础 Tool Call 示例

from openai import OpenAI
import json
import os

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

# 定义工具
tools = [{
    "type": "function",
    "function": {
        "name": "get_weather",
        "description": "获取指定城市的实时天气信息",
        "parameters": {
            "type": "object",
            "properties": {
                "city": {"type": "string", "description": "城市名称"},
                "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]}
            },
            "required": ["city"]
        }
    }
}, {
    "type": "function",
    "function": {
        "name": "get_stock_price",
        "description": "获取股票实时价格",
        "parameters": {
            "type": "object",
            "properties": {
                "symbol": {"type": "string", "description": "股票代码"}
            },
            "required": ["symbol"]
        }
    }
}]

# 发送请求
response = client.chat.completions.create(
    model='deepseek-v4-flash',
    messages=[{"role": "user", "content": "北京今天天气怎么样?顺便查一下 AAPL 股价"}],
    tools=tools,
    tool_choice="auto"
)

# 处理 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"调用: {func_name}({func_args})")

并行 Tool Calls

当用户请求涉及多个独立工具时,DeepSeek V4 会自动并行调用所有工具,大幅减少往返延迟。上面的示例中,天气查询和股价查询将同时执行。并行调用的优势:

  • 请求多个工具时只需一次 API 调用
  • 总延迟 = max(单个工具延迟),而非 sum
  • 自动处理依赖关系——有依赖的工具保持串行

严格模式(Strict Mode)

DeepSeek V4 支持 tool_choice 参数精确控制工具调用行为:

tool_choice 值行为
"auto"(默认)模型自主决定是否调用工具
"required"强制必须调用工具
"none"禁止调用工具,仅文本回复
{"type":"function","function":{"name":"xxx"}}强制调用指定函数

Node.js 完整示例

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_choice: 'auto',
  });

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

  if (msg.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) });
    }

    // 将结果返回给模型生成最终回复
    const final = await openai.chat.completions.create({
      model: 'deepseek-v4-pro',
      messages,
    });
    return final.choices[0].message.content;
  }

  return msg.content;
}

错误处理最佳实践

  • 工具执行失败:返回明确的错误信息(非空字符串),让模型知道失败原因并尝试备选方案
  • 超时控制:每个工具设置超时(建议 30s),超时后返回超时错误
  • 结果精简:返回给模型的结果应精简,只包含必要信息,避免超出上下文
  • 重试机制:工具执行失败时可以自动重试一次

多工具编排模式

模式说明适用场景
并行调用多个独立工具同时调用查天气+查股价+查新闻
串行依赖工具B依赖工具A的结果先搜索文档,再分析结果
条件分支根据用户输入选择不同工具客服:查询订单 or 查询退款
循环迭代反复调用直到满足条件分页获取全量数据