v1.5 多工具并发执行
将引擎的工具调用从串行改为并行:预分配结果切片 + sync.WaitGroup + 按索引无锁写入,模型一次请求多个工具时同时执行。
This commit is contained in:
Generated
+8
@@ -0,0 +1,8 @@
|
||||
# 默认忽略的文件
|
||||
/shelf/
|
||||
/workspace.xml
|
||||
# 基于编辑器的 HTTP 客户端请求
|
||||
/httpRequests/
|
||||
# Datasource local storage ignored files
|
||||
/dataSources/
|
||||
/dataSources.local.xml
|
||||
@@ -65,14 +65,16 @@ func main() {
|
||||
|
||||
## 版本历史
|
||||
|
||||
### v1.5 — Edit 工具:从"重写整个文件"进化到"精准局部替换"
|
||||
### v1.5 — Edit 工具 + 四级容错替换 + 多工具并发执行
|
||||
|
||||
#### 变更
|
||||
|
||||
- **新增 EditFileTool** — 实现四级容错降级替换算法(L1 精确 → L2 换行符归一 → L3 Trim Space → L4 逐行去缩进滑动窗口),解决大模型代码修改时缩进丢失、换行符不一致等幻觉问题
|
||||
- **工具扩展** — 工具集从 3 个(read / write / bash)扩展到 4 个(+ edit)
|
||||
- **工具集扩展** — 工具集从 3 个(read / write / bash)扩展到 4 个(+ edit)
|
||||
- **cmd/claw 任务更新** — 演示 edit_file 的局部替换能力,编辑 server.go 中的鉴权逻辑
|
||||
- **server.go** — 新增测试目标文件
|
||||
- **多工具并发执行** — 引擎从串行执行改为并行:预分配结果切片 + `sync.WaitGroup` + 按索引无锁写入,模型一次请求多个工具时同时执行,大幅缩短多文件操作场景的响应时间
|
||||
- **cmd/claw 任务切换** — 演示改为并发读取三个文件(a.txt / b.txt / c.txt),验证并发执行正确性
|
||||
|
||||
#### 踩坑记录
|
||||
|
||||
@@ -81,12 +83,14 @@ func main() {
|
||||
| 大模型生成的代码缩进不一致 | 模型推理时对源文件缩进(tab/空格)感知不准,产生多一个空格或少一个 tab | 编辑工具内建多级模糊匹配,不要求模型生成的 old_text 与原文件严格一致 |
|
||||
| 同一段代码在文件中出现多次 | 模型给的 old_text 上下文不够,匹配到多处 | 算法检测多匹配后直接返回错误给模型:"匹配到 X 处,请提供更多上下文" |
|
||||
| Windows 换行符 `\r\n` vs `\n` 不一致 | 模型通常输出 `\n`,Windows 文件可能是 `\r\n` | L2 换行符归一化:统一转成 `\n` 后再对比 |
|
||||
| Goroutine 闭包捕获 loop 变量 | Go 的 loop 变量是单地址复用,直接 `go func()` 捕获同一份引用 | 将 `i` 和 `toolCall` 作为参数传入 goroutine,确保每个协程拿到自己的副本 |
|
||||
|
||||
#### 经验教训
|
||||
|
||||
1. **Agent 工具要做"容错输入,严格输出"** — 接受模型可能不完美的输入(多级模糊匹配),但输出清晰的错误信息帮模型自我纠正("匹配到 3 处"而非"匹配失败")
|
||||
2. **工具语义要匹配模型的能力边界** — 模型擅长生成文本但弱于精确复制。`edit_file`(给 old_text + new_text)比"重写整个文件"更适合 Agent 场景,因为它不要求模型完整认知整个文件
|
||||
3. **工具组合产生协作效应** — read_file + edit_file 是天然搭档:read 建立上下文认知 → edit 执行局部修改 → bash 验证结果。单一工具的力量有限,组合后才是真正的 Agent
|
||||
4. **并发安全可以零成本** — 预分配切片 + 按索引写入 + 主 goroutine 串行读取,既不需要 Mutex 也不需要 Channel,比加锁方案更简洁高效
|
||||
|
||||
### v1.4 — 工具集扩展与 Windows 编码攻坚
|
||||
|
||||
|
||||
+12
-7
@@ -27,16 +27,21 @@ func main() {
|
||||
registry.Register(tools.NewEditFileTool(workDir))
|
||||
|
||||
// 实例化引擎,开启 EnableThinking = true
|
||||
eng := engine.NewAgentEngine(llmProvider, registry, workDir, false)
|
||||
eng := engine.NewAgentEngine(llmProvider, registry, workDir, true)
|
||||
|
||||
// 发起一个需要局部修改的指令
|
||||
//prompt := `
|
||||
//我当前目录下有一个 server.go 文件。
|
||||
//请帮我把里面 "TODO: 增加鉴权逻辑" 下面的那个 if 语句,整个替换为:
|
||||
//if user == nil {
|
||||
// fmt.Println("Forbidden!")
|
||||
// return
|
||||
//}
|
||||
//`
|
||||
|
||||
prompt := `
|
||||
我当前目录下有一个 server.go 文件。
|
||||
请帮我把里面 "TODO: 增加鉴权逻辑" 下面的那个 if 语句,整个替换为:
|
||||
if user == nil {
|
||||
fmt.Println("Forbidden!")
|
||||
return
|
||||
}
|
||||
我当前目录下有 a.txt, b.txt, c.txt 三个文件。
|
||||
为了节省时间,请你同时一次性读取这三个文件,并将它们的内容综合起来,告诉我它们分别记录了什么领域的信息。
|
||||
`
|
||||
|
||||
err := eng.Run(context.Background(), prompt)
|
||||
|
||||
+48
-22
@@ -4,6 +4,7 @@ import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log"
|
||||
"sync"
|
||||
|
||||
"go-tiny-claw/internal/provider"
|
||||
"go-tiny-claw/internal/schema"
|
||||
@@ -55,7 +56,6 @@ func dumpTools(tools []schema.ToolDefinition) {
|
||||
}
|
||||
}
|
||||
|
||||
// internal/engine/loop.go (续)
|
||||
func (e *AgentEngine) Run(ctx context.Context, userPrompt string) error {
|
||||
log.Printf("[Engine] 引擎启动,锁定工作区: %s\n", e.WorkDir)
|
||||
log.Printf("[Engine] 慢思考模式 (Thinking Phase): %v\n", e.EnableThinking)
|
||||
@@ -139,32 +139,58 @@ func (e *AgentEngine) Run(ctx context.Context, userPrompt string) error {
|
||||
break
|
||||
}
|
||||
|
||||
log.Printf("[Engine] 模型请求调用 %d 个工具...\n", len(actionResp.ToolCalls))
|
||||
log.Printf("[Engine] 模型请求并发调用 %d 个工具...\n", len(actionResp.ToolCalls))
|
||||
|
||||
for _, toolCall := range actionResp.ToolCalls {
|
||||
log.Printf(" -> 🛠️ 执行工具: %s, 参数: %s\n", toolCall.Name, string(toolCall.Arguments))
|
||||
// 【核心改造开始】: 从串行 (Sequential) 演进为并行 (Parallel)
|
||||
|
||||
result := e.registry.Execute(ctx, toolCall)
|
||||
// 1. 预分配一个固定长度的切片,用于安全地存放各个并发工具的执行结果(Observation)
|
||||
// 长度与 ToolCalls 的数量完全一致
|
||||
observationMsgs := make([]schema.Message, len(actionResp.ToolCalls))
|
||||
|
||||
status := "✅ 成功"
|
||||
if result.IsError {
|
||||
status = "❌ 失败"
|
||||
}
|
||||
log.Printf(" -> 📋 ToolCall %s: %s, 结果: %s\n", toolCall.ID, status, result.Output)
|
||||
// 2. 声明 WaitGroup 用于阻塞等待所有协程完成
|
||||
var wg sync.WaitGroup
|
||||
|
||||
if result.IsError {
|
||||
log.Printf(" -> ❌ 工具执行报错: %s\n", result.Output)
|
||||
} else {
|
||||
log.Printf(" -> ✅ 工具执行成功 (返回 %d 字节)\n", len(result.Output))
|
||||
}
|
||||
// 3. 遍历模型请求的所有工具,为每一个工具单独 Fork 出一个 Goroutine
|
||||
for i, toolCall := range actionResp.ToolCalls {
|
||||
wg.Add(1) // 增加计数器
|
||||
|
||||
// 将工具执行的观察结果追加到 Context,准备进入下一轮
|
||||
observationMsg := schema.Message{
|
||||
Role: schema.RoleUser,
|
||||
Content: result.Output,
|
||||
ToolCallID: toolCall.ID,
|
||||
}
|
||||
contextHistory = append(contextHistory, observationMsg)
|
||||
// 开启协程。注意:一定要将索引 i 和 toolCall 作为参数传入匿名函数,防止闭包变量捕获陷阱!
|
||||
go func(idx int, call schema.ToolCall) {
|
||||
defer wg.Done() // 协程结束时计数器减一
|
||||
|
||||
log.Printf(" -> [Go-%d] 🛠️ 触发并行执行: %s\n", idx, call.Name)
|
||||
|
||||
// 调用底层 Registry 执行工具(物理操作)
|
||||
result := e.registry.Execute(ctx, call)
|
||||
|
||||
if result.IsError {
|
||||
log.Printf(" -> [Go-%d] ❌ 工具执行报错: %s\n", idx, result.Output)
|
||||
} else {
|
||||
log.Printf(" -> [Go-%d] ✅ 工具执行成功 (返回 %d 字节)\n", idx, len(result.Output))
|
||||
}
|
||||
|
||||
// 将执行结果封装为一条用户消息 (RoleUser)
|
||||
obsMsg := schema.Message{
|
||||
Role: schema.RoleUser,
|
||||
Content: result.Output,
|
||||
ToolCallID: call.ID,
|
||||
}
|
||||
|
||||
// 【线程安全】: 由于每个 Goroutine 操作的是预分配切片的不同索引,
|
||||
// 这里不需要加锁 (Mutex),性能极高!
|
||||
observationMsgs[idx] = obsMsg
|
||||
|
||||
}(i, toolCall) // 闭包传参
|
||||
}
|
||||
|
||||
// 4. Join 阻塞等待:主循环挂起,直到所有的并发协程全部执行完毕
|
||||
wg.Wait()
|
||||
log.Println("[Engine] 所有并发工具执行完毕,开始聚合观察结果 (Observation)...")
|
||||
|
||||
// 5. 聚合装填:将并行的结果,按照原本的顺序,一次性追加到上下文时间线中
|
||||
// 这等价于 contextHistory = append(contextHistory, observationMsgs...)
|
||||
for _, obs := range observationMsgs {
|
||||
contextHistory = append(contextHistory, obs)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user