AI Agent / 系统课时
让模型生成结构化工具调用
让模型生成结构化工具调用
这一节解决“模型知道有哪些工具之后,如何把意图变成可执行请求”的问题。你会把 Python 工具绑定到聊天模型,读取 AIMessage.tool_calls 中的名称、参数和调用 ID,并据此把状态路由到工具执行分支,而不是从自然语言里猜模型想做什么。
学习目标
- 使用
bind_tools()把工具及其参数模式暴露给模型。 - 读取
tool_calls的name、args与id,理解它只是调用请求。 - 根据是否存在工具调用稳定地选择
tools或结束分支。
把工具描述绑定给模型
bind_tools() 不会执行函数,它做的是把工具名称、说明和参数 Schema 交给模型。模型若决定调用工具,会返回 AIMessage,并把结构化请求放入 tool_calls。因此,智能体不需要解析“请帮我调用 multiply”这类文本,只需要检查结构化字段。
一条典型调用包含三类信息:name 指定目标工具,args 是已经按 Schema 组织的参数,id 是本次调用的关联标识。后续工具执行完成后,ToolMessage.tool_call_id 必须与这个 ID 对上,模型才能知道哪条结果属于哪次请求。

读取 tool_calls 并验证分支
下面用 ChatOpenAI 做一个可重复的结构验证。示例假设环境已经安装 langchain-openai 与 langchain-core,并配置了 OPENAI_API_KEY。为了让结果稳定,第一条请求强制选择 multiply,第二条明确禁止工具;真正的智能体通常改用 tool_choice="auto" 让模型自行判断。
from typing import Literal
from langchain_core.messages import AIMessage
from langchain_core.tools import tool
from langchain_openai import ChatOpenAI
@tool
def multiply(a: int, b: int) -> int:
"""Multiply two integers."""
return a * b
def route_after_model(message: AIMessage) -> Literal["tools", "end"]:
# 路由只依赖结构化调用,不解析 message.content。
return "tools" if message.tool_calls else "end"
model = ChatOpenAI(model="gpt-5-nano")
forced_model = model.bind_tools(
[multiply],
tool_choice="multiply",
strict=True,
)
no_tool_model = model.bind_tools(
[multiply],
tool_choice="none",
strict=True,
)
tool_response = forced_model.invoke("请计算 17 × 23。")
plain_response = no_tool_model.invoke("只回复 OK。")
print("forced calls:", len(tool_response.tool_calls))
call = tool_response.tool_calls[0]
print("name:", call["name"])
print("args:", call["args"])
print("id exists:", bool(call.get("id")))
print("forced route:", route_after_model(tool_response))
print("plain calls:", len(plain_response.tool_calls))
print("plain route:", route_after_model(plain_response))预期输出
forced calls: 1
name: multiply
args: {'a': 17, 'b': 23}
id exists: True
forced route: tools
plain calls: 0
plain route: end工具调用 ID 的实际值由模型提供方动态生成,因此示例只验证它是否存在,不写死具体 <ID>。
让模型自行决定何时调用
进入智能体循环后,通常把绑定方式改成 tool_choice="auto",或者直接省略该参数使用提供方默认策略。此时“是否调用工具”成为模型决策的一部分:需要外部数据、确定性计算或副作用操作时倾向产生 tool_calls;普通对话则可以直接返回文本。
路由判断仍然不应依赖回答文字。最稳妥的规则是:最后一条 AIMessage 的 tool_calls 非空就进入工具节点,为空就结束或进入其他非工具分支。这样即使模型的自然语言风格变化,控制流也不会受影响。
当你能稳定区分“模型回答文本”和“模型发出工具请求”后,后续编排只需围绕这份结构化协议工作:模型负责决定调用,图中的路由负责分支,工具节点负责执行。