工具系统是 Agent 的 双手 —— 让 LLM 从「能说会道」进化到「能做实事」
蝙蝠侠之所以是蝙蝠侠,不是因为他有多强壮,而是因为他的 工具腰带。
蝙蝠镖、钩爪枪、烟雾弹……每样工具解决一个问题。
Agent 的工具系统就是它的 工具腰带。
LLM 本身只会「思考」,但有了工具,它就能 读写文件、执行命令、搜索代码。
工具系统的本质极其简单:加一个工具,只需要加一个 handler。整个系统围绕两个核心数据结构运转。
核心思想:TOOLS[] 告诉 LLM「你有什么工具可用」,TOOL_HANDLERS{} 告诉系统「收到调用时该执行什么」。一个是「名片」,一个是「电话簿」。
给 LLM 看的「工具说明书」。每个工具是一个 JSON Schema,描述名称、功能、参数。 LLM 根据这些信息决定「我该调用哪个工具、传什么参数」。
# TOOLS[] 中的一个条目 { "name": "bash", "description": "Execute a shell command", "parameters": { "type": "object", "properties": { "command": { "type": "string", "description": "The shell command to run" } }, "required": ["command"] } }
给系统用的「执行手册」。一个字典,key 是工具名,value 是实际执行函数。 LLM 返回 tool_call 后,系统在这里查找并执行。
# TOOL_HANDLERS 的结构 TOOL_HANDLERS = { "bash": bash_handler, "read_file": read_file_handler, "write_file": write_file_handler, "edit_file": edit_file_handler, "glob": glob_handler, } # 调用时: result = TOOL_HANDLERS["bash"](command="ls -la")
为什么要分开?因为 LLM 只需要知道「有哪些工具、怎么调用」(Schema),它不需要也不应该知道具体实现细节。分离让系统更安全、更灵活。
ToolRegistry 是管理所有工具的中心枢纽。它维护两张表:工具 Schema 和 Handler。
三个核心方法:register()、get_schemas()、get_handlers()。
class ToolRegistry: """Central hub for all tools.""" def __init__(self): self.tools: list[Tool] = [] # 工具实例列表 self.handlers: dict = {} # name → handler 函数 def register(self, tool: Tool): """注册一个工具:保存实例 + 绑定 handler""" self.tools.append(tool) self.handlers[tool.name] = tool.execute # 关键! def get_schemas(self) -> list[dict]: """返回所有工具的 JSON Schema(给 LLM 用)""" return [tool.get_schema() for tool in self.tools] def get_handlers(self) -> dict: """返回 name → handler 映射(给系统用)""" return self.handlers
所有工具都继承自 Tool 抽象基类(ABC)。它定义了每个工具必须具备的「身份证」和「执行能力」。
from abc import ABC, abstractmethod class Tool(ABC): """Abstract base class for all tools.""" # ① 工具名称 —— 唯一标识符 name: str # ② 工具描述 —— 告诉 LLM 这个工具是干什么的 description: str # ③ 参数定义 —— JSON Schema 格式,描述需要哪些参数 parameters: dict @abstractmethod def execute(self, **kwargs) -> str: """④ 执行方法 —— 子类必须实现""" ... def get_schema(self) -> dict: """⑤ 生成 JSON Schema —— 给 LLM 看的说明书""" return { "name": self.name, "description": self.description, "parameters": self.parameters, }
"bash"、"read_file"。LLM 返回的 tool_call 中必须匹配这个名字。
设计哲学:一个工具 = 一个类。加新工具只需要写一个类、调一次 register()。不需要修改任何已有代码。这就是 开闭原则(对扩展开放,对修改关闭)。
BashTool 是最重要的内置工具。它让 Agent 能执行任意 shell 命令,从而获得与计算机交互的能力。
import subprocess from .base import Tool class BashTool(Tool): name = "bash" description = "Execute a shell command and return output" parameters = { "type": "object", "properties": { "command": { "type": "string", "description": "Shell command to execute" } }, "required": ["command"] } def execute(self, command: str, **kwargs) -> str: """Execute command via subprocess.""" try: result = subprocess.run( command, shell=True, # 允许 shell 语法 capture_output=True, # 捕获 stdout + stderr text=True, # 返回字符串而非 bytes timeout=30 # 30秒超时保护 ) output = result.stdout if result.stderr: output += "\n[stderr]\n" + result.stderr return snip_large_output(output) except TimeoutExpired: return "Error: Command timed out after 30 seconds" except Exception as e: return f"Error: {str(e)}"
|、重定向 >、通配符 * 等语法。注意:这也意味着安全性依赖于外部防护。
while true 之类的死循环不会卡死整个系统。
[... snipped ...] 标记,防止上下文窗口被撑爆。
从用户输入到工具执行再到结果返回,每一步都有明确的职责。
点击下方按钮,模拟一次完整的工具调用流程
AgentForge 内置了 5 个核心工具,覆盖了最常见的文件操作和系统交互需求。
执行任意 shell 命令。这是最强大也最危险的工具,Agent 的「万能手」。
# 示例调用 bash(command="ls -la src/") bash(command="git log --oneline -5") bash(command="python -m pytest tests/")
读取文件内容,支持行号和分页。不会修改文件,是安全的只读操作。
# 示例调用 read_file(path="src/main.py") read_file(path="config.json", offset=10, limit=50)
写入文件内容,会完全覆盖原文件。创建新文件或覆写已有文件。
# 示例调用 write_file( path="src/utils.py", content="def hello():\n print('hi')" )
精确查找替换,支持模糊匹配。修改文件时用它而不是 write_file。
# 示例调用 edit_file( path="src/main.py", old_string="def old_name(", new_string="def new_name(" )
按模式搜索文件名。支持通配符,速度快,只返回文件路径列表。
# 示例调用 glob(pattern="**/*.py") glob(pattern="src/**/*test*")
添加自定义工具只需要三步:创建类 → 注册 → 自动可用。下面以 WeatherTool 为例。
import requests from .base import Tool class WeatherTool(Tool): """获取指定城市的天气信息""" # 第一步:定义工具身份 name = "get_weather" description = "Get current weather for a city" parameters = { "type": "object", "properties": { "city": { "type": "string", "description": "City name, e.g. 'Beijing'" }, "unit": { "type": "string", "enum": ["celsius", "fahrenheit"], "description": "Temperature unit" } }, "required": ["city"] } # 第二步:实现执行逻辑 def execute(self, city: str, unit: str = "celsius", **kwargs) -> str: try: resp = requests.get( f"https://api.weather.com/v1/{city}?unit={unit}", timeout=10 ) data = resp.json() return f"{city}: {data['temp']}°, {data['condition']}" except Exception as e: return f"Error fetching weather: {e}" # 第三步:注册(只需一行!) # registry.register(WeatherTool()) # 注册后,LLM 自动知道这个工具的存在并可以调用它
为什么这么简单?
因为 ToolRegistry 的 register() 方法自动完成了 Schema 提取和 Handler 绑定。你只需要写好类。
插件化架构
每个工具是独立的模块,互不影响。社区可以贡献新工具,无需修改核心代码。
工具系统给了 Agent 强大的能力,但也带来了风险。三道安全防线确保 Agent 不会「越界」。
文件操作被限制在指定的工作目录内。尝试访问 /etc/passwd 等敏感路径会被拒绝。
# 路径检查 def check_path(path): abs_path = os.path.abspath(path) if not abs_path.startswith(WORK_DIR): raise SecurityError( "Access denied: outside workdir" )
snip_large_output() 防止超大输出撑爆上下文窗口。超过阈值自动截断。
def snip_large_output( output, max_chars=50000 ): if len(output) > max_chars: return ( output[:max_chars] + "\n[... snipped ...]" ) return output
所有工具调用都被 try-catch 包裹。任何异常都被捕获并返回错误信息,不会导致系统崩溃。
try: result = handler(**args) except TimeoutExpired: return "Timeout error" except Exception as e: return f"Error: {e}" # 永远不会 crash
关于 isConcurrencySafe:某些工具标记为「并发安全」(如 read_file),可以并行执行以提高效率。而 bash、write_file 等修改状态的工具则必须串行执行,避免竞态条件。
# 并发执行工具调用 async def execute_tool_calls(tool_calls): results = [] safe_calls = [] unsafe_calls = [] # 分类:安全的可以并行,不安全的必须串行 for call in tool_calls: tool = registry.tools[call.name] if tool.is_concurrency_safe: safe_calls.append(call) else: unsafe_calls.append(call) # 并行执行安全的工具 if safe_calls: safe_results = await asyncio.gather( *[run_tool(c) for c in safe_calls] ) results.extend(safe_results) # 串行执行不安全的工具 for call in unsafe_calls: result = await run_tool(call) results.append(result) return results
5 道题,检验你对工具系统的掌握程度。
想要更深入?展开下面的卡片探索更多细节。
LLM 本身不知道工具的存在。工具信息通过 system prompt 注入:
# 系统在每次请求时动态构建 messages messages = [ {"role": "system", "content": system_prompt}, {"role": "system", "content": "Available tools:\n" + json.dumps(tools_schema)}, *conversation_history, {"role": "user", "content": user_message} ] # LLM 看到的 tools 参数 response = client.chat.completions.create( model="gpt-4", messages=messages, tools=registry.get_schemas(), # ← 工具 Schema 在这里注入 tool_choice="auto" )
关键洞察:不同的 LLM provider 对工具的支持方式不同。OpenAI 用 tools 参数,Anthropic 用 tool_use block,
但本质都是把 JSON Schema 传给模型,让模型知道有哪些工具可用。
def snip_large_output( output: str, max_chars: int = 50_000, head_chars: int = 10_000, tail_chars: int = 10_000, ) -> str: """Intelligently truncate large output. Strategy: keep head + tail, snip the middle. This preserves both the beginning (often most useful) and the end (often has summary/error info). """ if len(output) <= max_chars: return output snipped = len(output) - head_chars - tail_chars return ( output[:head_chars] + f"\n\n[... snipped {snipped} chars ...]\n\n" + output[-tail_chars:] )
为什么保留头尾?文件开头通常有 import 和类定义,结尾通常有 main 和错误信息。 中间部分往往是重复的代码,截断损失最小。
当 LLM 一次返回多个 tool_call 时,系统需要决定哪些可以并行:
# 工具的并发安全标记 class ReadFileTool(Tool): name = "read_file" is_concurrency_safe = True # ✅ 只读,可以并行 class WriteFileTool(Tool): name = "write_file" is_concurrency_safe = False # ❌ 写入,必须串行 class BashTool(Tool): name = "bash" is_concurrency_safe = False # ❌ 可能有副作用 # 执行策略 # 1. 收集所有 tool_calls # 2. 按 is_concurrency_safe 分组 # 3. safe 的用 asyncio.gather() 并行 # 4. unsafe 的用 for 循环串行
实际场景:LLM 同时要读 3 个文件,这 3 个 read_file 可以并行执行,总耗时等于最慢的那个而不是三者之和。
不同 LLM provider 对工具调用的支持格式不同,AgentForge 通过适配层统一:
# OpenAI 格式 tools = [{ "type": "function", "function": { "name": "bash", "description": "Execute shell command", "parameters": { ... } } }] # Anthropic 格式 tools = [{ "name": "bash", "description": "Execute shell command", "input_schema": { ... } }] # AgentForge 统一格式(内部) # Tool.get_schema() 返回标准格式 # Provider adapter 负责转换
关键:Tool 基类的 get_schema() 返回的是 provider 无关的格式。 各个 provider adapter(OpenAIAdapter、AnthropicAdapter 等)负责转换为对应格式。 添加新 provider 时,只需要写一个 adapter,所有现有工具自动兼容。
一张图记住工具系统的所有关键概念。
TOOLS[](JSON Schema 给 LLM 看)+ TOOL_HANDLERS{}(函数字典给系统用)
注册中心,三个方法:register()、get_schemas()、get_handlers()
ABC 抽象基类,定义 name、description、parameters、execute()、get_schema()
subprocess.run(shell=True, capture_output=True, timeout=30)
bash、read_file、write_file、edit_file、glob
创建类 → register() → 自动可用,零修改已有代码
路径限制、输出截断(snip_large_output)、错误处理
isConcurrencySafe 标记,只读工具可并行,写入工具必须串行
一句话总结:工具系统 = Agent 的双手。加一个工具只需要加一个 handler。LLM 通过 JSON Schema「知道」工具,系统通过 Handler 字典「执行」工具。就这么简单。