wordpress 站群模板,微电影网站源码,共享wifi小程序搭建,潍坊推广平台概述
工具调用是 Agent 与外部世界交互的核心机制。本教程将详细讲解整个工具调用的完整流程。一、什么是工具#xff1f;
工具就是普通的 Python 函数#xff0c;预先定义在 tools.py 中。
# tools/tools.pydef web_search(query: str, search_engine: str 工具工具就是普通的 Python 函数预先定义在tools.py中。# tools/tools.pydefweb_search(query:str,search_engine:strgoogle,max_results:int10)-str:Search for relevant information on the webreturnfSearched {query} on{search_engine}, returned{max_results}resultsdefdownload_file(url:str,save_path:str,file_type:strauto)-str:Download file from URL to local storagereturnfFile downloaded from{url}to{save_path}, file type:{file_type}defclassify_land_cover(image_path:str,classification_scheme:strCORINE)-str:Perform land cover classification on remote sensing imageryreturnfLand 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. 提取函数名namefunc.__name__# 2. 提取文档字符串作为描述descriptionfunc.__doc__orfExecute{name}function# 3. 分析函数签名获取参数信息siginspect.signature(func)parameters{type:object,properties:{},required:[]}# 4. 遍历参数分析类型forparam_name,paraminsig.parameters.items():ifparam_nameself:continueparam_typestring# 默认类型ifparam.annotation!inspect.Parameter.empty:ifparam.annotationint:param_typeintegerelifparam.annotationfloat:param_typenumberelifparam.annotationbool:param_typebooleanparameters[properties][param_name]{type:param_type,description:f{param_name}parameter}# 5. 记录必填参数ifparam.defaultinspect.Parameter.empty:parameters[required].append(param_name)# 6. 存储到字典self.tools[name]{func:func,# 函数本身description:description,parameters:parameters}2.2 注册示例# 创建 AgentagentReActAgent()# 注册工具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_callsself.parse_tool_trajectory(history)returnfBased 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_responseself.client.chat.completions.create(modelself.model,messages[{role:user,content:action_prompt}],toolstools_schema,# 告诉 LLM 有哪些工具可用tool_choiceauto# 让 LLM 自动选择)# 解析 LLM 的选择tool_callaction_response.choices[0].message.tool_calls[0]tool_nametool_call.function.name# 例如: web_searchargsjson.loads(tool_call.function.arguments)# 例如: {query: 天气, max_results: 5}四、工具的实际执行4.1 执行流程# 从字典中获取函数引用tool_funcself.tools[tool_name][func]# 使用 LLM 提供的参数调用函数resulttool_func(**args)# 示例实际执行# tool_func web_search 函数# args {query: 北京天气, max_results: 3}# result web_search(query北京天气, max_results3)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_pathimage.png, │ │ classification_schemeCORINE │ │ ) │ └─────────────────────────┬───────────────────────────────────────┘ │ ▼ ┌─────────────────────────────────────────────────────────────────┐ │ 返回执行结果 │ │ Land cover classification completed... │ └─────────────────────────────────────────────────────────────────┘五、不同 Agent 的工具调用方式对比5.1 ReAct Agent循环式# 特点每轮循环调用一次工具实时决定下一步defrun(self,query:str)-str:historyforstepinrange(self.max_steps):# 1. 思考阶段thoughtself.client.chat.completions.create(...)# 2. 行动阶段 - 调用 LLM 决定工具action_responseself.client.chat.completions.create(...,toolstools_schema,tool_choiceauto)# 3. 实际执行工具tool_callaction_response.tool_calls[0]resultself.tools[tool_name][func](**args)5.2 Plan Execute Agent规划式# 特点先规划所有工具调用再批量执行defrun(self,query:str)-str:# 1. 规划阶段 - LLM 生成完整计划planself.client.chat.completions.create(...,response_formatPlanSchema# JSON 格式)# 2. 执行阶段 - 按计划顺序执行所有工具forstepinplan.plan:resultself.tools[step.tool][func](**step.parameters)5.3 CoT Agent思维链式# 特点一次调用生成所有工具调用链不实际执行defrun(self,query:str)-str:# LLM 在一次调用中生成所有步骤resultself.client.chat.completions.create(modelself.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循环中每步调用实时决定✅ 执行PlanExecute规划阶段一次性决定按计划批量执行✅ 执行CoT一次生成所有步骤只解析轨迹❌ 不执行Debate多轮讨论后决定最终生成轨迹❌ 不执行六、完整代码示例# 完整的工具调用示例frombench.agentsimportReActAgentfrombench.toolsimportweb_search,download_file,classify_land_cover# 1. 创建 AgentagentReActAgent(modelgpt-4o-mini)# 2. 注册工具agent.add_tool(web_search)agent.add_tool(download_file)agent.add_tool(classify_land_cover)# 3. 运行 Agentuser_query搜索北京的城市规划信息然后下载相关文件result,historyagent.run(user_query)# 4. 查看工具调用轨迹trajectoryagent.run_and_return_tool_trajectory(user_query)print(trajectory)# [web_search, download_file]七、总结工具调用的核心流程工具定义 → 注册到字典 → LLM 理解问题 → LLM 选择工具 → 解析参数 → 执行函数 → 返回结果关键理解工具 普通函数预先写好的 Python 函数注册 信息提取提取函数名、描述、参数类型LLM 决策通过提示词告诉 LLM 有哪些工具LLM 根据问题决定调用哪个执行 函数调用找到字典中的函数引用用参数调用它整个机制的本质就是“LLM 决定 代码执行”的协作模式。