news 2026/5/1 8:15:54

多种类型Agent 工具调用机制讲解

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
多种类型Agent 工具调用机制讲解

概述

工具调用是 Agent 与外部世界交互的核心机制。本教程将详细讲解整个工具调用的完整流程。


一、什么是"工具"?

工具就是普通的 Python 函数,预先定义在tools.py中。

# tools/tools.pydefweb_search(query:str,search_engine:str="google",max_results:int=10)->str:"""Search for relevant information on the web"""returnf"Searched '{query}' on{search_engine}, returned{max_results}results"defdownload_file(url:str,save_path:str,file_type:str="auto")->str:"""Download file from URL to local storage"""returnf"File downloaded from{url}to{save_path}, file type:{file_type}"defclassify_land_cover(image_path:str,classification_scheme:str="CORINE")->str:"""Perform land cover classification on remote sensing imagery"""returnf"Land cover classification completed, classification scheme:{classification_scheme}"

工具的三要素

要素说明示例
函数名工具的唯一标识符web_search
文档字符串工具的功能描述"""Search for relevant information..."""
参数签名工具的输入参数query,search_engine,max_results

二、工具注册流程

2.1 add_tool 方法的核心实现

# agents/base.pydefadd_tool(self,func:Callable):"""Add a tool function to the agent."""# 1. 提取函数名name=func.__name__# 2. 提取文档字符串作为描述description=func.__doc__orf"Execute{name}function"# 3. 分析函数签名获取参数信息sig=inspect.signature(func)parameters={"type":"object","properties":{},"required":[]}# 4. 遍历参数,分析类型forparam_name,paraminsig.parameters.items():ifparam_name=='self':continueparam_type="string"# 默认类型ifparam.annotation!=inspect.Parameter.empty:ifparam.annotation==int:param_type="integer"elifparam.annotation==float:param_type="number"elifparam.annotation==bool:param_type="boolean"parameters["properties"][param_name]={"type":param_type,"description":f"{param_name}parameter"}# 5. 记录必填参数ifparam.default==inspect.Parameter.empty:parameters["required"].append(param_name)# 6. 存储到字典self.tools[name]={"func":func,# 函数本身"description":description,"parameters":parameters}

2.2 注册示例

# 创建 Agentagent=ReActAgent()# 注册工具agent.add_tool(web_search)agent.add_tool(download_file)agent.add_tool(classify_land_cover)# 注册后内部结构self.tools={"web_search":{"func":web_search_function,"description":"Search for relevant information on the web","parameters":{"type":"object","properties":{"query":{"type":"string","description":"query parameter"},"search_engine":{"type":"string","description":"search_engine parameter"},"max_results":{"type":"integer","description":"max_results parameter"}},"required":["query"]}},"download_file":{...},"classify_land_cover":{...}}

三、LLM 如何决定调用工具?

3.1 ReAct 模式的提示词设计

# agents/ReAct.pydefget_action_prompt(self,query:str,thought:str,history:str)->str:"""生成行动提示,引导 LLM 选择工具"""previous_tool_calls=self.parse_tool_trajectory(history)returnf"""Based on your thinking, decide the next action using function calling. User question:{query}Your thought:{thought}History:{history}Your previous_tool_calls:{previous_tool_calls}**Decision Rules**: 1. Check **previous_tool_calls** to avoid repeating same tool call 2. If sufficient information obtained, do NOT call any function 3. If must call tools, ensure clear distinction from previous calls """

3.2 使用 OpenAI Function Calling API

# 构建工具 Schematools_schema=[{"type":"function","function":{"name":"web_search","description":"Search for relevant information on the web","parameters":{"type":"object","properties":{"query":{"type":"string","description":"query parameter"},"max_results":{"type":"integer","description":"max_results parameter"}},"required":["query"]}}}]# 调用 LLMaction_response=self.client.chat.completions.create(model=self.model,messages=[{"role":"user","content":action_prompt}],tools=tools_schema,# 告诉 LLM 有哪些工具可用tool_choice="auto"# 让 LLM 自动选择)# 解析 LLM 的选择tool_call=action_response.choices[0].message.tool_calls[0]tool_name=tool_call.function.name# 例如: "web_search"args=json.loads(tool_call.function.arguments)# 例如: {"query": "天气", "max_results": 5}

四、工具的实际执行

4.1 执行流程

# 从字典中获取函数引用tool_func=self.tools[tool_name]["func"]# 使用 LLM 提供的参数调用函数result=tool_func(**args)# 示例:实际执行# tool_func = web_search 函数# args = {"query": "北京天气", "max_results": 3}# result = web_search(query="北京天气", max_results=3)

4.2 完整执行流程图

┌─────────────────────────────────────────────────────────────────┐ │ 用户提问 │ │ "分析这张遥感图像的土地覆盖类型" │ └─────────────────────────┬───────────────────────────────────────┘ │ ▼ ┌─────────────────────────────────────────────────────────────────┐ │ LLM 理解问题 │ │ 确定需要调用 classify_land_cover 工具 │ └─────────────────────────┬───────────────────────────────────────┘ │ ▼ ┌─────────────────────────────────────────────────────────────────┐ │ LLM 决定调用参数 │ │ tool_name = "classify_land_cover" │ │ args = {"image_path": "image.png", │ │ "classification_scheme": "CORINE"} │ └─────────────────────────┬───────────────────────────────────────┘ │ ▼ ┌─────────────────────────────────────────────────────────────────┐ │ 解析并执行工具 │ │ result = self.tools["classify_land_cover"]["func"]( │ │ image_path="image.png", │ │ classification_scheme="CORINE" │ │ ) │ └─────────────────────────┬───────────────────────────────────────┘ │ ▼ ┌─────────────────────────────────────────────────────────────────┐ │ 返回执行结果 │ │ "Land cover classification completed..." │ └─────────────────────────────────────────────────────────────────┘

五、不同 Agent 的工具调用方式对比

5.1 ReAct Agent(循环式)

# 特点:每轮循环调用一次工具,实时决定下一步defrun(self,query:str)->str:history=""forstepinrange(self.max_steps):# 1. 思考阶段thought=self.client.chat.completions.create(...)# 2. 行动阶段 - 调用 LLM 决定工具action_response=self.client.chat.completions.create(...,tools=tools_schema,tool_choice="auto")# 3. 实际执行工具tool_call=action_response.tool_calls[0]result=self.tools[tool_name]["func"](**args)

5.2 Plan & Execute Agent(规划式)

# 特点:先规划所有工具调用,再批量执行defrun(self,query:str)->str:# 1. 规划阶段 - LLM 生成完整计划plan=self.client.chat.completions.create(...,response_format=PlanSchema# JSON 格式)# 2. 执行阶段 - 按计划顺序执行所有工具forstepinplan.plan:result=self.tools[step.tool]["func"](**step.parameters)

5.3 CoT Agent(思维链式)

# 特点:一次调用生成所有工具调用链,不实际执行defrun(self,query:str)->str:# LLM 在一次调用中生成所有步骤result=self.client.chat.completions.create(model=self.model,messages=[{"role":"user","content":cot_prompt}],)# 解析轨迹(不执行)tool_trajectory=[]forstepinresult.split("\n"):ifstep.startswith("step"):tool_trajectory.append(step.split(";")[1].strip())

5.4 对比总结

Agent 类型调用时机执行方式实际执行
ReAct循环中每步调用实时决定✅ 执行
Plan&Execute规划阶段一次性决定按计划批量执行✅ 执行
CoT一次生成所有步骤只解析轨迹❌ 不执行
Debate多轮讨论后决定最终生成轨迹❌ 不执行

六、完整代码示例

# 完整的工具调用示例frombench.agentsimportReActAgentfrombench.toolsimportweb_search,download_file,classify_land_cover# 1. 创建 Agentagent=ReActAgent(model="gpt-4o-mini")# 2. 注册工具agent.add_tool(web_search)agent.add_tool(download_file)agent.add_tool(classify_land_cover)# 3. 运行 Agentuser_query="搜索北京的城市规划信息,然后下载相关文件"result,history=agent.run(user_query)# 4. 查看工具调用轨迹trajectory=agent.run_and_return_tool_trajectory(user_query)print(trajectory)# ['web_search', 'download_file']

七、总结

工具调用的核心流程

工具定义 → 注册到字典 → LLM 理解问题 → LLM 选择工具 → 解析参数 → 执行函数 → 返回结果

关键理解

  1. 工具 = 普通函数:预先写好的 Python 函数
  2. 注册 = 信息提取:提取函数名、描述、参数类型
  3. LLM 决策:通过提示词告诉 LLM 有哪些工具,LLM 根据问题决定调用哪个
  4. 执行 = 函数调用:找到字典中的函数引用,用参数调用它

整个机制的本质就是“LLM 决定 + 代码执行”的协作模式。

版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/5/1 5:50:31

3分钟让你的Windows桌面焕然一新:任务栏透明美化终极指南

3分钟让你的Windows桌面焕然一新:任务栏透明美化终极指南 【免费下载链接】TranslucentTB 项目地址: https://gitcode.com/gh_mirrors/tra/TranslucentTB 厌倦了千篇一律的Windows默认界面?想要一个既美观又实用的个性化桌面?今天就来…

作者头像 李华
网站建设 2026/4/30 20:38:49

Rust 编程语言教学目录

Rust 编程语言教学目录 第一部分:基础入门篇 (1-2周) 第1章:Rust 初体验 1.1 Rust 语言概述与设计哲学1.2 安装 Rust 工具链 rustup 安装与配置Cargo 包管理器介绍 1.3 第一个 Rust 程序 Hello World使用 Cargo 创建项目 1.4 开发环境配置 VS Code Rust…

作者头像 李华
网站建设 2026/4/21 8:30:03

Arduino IDE安装全过程:从驱动到端口检测的深度剖析

Arduino IDE安装全过程:从驱动到端口检测的深度剖析 你有没有遇到过这样的情况? 新买的Arduino板子插上电脑,打开Arduino IDE,却发现“工具 > 端口”菜单一片灰——不可选、不显示、甚至设备管理器里还挂着个“未知设备”。明…

作者头像 李华
网站建设 2026/4/23 12:28:14

智能助手如何让英雄联盟体验提升300%?

智能助手如何让英雄联盟体验提升300%? 【免费下载链接】LeagueAkari ✨兴趣使然的,功能全面的英雄联盟工具集。支持战绩查询、自动秒选等功能。基于 LCU API。 项目地址: https://gitcode.com/gh_mirrors/le/LeagueAkari 您在英雄联盟中是否经历过…

作者头像 李华
网站建设 2026/5/1 6:10:23

SillyTavern桌面版终极打包指南:从零构建跨平台桌面应用

SillyTavern桌面版终极打包指南:从零构建跨平台桌面应用 【免费下载链接】SillyTavern LLM Frontend for Power Users. 项目地址: https://gitcode.com/GitHub_Trending/si/SillyTavern 还在为每次启动SillyTavern都要打开命令行而烦恼吗?想要像使…

作者头像 李华