函数调用

函数调用允许模型为你定义的函数生成结构化参数。模型本身不会直接执行函数,而是输出 JSON,你可以在代码中据此调用该函数。

工作原理

  1. 定义工具 — 在请求中提供函数 schema
  2. 模型决策 — 模型决定是否调用一个或多个工具
  3. 由你执行 — 解析模型的工具调用并运行实际函数
  4. 返回结果 — 将函数输出回传给模型
  5. 模型响应 — 模型基于工具结果生成最终回答

定义工具

from openai import OpenAI

client = OpenAI(
    base_url="https://openapi.linkwo.ai/v1",
    api_key="YOUR_API_KEY"
)

tools = [
    {
        "type": "function",
        "function": {
            "name": "get_weather",
            "description": "Get the current weather for a given location",
            "parameters": {
                "type": "object",
                "properties": {
                    "location": {
                        "type": "string",
                        "description": "City name, e.g., Beijing"
                    },
                    "unit": {
                        "type": "string",
                        "enum": ["celsius", "fahrenheit"],
                        "description": "Temperature unit"
                    }
                },
                "required": ["location"]
            }
        }
    }
]

完整示例

import json

response = client.chat.completions.create(
    model="deepseek/deepseek-v4-pro",
    messages=[{"role": "user", "content": "What's the weather like in Shanghai?"}],
    tools=tools,
    tool_choice="auto"
)

message = response.choices[0].message

if message.tool_calls:
    for tool_call in message.tool_calls:
        function_name = tool_call.function.name
        function_args = json.loads(tool_call.function.arguments)

        # Execute the function
        if function_name == "get_weather":
            result = get_weather(**function_args)

        # Send result back to the model
        response = client.chat.completions.create(
            model="deepseek/deepseek-v4-pro",
            messages=[
                {"role": "user", "content": "What's the weather like in Shanghai?"},
                message,
                {
                    "role": "tool",
                    "tool_call_id": tool_call.id,
                    "content": str(result)
                }
            ]
        )

        print(response.choices[0].message.content)

工具选择

说明
auto由模型决定是否调用工具(默认)
none模型不会调用任何工具
required模型必须至少调用一个工具
{"type": "function", "function": {"name": "..."}}强制调用指定函数

多个工具

你可以在单次请求中定义多个工具:

tools = [
    {
        "type": "function",
        "function": {
            "name": "search_products",
            "description": "Search the product catalog",
            "parameters": {
                "type": "object",
                "properties": {
                    "query": {"type": "string"},
                    "category": {"type": "string"},
                    "max_price": {"type": "number"}
                },
                "required": ["query"]
            }
        }
    },
    {
        "type": "function",
        "function": {
            "name": "place_order",
            "description": "Place an order for a product",
            "parameters": {
                "type": "object",
                "properties": {
                    "product_id": {"type": "string"},
                    "quantity": {"type": "integer"}
                },
                "required": ["product_id", "quantity"]
            }
        }
    }
]

最佳实践

  • 编写清晰的描述 — 模型依赖函数和参数的描述来决定何时以及如何调用它们
  • 为受限值使用 enum — 尽可能用 enum 限定参数取值
  • 标注必填字段 — 始终将必要参数标记为 required
  • 优雅地处理错误 — 将错误信息作为工具结果返回,便于模型自我纠正
  • 控制工具数量 — 工具过多会让模型困惑,请保持聚焦

并行工具调用

部分模型支持在单次响应中调用多个工具。可遍历 message.tool_calls 来处理:

if message.tool_calls:
    tool_results = []
    for tool_call in message.tool_calls:
        result = execute_function(tool_call.function.name, json.loads(tool_call.function.arguments))
        tool_results.append({
            "role": "tool",
            "tool_call_id": tool_call.id,
            "content": str(result)
        })

相关文档