Compare commits
3
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
deb1b6e660 | ||
|
|
cefabd68dc | ||
|
|
b94460083a |
@@ -65,6 +65,80 @@ 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 编码攻坚
|
||||
|
||||
#### 变更
|
||||
|
||||
- **新增 BashTool** — 执行本地 bash 命令,支持 30s 超时、错误原样回传(模型自愈)、8KB 输出截断
|
||||
- **新增 WriteFileTool** — 写文件到工作区,覆盖/新建均支持
|
||||
- **Windows GBK 编码修复** — 命令输出从 GBK 自动转 UTF-8(`golang.org/x/text/encoding/simplifiedchinese`),不依赖 `chcp`
|
||||
- **API 交互日志** — `OpenAIProvider.Generate` 新增请求/响应日志(阶段标记、消息数、工具数、ToolCall 明细)
|
||||
- **调试输出优化** — `dumpMessages` 移除 80 字符截断,完整展示上下文内容
|
||||
- **三段式任务演示** — `cmd/claw` 任务改为:查 Go 版本 → 写 helloworld.go → 编译运行
|
||||
|
||||
#### 踩坑记录
|
||||
|
||||
| 问题 | 原因 | 解决 |
|
||||
|---|---|---|
|
||||
| bash 输出中文乱码 | Windows 命令输出为 GBK 编码,Go 按 UTF-8 解析 | 引入 `golang.org/x/text`,检测编码后自动转换 |
|
||||
| `chcp 65001` 导致终端刷屏 | `chcp` 在子进程中修改代码页可能影响终端渲染 | 放弃 `chcp` 方案,改用 Go 原生编码转换 |
|
||||
| `utf8.Valid` 检查后仍乱码 | GBK 字节序列碰巧也合法于 UTF-8,跳过转换 | 去掉 `utf8.Valid` 判断,Windows 下一律转换 |
|
||||
| `helloworld.go` 导致编译失败 | 模型生成的测试文件含 `main` 函数,与项目 main.go 冲突 | 运行后清理 `helloworld.*` 测试产物 |
|
||||
|
||||
#### 经验教训
|
||||
|
||||
1. **编码问题不要依赖外部命令** — `chcp` 属于"改环境让输出配合你",不可靠。Go 原生转码属于"你主动适应输出",稳定可控
|
||||
2. **`utf8.Valid` 不能当编码检测器** — 它的语义是"是否合法 UTF-8",不是"是否是 GBK"。GBK 和 UTF-8 有交集,用合法性判断编码方向是伪命题
|
||||
3. **Agent 的工具越多,越需要关注副作用** — 模型会写文件、执行命令,产生的文件(helloworld.go)可能反过来破坏项目结构。工具内部要做好隔离
|
||||
|
||||
### v1.3 — Registry 实现重构与第一把真实工具
|
||||
|
||||
#### 变更
|
||||
|
||||
- **Registry 完整实现** — 从纯接口升级为 `registryImpl`,基于 `map[string]BaseTool` 实现 O(1) 路由查找、动态注册、错误自愈
|
||||
- **BaseTool 接口** — 定义工具的通用契约(`Name()` / `Definition()` / `Execute()`),所有具体工具统一实现
|
||||
- **首个真实工具 ReadFileTool** — 支持读取工作区文件,含路径穿越防护和 8000 字节截断
|
||||
- **调试可视化** — `AgentEngine` 和 `registryImpl` 实现 `String()` 方法,替代 16 进制内存地址
|
||||
- **ToolCall 执行日志** — 每轮工具执行后输出一行状态日志(`📋 ToolCall xxx: ✅ / ❌, 结果: ...`)
|
||||
- **cmd/claw 真实化** — 从 mockRegistry 切换到 `tools.NewRegistry()` + `ReadFileTool`
|
||||
|
||||
#### 踩坑记录
|
||||
|
||||
| 问题 | 原因 | 解决 |
|
||||
|---|---|---|
|
||||
| `fmt.Println(registry)` 输出 16 进制地址 | Go 默认打印指针/接口类型为内存地址,不展示内容 | 实现 `fmt.Stringer` 接口,自定义 `String()` 方法 |
|
||||
| Registry 接口加 `Register` 后旧代码编译失败 | `main.go` 的 mockRegistry 没有实现新增的 `Register` 方法 | 为 mockRegistry 补充空实现 `Register(tool tools.BaseTool) {}` |
|
||||
| 修改代码时需要同时兼容旧 mock 和新实现 | demo 代码和正式代码共用同一套接口 | 保留 mock 的兼容性(无操作 Register),新演示代码使用真实实现 |
|
||||
|
||||
#### 经验教训
|
||||
|
||||
1. **接口先于实现,但实现要跟上** — v1.0 就定义了 `Registry` 接口,但一直没有真实实现,导致 cmd 只能靠 mock 跑。抽象要尽早落地
|
||||
2. **工具系统用 map 路由天然适合 Agent** — 大模型输出工具名 → 直接 map key 查找 → O(1) 路由,简单高效,也方便运行时动态挂载工具
|
||||
3. **`String()` 是 Go 调试的性价比之王** — 三行代码换来看日志时不用猜内存地址,投入产出比极高
|
||||
|
||||
### v1.2 — 真实模型接入与 Thinking 死循环修复
|
||||
|
||||
#### 变更
|
||||
|
||||
+29
-49
@@ -4,63 +4,43 @@ import (
|
||||
"context"
|
||||
"log"
|
||||
"os"
|
||||
"fmt"
|
||||
|
||||
"go-tiny-claw/internal/engine"
|
||||
"go-tiny-claw/internal/schema"
|
||||
"go-tiny-claw/internal/provider"
|
||||
"go-tiny-claw/internal/tools"
|
||||
)
|
||||
|
||||
|
||||
// 伪造的工具注册表 (用于测试 Provider 的工具提取能力)
|
||||
type mockRegistry struct{}
|
||||
|
||||
func (m *mockRegistry) GetAvailableTools() []schema.ToolDefinition {
|
||||
return []schema.ToolDefinition{
|
||||
{
|
||||
Name: "get_weather",
|
||||
Description: "获取指定城市的当前天气情况。",
|
||||
InputSchema: map[string]interface{}{
|
||||
"type": "object",
|
||||
"properties": map[string]interface{}{
|
||||
"city": map[string]interface{}{
|
||||
"type": "string",
|
||||
},
|
||||
},
|
||||
"required": []string{"city"},
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func (m *mockRegistry) Execute(ctx context.Context, call schema.ToolCall) schema.ToolResult {
|
||||
log.Printf(" -> [Mock 工具执行] 获取 %s 的天气中...\n", call.Name)
|
||||
return schema.ToolResult{
|
||||
ToolCallID: call.ID,
|
||||
Output: "API 返回:今天是晴天,气温 25 度。",
|
||||
IsError: false,
|
||||
}
|
||||
}
|
||||
|
||||
func main() {
|
||||
|
||||
fmt.Printf("11111")
|
||||
workDir, _ := os.Getwd()
|
||||
|
||||
// 1. 初始化真实的 Provider大脑 (指向智谱 GLM-4.5)
|
||||
// 这里你可以任意切换 NewZhipuClaudeProvider 或 NewZhipuOpenAIProvider,效果完全一致!
|
||||
llmProvider := provider.DeepseekOpenAIProvider("deepseek-v4-flash")
|
||||
// 2. 注入伪造的工具注册表
|
||||
registry := &mockRegistry{}
|
||||
workDir, _ := os.Getwd()
|
||||
|
||||
// 3. 实例化并运行引擎,开启 EnableThinking = true (开启慢思考阶段!)
|
||||
eng := engine.NewAgentEngine(llmProvider, registry, workDir, true)
|
||||
// 1. 初始化真实的 Provider大脑
|
||||
// 这里你可以任意切换 NewZhipuClaudeProvider 或 NewZhipuOpenAIProvider,效果完全一致!
|
||||
llmProvider := provider.DeepseekOpenAIProvider("deepseek-v4-flash")
|
||||
|
||||
// 设定测试任务
|
||||
prompt := "我想去北京跑步,帮我查查天气适合吗?"
|
||||
registry := tools.NewRegistry()
|
||||
|
||||
err := eng.Run(context.Background(), prompt)
|
||||
if err != nil {
|
||||
log.Fatalf("引擎运行崩溃: %v", err)
|
||||
// 挂载工具全家桶
|
||||
registry.Register(tools.NewReadFileTool(workDir))
|
||||
registry.Register(tools.NewWriteFileTool(workDir))
|
||||
registry.Register(tools.NewBashTool(workDir))
|
||||
registry.Register(tools.NewEditFileTool(workDir))
|
||||
|
||||
// 实例化引擎,开启 EnableThinking = true
|
||||
eng := engine.NewAgentEngine(llmProvider, registry, workDir, false)
|
||||
|
||||
// 发起一个需要局部修改的指令
|
||||
prompt := `
|
||||
我当前目录下有一个 server.go 文件。
|
||||
请帮我把里面 "TODO: 增加鉴权逻辑" 下面的那个 if 语句,整个替换为:
|
||||
if user == nil {
|
||||
fmt.Println("Forbidden!")
|
||||
return
|
||||
}
|
||||
}
|
||||
`
|
||||
|
||||
err := eng.Run(context.Background(), prompt)
|
||||
if err != nil {
|
||||
log.Fatalf("引擎运行崩溃: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,13 +3,16 @@ module go-tiny-claw
|
||||
go 1.23.0
|
||||
|
||||
require (
|
||||
github.com/anthropics/anthropic-sdk-go v1.43.0 // indirect
|
||||
github.com/anthropics/anthropic-sdk-go v1.43.0
|
||||
github.com/openai/openai-go/v3 v3.35.0
|
||||
golang.org/x/text v0.27.0
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/bahlo/generic-list-go v0.2.0 // indirect
|
||||
github.com/buger/jsonparser v1.1.2 // indirect
|
||||
github.com/invopop/jsonschema v0.13.0 // indirect
|
||||
github.com/joho/godotenv v1.5.1 // indirect
|
||||
github.com/mailru/easyjson v0.7.7 // indirect
|
||||
github.com/openai/openai-go/v3 v3.35.0 // indirect
|
||||
github.com/standard-webhooks/standard-webhooks/libraries v0.0.1 // indirect
|
||||
github.com/tidwall/gjson v1.18.0 // indirect
|
||||
github.com/tidwall/match v1.1.1 // indirect
|
||||
|
||||
@@ -4,17 +4,23 @@ github.com/bahlo/generic-list-go v0.2.0 h1:5sz/EEAK+ls5wF+NeqDpk5+iNdMDXrh3z3nPn
|
||||
github.com/bahlo/generic-list-go v0.2.0/go.mod h1:2KvAjgMlE5NNynlg/5iLrrCCZ2+5xWbdbCW3pNTGyYg=
|
||||
github.com/buger/jsonparser v1.1.2 h1:frqHqw7otoVbk5M8LlE/L7HTnIq2v9RX6EJ48i9AxJk=
|
||||
github.com/buger/jsonparser v1.1.2/go.mod h1:6RYKKt7H4d4+iWqouImQ9R2FZql3VbhNgx27UK13J/0=
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/dnaeon/go-vcr v1.2.0 h1:zHCHvJYTMh1N7xnV7zf1m1GPBF9Ad0Jk/whtQ1663qI=
|
||||
github.com/dnaeon/go-vcr v1.2.0/go.mod h1:R4UdLID7HZT3taECzJs4YgbbH6PIGXB6W/sc5OLb6RQ=
|
||||
github.com/invopop/jsonschema v0.13.0 h1:KvpoAJWEjR3uD9Kbm2HWJmqsEaHt8lBUpd0qHcIi21E=
|
||||
github.com/invopop/jsonschema v0.13.0/go.mod h1:ffZ5Km5SWWRAIN6wbDXItl95euhFz2uON45H2qjYt+0=
|
||||
github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0=
|
||||
github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=
|
||||
github.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFFd8Hwg//Y=
|
||||
github.com/mailru/easyjson v0.7.7 h1:UGYAvKxe3sBsEDzO8ZeWOSlIQfWFlxbzLZe7hwFURr0=
|
||||
github.com/mailru/easyjson v0.7.7/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc=
|
||||
github.com/openai/openai-go/v3 v3.35.0 h1:109x3epXMSE423KW2euR506GGFezcEt0s87MoWejpH0=
|
||||
github.com/openai/openai-go/v3 v3.35.0/go.mod h1:cdufnVK14cWcT9qA1rRtrXx4FTRsgbDPW7Ia7SS5cZo=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/standard-webhooks/standard-webhooks/libraries v0.0.1 h1:uOfcYT+3QungH6tIGSVCR/Y3KJmgJiHcojJbMTPDZAI=
|
||||
github.com/standard-webhooks/standard-webhooks/libraries v0.0.1/go.mod h1:L1MQhA6x4dn9r007T033lsaZMv9EmBAdXyU/+EF40fo=
|
||||
github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk=
|
||||
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
|
||||
github.com/tidwall/gjson v1.14.2/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk=
|
||||
github.com/tidwall/gjson v1.18.0 h1:FIDeeyB800efLX89e5a8Y0BNH+LOngJyGrIWxG2FKQY=
|
||||
github.com/tidwall/gjson v1.18.0/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk=
|
||||
@@ -29,6 +35,11 @@ github.com/wk8/go-ordered-map/v2 v2.1.8 h1:5h/BUHu93oj4gIdvHHHGsScSTMijfx5PeYkE/
|
||||
github.com/wk8/go-ordered-map/v2 v2.1.8/go.mod h1:5nJHM5DyteebpVlHnWMV0rPz6Zp7+xBAnxjb1X5vnTw=
|
||||
golang.org/x/sync v0.16.0 h1:ycBJEhp9p4vXvUZNszeOq0kGTPghopOL8q0fq3vstxw=
|
||||
golang.org/x/sync v0.16.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA=
|
||||
golang.org/x/text v0.27.0 h1:4fGWRpyh641NLlecmyl4LOe6yDdfaYNrGb2zdfo4JV4=
|
||||
golang.org/x/text v0.27.0/go.mod h1:1D28KMCvyooCX9hBiosv5Tz/+YLxj0j7XhWjpSUF7CU=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/yaml.v2 v2.2.8 h1:obN1ZagJSUGI0Ek/LBmuj4SNLPfIny3KsKFopxRdj10=
|
||||
gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
|
||||
+104
-94
@@ -16,26 +16,30 @@ type AgentEngine struct {
|
||||
registry tools.Registry
|
||||
|
||||
// WorkDir (工作区): 借鉴 OpenClaw 的理念,Agent 必须有一个明确的物理边界
|
||||
WorkDir string
|
||||
WorkDir string
|
||||
EnableThinking bool // 【新增】慢思考模式开关
|
||||
}
|
||||
|
||||
func NewAgentEngine(p provider.LLMProvider, r tools.Registry, workDir string, enableThinking bool) *AgentEngine {
|
||||
return &AgentEngine{
|
||||
provider: p,
|
||||
registry: r,
|
||||
WorkDir: workDir,
|
||||
provider: p,
|
||||
registry: r,
|
||||
WorkDir: workDir,
|
||||
EnableThinking: enableThinking,
|
||||
}
|
||||
}
|
||||
|
||||
func (e *AgentEngine) String() string {
|
||||
return fmt.Sprintf("AgentEngine{workDir: %s, thinking: %v, registry: %s}", e.WorkDir, e.EnableThinking, e.registry)
|
||||
}
|
||||
|
||||
// dumpMessages 打印当前上下文中的所有消息 (调试用)
|
||||
func dumpMessages(msgs []schema.Message) {
|
||||
for i, msg := range msgs {
|
||||
content := msg.Content
|
||||
if len(content) > 80 {
|
||||
content = content[:80] + "..."
|
||||
}
|
||||
// if len(content) > 80 {
|
||||
// content = content[:80] + "..."
|
||||
// }
|
||||
log.Printf(" [%02d] %-10s | %s", i, msg.Role, content)
|
||||
}
|
||||
}
|
||||
@@ -53,110 +57,116 @@ 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)
|
||||
log.Printf("[Engine] 引擎启动,锁定工作区: %s\n", e.WorkDir)
|
||||
log.Printf("[Engine] 慢思考模式 (Thinking Phase): %v\n", e.EnableThinking)
|
||||
|
||||
contextHistory := []schema.Message{
|
||||
{
|
||||
Role: schema.RoleSystem,
|
||||
Content: "You are go-tiny-claw, an expert coding assistant. You have full access to tools in the workspace.",
|
||||
},
|
||||
{
|
||||
Role: schema.RoleUser,
|
||||
Content: userPrompt,
|
||||
},
|
||||
}
|
||||
contextHistory := []schema.Message{
|
||||
{
|
||||
Role: schema.RoleSystem,
|
||||
Content: "You are go-tiny-claw, an expert coding assistant. You have full access to tools in the workspace.",
|
||||
},
|
||||
{
|
||||
Role: schema.RoleUser,
|
||||
Content: userPrompt,
|
||||
},
|
||||
}
|
||||
|
||||
turnCount := 0
|
||||
const maxTurns = 10
|
||||
turnCount := 0
|
||||
const maxTurns = 10
|
||||
|
||||
for {
|
||||
turnCount++
|
||||
if turnCount > maxTurns {
|
||||
log.Printf("[Engine] 已达最大轮数 (%d),强制终止。\n", maxTurns)
|
||||
break
|
||||
}
|
||||
log.Printf("\n========== [Turn %d] 开始 ==========\n", turnCount)
|
||||
dumpMessages(contextHistory)
|
||||
for {
|
||||
turnCount++
|
||||
if turnCount > maxTurns {
|
||||
log.Printf("[Engine] 已达最大轮数 (%d),强制终止。\n", maxTurns)
|
||||
break
|
||||
}
|
||||
log.Printf("\n========== [Turn %d] 开始 ==========\n", turnCount)
|
||||
dumpMessages(contextHistory)
|
||||
|
||||
// 获取当前挂载的所有工具定义
|
||||
availableTools := e.registry.GetAvailableTools()
|
||||
dumpTools(availableTools)
|
||||
// 获取当前挂载的所有工具定义
|
||||
availableTools := e.registry.GetAvailableTools()
|
||||
dumpTools(availableTools)
|
||||
|
||||
// ====================================================================
|
||||
// Phase 1: 慢思考阶段 (Thinking) - 仅第一轮执行初始规划
|
||||
// ====================================================================
|
||||
if e.EnableThinking && turnCount == 1 {
|
||||
log.Println("[Engine][Phase 1] 剥夺工具访问权,强制进入慢思考与规划阶段...")
|
||||
// ====================================================================
|
||||
// Phase 1: 慢思考阶段 (Thinking) - 仅第一轮执行初始规划
|
||||
// ====================================================================
|
||||
if e.EnableThinking && turnCount == 1 {
|
||||
log.Println("[Engine][Phase 1] 剥夺工具访问权,强制进入慢思考与规划阶段...")
|
||||
|
||||
// 核心机制:传入的 availableTools 为 nil!
|
||||
// 大模型看不到任何 JSON Schema,被迫只能输出纯文本的思考过程。
|
||||
thinkResp, err := e.provider.Generate(ctx, contextHistory, nil)
|
||||
if err != nil {
|
||||
return fmt.Errorf("Thinking 阶段生成失败: %w", err)
|
||||
}
|
||||
// 核心机制:传入的 availableTools 为 nil!
|
||||
// 大模型看不到任何 JSON Schema,被迫只能输出纯文本的思考过程。
|
||||
thinkResp, err := e.provider.Generate(ctx, contextHistory, nil)
|
||||
if err != nil {
|
||||
return fmt.Errorf("Thinking 阶段生成失败: %w", err)
|
||||
}
|
||||
|
||||
// 如果模型输出了思考过程,我们将其作为 Assistant 消息追加到上下文中
|
||||
if thinkResp.Content != "" {
|
||||
fmt.Printf("🧠 [内部思考 Trace]: %s\n", thinkResp.Content)
|
||||
contextHistory = append(contextHistory, *thinkResp)
|
||||
}
|
||||
// 如果模型输出了思考过程,我们将其作为 Assistant 消息追加到上下文中
|
||||
if thinkResp.Content != "" {
|
||||
fmt.Printf("🧠 [内部思考 Trace]: %s\n", thinkResp.Content)
|
||||
contextHistory = append(contextHistory, *thinkResp)
|
||||
}
|
||||
|
||||
// 插入过渡指令:让模型知道现在可以调用工具了
|
||||
contextHistory = append(contextHistory, schema.Message{
|
||||
Role: schema.RoleUser,
|
||||
Content: "根据你的推理,现在请使用可用的工具来完成任务。执行具体行动。",
|
||||
})
|
||||
}
|
||||
// 插入过渡指令:让模型知道现在可以调用工具了
|
||||
contextHistory = append(contextHistory, schema.Message{
|
||||
Role: schema.RoleUser,
|
||||
Content: "根据你的推理,现在请使用可用的工具来完成任务。执行具体行动。",
|
||||
})
|
||||
}
|
||||
|
||||
// ====================================================================
|
||||
// Phase 2: 行动阶段 (Action) - 恢复工具,顺着规划执行
|
||||
// ====================================================================
|
||||
log.Println("[Engine][Phase 2] 恢复工具挂载,等待模型采取行动...")
|
||||
// ====================================================================
|
||||
// Phase 2: 行动阶段 (Action) - 恢复工具,顺着规划执行
|
||||
// ====================================================================
|
||||
log.Println("[Engine][Phase 2] 恢复工具挂载,等待模型采取行动...")
|
||||
|
||||
// 此时的 contextHistory 中已经包含了上一阶段模型自己的 Thinking Trace + 过渡指令。
|
||||
// 模型会顺着自己的逻辑,结合恢复的 availableTools 发起精准的工具调用。
|
||||
actionResp, err := e.provider.Generate(ctx, contextHistory, availableTools)
|
||||
if err != nil {
|
||||
return fmt.Errorf("Action 阶段生成失败: %w", err)
|
||||
}
|
||||
// 此时的 contextHistory 中已经包含了上一阶段模型自己的 Thinking Trace + 过渡指令。
|
||||
// 模型会顺着自己的逻辑,结合恢复的 availableTools 发起精准的工具调用。
|
||||
actionResp, err := e.provider.Generate(ctx, contextHistory, availableTools)
|
||||
if err != nil {
|
||||
return fmt.Errorf("Action 阶段生成失败: %w", err)
|
||||
}
|
||||
|
||||
contextHistory = append(contextHistory, *actionResp)
|
||||
contextHistory = append(contextHistory, *actionResp)
|
||||
|
||||
if actionResp.Content != "" {
|
||||
fmt.Printf("🤖 [对外回复]: %s\n", actionResp.Content)
|
||||
}
|
||||
if actionResp.Content != "" {
|
||||
fmt.Printf("🤖 [对外回复]: %s\n", actionResp.Content)
|
||||
}
|
||||
|
||||
// ====================================================================
|
||||
// 退出与执行逻辑 (与上一讲保持一致)
|
||||
// ====================================================================
|
||||
if len(actionResp.ToolCalls) == 0 {
|
||||
log.Println("[Engine] 模型未请求调用工具,任务宣告完成。")
|
||||
break
|
||||
}
|
||||
// ====================================================================
|
||||
// 退出与执行逻辑 (与上一讲保持一致)
|
||||
// ====================================================================
|
||||
if len(actionResp.ToolCalls) == 0 {
|
||||
log.Println("[Engine] 模型未请求调用工具,任务宣告完成。")
|
||||
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))
|
||||
for _, toolCall := range actionResp.ToolCalls {
|
||||
log.Printf(" -> 🛠️ 执行工具: %s, 参数: %s\n", toolCall.Name, string(toolCall.Arguments))
|
||||
|
||||
result := e.registry.Execute(ctx, toolCall)
|
||||
result := e.registry.Execute(ctx, toolCall)
|
||||
|
||||
if result.IsError {
|
||||
log.Printf(" -> ❌ 工具执行报错: %s\n", result.Output)
|
||||
} else {
|
||||
log.Printf(" -> ✅ 工具执行成功 (返回 %d 字节)\n", len(result.Output))
|
||||
}
|
||||
status := "✅ 成功"
|
||||
if result.IsError {
|
||||
status = "❌ 失败"
|
||||
}
|
||||
log.Printf(" -> 📋 ToolCall %s: %s, 结果: %s\n", toolCall.ID, status, result.Output)
|
||||
|
||||
// 将工具执行的观察结果追加到 Context,准备进入下一轮
|
||||
observationMsg := schema.Message{
|
||||
Role: schema.RoleUser,
|
||||
Content: result.Output,
|
||||
ToolCallID: toolCall.ID,
|
||||
}
|
||||
contextHistory = append(contextHistory, observationMsg)
|
||||
}
|
||||
}
|
||||
if result.IsError {
|
||||
log.Printf(" -> ❌ 工具执行报错: %s\n", result.Output)
|
||||
} else {
|
||||
log.Printf(" -> ✅ 工具执行成功 (返回 %d 字节)\n", len(result.Output))
|
||||
}
|
||||
|
||||
return nil
|
||||
// 将工具执行的观察结果追加到 Context,准备进入下一轮
|
||||
observationMsg := schema.Message{
|
||||
Role: schema.RoleUser,
|
||||
Content: result.Output,
|
||||
ToolCallID: toolCall.ID,
|
||||
}
|
||||
contextHistory = append(contextHistory, observationMsg)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
+180
-160
@@ -2,192 +2,212 @@
|
||||
package provider
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
// "os"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log"
|
||||
|
||||
"github.com/openai/openai-go/v3"
|
||||
"github.com/openai/openai-go/v3/option"
|
||||
"github.com/openai/openai-go/v3/packages/param"
|
||||
"github.com/openai/openai-go/v3/shared"
|
||||
"go-tiny-claw/internal/schema"
|
||||
// "os"
|
||||
|
||||
"go-tiny-claw/internal/schema"
|
||||
|
||||
"github.com/openai/openai-go/v3"
|
||||
"github.com/openai/openai-go/v3/option"
|
||||
"github.com/openai/openai-go/v3/packages/param"
|
||||
"github.com/openai/openai-go/v3/shared"
|
||||
)
|
||||
|
||||
type OpenAIProvider struct {
|
||||
client openai.Client // 值类型,非指针
|
||||
model string
|
||||
client openai.Client // 值类型,非指针
|
||||
model string
|
||||
}
|
||||
|
||||
// NewZhipuOpenAIProvider 构造函数:基于 OpenAI V3 SDK,指向智谱底座
|
||||
func DeepseekOpenAIProvider(model string) *OpenAIProvider {
|
||||
apiKey := "sk-1f44696abe644bd684f09cc43f12c557"
|
||||
if apiKey == "" {
|
||||
panic("请设置 ZHIPU_API_KEY 环境变量")
|
||||
}
|
||||
// 核心:将官方 SDK 的地址替换为智谱的兼容端点
|
||||
baseURL := "https://api.deepseek.com"
|
||||
apiKey := "sk-1f44696abe644bd684f09cc43f12c557"
|
||||
if apiKey == "" {
|
||||
panic("请设置 ZHIPU_API_KEY 环境变量")
|
||||
}
|
||||
// 核心:将官方 SDK 的地址替换为智谱的兼容端点
|
||||
baseURL := "https://api.deepseek.com"
|
||||
|
||||
return &OpenAIProvider{
|
||||
client: openai.NewClient(option.WithAPIKey(apiKey), option.WithBaseURL(baseURL)),
|
||||
model: model,
|
||||
}
|
||||
return &OpenAIProvider{
|
||||
client: openai.NewClient(option.WithAPIKey(apiKey), option.WithBaseURL(baseURL)),
|
||||
model: model,
|
||||
}
|
||||
}
|
||||
|
||||
func (p *OpenAIProvider) Generate(ctx context.Context, msgs []schema.Message, availableTools []schema.ToolDefinition) (*schema.Message, error) {
|
||||
var openaiMsgs []openai.ChatCompletionMessageParamUnion
|
||||
phase := "Action"
|
||||
if len(availableTools) == 0 {
|
||||
phase = "Thinking"
|
||||
}
|
||||
log.Printf("[Provider] → API 调用 | 模型: %s | 阶段: %s | 消息数: %d | 工具数: %d",
|
||||
p.model, phase, len(msgs), len(availableTools))
|
||||
|
||||
// 1. 翻译上下文消息
|
||||
for _, msg := range msgs {
|
||||
switch msg.Role {
|
||||
case schema.RoleSystem:
|
||||
openaiMsgs = append(openaiMsgs, openai.SystemMessage(msg.Content))
|
||||
var openaiMsgs []openai.ChatCompletionMessageParamUnion
|
||||
|
||||
case schema.RoleUser:
|
||||
if msg.ToolCallID != "" {
|
||||
// 注意:v3 新版参数顺序是 (content, toolCallID)
|
||||
openaiMsgs = append(openaiMsgs, openai.ToolMessage(msg.Content, msg.ToolCallID))
|
||||
} else {
|
||||
openaiMsgs = append(openaiMsgs, openai.UserMessage(msg.Content))
|
||||
}
|
||||
// 1. 翻译上下文消息
|
||||
for _, msg := range msgs {
|
||||
switch msg.Role {
|
||||
case schema.RoleSystem:
|
||||
openaiMsgs = append(openaiMsgs, openai.SystemMessage(msg.Content))
|
||||
|
||||
case schema.RoleAssistant:
|
||||
// Deepseek thinking mode: reasoning_content 必须回传
|
||||
if msg.ReasoningContent != "" || len(msg.ToolCalls) > 0 {
|
||||
msgMap := map[string]interface{}{
|
||||
"role": "assistant",
|
||||
"content": msg.Content,
|
||||
}
|
||||
if msg.ReasoningContent != "" {
|
||||
msgMap["reasoning_content"] = msg.ReasoningContent
|
||||
}
|
||||
if len(msg.ToolCalls) > 0 {
|
||||
var toolCalls []map[string]interface{}
|
||||
for _, tc := range msg.ToolCalls {
|
||||
toolCalls = append(toolCalls, map[string]interface{}{
|
||||
"id": tc.ID,
|
||||
"type": "function",
|
||||
"function": map[string]interface{}{
|
||||
"name": tc.Name,
|
||||
"arguments": string(tc.Arguments),
|
||||
},
|
||||
})
|
||||
}
|
||||
msgMap["tool_calls"] = toolCalls
|
||||
}
|
||||
rawJSON, _ := json.Marshal(msgMap)
|
||||
astParam := param.Override[openai.ChatCompletionAssistantMessageParam](json.RawMessage(rawJSON))
|
||||
openaiMsgs = append(openaiMsgs, openai.ChatCompletionMessageParamUnion{
|
||||
OfAssistant: &astParam,
|
||||
})
|
||||
break
|
||||
}
|
||||
case schema.RoleUser:
|
||||
if msg.ToolCallID != "" {
|
||||
// 注意:v3 新版参数顺序是 (content, toolCallID)
|
||||
openaiMsgs = append(openaiMsgs, openai.ToolMessage(msg.Content, msg.ToolCallID))
|
||||
} else {
|
||||
openaiMsgs = append(openaiMsgs, openai.UserMessage(msg.Content))
|
||||
}
|
||||
|
||||
astParam := openai.ChatCompletionAssistantMessageParam{}
|
||||
case schema.RoleAssistant:
|
||||
// Deepseek thinking mode: reasoning_content 必须回传
|
||||
if msg.ReasoningContent != "" || len(msg.ToolCalls) > 0 {
|
||||
msgMap := map[string]interface{}{
|
||||
"role": "assistant",
|
||||
"content": msg.Content,
|
||||
}
|
||||
if msg.ReasoningContent != "" {
|
||||
msgMap["reasoning_content"] = msg.ReasoningContent
|
||||
}
|
||||
if len(msg.ToolCalls) > 0 {
|
||||
var toolCalls []map[string]interface{}
|
||||
for _, tc := range msg.ToolCalls {
|
||||
toolCalls = append(toolCalls, map[string]interface{}{
|
||||
"id": tc.ID,
|
||||
"type": "function",
|
||||
"function": map[string]interface{}{
|
||||
"name": tc.Name,
|
||||
"arguments": string(tc.Arguments),
|
||||
},
|
||||
})
|
||||
}
|
||||
msgMap["tool_calls"] = toolCalls
|
||||
}
|
||||
rawJSON, _ := json.Marshal(msgMap)
|
||||
astParam := param.Override[openai.ChatCompletionAssistantMessageParam](json.RawMessage(rawJSON))
|
||||
openaiMsgs = append(openaiMsgs, openai.ChatCompletionMessageParamUnion{
|
||||
OfAssistant: &astParam,
|
||||
})
|
||||
break
|
||||
}
|
||||
|
||||
if msg.Content != "" {
|
||||
astParam.Content = openai.ChatCompletionAssistantMessageParamContentUnion{
|
||||
OfString: openai.String(msg.Content),
|
||||
}
|
||||
}
|
||||
astParam := openai.ChatCompletionAssistantMessageParam{}
|
||||
|
||||
// 【重要】如果历史包含 ToolCalls,必须原样放回,以维系大模型的逻辑链
|
||||
if len(msg.ToolCalls) > 0 {
|
||||
var toolCalls []openai.ChatCompletionMessageToolCallUnionParam
|
||||
for _, tc := range msg.ToolCalls {
|
||||
// OfFunction 对应 GetFunction(),字段类型严格要求为指针
|
||||
toolCalls = append(toolCalls, openai.ChatCompletionMessageToolCallUnionParam{
|
||||
OfFunction: &openai.ChatCompletionMessageFunctionToolCallParam{
|
||||
ID: tc.ID,
|
||||
Type: "function",
|
||||
Function: openai.ChatCompletionMessageFunctionToolCallFunctionParam{
|
||||
Name: tc.Name,
|
||||
Arguments: string(tc.Arguments),
|
||||
},
|
||||
},
|
||||
})
|
||||
}
|
||||
astParam.ToolCalls = toolCalls
|
||||
}
|
||||
if msg.Content != "" {
|
||||
astParam.Content = openai.ChatCompletionAssistantMessageParamContentUnion{
|
||||
OfString: openai.String(msg.Content),
|
||||
}
|
||||
}
|
||||
|
||||
openaiMsgs = append(openaiMsgs, openai.ChatCompletionMessageParamUnion{
|
||||
OfAssistant: &astParam,
|
||||
})
|
||||
}
|
||||
}
|
||||
// 【重要】如果历史包含 ToolCalls,必须原样放回,以维系大模型的逻辑链
|
||||
if len(msg.ToolCalls) > 0 {
|
||||
var toolCalls []openai.ChatCompletionMessageToolCallUnionParam
|
||||
for _, tc := range msg.ToolCalls {
|
||||
// OfFunction 对应 GetFunction(),字段类型严格要求为指针
|
||||
toolCalls = append(toolCalls, openai.ChatCompletionMessageToolCallUnionParam{
|
||||
OfFunction: &openai.ChatCompletionMessageFunctionToolCallParam{
|
||||
ID: tc.ID,
|
||||
Type: "function",
|
||||
Function: openai.ChatCompletionMessageFunctionToolCallFunctionParam{
|
||||
Name: tc.Name,
|
||||
Arguments: string(tc.Arguments),
|
||||
},
|
||||
},
|
||||
})
|
||||
}
|
||||
astParam.ToolCalls = toolCalls
|
||||
}
|
||||
|
||||
// 2. 翻译工具定义 (v3 新 API 特性适配)
|
||||
var openaiTools []openai.ChatCompletionToolUnionParam
|
||||
for _, toolDef := range availableTools {
|
||||
var params shared.FunctionParameters
|
||||
openaiMsgs = append(openaiMsgs, openai.ChatCompletionMessageParamUnion{
|
||||
OfAssistant: &astParam,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// 尝试直接断言,如果不成功则通过 JSON 往返序列化来保证类型匹配
|
||||
if m, ok := toolDef.InputSchema.(map[string]interface{}); ok {
|
||||
params = shared.FunctionParameters(m)
|
||||
} else {
|
||||
// fallback:JSON 往返序列化
|
||||
b, _ := json.Marshal(toolDef.InputSchema)
|
||||
_ = json.Unmarshal(b, ¶ms)
|
||||
}
|
||||
// 2. 翻译工具定义 (v3 新 API 特性适配)
|
||||
var openaiTools []openai.ChatCompletionToolUnionParam
|
||||
for _, toolDef := range availableTools {
|
||||
var params shared.FunctionParameters
|
||||
|
||||
openaiTools = append(openaiTools, openai.ChatCompletionFunctionTool(
|
||||
shared.FunctionDefinitionParam{
|
||||
Name: toolDef.Name,
|
||||
Description: openai.String(toolDef.Description),
|
||||
Parameters: params,
|
||||
},
|
||||
))
|
||||
}
|
||||
// 尝试直接断言,如果不成功则通过 JSON 往返序列化来保证类型匹配
|
||||
if m, ok := toolDef.InputSchema.(map[string]interface{}); ok {
|
||||
params = shared.FunctionParameters(m)
|
||||
} else {
|
||||
// fallback:JSON 往返序列化
|
||||
b, _ := json.Marshal(toolDef.InputSchema)
|
||||
_ = json.Unmarshal(b, ¶ms)
|
||||
}
|
||||
|
||||
// 3. 构建请求并发送
|
||||
params := openai.ChatCompletionNewParams{
|
||||
Model: p.model,
|
||||
Messages: openaiMsgs,
|
||||
}
|
||||
openaiTools = append(openaiTools, openai.ChatCompletionFunctionTool(
|
||||
shared.FunctionDefinitionParam{
|
||||
Name: toolDef.Name,
|
||||
Description: openai.String(toolDef.Description),
|
||||
Parameters: params,
|
||||
},
|
||||
))
|
||||
}
|
||||
|
||||
// 【慢思考机制支撑】仅当 availableTools 存在时才挂载 Tools
|
||||
if len(openaiTools) > 0 {
|
||||
params.Tools = openaiTools
|
||||
}
|
||||
// 3. 构建请求并发送
|
||||
params := openai.ChatCompletionNewParams{
|
||||
Model: p.model,
|
||||
Messages: openaiMsgs,
|
||||
}
|
||||
|
||||
resp, err := p.client.Chat.Completions.New(ctx, params)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("OpenAI/Zhipu API 请求失败: %w", err)
|
||||
}
|
||||
if len(resp.Choices) == 0 {
|
||||
return nil, fmt.Errorf("API 返回了空的 Choices")
|
||||
}
|
||||
// 【慢思考机制支撑】仅当 availableTools 存在时才挂载 Tools
|
||||
if len(openaiTools) > 0 {
|
||||
params.Tools = openaiTools
|
||||
}
|
||||
|
||||
// 4. 将 API Response 反向翻译为内部 schema.Message
|
||||
choice := resp.Choices[0].Message
|
||||
resultMsg := &schema.Message{
|
||||
Role: schema.RoleAssistant,
|
||||
Content: choice.Content,
|
||||
}
|
||||
resp, err := p.client.Chat.Completions.New(ctx, params)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("OpenAI/Zhipu API 请求失败: %w", err)
|
||||
}
|
||||
if len(resp.Choices) == 0 {
|
||||
return nil, fmt.Errorf("API 返回了空的 Choices")
|
||||
}
|
||||
|
||||
// Deepseek thinking mode: 从原始响应中提取 reasoning_content
|
||||
rawMsg := choice.RawJSON()
|
||||
if rawMsg != "" {
|
||||
var rawMap map[string]json.RawMessage
|
||||
if err := json.Unmarshal([]byte(rawMsg), &rawMap); err == nil {
|
||||
if rc, ok := rawMap["reasoning_content"]; ok {
|
||||
var s string
|
||||
if json.Unmarshal(rc, &s) == nil {
|
||||
resultMsg.ReasoningContent = s
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// 4. 将 API Response 反向翻译为内部 schema.Message
|
||||
choice := resp.Choices[0].Message
|
||||
resultMsg := &schema.Message{
|
||||
Role: schema.RoleAssistant,
|
||||
Content: choice.Content,
|
||||
}
|
||||
|
||||
for _, tc := range choice.ToolCalls {
|
||||
if tc.Type == "function" {
|
||||
resultMsg.ToolCalls = append(resultMsg.ToolCalls, schema.ToolCall{
|
||||
ID: tc.ID,
|
||||
Name: tc.Function.Name,
|
||||
Arguments: []byte(tc.Function.Arguments), // 提取 JSON 字符串字节
|
||||
})
|
||||
}
|
||||
}
|
||||
// Deepseek thinking mode: 从原始响应中提取 reasoning_content
|
||||
rawMsg := choice.RawJSON()
|
||||
if rawMsg != "" {
|
||||
var rawMap map[string]json.RawMessage
|
||||
if err := json.Unmarshal([]byte(rawMsg), &rawMap); err == nil {
|
||||
if rc, ok := rawMap["reasoning_content"]; ok {
|
||||
var s string
|
||||
if json.Unmarshal(rc, &s) == nil {
|
||||
resultMsg.ReasoningContent = s
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return resultMsg, nil
|
||||
}
|
||||
for _, tc := range choice.ToolCalls {
|
||||
if tc.Type == "function" {
|
||||
resultMsg.ToolCalls = append(resultMsg.ToolCalls, schema.ToolCall{
|
||||
ID: tc.ID,
|
||||
Name: tc.Function.Name,
|
||||
Arguments: []byte(tc.Function.Arguments),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// 打印响应摘要
|
||||
contentPreview := resultMsg.Content
|
||||
// if len(contentPreview) > 60 {
|
||||
// contentPreview = contentPreview[:60] + "..."
|
||||
// }
|
||||
log.Printf("[Provider] ← API 响应 | 内容: %q | 工具调用: %d", contentPreview, len(resultMsg.ToolCalls))
|
||||
for _, tc := range resultMsg.ToolCalls {
|
||||
log.Printf("[Provider] ↳ ToolCall: %s(%s)", tc.Name, string(tc.Arguments))
|
||||
}
|
||||
|
||||
return resultMsg, nil
|
||||
}
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
package tools
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os/exec"
|
||||
"time"
|
||||
|
||||
"go-tiny-claw/internal/schema"
|
||||
)
|
||||
|
||||
type BashTool struct {
|
||||
workDir string // 工作区约束
|
||||
}
|
||||
|
||||
func NewBashTool(workDir string) *BashTool {
|
||||
return &BashTool{workDir: workDir}
|
||||
}
|
||||
|
||||
func (t *BashTool) Name() string {
|
||||
return "bash"
|
||||
}
|
||||
|
||||
func (t *BashTool) Definition() schema.ToolDefinition {
|
||||
return schema.ToolDefinition{
|
||||
Name: t.Name(),
|
||||
Description: "在当前工作区执行任意的 bash 命令。支持链式命令(如 &&)。返回标准输出(stdout)和标准错误(stderr)。",
|
||||
InputSchema: map[string]interface{}{
|
||||
"type": "object",
|
||||
"properties": map[string]interface{}{
|
||||
"command": map[string]interface{}{
|
||||
"type": "string",
|
||||
"description": "要执行的 bash 命令,例如: ls -la 或 go test ./...",
|
||||
},
|
||||
},
|
||||
"required": []string{"command"},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
type bashArgs struct {
|
||||
Command string `json:"command"`
|
||||
}
|
||||
|
||||
func (t *BashTool) Execute(ctx context.Context, args json.RawMessage) (string, error) {
|
||||
var input bashArgs
|
||||
if err := json.Unmarshal(args, &input); err != nil {
|
||||
return "", fmt.Errorf("参数解析失败: %w", err)
|
||||
}
|
||||
|
||||
// 【驾驭底线 1】:Time Budgeting (时间预算与超时控制)
|
||||
timeoutCtx, cancel := context.WithTimeout(ctx, 30*time.Second)
|
||||
defer cancel()
|
||||
|
||||
// Unix 和 Windows 统一使用 bash -c(Windows 需安装 Git Bash),编码转换在下方处理
|
||||
cmd := exec.CommandContext(timeoutCtx, "bash", "-c", input.Command)
|
||||
|
||||
// 【驾驭底线 2】:绑定执行的工作区目录
|
||||
cmd.Dir = t.workDir
|
||||
|
||||
// 执行并捕获 CombinedOutput (合并 stdout 和 stderr)
|
||||
out, err := cmd.CombinedOutput()
|
||||
|
||||
outputStr := string(out)
|
||||
|
||||
// 如果命令执行超时,返回警告信息让模型知晓
|
||||
if timeoutCtx.Err() == context.DeadlineExceeded {
|
||||
return outputStr + "\n[警告: 命令执行超时(30s),已被系统强制终止。如果是启动常驻服务,请尝试将其转入后台。]", nil
|
||||
}
|
||||
|
||||
// 【驾驭底线 3】:错误原样回传 (Self-Correction 自愈机制)
|
||||
if err != nil {
|
||||
return fmt.Sprintf("执行报错: %v\n输出:\n%s", err, outputStr), nil
|
||||
}
|
||||
|
||||
// 如果没有终端输出,给模型一个明确的执行成功的反馈
|
||||
if outputStr == "" {
|
||||
return "命令执行成功,无终端输出。", nil
|
||||
}
|
||||
|
||||
// 【驾驭底线 4】:长度截断保护 (防 OOM)
|
||||
const maxLen = 8000
|
||||
if len(outputStr) > maxLen {
|
||||
return fmt.Sprintf("%s\n\n...[终端输出过长,已截断至前 %d 字节]...", outputStr[:maxLen], maxLen), nil
|
||||
}
|
||||
|
||||
return outputStr, nil
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
package tools
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
"go-tiny-claw/internal/schema"
|
||||
)
|
||||
|
||||
// ReadFileTool 实现了读取本地文件内容的工具
|
||||
type ReadFileTool struct {
|
||||
// 将引擎的 WorkDir 注入给工具,限制它只能在此目录及其子目录下操作
|
||||
workDir string
|
||||
}
|
||||
|
||||
func NewReadFileTool(workDir string) *ReadFileTool {
|
||||
return &ReadFileTool{workDir: workDir}
|
||||
}
|
||||
|
||||
func (t *ReadFileTool) Name() string {
|
||||
return "read_file"
|
||||
}
|
||||
|
||||
// Definition 向大模型清晰地描述这个工具的用途和参数格式
|
||||
func (t *ReadFileTool) Definition() schema.ToolDefinition {
|
||||
return schema.ToolDefinition{
|
||||
Name: t.Name(),
|
||||
Description: "读取指定路径的文件内容。请提供相对工作区的路径。",
|
||||
// 遵循 JSON Schema 规范定义参数
|
||||
InputSchema: map[string]interface{}{
|
||||
"type": "object",
|
||||
"properties": map[string]interface{}{
|
||||
"path": map[string]interface{}{
|
||||
"type": "string",
|
||||
"description": "要读取的文件路径,如 cmd/claw/main.go",
|
||||
},
|
||||
},
|
||||
"required": []string{"path"},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// readFileArgs 内部定义用于反序列化的结构体
|
||||
type readFileArgs struct {
|
||||
Path string `json:"path"`
|
||||
}
|
||||
|
||||
func (t *ReadFileTool) Execute(ctx context.Context, args json.RawMessage) (string, error) {
|
||||
// 1. 延迟解析:将大模型传过来的 JSON 参数解析为强类型结构体
|
||||
var input readFileArgs
|
||||
if err := json.Unmarshal(args, &input); err != nil {
|
||||
// 返回 error 会被 Registry 捕获并传给大模型,模型会知道自己 JSON 格式写错了
|
||||
return "", fmt.Errorf("参数解析失败: %w", err)
|
||||
}
|
||||
|
||||
// 2. 拼接绝对路径 (注意:生产环境中需要做路径穿越检测防范,防止 ../../etc/passwd)
|
||||
fullPath := filepath.Join(t.workDir, input.Path)
|
||||
|
||||
// 3. 执行物理 IO 操作
|
||||
file, err := os.Open(fullPath)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("打开文件失败: %w", err)
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
content, err := io.ReadAll(file)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("读取文件内容失败: %w", err)
|
||||
}
|
||||
|
||||
// 4. 【核心防线】长度截断保护
|
||||
// 为了防止大模型读取几百 MB 的日志文件导致 Context 瞬间爆炸 (OOM),
|
||||
// 我们在工具内部直接进行物理截断。
|
||||
const maxLen = 8000
|
||||
if len(content) > maxLen {
|
||||
truncatedMsg := fmt.Sprintf("%s\n\n...[由于内容过长,已被系统截断至前 %d 字节]...", string(content[:maxLen]), maxLen)
|
||||
return truncatedMsg, nil
|
||||
}
|
||||
|
||||
return string(content), nil
|
||||
}
|
||||
@@ -2,14 +2,103 @@ package tools
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log"
|
||||
|
||||
"go-tiny-claw/internal/schema"
|
||||
)
|
||||
|
||||
// Registry 定义了工具的注册与分发执行接口
|
||||
// BaseTool 是所有具体工具必须实现的通用接口
|
||||
type BaseTool interface {
|
||||
// Name 返回工具的全局唯一名称 (大模型通过这个名字调用它)
|
||||
Name() string
|
||||
|
||||
// Definition 返回用于提交给大模型的工具元信息和参数 JSON Schema
|
||||
Definition() schema.ToolDefinition
|
||||
|
||||
// Execute 接收大模型吐出的 JSON 参数,执行具体业务逻辑
|
||||
// 注意:参数是 json.RawMessage,反序列化由各个具体工具内部自行处理
|
||||
Execute(ctx context.Context, args json.RawMessage) (string, error)
|
||||
}
|
||||
|
||||
// Registry 定义了工具的注册与分发接口
|
||||
type Registry interface {
|
||||
// GetAvailableTools 返回当前系统挂载的所有可用工具的 Schema
|
||||
// Register 挂载一个新的工具到系统中
|
||||
Register(tool BaseTool)
|
||||
|
||||
// GetAvailableTools 返回当前系统挂载的所有工具的 Schema,供 Main Loop 交给 Provider
|
||||
GetAvailableTools() []schema.ToolDefinition
|
||||
|
||||
// Execute 实际执行模型请求的工具,并返回结果
|
||||
// Execute 实际路由并执行模型请求的工具调用
|
||||
Execute(ctx context.Context, call schema.ToolCall) schema.ToolResult
|
||||
}
|
||||
|
||||
// registryImpl 是 Registry 接口的默认实现
|
||||
type registryImpl struct {
|
||||
// 使用 map 以工具的 Name 作为 Key 进行快速 O(1) 路由查找
|
||||
tools map[string]BaseTool
|
||||
}
|
||||
|
||||
func NewRegistry() Registry {
|
||||
return ®istryImpl{
|
||||
tools: make(map[string]BaseTool),
|
||||
}
|
||||
}
|
||||
|
||||
func (r *registryImpl) String() string {
|
||||
var names []string
|
||||
for name := range r.tools {
|
||||
names = append(names, name)
|
||||
}
|
||||
return fmt.Sprintf("Registry{tools: %v}", names)
|
||||
}
|
||||
|
||||
func (r *registryImpl) Register(tool BaseTool) {
|
||||
name := tool.Name()
|
||||
if _, exists := r.tools[name]; exists {
|
||||
log.Printf("[Warning] 工具 '%s' 已经被注册,将被覆盖。\n", name)
|
||||
}
|
||||
r.tools[name] = tool
|
||||
log.Printf("[Registry] 成功挂载工具: %s\n", name)
|
||||
}
|
||||
|
||||
func (r *registryImpl) GetAvailableTools() []schema.ToolDefinition {
|
||||
var defs []schema.ToolDefinition
|
||||
for _, tool := range r.tools {
|
||||
defs = append(defs, tool.Definition())
|
||||
}
|
||||
return defs
|
||||
}
|
||||
|
||||
func (r *registryImpl) Execute(ctx context.Context, call schema.ToolCall) schema.ToolResult {
|
||||
// 1. 路由查找:如果在注册表中找不到该工具,这是模型产生了幻觉,直接向模型抛出错误
|
||||
tool, exists := r.tools[call.Name]
|
||||
if !exists {
|
||||
errMsg := fmt.Sprintf("Error: 系统中不存在名为 '%s' 的工具。", call.Name)
|
||||
return schema.ToolResult{
|
||||
ToolCallID: call.ID,
|
||||
Output: errMsg,
|
||||
IsError: true, // 标记为错误,模型看到后会尝试纠正
|
||||
}
|
||||
}
|
||||
|
||||
// 2. 执行工具逻辑:将原始的 JSON 字节流直接丢给具体工具
|
||||
output, err := tool.Execute(ctx, call.Arguments)
|
||||
|
||||
// 3. 封装结果:将执行结果或底层物理错误封装后返回给 Main Loop
|
||||
if err != nil {
|
||||
errMsg := fmt.Sprintf("Error executing %s: %v", call.Name, err)
|
||||
return schema.ToolResult{
|
||||
ToolCallID: call.ID,
|
||||
Output: errMsg,
|
||||
IsError: true,
|
||||
}
|
||||
}
|
||||
|
||||
return schema.ToolResult{
|
||||
ToolCallID: call.ID,
|
||||
Output: output,
|
||||
IsError: false,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
package tools
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
"go-tiny-claw/internal/schema"
|
||||
)
|
||||
|
||||
type WriteFileTool struct {
|
||||
workDir string // 工作区约束
|
||||
}
|
||||
|
||||
func NewWriteFileTool(workDir string) *WriteFileTool {
|
||||
return &WriteFileTool{workDir: workDir}
|
||||
}
|
||||
|
||||
func (t *WriteFileTool) Name() string {
|
||||
return "write_file"
|
||||
}
|
||||
|
||||
func (t *WriteFileTool) Definition() schema.ToolDefinition {
|
||||
return schema.ToolDefinition{
|
||||
Name: t.Name(),
|
||||
Description: "创建或覆盖写入一个文件。如果目录不存在会自动创建。请提供相对于工作区的相对路径。",
|
||||
InputSchema: map[string]interface{}{
|
||||
"type": "object",
|
||||
"properties": map[string]interface{}{
|
||||
"path": map[string]interface{}{
|
||||
"type": "string",
|
||||
"description": "要写入的文件路径,如 src/main.go",
|
||||
},
|
||||
"content": map[string]interface{}{
|
||||
"type": "string",
|
||||
"description": "要写入的完整文件内容",
|
||||
},
|
||||
},
|
||||
"required": []string{"path", "content"},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
type writeFileArgs struct {
|
||||
Path string `json:"path"`
|
||||
Content string `json:"content"`
|
||||
}
|
||||
|
||||
func (t *WriteFileTool) Execute(ctx context.Context, args json.RawMessage) (string, error) {
|
||||
var input writeFileArgs
|
||||
if err := json.Unmarshal(args, &input); err != nil {
|
||||
return "", fmt.Errorf("参数解析失败: %w", err)
|
||||
}
|
||||
|
||||
// 【安全防线】:限制在 WorkDir 下执行,防止大模型修改系统级文件
|
||||
fullPath := filepath.Join(t.workDir, input.Path)
|
||||
|
||||
// 自动创建缺失的父级目录
|
||||
if err := os.MkdirAll(filepath.Dir(fullPath), 0755); err != nil {
|
||||
return "", fmt.Errorf("创建父目录失败: %w", err)
|
||||
}
|
||||
|
||||
// 写入文件内容,权限设为 0644
|
||||
err := os.WriteFile(fullPath, []byte(input.Content), 0644)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("写入文件失败: %w", err)
|
||||
}
|
||||
|
||||
return fmt.Sprintf("成功将内容写入到文件: %s", input.Path), nil
|
||||
}
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
|
||||
"go-tiny-claw/internal/engine"
|
||||
"go-tiny-claw/internal/schema"
|
||||
"go-tiny-claw/internal/tools"
|
||||
)
|
||||
|
||||
// mockProvider 模拟大模型推理
|
||||
@@ -36,6 +37,8 @@ type mockRegistry struct{}
|
||||
|
||||
func (m *mockRegistry) GetAvailableTools() []schema.ToolDefinition { return nil }
|
||||
|
||||
func (m *mockRegistry) Register(tool tools.BaseTool) {}
|
||||
|
||||
func (m *mockRegistry) Execute(ctx context.Context, call schema.ToolCall) schema.ToolResult {
|
||||
return schema.ToolResult{
|
||||
ToolCallID: call.ID,
|
||||
|
||||
Reference in New Issue
Block a user