Lesson 02

Tool Dispatch 工具分发

循环没变,只是多了工具

// Dispatch Map Architecture

block.name → Map.get(name) → handler.execute(input) LLM Dispatch Center Bash 命令执行 Read File 文件读取 Write File 文件写入 Edit File 文件编辑 safePath() boundary Map<String, Handler> "bash" → BashTool "read_file" → ReadTool "write_file" → WriteTool "edit_file" → EditTool

Key Concepts 核心概念

01

分发模式 Dispatch Pattern

Map<String, ToolHandler> 实现工具注册。模型返回 block.name,代码用 map.get() 找到对应 handler 执行。

A simple Map lookup replaces if-else chains. Tool name from the model maps directly to a handler instance.

02

安全边界 Safety Boundary

safePath() 检查路径不越界,危险命令(rm -rf /、sudo)被拦截。安全层独立于业务逻辑。

safePath() validates file paths stay within project boundaries. Dangerous commands are intercepted before execution.

03

零改动循环 Zero-Change Loop

Agent loop 代码一字未改。新增工具只需往 Map 里注册一个 handler,循环自动分发。开闭原则的完美体现。

The agent loop code is unchanged from S01. Adding tools only requires registering new handlers in the map.

Tool Interface 工具接口

Tool Name Handler Method 说明
bash BashTool.execute(command) 执行 shell 命令,返回 stdout/stderr
read_file ReadFileTool.execute(path) 读取文件内容,safePath 校验
write_file WriteFileTool.execute(path, content) 写入文件,自动创建目录
edit_file EditFileTool.execute(path, old, new) 精准替换,避免重写整个文件

试一试 Try It Out

1

"读取 pom.xml 文件"

"Read the file pom.xml"

2

"创建一个名为 Greeter.java 的文件,包含一个 greet(name) 方法"

"Create a file called Greeter.java with a greet(name) function"

3

"编辑 Greeter.java,为方法添加文档注释"

"Edit Greeter.java to add a docstring to the function"

4

"读取 Greeter.java 验证编辑成功"

"Read Greeter.java to verify the edit worked"