核心结论:Agent 调用工具不是「模型自己用代码调函数」,而是一次请求—决策—执行—回传—再生成的多轮闭环。模型只负责「决定用哪个工具、填什么参数」,真正的执行在应用程序侧完成。理解这条链路,是做好 Agent 工程的第一课。
目录
- 一句话抓住本质:模型只是「指挥官」
- 工具调用链路:一次完整的四/五阶段闭环
- 工具定义(schema)写得好,模型才调得对
- 参数校验:模型会「骗」你,你必须校验
- 可运行的完整示例:Python + OpenAI Function Calling
- 常见坑与对照表:症状 → 原因 → 解法
- 什么时候不用工具调用
- 总结:把模型当「决策者」,把应用当「执行者」
1. 一句话抓住本质:模型只是「指挥官」
很多人以为 Agent 调用工具是「大模型长了手,自己去执行」。不是。模型本质是一个纯粹的推理引擎,它没有权限、也没有能力真的去访问数据库或调 API。它只做一件事:基于你喂给它的工具清单,输出一个结构化的「调用指令」——用哪个工具、参数填什么。
真正执行这个指令的是你(应用程序)。这就好比:AI 是项目经理(generates a plan),你才是执行团队(executes the plan)。理解这个角色分工,后面所有环节才不会乱。
比喻一下 🎭:模型像一支笔,它只能「写出」调用某工具的指令;而你像「执行密钥」,只有你能把这张指令翻译成真实的系统动作。模型负责"想",应用负责"做"。
2. 工具调用链路:一次完整的四/五阶段闭环
不同文档把工具调用拆成四步或五步,本质是同一件事。以最常见的四阶段闭环为例,我用一个「查天气」的例子串起来:
① 请求(Request):应用程序把用户的提问、上下文,连同「可用工具清单」一起发给模型。工具清单就是你预先定义好的 JSON schema,比如「get_weather(城市)」「search_docs(关键词)」。
② 决策(Decide):模型分析后做决定——是直接回答,还是需要调用工具。如果它判定需要工具,就输出一个结构化对象,包含 tool name(工具名)和 arguments(参数),例如:
{"name": "get_weather", "arguments": {"city": "北京"}}
③ 执行(Execute):由应用程序来执行。应用层根据工具名找到对应的执行函数,把参数填进去,真实地跑一遍,拿到结果(如「25℃ 晴」)。
④ 回传(Return):应用把工具执行结果以 tool 角色的消息回传给模型。
⑤ 再生成(Finalize):模型基于这个结果,生成最终的自然语言回答,或者继续发起下一轮工具调用(当任务需要连续多步时)。
这是一个循环:模型「想」→ 应用「做」→ 结果「喂回」→ 模型「再想」。Agent 能不能完成复杂任务,就看这个循环能不能稳定转起来。火山引擎的 docs 把它统一称为「五个阶段」,微软把「定义函数」也算作前置步骤,本质一致。
3. 工具定义(schema)写得好,模型才调得对
这是整个工具调用里最容易被忽视、但最影响效果的一环。因为模型判断「什么时候该用这个工具、参数填什么」,唯一依据就是你写的工具描述(description)。描述写得模糊,模型就会瞎猜,要么不调用,要么传错参数。
一个规范的 tool schema 至少包含四要素(以 Anthropic 的规范为例):
写 description 的黄金法则:要准确,不要含糊。用动词开头,写清「当用户请求 X 时使用;当用户只是想聊天时不要用」。例如:
- ❌ 查询天气
- ✅ 当用户问到某地天气或温度时调用;仅聊天不调用。参数 city 为城市名,如"北京"。返回 温度、天气状况。
实测表明,description 是影响工具调用准确率的最大单一因素——它几乎是模型判断「何时调用、参数怎么填」的唯一上下文。所以你花在打磨 description 上的功夫,回报远高于调整 prompt。
此外,工具名要语义化:search_docs 比 docs 好,因为模型能从中读懂意图。参数要在 schema 里写清类型、是否必填、单位、枚举值。Vague schema 会诱导模型编造参数(invents invented arguments)或选错工具。
4. 参数校验:模型会「骗」你,你必须校验
这是新人最容易踩的坑:拿到模型输出的 arguments 就直接执行。千万不要。模型输出的参数是基于文本生成的猜测,不是真实可靠的数据。它可能:
- 把字符串列表 ["P001","P002"] 输出成 "P001,P002"(类型错误)
- 把数字输出成字符串 "25" 而不是 25
- 编造一个你根本不存在的城市名
- 漏掉必填参数
所以在真正执行前,必须做一层参数校验:用 JSON Schema 校验参数结构、类型、必填项;对高危操作(删除、发送、转账)再做二次确认,涉及用户身份、租户范围还要校验权限。这一步决定了你的 Agent 是「可靠助手」还是「会闯祸的玩具」。
一个原则:模型输出永远是「候选参数」,经过你的校验与清洗后才变成「可执行参数」。这也是为什么我之前在 AI07 里专门写了防护层——校验是工具调用链路里不可或缺的一环。
5. 可运行的完整示例:Python + OpenAI Function Calling
下面给一段复制粘贴就能跑的完整代码。用 OpenAI 兼容接口演示「查天气」工具调用的完整闭环。运行前装上 pip install openai,并设置你的 API key。
import json
from openai import OpenAI
client = OpenAI(api_key="你的API-KEY")
# 1. 定义工具(schema)——描述写得越准,模型调得越对
tools = [
{
"type": "function",
"function": {
"name": "get_weather",
"description": "当用户问到某地天气或温度时调用;仅聊天不调用。"
"参数 city 为城市名,如'北京',返回温度与天气状况。",
"parameters": {
"type": "object",
"properties": {
"city": {"type": "string", "description": "城市名,如'北京'"}
},
"required": ["city"]
}
}
}
]
# 2. 模拟真实执行的工具函数(模型自己不会跑,由应用来跑)
def get_weather(city: str) -> str:
"""真实的后端查询,这里用假数据代替。"""
return f"{city}今天25℃,晴"
# 3. 用户发问,应用把工具清单一起发给模型
messages = [{"role": "user", "content": "北京今天天气怎么样?"}]
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=messages,
tools=tools,
tool_choice="auto", # auto=模型自己决定是否调用
)
# 4. 模型决定调用工具,输出结构化指令
msg = response.choices[0].message
if msg.tool_calls:
call = msg.tool_calls[0]
print("模型要调用工具:", call.function.name)
# 5. 应用侧拿到参数,先校验(这里演示最简校验),再真实执行
args = json.loads(call.function.arguments)
if "city" not in args or not isinstance(args["city"], str):
raise ValueError("参数校验失败:city 缺失或类型错误")
result = get_weather(args["city"]) # 6. 执行工具
# 7. 把执行结果以 tool 角色回传给模型
messages.append(msg) # 模型的选择也进上下文
messages.append({
"role": "tool",
"tool_call_id": call.id,
"content": result,
})
# 8. 模型基于结果生成最终自然语言回答
final = client.chat.completions.create(
model="gpt-4o-mini",
messages=messages,
tools=tools,
)
print("最终回答:", final.choices[0].message.content)
else:
# 模型判定不需要工具,直接回答
print("直接回答:", msg.content)
运行逻辑:模型输出 get_weather 指令 → 应用校验参数 → 真实执行 get_weather("北京") → 把 25℃晴 回传 → 模型生成「北京今天25℃,晴」。整个闭环里,模型没有真正调函数,是应用在调。
6. 常见坑与对照表:症状 → 原因 → 解法
工具调用的错误大多有迹可循。下面是症状 → 原因 → 解法对照表,出问题时优先对照排查:
7. 什么时候不用工具调用
不是所有场景都需要工具调用。工具调用有延迟、有成本、有出错风险,能用模型直接回答就别勉强上工具。
- 该用:需要实时数据、外部系统、业务内部信息、执行真实动作时。
- 不该用:纯知识问答、语义理解、文本生成这类模型擅长的任务——直接回答更快、更稳、更便宜。
判断依据:问自己「这个问题,模型不查外部数据能答对吗?」。如果能,就别加工具。把工具调用留给那些「模型自己答不了、必须依赖外部信息或动作」的场景,Agent 才会又稳又省。
8. 总结:把模型当「决策者」,把应用当「执行者」
工具调用的本质,是模型与应用之间的分工协作:
- 模型:负责理解意图、选择工具、生成参数(决策者)
- 应用:负责校验参数、真实执行、回传结果(执行者)
你要做的是:把工具描述打磨到让模型一眼看懂该不该用、参数怎么填;在执行前做好参数校验与高危二次确认;并让模型输出始终是候选参数,经过你的清洗才落地。想更深入了解工具调用出错的工程防线,可以回看 AI07 防护层 与 AI06 误调用问题排查。
判断收尾:当任务需要实时数据、外部系统或真实动作时,用工具调用;当模型能直接答对时,别上工具——工具是能力扩展,不是万能钥匙。
专栏介绍:本专栏《AI Agent 工具》专注 Agent 工具调用的落地实践,从工具调用机制、参数校验、误调用排查一路讲到防护层实现,每篇都配一段可直接运行的代码,每周更新一篇。想按顺序读完,可在专栏页订阅。
本文由 AI图鉴自动抓取并翻译,版权归原作者所有;如需查看原文请点下方链接。
Core conclusion: Agent's call tool is not a "model-to-code function" but a multi-cycle closed loop generated by a request-to-decision-to-exercise-to-return. The model is only responsible for "determinating which tools and parameters to use" and the real implementation is done on the side of the application. Understanding this link is the first lesson in the Agent project.
Contents
- One sentence captures the essence: the model is only the commander.
- tool call link: a complete IV/V closure
- The tool definition is right.
- Parameter verification: The model's a lie. You have to check.
- Full example of running: Python + Open AI Fund Calling
- Common pits and control tables: symptoms cause solution
- When do you need tool call?
- Summarizing: using models as "decision makers" and applications as "implementers"
1. One sentence captures the essence: the model is a "commander"
Many people think that Agent's call tool is "LLM has long hands, go do it." Nope. The model is in essence a purely reasoned engine that does not have permission or the ability to actually access databases or transfer API. It does only one thing: to export a structured "call order" based on the list of tools you feed it -- which tool, which parameters to fill.
You're the one who's actually doing this. This is like: AI is the project manager and you are the executive team. Understanding this division of roles will keep everything that follows.
For example, the model is like a pen, which can only "write" a command calling a tool, and you're like "implement a key" and you're the only one who can translate it into a real system action. Models are for thinking, applications for doing.
2. tool call link: a complete IV/V closure
Different documents tear tool call into four or five steps, essentially the same thing. For example, the most common four-stage closed loop, I used an example of "the weather":
1 Request (Request): The application distributes user questions, context, along with the list of tools available, to the model. The list of tools is a predefined JSON scheme, such as "get weather" and "search docs."
2 Decision-making (Decide): a model analysis is followed by a decision — a direct answer or a call to a tool. If it determines that tools are needed, output a structured object containing tool name (toolname) and arguments (parameters), e.g.:
"name": "get weather", "arguments": "city": "Beijing"
3 Implementation (Execute): by application. The application layer finds the corresponding performance function according to the toolname, fills in the parameters, runs back and gets the results (e.g. "25°C clear").
4 Return (Return): Apply to the model information on the results of the tool's execution as a tool role.
5 Generating (Finalize): The model is based on this result, generating the final natural language answer or continuing the next round of tool call (when the task requires multiple steps).
This is a cycle: the model "want" to apply "do" and the result "feed back" to the model "think again." Agent's ability to do a complex task depends on whether the cycle is stable. Volcengine's docs refer to it as a single "five-stage" and Microsoft counts the "defining function" as a pre-emptive step, essentially the same.
3. Tool definition (schema) is well written before the model is right
This is one of the most easily neglected, but most influential, links in the entire tool call. The only basis for this is the tool description you wrote. The description is vague and the model is guessed, either it is not called or the parameters are passed wrong.
A norm tool schemea contains at least four elements (in the case of Anthropic regulation):
Writes the golden rule of description: be precise, not ambiguous. Start with the verb with the words "used when the user requests X; not when the user wants to chat". For example:
- Check the weather.
- Call when the user asks about weather or temperature; only chats are not called. Parameter city is city name, like "Beijing". Return to temperature, weather conditions.
Based on measurements, description is the single largest factor affecting the accuracy rate of tool call - It's almost the only context model that judge when to call, how to fill the parameters. So you're spending much more effort on grinding, much more on adjustment.
In addition, the tool name is semantic: the search docs are better than the docs because the model can read the intent. Parameters are to be written in the schema for type, mandatory, unit, item count values. Vague schema induces modelling parameters (invents invented arguments) or wrong tools.
4. Parameter verification: The model is a lie. You have to verify.
It's the easiest pit for a new man to step on: get the models out of the arguments and do it directly. Never. Model output parameters are based on text-generated guesses and are not authentic data. It could:
- Put the string list ["P001", "P002"] into "P001, P002" (type error)
- Put the number out into string "25" instead of 25.
- Make up a city you don't exist. First Name
- It's missing the parameters.
Thus, before real implementation, one layer of parameters has to be verified: the JSON Schema verification of the parameter structure, type, required entries; and a second confirmation of high-risk operations (deleting, sending, transferring) involving the identity of the user, the range of tenants and the verification of permission. This step determines whether your Agent is a "reliable assistant" or a "crash toy".
One principle: Model output is always a "nominal parameter" and becomes an "executable parameter" after your verification and cleaning. That's why I used to write in AI07. - Validation is an indispensable link in the tool call link.
5. Full and runable example: Python + Open AI Fund Calling
Here's a copy of the complete code that can run. tool call shows the full closed ring of the "Chattering the Weather" with an Open AI compatible interface. Run the prep load openai and set your API key.
import json
from openai import OpenAI
== sync, corrected by elderman ==
#1 Definition tool (schema) — the more accurate the description, the better the model is
tools = [
{
"type": "function",
"function": {
"name": "get_weather",
"Description": "Call when the user asks about weather or temperature; only chats are not called."
"parameter city is city name, like 'Beijing', returns temperature and weather conditions. " I don't know.
"parameters": {
"type": "object",
"properties": {
"city": "type": "string", "description": "city name, like'Beijing"
},
"required": ["city"]
}
}
}
]
2. Tool functions to simulate real execution (models do not run by themselves, run by application)
def get_weather(city: str) -> str:
""The real back-end query, here's the fake data instead."
Turn f "City" today at 25°C, clear."
# 3. User queries, use to send the tool list to the model
== sync, corrected by elderman == @elder man
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=messages,
tools=tools,
# Autumn #
)
# 4. Model decision call tool, output structured command
msg = response.choices[0].message
if msg.tool_calls:
call = msg.tool_calls[0]
Print("Model to Call Tool:", call.finance.name)
# 5. Apply side to get the parameters, check them first (here shows the most concise) and then execute them honestly
args = json.loads(call.function.arguments)
if "city" not in args or not isinstance(args["city"], str):
Rice ValueError ("parameter verification failed: city missing or type error")
#6 Implementation tool
# 7. Pass the results back to the model with the tool role
Messages.append(msg)# Model selection is also in context
messages.append({
"role": "tool",
"tool_call_id": call.id,
"content": result,
})
#8. Models are based on the result to generate the final natural language answer
final = client.chat.completions.create(
model="gpt-4o-mini",
messages=messages,
tools=tools,
)
"Final answer:", final.ices [0].message.content)
else:
# Modeling doesn't require tools, answer directly
Right.
Run logic: get weather command apply verification parameters get weather ( "Beijing") → send back the 25°C → model to "Beijing today 25°C, clear". The whole ring, the model has no real modulation, it's applied.
Common pits and control tables: symptoms causes
Most of the mistakes of tool call are documented. Here's the symptoms, the causes, the decomposition comparison table, the priority cross-check of the problem:
7. When do not use tool call?
Not all scenes need tool call. tool call has the risk of delay, cost and error, and is able to respond directly with a model.
- Use of real-time data, external systems, in-house information, real actions.
- Should not be used: purely knowledge-based questions and answers, semantic understanding, task of producing a model of this kind — to answer more quickly, more steadily and cheaper.
On the basis of the judgement: ask yourself, "Is it true that the model does not look at external data?" If so, no tools. If you leave tool call to a scene where you can't answer on your own, you have to rely on external information or actions, then Agent will be able to stabilize and save.
8. Summary: Models as "decision makers" and applications as "implementers"
The essence of tool call is the division of labour between models and applications:
- Models: responsible for understanding intent, selecting tools, generating parameters (decision makers)
- Application: responsible for verification of parameters, real execution, return of results (executors)
What you're going to do is grind the description of the tool to the point where the model can see whether it should be used or not, how the parameters should be filled; check the parameters and double-check the risks before implementation; and keep the model output as a candidate, after your cleaning. If you want to get a deeper view of the project line where tool call is wrong, you can look back at the AI07 protective layer and the AI06 error call check.
End of judgement: When a mission requires real-time data, an external system or real action, use tool call; when the model is able to answer the right question, do not use the tool - the tool is a capability extension, not a master key.
The column describes the landing practice of this column, " AI Agent Tool ", which focuses on Agent Z17Z, from the tool call mechanism, the verification of parameters, the misalignment check, to the realization of the protective layer, each with a directly operational code, updated once a week. To read in order, you can subscribe to the column page.
Auto-fetched and translated by AI Atlas. All rights belong to the original author.