Skip to content
目标:深入原理✓ 来源核实于 2026-11-24Function CallingAgent Loop

Tool Calling:让模型调用你的函数 ​

它是 Agent 编排、computer use、MCP 的共同基础。链路「编排」和「Agent 编排」都建立在这一层上。

核心概念 ​

  • 工具定义:名称 + 描述 + 参数的 JSON Schema。模型只「决定调用哪个工具、传什么参数」,真正执行的是你的代码。
  • 消息循环:模型返回工具调用请求 → 你执行 → 把结果作为新消息回传 → 模型继续,直到不再请求工具。
  • 并行工具调用:一次回复里可以包含多个工具调用,你可以并发执行后一次性回传全部结果。
  • tool_choice:控制模型是自动决定、必须调用某个工具,还是禁止调用。
  • strict 模式:在工具定义上设置 strict: true,让参数严格符合 schema(Anthropic、OpenAI 都支持)。

原理:一轮完整的消息循环(Anthropic Messages API 形态) ​

user: "查一下订单 123 的状态"
assistant: [tool_use id=tu_1 name=get_order input={"order_id":"123"}]    ← stop_reason = "tool_use"
user:      [tool_result tool_use_id=tu_1 content="已发货"]               ← 你执行后回传
assistant: "订单 123 已发货。"                                            ← stop_reason = "end_turn"
  • 每个 tool_result 必须用 tool_use_id 对应到请求,否则接口报错。
  • 工具执行出错时,不要抛异常中断循环,而是回传 is_error: true 和错误信息,让模型自己决定重试或换方案。
  • OpenAI Responses API 的形态是 function_call / function_call_output 项,用 call_id 对应,原理相同。

实战用法:不依赖框架的最小 tool loop ​

python
import asyncio, json

MAX_STEPS = 8
TOOLS = {"get_order": get_order, "search_docs": search_docs}   # 你的 async 函数

async def run_tool(block):
    fn = TOOLS.get(block.name)
    if fn is None:
        return {"type": "tool_result", "tool_use_id": block.id, "is_error": True, "content": f"未知工具 {block.name}"}
    try:
        result = await asyncio.wait_for(fn(**block.input), timeout=20)
        return {"type": "tool_result", "tool_use_id": block.id, "content": json.dumps(result, ensure_ascii=False)}
    except Exception as e:  # 错误回传给模型,而不是中断
        return {"type": "tool_result", "tool_use_id": block.id, "is_error": True, "content": str(e)}

async def agent(messages, tool_specs):
    for step in range(MAX_STEPS):
        resp = await client.messages.create(model=MODEL, max_tokens=2048, tools=tool_specs, messages=messages)
        messages.append({"role": "assistant", "content": resp.content})
        if resp.stop_reason != "tool_use":
            return resp
        calls = [b for b in resp.content if b.type == "tool_use"]
        results = await asyncio.gather(*(run_tool(c) for c in calls))   # 并行执行
        messages.append({"role": "user", "content": list(results)})
    raise NeedHumanReview(f"超过最大步数 {MAX_STEPS}")

要点:最大步数、单个工具超时、错误回传、并行执行、每一步写追溯日志。

常见坑 ​

  1. 工具描述太简略:模型靠描述决定何时调用,写清「什么时候用、什么时候不要用、参数格式示例」。
  2. 工具太多:几十个工具会降低选择准确率并占上下文。按任务分组、按需加载,或用路由先缩小范围。
  3. 把危险操作直接暴露成工具:删除、付款、发消息类工具应走人工确认(见「人工接管」)。
  4. 没有最大步数:模型陷入循环,成本失控。
  5. 工具结果太长:直接把整页 HTML 回传会撑爆上下文,先截断或摘要。

高频面试题 ​

  1. 画出 tool calling 的完整消息循环。stop_reason 有哪些值?
  2. 并行工具调用怎么执行和回传?
  3. 工具执行失败时你怎么处理?为什么不直接抛异常?
  4. 如何防止 Agent 无限循环、成本失控?
  5. Tool calling 和 MCP 是什么关系?(MCP 是把工具「标准化地提供出来」的协议,模型侧仍通过 tool calling 使用)

与我项目的关联 ​

信息来源 ​

Vin Amory · AI 开发 × 内容创作 · 技术内容以文末「信息来源」中的官方文档为准