01 Agent Loop → 当前 02 Tool System

🔧 Tool System

工具系统是 Agent 的 双手 —— 让 LLM 从「能说会道」进化到「能做实事」

🦇
蝙蝠侠的工具腰带

蝙蝠侠之所以是蝙蝠侠,不是因为他有多强壮,而是因为他的 工具腰带。 蝙蝠镖、钩爪枪、烟雾弹……每样工具解决一个问题。
Agent 的工具系统就是它的 工具腰带。 LLM 本身只会「思考」,但有了工具,它就能 读写文件、执行命令、搜索代码。

📦 01 · 核心概念

什么是工具?两个核心

工具系统的本质极其简单:加一个工具,只需要加一个 handler。整个系统围绕两个核心数据结构运转。

💡

核心思想:TOOLS[] 告诉 LLM「你有什么工具可用」,TOOL_HANDLERS{} 告诉系统「收到调用时该执行什么」。一个是「名片」,一个是「电话簿」。

📋 TOOLS[] — JSON Schema 数组

给 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"]
  }
}
⚡ TOOL_HANDLERS{} — 函数字典

给系统用的「执行手册」。一个字典,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),它不需要也不应该知道具体实现细节。分离让系统更安全、更灵活。

🗂️ 02 · 注册中心

ToolRegistry — 工具注册中心

ToolRegistry 是管理所有工具的中心枢纽。它维护两张表:工具 Schema 和 Handler。 三个核心方法:register()、get_schemas()、get_handlers()。

📋 get_schemas() → TOOLS[]

bash
Execute shell commands
read_file
Read file contents with line numbers
write_file
Write content to a file
edit_file
Find and replace in files
glob
Find files by pattern
⟷ ⟷ ⟷ ⟷ ⟷

⚡ get_handlers() → HANDLERS{}

bash → bash_handler()
subprocess.run(...)
read_file → read_handler()
open(path).read()
write_file → write_handler()
open(path, 'w').write()
edit_file → edit_handler()
str.replace(old, new)
glob → glob_handler()
glob.glob(pattern)
tool_registry.py
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
1 register() 是核心 —— 调用一次 register,同时完成两件事:把 Schema 加入 TOOLS[],把 execute 函数绑定到 HANDLERS{}。
2 get_schemas() 给 LLM —— 在每次对话开始时,系统调用此方法拿到所有工具的 JSON Schema,作为 system prompt 的一部分传给 LLM。
3 get_handlers() 给系统 —— 当 LLM 返回 tool_call 时,系统从此字典中查找对应的 handler 并执行。
🏗️ 03 · 基类设计

Tool 基类 — 一切工具的模板

所有工具都继承自 Tool 抽象基类(ABC)。它定义了每个工具必须具备的「身份证」和「执行能力」。

tools/base.py
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,
        }
① name —— 工具的唯一标识,如 "bash"、"read_file"。LLM 返回的 tool_call 中必须匹配这个名字。
② description —— 越清晰越好!LLM 靠这段文字决定「该不该用这个工具」。
③ parameters —— JSON Schema 格式,定义参数名称、类型、是否必填。LLM 根据此结构生成参数。
④ execute() —— 抽象方法,子类必须实现。这是工具真正「干活」的地方。
⑤ get_schema() —— 把 name + description + parameters 打包成一个 dict,注册时由 ToolRegistry 调用。
🎯

设计哲学:一个工具 = 一个类。加新工具只需要写一个类、调一次 register()。不需要修改任何已有代码。这就是 开闭原则(对扩展开放,对修改关闭)。

💻 04 · 核心工具

BashTool — Agent 的万能手

BashTool 是最重要的内置工具。它让 Agent 能执行任意 shell 命令,从而获得与计算机交互的能力。

tools/bash_tool.py
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)}"
1 shell=True —— 启用 shell 解释器,支持管道 |、重定向 >、通配符 * 等语法。注意:这也意味着安全性依赖于外部防护。
2 capture_output=True —— 将 stdout 和 stderr 都捕获到内存中,而不是直接打印到终端。Agent 需要读取输出结果。
3 timeout=30 —— 防止命令挂起。如果 30 秒内没完成,自动终止并返回超时错误。while true 之类的死循环不会卡死整个系统。
4 snip_large_output() —— 输出截断函数。如果命令输出超过阈值(如 50KB),自动截断并添加 [... snipped ...] 标记,防止上下文窗口被撑爆。
🔄 05 · 执行流程

工具调用的完整生命周期

从用户输入到工具执行再到结果返回,每一步都有明确的职责。

1
用户发送消息
"帮我看看 src/ 目录下有哪些 Python 文件"
2
系统注入工具 Schema
将 TOOL_HANDLERS 中所有工具的 JSON Schema 放入 system prompt
tools = registry.get_schemas()
3
LLM 决策并返回 tool_call
LLM 分析需求,决定调用 glob 工具
{"name": "glob", "args": {"pattern": "src/**/*.py"}}
4
系统查找 Handler
从 TOOL_HANDLERS 字典中找到对应的执行函数
handler = TOOL_HANDLERS["glob"]
5
执行并返回结果
调用 handler,获取执行结果,格式化后返回给 LLM
result = handler(pattern="src/**/*.py")
6
LLM 解读结果并回复用户
LLM 拿到文件列表后,组织语言回答用户
🎮 交互演示:工具调用模拟

点击下方按钮,模拟一次完整的工具调用流程

点击「模拟调用」开始...
🧰 06 · 内置工具

5 个内置工具

AgentForge 内置了 5 个核心工具,覆盖了最常见的文件操作和系统交互需求。

💻 bash

执行任意 shell 命令。这是最强大也最危险的工具,Agent 的「万能手」。

# 示例调用
bash(command="ls -la src/")
bash(command="git log --oneline -5")
bash(command="python -m pytest tests/")
📖 read_file

读取文件内容,支持行号和分页。不会修改文件,是安全的只读操作。

# 示例调用
read_file(path="src/main.py")
read_file(path="config.json", offset=10, limit=50)
✏️ write_file

写入文件内容,会完全覆盖原文件。创建新文件或覆写已有文件。

# 示例调用
write_file(
  path="src/utils.py",
  content="def hello():\n    print('hi')"
)
🔧 edit_file

精确查找替换,支持模糊匹配。修改文件时用它而不是 write_file。

# 示例调用
edit_file(
  path="src/main.py",
  old_string="def old_name(",
  new_string="def new_name("
)
🔍 glob

按模式搜索文件名。支持通配符,速度快,只返回文件路径列表。

# 示例调用
glob(pattern="**/*.py")
glob(pattern="src/**/*test*")
🎨 07 · 自定义工具

创建自定义工具

添加自定义工具只需要三步:创建类 → 注册 → 自动可用。下面以 WeatherTool 为例。

tools/weather_tool.py
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 绑定。你只需要写好类。

🔌

插件化架构
每个工具是独立的模块,互不影响。社区可以贡献新工具,无需修改核心代码。

🛡️ 08 · 安全机制

三道安全防线

工具系统给了 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
🧠 09 · 知识检验

Quiz — 测测你的理解

5 道题,检验你对工具系统的掌握程度。

QUESTION 01 / 05
TOOLS[] 和 TOOL_HANDLERS{} 分别是什么?
A TOOLS[] 是执行函数,HANDLERS{} 是 JSON Schema
B TOOLS[] 是 JSON Schema 数组(给 LLM 看),HANDLERS{} 是函数字典(给系统用)
C 两者完全相同,只是格式不同
D TOOLS[] 存储配置,HANDLERS{} 存储日志
QUESTION 02 / 05
ToolRegistry 的 register() 方法做了什么?
A 只将工具的 Schema 加入 TOOLS[]
B 只将 execute 函数绑定到 HANDLERS{}
C 同时完成 Schema 提取和 Handler 绑定
D 创建一个新的 Tool 子类
QUESTION 03 / 05
BashTool 使用 subprocess.run 时,timeout 参数的作用是?
A 防止命令挂起,超时后自动终止并返回错误
B 限制输出的字符数量
C 限制命令的复杂度
D 设置命令的优先级
QUESTION 04 / 05
添加一个新的自定义工具需要几步?
A 需要修改 ToolRegistry 源码、添加 handler、更新配置文件
B 需要修改 LLM 的 system prompt 和添加执行代码
C 需要重启整个系统并重新加载配置
D 创建 Tool 子类 + 调用 registry.register(),无需修改任何已有代码
QUESTION 05 / 05
isConcurrencySafe 标记的作用是什么?
A 标记工具是否需要用户授权
B 标记工具是否可以与其他工具并行执行
C 标记工具是否可以在网络上运行
D 标记工具是否支持多语言
🔬 10 · 深度探索

Deep Dives

想要更深入?展开下面的卡片探索更多细节。

🧠 LLM 是如何「看到」工具的? ARCHITECTURE

▼

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 传给模型,让模型知道有哪些工具可用。

⚡ snip_large_output 的设计细节 IMPLEMENTATION

▼
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 和错误信息。 中间部分往往是重复的代码,截断损失最小。

🔀 工具并行执行的实现 CONCURRENCY

▼

当 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 可以并行执行,总耗时等于最慢的那个而不是三者之和。

🌐 跨 Provider 工具兼容 COMPATIBILITY

▼

不同 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,所有现有工具自动兼容。

📌 11 · 本章总结

Tool System 核心要点

一张图记住工具系统的所有关键概念。

🎯

两个核心

TOOLS[](JSON Schema 给 LLM 看)+ TOOL_HANDLERS{}(函数字典给系统用)

🗂️

ToolRegistry

注册中心,三个方法:register()、get_schemas()、get_handlers()

🏗️

Tool 基类

ABC 抽象基类,定义 name、description、parameters、execute()、get_schema()

💻

BashTool

subprocess.run(shell=True, capture_output=True, timeout=30)

🧰

5 个内置工具

bash、read_file、write_file、edit_file、glob

🎨

自定义工具

创建类 → register() → 自动可用,零修改已有代码

🛡️

三道安全防线

路径限制、输出截断(snip_large_output)、错误处理

⚡

并发安全

isConcurrencySafe 标记,只读工具可并行,写入工具必须串行

💡

一句话总结:工具系统 = Agent 的双手。加一个工具只需要加一个 handler。LLM 通过 JSON Schema「知道」工具,系统通过 Handler 字典「执行」工具。就这么简单。