v1.5 Edit 工具 + 四级容错替换算法

- 新增 EditFileTool,支持局部字符串替换
- 四级容错降级:精确匹配 → 换行符归一 → Trim Space → 逐行滑动窗口
- 工具集扩展至 4 个(read/write/edit/bash)
- 新增 server.go 测试目标文件
This commit is contained in:
zhuyongxin
2026-05-15 18:32:57 +08:00
parent cefabd68dc
commit deb1b6e660
4 changed files with 219 additions and 7 deletions
+23
View File
@@ -65,6 +65,29 @@ func main() {
## 版本历史 ## 版本历史
### v1.5 — Edit 工具:从"重写整个文件"进化到"精准局部替换"
#### 变更
- **新增 EditFileTool** — 实现四级容错降级替换算法(L1 精确 → L2 换行符归一 → L3 Trim Space → L4 逐行去缩进滑动窗口),解决大模型代码修改时缩进丢失、换行符不一致等幻觉问题
- **工具扩展** — 工具集从 3 个(read / write / bash)扩展到 4 个(+ edit)
- **cmd/claw 任务更新** — 演示 edit_file 的局部替换能力,编辑 server.go 中的鉴权逻辑
- **server.go** — 新增测试目标文件
#### 踩坑记录
| 问题 | 原因 | 解决 |
|---|---|---|
| 大模型生成的代码缩进不一致 | 模型推理时对源文件缩进(tab/空格)感知不准,产生多一个空格或少一个 tab | 编辑工具内建多级模糊匹配,不要求模型生成的 old_text 与原文件严格一致 |
| 同一段代码在文件中出现多次 | 模型给的 old_text 上下文不够,匹配到多处 | 算法检测多匹配后直接返回错误给模型:"匹配到 X 处,请提供更多上下文" |
| Windows 换行符 `\r\n` vs `\n` 不一致 | 模型通常输出 `\n`,Windows 文件可能是 `\r\n` | L2 换行符归一化:统一转成 `\n` 后再对比 |
#### 经验教训
1. **Agent 工具要做"容错输入,严格输出"** — 接受模型可能不完美的输入(多级模糊匹配),但输出清晰的错误信息帮模型自我纠正("匹配到 3 处"而非"匹配失败")
2. **工具语义要匹配模型的能力边界** — 模型擅长生成文本但弱于精确复制。`edit_file`(给 old_text + new_text)比"重写整个文件"更适合 Agent 场景,因为它不要求模型完整认知整个文件
3. **工具组合产生协作效应** — read_file + edit_file 是天然搭档:read 建立上下文认知 → edit 执行局部修改 → bash 验证结果。单一工具的力量有限,组合后才是真正的 Agent
### v1.4 — 工具集扩展与 Windows 编码攻坚 ### v1.4 — 工具集扩展与 Windows 编码攻坚
#### 变更 #### 变更
+10 -7
View File
@@ -20,20 +20,23 @@ func main() {
registry := tools.NewRegistry() registry := tools.NewRegistry()
// 挂载极简工具集 // 挂载工具全家桶
registry.Register(tools.NewReadFileTool(workDir)) registry.Register(tools.NewReadFileTool(workDir))
registry.Register(tools.NewWriteFileTool(workDir)) registry.Register(tools.NewWriteFileTool(workDir))
registry.Register(tools.NewBashTool(workDir)) registry.Register(tools.NewBashTool(workDir))
registry.Register(tools.NewEditFileTool(workDir))
// 实例化核心引擎,关闭慢思考阶段,享受 YOLO 急速模式 // 实例化引擎,开启 EnableThinking = true
eng := engine.NewAgentEngine(llmProvider, registry, workDir, false) eng := engine.NewAgentEngine(llmProvider, registry, workDir, false)
// 发起一个需要连贯物理动作的任务 // 发起一个需要局部修改的指令
prompt := ` prompt := `
请帮我执行以下操作: 我当前目录下有一个 server.go 文件。
1. 用 bash 查看一下我当前电脑的 Go 版本,我的电脑是windows系统。 请帮我把里面 "TODO: 增加鉴权逻辑" 下面的那个 if 语句,整个替换为:
2. 帮我写一个简单的 helloworld.go 文件,输出 "Hello, go-tiny-claw!"。 if user == nil {
3. 用 bash 编译并运行这个 go 文件,确认它能正常工作。 fmt.Println("Forbidden!")
return
}
` `
err := eng.Run(context.Background(), prompt) err := eng.Run(context.Background(), prompt)
+172
View File
@@ -0,0 +1,172 @@
package tools
import (
"context"
"encoding/json"
"fmt"
"go-tiny-claw/internal/schema"
"os"
"path/filepath"
"strings"
)
type EditFileTool struct {
workDir string
}
func NewEditFileTool(workDir string) *EditFileTool {
return &EditFileTool{workDir: workDir}
}
func (t *EditFileTool) Name() string {
return "edit_file"
}
func (t *EditFileTool) Definition() schema.ToolDefinition {
return schema.ToolDefinition{
Name: t.Name(),
Description: "对现有文件进行局部的字符串替换。这比重写整个文件更安全、更快速。请提供足够的 old_text 上下文以确保匹配的唯一性。",
InputSchema: map[string]interface{}{
"type": "object",
"properties": map[string]interface{}{
"path": map[string]interface{}{
"type": "string",
"description": "要修改的文件路径",
},
"old_text": map[string]interface{}{
"type": "string",
"description": "文件中原有的文本。必须包含足够的上下文(建议上下各多包含几行),以确保在文件中的唯一性。",
},
"new_text": map[string]interface{}{
"type": "string",
"description": "要替换成的新文本",
},
},
"required": []string{"path", "old_text", "new_text"},
},
}
}
type editFileArgs struct {
Path string `json:"path"`
OldText string `json:"old_text"`
NewText string `json:"new_text"`
}
// fuzzyReplace 实现了四级容错降级替换算法
func fuzzyReplace(originalContent, oldText, newText string) (string, error) {
// L1: 精确匹配
count := strings.Count(originalContent, oldText)
if count == 1 {
return strings.Replace(originalContent, oldText, newText, 1), nil
}
if count > 1 {
return "", fmt.Errorf("old_text 匹配到了 %d 处,请提供更多的上下文代码以确保唯一性", count)
}
// L2: 换行符归一化 (统一将 \r\n 转换为 \n)
normalizedContent := strings.ReplaceAll(originalContent, "\r\n", "\n")
normalizedOld := strings.ReplaceAll(oldText, "\r\n", "\n")
count = strings.Count(normalizedContent, normalizedOld)
if count == 1 {
return strings.Replace(normalizedContent, normalizedOld, newText, 1), nil
}
// L3: Trim Space 匹配 (忽略首尾的空行和空格)
trimmedOld := strings.TrimSpace(normalizedOld)
if trimmedOld != "" {
count = strings.Count(normalizedContent, trimmedOld)
if count == 1 {
// 注意:这里替换时,我们只能替换被 Trim 后的部分,不能直接用 newText 破坏原本的缩进
// 为了保持本专栏代码不过于冗长复杂,当触发 L3/L4 时,如果 newText 没有带有正确的缩进,
// 可能会导致替换后代码格式不美观。但这总比直接报错让 Agent 死循环要好。
return strings.Replace(normalizedContent, trimmedOld, newText, 1), nil
}
}
// L4: 逐行去缩进匹配 (最强力的容错:消除大模型遗漏缩进的幻觉)
return lineByLineReplace(normalizedContent, normalizedOld, newText)
}
// lineByLineReplace 将文本按行切割,去除首尾空白后进行滑动窗口匹配
func lineByLineReplace(content, oldText, newText string) (string, error) {
contentLines := strings.Split(content, "\n")
oldLines := strings.Split(strings.TrimSpace(oldText), "\n")
if len(oldLines) == 0 || len(contentLines) < len(oldLines) {
return "", fmt.Errorf("找不到该代码片段")
}
// 清理 oldLines 的每行首尾空白
for i := range oldLines {
oldLines[i] = strings.TrimSpace(oldLines[i])
}
matchCount := 0
matchStartIndex := -1
matchEndIndex := -1
// 滑动窗口在原始文件中寻找匹配块
for i := 0; i <= len(contentLines)-len(oldLines); i++ {
isMatch := true
for j := 0; j < len(oldLines); j++ {
if strings.TrimSpace(contentLines[i+j]) != oldLines[j] {
isMatch = false
break
}
}
if isMatch {
matchCount++
matchStartIndex = i
matchEndIndex = i + len(oldLines)
}
}
if matchCount == 0 {
return "", fmt.Errorf("在文件中未找到 old_text,请大模型先调用 read_file 仔细确认文件内容和缩进")
}
if matchCount > 1 {
return "", fmt.Errorf("模糊匹配到了 %d 处相似代码,请提供更多上下行代码以精确定位", matchCount)
}
// 执行替换:将匹配到的原始行范围替换为 newText 拆分后的行
// (这里简单处理,将 newText 直接作为整体替换进去)
var newContentLines []string
newContentLines = append(newContentLines, contentLines[:matchStartIndex]...)
newContentLines = append(newContentLines, newText) // 插入新内容
newContentLines = append(newContentLines, contentLines[matchEndIndex:]...)
return strings.Join(newContentLines, "\n"), nil
}
func (t *EditFileTool) Execute(ctx context.Context, args json.RawMessage) (string, error) {
var input editFileArgs
if err := json.Unmarshal(args, &input); err != nil {
return "", fmt.Errorf("参数解析失败: %w", err)
}
fullPath := filepath.Join(t.workDir, input.Path)
// 1. 读取原文件内容
contentBytes, err := os.ReadFile(fullPath)
if err != nil {
return "", fmt.Errorf("读取文件失败,请确认路径是否正确: %w", err)
}
originalContent := string(contentBytes)
// 2. 调用多级模糊替换算法
newContent, err := fuzzyReplace(originalContent, input.OldText, input.NewText)
if err != nil {
// 【驾驭哲学】将具体的报错原因 (如匹配到多处) 原样返回,让大模型自行纠正
return "", err
}
// 3. 将新内容安全地写回磁盘
if err := os.WriteFile(fullPath, []byte(newContent), 0644); err != nil {
return "", fmt.Errorf("写回文件失败: %w", err)
}
return fmt.Sprintf("✅ 成功修改文件: %s", input.Path), nil
}
+14
View File
@@ -0,0 +1,14 @@
package main
import "fmt"
func main() {
// 启动服务器
fmt.Println("Server is starting on port 8080...")
// TODO: 增加鉴权逻辑
if user == nil {
fmt.Println("Forbidden!")
return
}
}