Skip to content

工具调用(Function Calling)

部分模型支持 OpenAI 风格的工具调用(也称函数调用)。当模型认为需要外部信息时,会在回复中返回 tool_calls,由您执行工具后再把结果回传给模型。

提示

不同模型对工具调用的支持程度不同。如果模型不支持,可能会直接忽略 tools 字段或返回错误。建议先用少量请求做验证。

一次完整流程

  1. 发送 tools 描述,提示模型可以调用哪些函数
  2. 模型返回 tool_calls
  3. 您执行对应函数,把结果以 role: "tool" 回传
  4. 再次请求,让模型基于工具结果生成最终回答

示例(JavaScript)

javascript
const BASE_URL = "https://ask.ling.rest/api/v1";
const API_KEY = "YOUR_API_KEY_HERE";
const MODEL = "YOUR_MODEL_ID_HERE";

async function callOpenAI(body) {
  const res = await fetch(`${BASE_URL}/chat/completions`, {
    method: "POST",
    headers: {
      "Authorization": `Bearer ${API_KEY}`,
      "Content-Type": "application/json",
    },
    body: JSON.stringify(body),
  });
  if (!res.ok) throw new Error(`HTTP ${res.status}: ${await res.text()}`);
  return res.json();
}

function getWeather({ city }) {
  return { city, weather: "sunny", temperatureC: 26 };
}

async function main() {
  const tools = [
    {
      type: "function",
      function: {
        name: "get_weather",
        description: "查询某城市天气",
        parameters: {
          type: "object",
          properties: { city: { type: "string" } },
          required: ["city"],
        },
      },
    },
  ];

  const first = await callOpenAI({
    model: MODEL,
    messages: [{ role: "user", content: "北京天气怎么样?" }],
    tools,
  });

  const msg = first.choices?.[0]?.message ?? {};
  const toolCalls = msg.tool_calls ?? [];
  if (toolCalls.length === 0) {
    console.log(msg.content ?? "");
    return;
  }

  const toolResults = toolCalls.map(tc => {
    const args = JSON.parse(tc.function.arguments || "{}");
    const result = getWeather(args);
    return {
      role: "tool",
      tool_call_id: tc.id,
      content: JSON.stringify(result),
    };
  });

  const second = await callOpenAI({
    model: MODEL,
    messages: [
      { role: "user", content: "北京天气怎么样?" },
      msg,
      ...toolResults,
    ],
  });

  console.log(second.choices?.[0]?.message?.content ?? "");
}

main().catch(console.error);

建议

  • 工具返回内容尽量结构化(JSON),方便模型理解
  • 工具名称保持简短、语义清晰
  • 对工具入参做校验,避免模型传入异常参数导致崩溃