跳转到主要内容

函数调用(Tools)

函数调用(function calling)允许模型在合适的时候调用您定义的工具,并返回一个结构化请求,说明要调用哪个函数、传入哪些参数。随后由您的应用执行该函数并返回结果,模型再基于这些结果生成最终答案。这是构建智能体、检索系统以及接入外部系统(如天气、数据库、内部 API)的基础能力。 该接口与 OpenAI 保持兼容:您只需在请求中传入 tools 数组,从响应中读取 tool_calls,再将工具执行结果以 role: "tool" 消息回传即可。平台上的大多数对话模型都支持这一能力。

1. 使用场景

  • 实时数据:查询天气、价格、库存或其他实时信息。
  • 执行操作:从自然语言创建工单、发送消息或触发工作流。
  • 检索 / RAG:让模型自行决定何时查询知识库或搜索 API。
  • 智能体:串联多次工具调用以完成多步骤任务。

2. 工作原理

  1. 将用户消息和 tools 定义(即每个函数参数的 JSON Schema)一起发送给模型。
  2. 如果模型决定调用工具,响应中会返回 finish_reason: "tool_calls",并在 message.tool_calls 中给出调用信息。
  3. 由您的应用实际执行对应函数,再把 assistant 消息和一条带有匹配 tool_call_idrole: "tool" 消息追加到会话中。
  4. 再次调用 API,模型会结合工具执行结果生成最终答案。
可以通过 tool_choice 控制调用行为:"auto"(默认,由模型自行决定)、"none"(禁止调用工具),或强制调用某个特定函数。

3. 示例(OpenAI Python SDK)

import os
import json
from openai import OpenAI

client = OpenAI(
    api_key=os.getenv("API_KEY") or "<YOUR API KEY>",
    base_url="https://api.siflow.cn/model-api",
)

tools = [{
    "type": "function",
    "function": {
        "name": "get_weather",
        "description": "Get the current weather for a city",
        "parameters": {
            "type": "object",
            "properties": {"city": {"type": "string", "description": "City name"}},
            "required": ["city"],
        },
    },
}]

def get_weather(city: str) -> dict:
    # Replace with a real API call
    return {"city": city, "temp_c": 21, "condition": "Sunny"}

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

# 1) First call — the model decides to use the tool
resp = client.chat.completions.create(
    model="Qwen/Qwen3-32B",
    messages=messages,
    tools=tools,
    tool_choice="auto",
    max_completion_tokens=1024,
)

msg = resp.choices[0].message
if msg.tool_calls:
    messages.append(msg)  # append the assistant turn with tool_calls
    for call in msg.tool_calls:
        args = json.loads(call.function.arguments)
        result = get_weather(**args)
        # 2) Return the tool result, linked by tool_call_id
        messages.append({
            "role": "tool",
            "tool_call_id": call.id,
            "content": json.dumps(result),
        })

    # 3) Second call — the model writes the final answer
    final = client.chat.completions.create(
        model="Qwen/Qwen3-32B",
        messages=messages,
        max_completion_tokens=1024,
    )
    print(final.choices[0].message.content)
else:
    print(msg.content)

4. 注意事项

  • 参数 Schema:请用清晰的 namedescriptionparameters JSON Schema 描述每个函数;定义越清楚,模型调用越稳定。
  • 多次调用:一次响应中的 tool_calls 可能包含多个调用项;请逐一执行,并在再次调用 API 前,为每个调用补充对应的 role: "tool" 消息。
  • Token 预算:请为 max_completion_tokens 预留足够空间;对于带推理能力的模型,思考过程本身也会消耗预算。
  • 校验参数:参数由模型生成,因此在执行任何实际操作前请先校验。