当前位置: 首页 > article >正文

AI Agent 工具调用系统设计:让大模型掌控世界

AI Agent 工具调用系统设计让大模型掌控世界前言工具调用Tool Use / Function Calling是 AI Agent 实现复杂任务的关键能力。通过工具调用大模型可以与外部世界交互执行计算、查询数据库、调用 API真正变成一个能够行动的智能体。我之前设计的代码审查 Agent 就有完善的工具调用能力可以搜索文档、读写文件、执行代码。工具调用系统设计得好不好直接决定了 Agent 的能力边界。今天分享一些我在实践中总结的设计模式和经验。工具调用的基本原理什么是 Function CallingFunction Calling 是让大模型生成结构化调用指令的能力# OpenAI API 的 Function Calling 示例 response client.chat.completions.create( modelgpt-4, messages[{role: user, content: 北京今天天气怎么样}], tools[ { type: function, function: { name: get_weather, description: 获取指定城市的天气信息, parameters: { type: object, properties: { city: { type: string, description: 城市名称 }, unit: { type: string, enum: [celsius, fahrenheit], description: 温度单位 } }, required: [city] } } } ] ) # 模型可能返回 # { # tool_calls: [{ # id: call_xxx, # function: { # name: get_weather, # arguments: {city: 北京, unit: celsius} # } # }] # }工具调用的工作流程用户输入 → LLM 判断是否需要工具 → 是 → 解析工具和参数 → 执行工具 → 返回结果 → LLM 生成最终回答 ↓ 否 直接生成回答工具描述设计Schema 设计原则工具的 JSON Schema 描述直接决定模型能否正确理解和使用工具# 好的工具描述示例 good_tool_schema { name: search_documents, description: 在企业知识库中搜索相关文档。适用于查找技术文档、API说明、最佳实践等。, parameters: { type: object, properties: { query: { type: string, description: 搜索查询语句建议使用完整的问句或关键词组合。例如如何使用 REST API 或 REST API 使用方法 }, top_k: { type: integer, description: 返回的最多文档数量默认 5, default: 5 } }, required: [query] } } # 不好的工具描述示例 bad_tool_schema { name: search, description: 搜索, parameters: { type: object, properties: { q: {type: string} }, required: [q] } }工具分组策略当工具数量很多时应该进行分组TOOL_GROUPS { information: { description: 信息查询类工具, tools: [search_documents, get_weather, get_time] }, code: { description: 代码处理类工具, tools: [execute_code, read_file, write_file] }, communication: { description: 通信类工具, tools: [send_email, send_message] } } def get_tools_for_scenario(scenario: str) - List[dict]: 根据场景选择合适的工具组 if scenario technical_support: return [get_tool_schema(information), get_tool_schema(code)] elif scenario business: return [get_tool_schema(information), get_tool_schema(communication)] else: return get_all_tools()工具执行框架基础执行器from dataclasses import dataclass from typing import Dict, List, Callable, Any import json dataclass class ToolCall: 工具调用请求 id: str name: str arguments: dict dataclass class ToolResult: 工具执行结果 call_id: str success: bool result: Any error: str None class ToolExecutor: 工具执行器 def __init__(self): self.tools: Dict[str, Callable] {} self.schemas: Dict[str, dict] {} def register(self, name: str, schema: dict, func: Callable): 注册工具 self.tools[name] func self.schemas[name] schema def execute(self, call: ToolCall) - ToolResult: 执行工具调用 if call.name not in self.tools: return ToolResult( call_idcall.id, successFalse, resultNone, errorfUnknown tool: {call.name} ) try: func self.tools[call.name] result func(**call.arguments) return ToolResult( call_idcall.id, successTrue, resultresult ) except Exception as e: return ToolResult( call_idcall.id, successFalse, resultNone, errorstr(e) ) def execute_batch(self, calls: List[ToolCall]) - List[ToolResult]: 批量执行工具调用 return [self.execute(call) for call in calls]实际工具实现# 注册实际工具 executor ToolExecutor() # 搜索引擎 def search_web(query: str, num_results: int 5) - dict: 搜索网页 # 实际实现调用搜索引擎 API results google_search(query, num_results) return { query: query, results: [ { title: r.title, snippet: r.snippet, url: r.url } for r in results ] } executor.register( search_web, { name: search_web, description: 搜索网页获取最新信息。适用于查询实时新闻、未知问题等。, parameters: { type: object, properties: { query: {type: string, description: 搜索查询}, num_results: { type: integer, description: 返回结果数量, default: 5 } }, required: [query] } }, search_web ) # 计算器 def calculator(expression: str) - dict: 安全计算数学表达式 # 只允许基本运算 allowed_chars set(0123456789-*/.() ) if not all(c in allowed_chars for c in expression): return {error: 不允许的字符} try: result eval(expression) return {expression: expression, result: result} except Exception as e: return {error: str(e)} executor.register( calculator, { name: calculator, description: 计算数学表达式的值。只支持基本运算符加()、减(-)、乘(*)、除(/)。, parameters: { type: object, properties: { expression: { type: string, description: 数学表达式例如23*4 或 (105)/3 } }, required: [expression] } }, calculator )Agent 工具调用循环完整的工具调用循环class ToolUsingAgent: 支持工具调用的 Agent def __init__(self, llm, executor: ToolExecutor, max_iterations: int 10): self.llm llm self.executor executor self.max_iterations max_iterations def run(self, user_input: str) - str: 运行 Agent 处理用户输入 messages [ {role: system, content: self._get_system_prompt()}, {role: user, content: user_input} ] for iteration in range(self.max_iterations): # 1. 获取 LLM 响应 response self.llm.chat(messages, toolsself.executor.get_all_schemas()) # 2. 检查是否有工具调用 if not response.tool_calls: # 没有工具调用直接返回 return response.content # 3. 执行工具调用 tool_results [] for call in response.tool_calls: tool_call ToolCall( idcall.id, namecall.function.name, argumentsjson.loads(call.function.arguments) ) result self.executor.execute(tool_call) tool_results.append(result) # 4. 将结果添加到消息 messages.append(response.to_message()) for result in tool_results: messages.append({ role: tool, tool_call_id: result.call_id, content: json.dumps(result.result) if result.success else result.error }) return 达到最大迭代次数 def _get_system_prompt(self) - str: return 你是一个智能助手可以通过调用工具来完成任务。 Available tools: self.executor.get_tools_description()结果验证与重试class VerifiedToolExecutor(ToolExecutor): 带验证的工具执行器 def execute_with_verification( self, call: ToolCall, expected_format: dict None ) - ToolResult: 执行并验证结果 result self.execute(call) if not result.success: return result if expected_format: # 验证结果格式 is_valid, error self._verify_format(result.result, expected_format) if not is_valid: return ToolResult( call_idcall.id, successFalse, resultNone, errorfResult format error: {error} ) return result def _verify_format(self, result: Any, expected: dict) - tuple: 验证结果格式 if expected.get(type) array: if not isinstance(result, list): return False, Expected array elif expected.get(type) object: if not isinstance(result, dict): return False, Expected object for key in expected.get(required, []): if key not in result: return False, fMissing required field: {key} return True, None工具调用的安全考虑输入验证class SecureToolExecutor(ToolExecutor): 安全的工具执行器 def execute(self, call: ToolCall) - ToolResult: # 1. 参数验证 schema self.schemas.get(call.name) if not schema: return ToolResult(call.id, False, None, Unknown tool) # 检查必需参数 required schema.get(parameters, {}).get(required, []) for param in required: if param not in call.arguments: return ToolResult( call.id, False, None, fMissing required parameter: {param} ) # 2. 值域检查 properties schema.get(parameters, {}).get(properties, {}) for param, spec in properties.items(): if param in call.arguments: value call.arguments[param] if not self._validate_param_value(value, spec): return ToolResult( call.id, False, None, fInvalid value for parameter {param} ) # 3. 敏感操作检查 if self._is_sensitive_operation(call): # 记录审计日志 self._audit_log(call) return super().execute(call) def _validate_param_value(self, value, spec) - bool: 验证参数值 param_type spec.get(type) if param_type string: if maxLength in spec and len(value) spec[maxLength]: return False if enum in spec and value not in spec[enum]: return False elif param_type integer: if not isinstance(value, int): return False if minimum in spec and value spec[minimum]: return False if maximum in spec and value spec[maximum]: return False return True def _is_sensitive_operation(self, call: ToolCall) - bool: 检查是否为敏感操作 sensitive_tools {delete_file, send_email, execute_sql} return call.name in sensitive_tools异步工具调用import asyncio from typing import List class AsyncToolExecutor: 异步工具执行器 def __init__(self): self.tools: Dict[str, Callable] {} def register(self, name: str, func: Callable): self.tools[name] func async def execute_async(self, call: ToolCall) - ToolResult: 异步执行单个工具 if call.name not in self.tools: return ToolResult(call.id, False, None, Unknown tool) try: func self.tools[call.name] # 如果是异步函数 if asyncio.iscoroutinefunction(func): result await func(**call.arguments) else: # 在线程池中运行同步函数 loop asyncio.get_event_loop() result await loop.run_in_executor(None, lambda: func(**call.arguments)) return ToolResult(call.id, True, result) except Exception as e: return ToolResult(call.id, False, None, str(e)) async def execute_batch_async(self, calls: List[ToolCall]) - List[ToolResult]: 批量异步执行 tasks [self.execute_async(call) for call in calls] return await asyncio.gather(*tasks)工具调用优化并行 vs 串行class SmartToolExecutor(ToolExecutor): 智能工具执行器 def execute_with_plan(self, calls: List[ToolCall]) - List[ToolResult]: 分析依赖关系并优化执行顺序 # 1. 构建依赖图 dependencies self._build_dependency_graph(calls) # 2. 找出可以并行的调用 independent_calls [ call for call in calls if not dependencies.get(call.id) ] # 3. 并行执行独立的调用 parallel_results self.execute_batch(independent_calls) # 4. 串行执行有依赖的调用 remaining_calls [c for c in calls if c.id in dependencies] serial_results [] for call in remaining_calls: deps dependencies[call.id] # 等待依赖完成 for dep_id in deps: self._wait_for_result(dep_id) result self.execute(call) serial_results.append(result) return parallel_results serial_results总结工具调用是 AI Agent 实现复杂任务的核心能力。设计一个好的工具调用系统需要考虑清晰的工具描述让模型准确理解工具用途和参数健壮的执行框架错误处理、验证、重试机制安全保障输入验证、敏感操作审计性能优化并行执行、依赖分析希望这些经验对大家有帮助。

相关文章:

AI Agent 工具调用系统设计:让大模型掌控世界

AI Agent 工具调用系统设计:让大模型掌控世界 前言 工具调用(Tool Use / Function Calling)是 AI Agent 实现复杂任务的关键能力。通过工具调用,大模型可以与外部世界交互,执行计算、查询数据库、调用 API,…...

如何免费使用ColabFold进行蛋白质结构预测:面向新手的终极指南

如何免费使用ColabFold进行蛋白质结构预测:面向新手的终极指南 【免费下载链接】ColabFold Making Protein folding accessible to all! 项目地址: https://gitcode.com/gh_mirrors/co/ColabFold ColabFold蛋白质结构预测是生物信息学领域的一项革命性技术&a…...

揭秘AI专著写作:如何利用AI工具一键生成20万字专著并降低查重率?

撰写学术专著的挑战与AI工具解决方案 撰写学术专著不仅考验研究者的学术能力,更是对心理承受力的一种考验。与团队协作完成论文不同,专著的撰写往往是一个人的战斗。研究者需要在选题、构建框架到内容撰写和修改的每个环节都独立面对。长时间的孤独创作…...

Akebi-GC 实战指南:掌握游戏功能修改与自动化测试技术

Akebi-GC 实战指南:掌握游戏功能修改与自动化测试技术 【免费下载链接】Akebi-GC (Fork) The great software for some game that exploiting anime girls (and boys). 项目地址: https://gitcode.com/gh_mirrors/ak/Akebi-GC 作为一款专注于游戏功能修改与自…...

揭秘AI专著撰写:工具加持,20万字专著快速成型!

AI专著写作:挑战与工具解决方案 学术专著的撰写,不仅考验着研究者的学术能力,更是对心理耐受力的一种挑战。与团队合作撰写论文不同,专著大多是由个人独立完成的。从选题到框架构建,再到具体内容的撰写、修改&#xf…...

AI专著生成神器来袭!用AI写专著,20万字专著轻松到手!

创新是学术专著的核心,也是写作中最具挑战性的部分。一部合格的专著不能仅仅是已有成果的简单堆叠,而是需要展现贯穿整本书的独到见解、理论框架或者研究方法。面对浩如烟海的学术文献,寻找那些尚未被挖掘的研究空白实属不易——有时选题已经…...

AI专著撰写神器来袭!一键生成20万字专著,附带专业框架和低查重保障!

写学术专著的挑战与AI工具助力 写学术专著是一项挑战,不仅考验学术能力,也对心理承受力提出了要求。与团队合作的论文写作不同,专著通常是独立完成的过程。从选题、框架搭建到具体内容的撰写与修改,每个环节都需要作者亲自去完成…...

如何快速掌握Subtitle Edit:免费开源字幕编辑器的终极指南

如何快速掌握Subtitle Edit:免费开源字幕编辑器的终极指南 【免费下载链接】subtitleedit the subtitle editor :) 项目地址: https://gitcode.com/gh_mirrors/su/subtitleedit 想要为视频添加专业字幕却苦于找不到合适的工具?Subtitle Edit作为一…...

保姆级教程:在Ubuntu 22.04 LTS上从零部署Zabbix 6.0监控系统(含MariaDB配置)

从零构建企业级监控系统:Ubuntu 22.04下Zabbix 6.0与MariaDB深度整合指南 第一次接触服务器监控系统时,我被各种专业术语和复杂的配置步骤弄得晕头转向。直到遇到Zabbix,这个开箱即用的监控解决方案彻底改变了我的运维工作方式。本文将带你完…...

Mac Mouse Fix:3步让你的普通鼠标超越苹果触控板体验

Mac Mouse Fix:3步让你的普通鼠标超越苹果触控板体验 【免费下载链接】mac-mouse-fix Mac Mouse Fix - Make Your $10 Mouse Better Than an Apple Trackpad! 项目地址: https://gitcode.com/GitHub_Trending/ma/mac-mouse-fix 你是否曾为macOS上鼠标功能受限…...

百度文库纯净打印助手:3步实现无广告文档导出

百度文库纯净打印助手:3步实现无广告文档导出 【免费下载链接】baidu-wenku fetch the document for free 项目地址: https://gitcode.com/gh_mirrors/ba/baidu-wenku 百度文库纯净打印助手是一个开源JavaScript脚本,专为解决百度文库文档阅读和保…...

AI不可靠性工程指南:从失效机理到五层防护网

1. 这不是一句抱怨,而是一条必须写进操作手册的警告 “AI Is Unreliable”——当我在第三个项目里连续两次被同一个大模型生成的Python函数在边界条件下 silently 返回 None 而不是抛出异常、导致下游数据管道静默丢失23%的样本后,我把这句话钉在了团队共…...

G-Helper终极指南:3步释放华硕笔记本完整性能的轻量控制革命

G-Helper终极指南:3步释放华硕笔记本完整性能的轻量控制革命 【免费下载链接】g-helper Lightweight Armoury Crate alternative for Asus laptops with nearly the same functionality. Works with ROG Zephyrus, Flow, TUF, Strix, Scar, ProArt, Vivobook, Zenbo…...

基于AI流动性监测模型的黄金波动分析:油价跳水与美元回落下的黄金震荡企稳机制解析

摘要:本文通过AI宏观情绪识别模型、美元流动性监测框架以及能源价格传导算法,结合近期原油、美元与美债收益率变化,分析黄金在高波动市场环境下的价格修复逻辑,并探讨避险需求、通胀预期与美联储政策路径之间的动态博弈关系。一、…...

东南大学论文模板:告别格式烦恼,专注学术创新的8倍效率解决方案

东南大学论文模板:告别格式烦恼,专注学术创新的8倍效率解决方案 【免费下载链接】SEUThesis 东南大学论文模板 项目地址: https://gitcode.com/gh_mirrors/seu/SEUThesis 东南大学SEUThesis论文模板库是专为东大学子设计的学术写作利器&#xff0…...

在OpenClaw Agent工作流中无缝接入Taotoken调用多模型能力

🚀 告别海外账号与网络限制!稳定直连全球优质大模型,限时半价接入中。 👉 点击领取海量免费额度 在OpenClaw Agent工作流中无缝接入Taotoken调用多模型能力 对于使用OpenClaw构建智能体工作流的开发者而言,能够灵活调…...

ML模型服务化落地实战:从Notebook到高稳定生产环境

1. 项目概述:这不是一次“部署上线”演示,而是一场真实世界的ML交付实战复盘“From Notebook to Production: Running ML in the Real World (Part 4)”——这个标题里藏着三个关键信号:Notebook是起点,不是终点;Produ…...

3步解锁百度网盘全速下载:baidu-wangpan-parse技术解析与应用实践

3步解锁百度网盘全速下载:baidu-wangpan-parse技术解析与应用实践 【免费下载链接】baidu-wangpan-parse 获取百度网盘分享文件的下载地址 项目地址: https://gitcode.com/gh_mirrors/ba/baidu-wangpan-parse 你是否曾面对百度网盘那令人绝望的下载速度而束手…...

预训练模型技术演进史:从Word2Vec到多模态大模型

1. 项目概述:这本“沙滩读物”到底在讲什么? “Beach Reading: a Short History of Pre-Trained Models”——光看标题,你可能会以为这是本躺在夏威夷躺椅上、椰子水还没喝完就能翻完的轻松小册子。但别被“Beach Reading”这个温柔前缀骗了。…...

终极Mac抢票解决方案:12306ForMac让你的购票体验飞起来

终极Mac抢票解决方案:12306ForMac让你的购票体验飞起来 【免费下载链接】12306ForMac An unofficial 12306 Client for Mac 项目地址: https://gitcode.com/gh_mirrors/12/12306ForMac 还在为Mac上抢不到火车票而烦恼吗?作为Mac用户,你…...

SAP ABAP实战:用BAPI_PO_CREATE1创建采购订单时,如何彻底隐藏PBXX条件类型?

SAP ABAP实战:彻底隐藏BAPI_PO_CREATE1中的PBXX条件类型 最近在实施一个外协加工采购项目时,遇到了一个让人头疼的问题:使用BAPI_PO_CREATE1创建采购订单时,系统总是自动生成价格为0的PBXX条件类型行。这看起来像是个小问题&…...

甲骨文免费服务器到手后,用Xshell连接不上?这份SSH密钥配置避坑指南请收好

甲骨文云SSH连接全攻略:从密钥解析到Xshell实战配置 密钥管理的核心逻辑与常见误区 初次接触甲骨文云免费实例的用户,90%的SSH连接问题都源于密钥处理不当。与常规密码登录不同,甲骨文云强制采用密钥对认证机制,这种设计虽然提升了…...

利用 AI Agent 优化日常办公自动化流程

AI Agent优化办公自动化流程的核心逻辑是「人定规则,AI跑流程」‌,通过把重复、步骤明确的工作交给AI Agent自主执行,实现提效降本,具体可以按照以下方法落地:一、先明确落地逻辑把目标工作拆成「触发条件→执行步骤→…...

Lovable电商系统从零部署:手把手教你用Vue+Node+MongoDB搭建高转化率商城(含完整源码)

更多请点击: https://kaifayun.com 第一章:Lovable电商系统从零部署:手把手教你用VueNodeMongoDB搭建高转化率商城(含完整源码) Lovable电商系统是一套面向中小企业的轻量级高转化率商城解决方案,采用前后…...

突发环境事件怎么模拟?用Python+GIS实现高斯烟团模型(附完整代码)

突发污染事件动态模拟:Python与GIS融合的高斯烟团建模实战 化工泄漏、危险品运输事故等突发环境事件往往需要快速响应与精准评估。传统烟羽模型在瞬态污染场景中存在局限性,而高斯烟团模型凭借其动态扩散模拟能力成为应急决策的利器。本文将手把手带您实…...

Windows任务栏透明美化神器:5分钟掌握TranslucentTB完整使用指南

Windows任务栏透明美化神器:5分钟掌握TranslucentTB完整使用指南 【免费下载链接】TranslucentTB A lightweight utility that makes the Windows taskbar translucent/transparent. 项目地址: https://gitcode.com/gh_mirrors/tr/TranslucentTB 想要让你的W…...

如何利用 AI Agent 优化日常办公自动化流程?

用 AI Agent 优化办公自动化,核心是把高频重复、规则清晰、跨系统搬运的工作交给 Agent,人专注决策与创意;先试点、再打通数据、最后规模化,通常能把事务性时间压减 50%–80%。下面从落地框架、核心场景、搭建步骤、工具选型与避坑…...

终极指南:3分钟掌握英雄联盟智能助手League Akari的完整使用技巧 [特殊字符]

终极指南:3分钟掌握英雄联盟智能助手League Akari的完整使用技巧 🚀 【免费下载链接】League-Toolkit An all-in-one toolkit for LeagueClient. Gathering power 🚀. 项目地址: https://gitcode.com/gh_mirrors/le/League-Toolkit 想…...

从SysTick中断到任务就绪:深入追踪FreeRTOS一次Tick如何触发PendSV切换

从SysTick中断到任务就绪:深入追踪FreeRTOS一次Tick如何触发PendSV切换 在嵌入式实时操作系统的世界里,任务切换的精确性和可靠性直接决定了系统的实时性能。对于使用FreeRTOS的开发者而言,理解从SysTick中断到最终任务切换的完整链条&#x…...

QKeyMapper:免费开源的Windows按键映射工具,彻底解放你的操作习惯

QKeyMapper:免费开源的Windows按键映射工具,彻底解放你的操作习惯 【免费下载链接】QKeyMapper [按键映射工具] QKeyMapper,Qt开发Win10&Win11可用,不修改注册表、不需重新启动系统,可立即生效和停止。支持游戏手柄…...