切换语言

函数调用

通过函数定义让模型调用外部工具与 API。

函数调用让模型能够与外部工具和 API 交互。你定义可供模型调用的函数,模型返回结构化参数,由你在本地执行。

工作流程

tools 数组中用 JSON Schema 描述参数。
发送请求 — 模型可能返回 tool_calls 而非普通文本。
使用返回的参数在本地执行函数。
将执行结果再发回模型,生成最终回答。

完整示例

1. 初始化客户端

from openai import OpenAI
import json

client = OpenAI(
    base_url="https://api-inference.bitdeer.ai/v1",
    api_key="YOUR_API_KEY",
)

2. 定义函数

def get_weather(location: str) -> str:
    """Simulate fetching weather data."""
    return json.dumps({"location": location, "temperature": "22°C", "condition": "sunny"})

3. 携带 tools 发送请求

tools = [
    {
        "type": "function",
        "function": {
            "name": "get_weather",
            "description": "Get the current weather for a location",
            "parameters": {
                "type": "object",
                "properties": {
                    "location": {
                        "type": "string",
                        "description": "City name, e.g. 'San Francisco, CA'",
                    }
                },
                "required": ["location"],
            },
        },
    }
]

messages = [{"role": "user", "content": "What's the weather in Tokyo?"}]

response = client.chat.completions.create(
    model="deepseek-ai/DeepSeek-V4-Pro",
    messages=messages,
    tools=tools,
)

tool_call = response.choices[0].message.tool_calls[0]
print(tool_call.function.name)       # "get_weather"
print(tool_call.function.arguments)  # '{"location": "Tokyo"}'

4. 执行并把结果写回对话

messages.append(response.choices[0].message)

function_args = json.loads(tool_call.function.arguments)
result = get_weather(**function_args)

messages.append({
    "tool_call_id": tool_call.id,
    "role": "tool",
    "content": result,
})

final_response = client.chat.completions.create(
    model="deepseek-ai/DeepSeek-V4-Pro",
    messages=messages,
)

print(final_response.choices[0].message.content)
# "The weather in Tokyo is currently 22°C and sunny."

工具 schema 参考

{
  "type": "function",
  "function": {
    "name": "function_name",
    "description": "What the function does",
    "parameters": {
      "type": "object",
      "properties": { },
      "required": ["param1"]
    },
    "strict": false
  }
}
字段类型说明
namestring函数名(a-z、A-Z、0-9、下划线/连字符,最长 64)
descriptionstring帮助模型判断何时调用
parametersobject描述参数的 JSON Schema
strictbooleantrue 时模型更严格遵循 schema

最后更新于

本页目录

函数调用 · Bitdeer AI