Tbye.
AI··7 min read

Tool Calling 实战 - 让 Agent 自主调用外部工具

如何让 AI Agent 自己决定何时调用 API、查询数据库、生成图表?深入理解 Tool Calling 机制,构建能自主行动的智能助手。

Tool Calling 实战 - 让 Agent 自主调用外部工具

一句话概括

Tool Calling(工具调用)让 AI 不再只会"说话",而是能主动决定何时调用外部工具完成实际任务。


问题:AI 只会聊天,干不了实事

传统的 LLM 对话有个致命缺陷:它只能生成文字,无法直接操作外部系统

当用户问:"帮我查一下北京明天的天气",AI 只能这样回答:

"抱歉,我无法实时获取天气信息,请访问天气网站查询。"

这就像雇了个助手,他只会说"您可以自己去做",完全没用。

我们需要的是:AI 能自己判断需要调用天气 API,拿到数据,然后告诉你结果。


Tool Calling 如何工作?

核心流程

用户问:"查北京明天天气",AI 判断需要调用 get_weather 函数,系统执行后返回天气数据,AI 整合信息回答用户。

关键在于:AI 自己决定何时、调用哪个工具、传什么参数

技术原理

  • 定义工具:告诉 AI 有哪些函数可用、参数格式
  • AI 决策:模型判断是否需要调用工具
  • 执行调用:你的代码真正执行函数
  • 返回结果:把结果塞回对话,AI 继续处理

快速上手:构建天气助手

定义工具

const tools = [
  {
    type: "function",
    function: {
      name: "get_weather",
      description: "获取指定城市的天气信息",
      parameters: {
        type: "object",
        properties: {
          city: { type: "string" },
          date: { type: "string" },
        },
        required: ["city", "date"],
      },
    },
  },
]

关键点:description 要清晰,AI 靠这个判断何时调用。

处理 Tool Call

const response = await openai.chat.completions.create({
  model: "gpt-4o",
  messages: [{ role: "user", content: "北京明天天气?" }],
  tools: tools,
})
 
const toolCall = response.choices[0].message.tool_calls?.[0]
 
if (toolCall) {
  const args = JSON.parse(toolCall.function.arguments)
  const result = await get_weather(args.city, args.date)
 
  const finalResponse = await openai.chat.completions.create({
    model: "gpt-4o",
    messages: [
      { role: "user", content: "北京明天天气?" },
      response.choices[0].message,
      {
        role: "tool",
        tool_call_id: toolCall.id,
        content: JSON.stringify(result),
      },
    ],
  })
 
  console.log(finalResponse.choices[0].message.content)
}

高级场景:多工具协同

智能数据分析助手

用户问:"帮我分析一下上个月的销售数据,并生成趋势图。"

AI 需要:查询数据库 → 生成图表 → 计算趋势

工具定义:

const tools = [
  {
    type: "function",
    function: {
      name: "query_database",
      description: "从数据库查询销售数据",
      parameters: {
        type: "object",
        properties: {
          table: { type: "string" },
          month: { type: "string" },
        },
      },
    },
  },
  {
    type: "function",
    function: {
      name: "generate_chart",
      description: "生成数据可视化图表",
      parameters: {
        type: "object",
        properties: {
          data: { type: "array" },
          type: { type: "string" },
        },
      },
    },
  },
]

AI 会自动编排:先查数据 → 生成图表 → 整合结果回答。


最佳实践

工具描述要精准

  • 不好:description 写 '获取天气'
  • 好:description 写 '获取指定城市未来3天的天气预报,包括温度、湿度、风力'

AI 依赖描述判断是否调用,模糊的描述会导致误调用或不调用。

参数校验

虽然 JSON Schema 做了约束,但 AI 可能生成非预期值,代码层再验证一次。

function get_weather(city: string, date: string) {
  if (!["今天", "明天", "后天"].includes(date)) {
    throw new Error("date 参数错误")
  }
  // 实际调用天气 API
}

错误处理

try {
  const result = await get_weather(args.city, args.date)
} catch (error) {
  return { error: error.message }
}

把错误信息返回给 AI,让它重新处理。


框架支持

Vercel AI SDK

import { openai } from "@ai-sdk/openai"
import { generateText } from "ai"
 
const { text } = await generateText({
  model: openai("gpt-4o"),
  prompt: "北京明天天气?",
  tools: {
    getWeather: {
      description: "获取天气信息",
      parameters: z.object({
        city: z.string(),
        date: z.string(),
      }),
      execute: async ({ city, date }) => {
        return await fetch("...")
      },
    },
  },
})

优势:自动处理工具调用流程,支持流式响应 + Tool Calling。


实战案例:智能客服机器人

需求:用户咨询订单状态、退款、修改地址。

工具定义

  • query_order:查询订单状态
  • request_refund:发起退款申请
  • update_address:修改收货地址

对话流程示例

用户问:"帮我查一下订单号12345的物流",AI 调用 query_order,系统返回已发货状态,AI 回复:"您的订单已发货,顺丰单号 SF1234567890"。

用户说:"帮我改一下收货地址",AI 回复:"请提供新的收货地址",用户提供地址后,AI 调用 update_address,成功后回复:"地址已修改成功"。

关键:AI 自己判断何时需要工具、何时需要追问用户、何时直接回答。


总结

Tool Calling 让 AI 从"对话系统"升级为"行动系统"

  • 自主决策:AI 判断何时需要工具
  • 参数推理:从用户输入中提取调用参数
  • 多工具编排:自动组合多个工具完成复杂任务
  • 错误恢复:调用失败后重试或请求用户帮助

下一步:结合 Durable Execution + Multimodal + Tool Calling,你就能构建真正可靠、全能的 AI Agent。

明日预告:《Agent 的长期记忆 - RAG 与向量数据库实战》,解决 AI "健忘症"问题。


推荐阅读

  • OpenAI Function Calling 官方文档
  • Vercel AI SDK Tools
  • 第1篇:为什么 Agent 需要独立的基础设施?