Compare commits
7
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
572665b3ac | ||
|
|
e480c5c55e | ||
|
|
3e91c7d0a1 | ||
|
|
d84fdbd24e | ||
|
|
deb1b6e660 | ||
|
|
cefabd68dc | ||
|
|
b94460083a |
Generated
+8
@@ -0,0 +1,8 @@
|
||||
# 默认忽略的文件
|
||||
/shelf/
|
||||
/workspace.xml
|
||||
# 基于编辑器的 HTTP 客户端请求
|
||||
/httpRequests/
|
||||
# Datasource local storage ignored files
|
||||
/dataSources/
|
||||
/dataSources.local.xml
|
||||
@@ -0,0 +1,9 @@
|
||||
# 欢迎来到 go-tiny-claw 项目工作区
|
||||
|
||||
## 架构说明
|
||||
- 本项目采用 Go 语言编写,追求极致性能。
|
||||
- 所有的 API 接口都必须返回 JSON 格式,且包含 `code` 和 `message` 字段。
|
||||
- 所有的错误处理,必须返回中文报错信息,绝对禁止使用英文抛错。
|
||||
|
||||
## 禁忌事项
|
||||
- 不允许删除根目录的任何文件。
|
||||
@@ -65,6 +65,127 @@ func main() {
|
||||
|
||||
## 版本历史
|
||||
|
||||
### v1.7 — Session 会话机制 + 多工作区隔离 + Reporter 抽象
|
||||
|
||||
#### 变更
|
||||
|
||||
- **Session 会话机制** — 新增 `Session` 结构体,维护完整的对话历史(`[]schema.Message`),通过 `RWMutex` 实现线程安全的并发读写。全局 `SessionManager` 支持多会话隔离(`GetOrCreate`),基于 `map[string]*Session` 路由
|
||||
- **Working Memory 滑动窗口** — `GetWorkingMemory(limit)` 从后往前截取最近 N 条消息作为"短期工作记忆",并实现孤儿 ToolResult 防线:截断后若首条消息是孤立的工具响应(对应 ToolCall 已被丢弃),自动舍弃防止 API 400
|
||||
- **Reporter 输出抽象** — 新增 `Reporter` 接口(`OnThinking` / `OnToolCall` / `OnToolResult` / `OnMessage`),将引擎输出与展现层解耦。`TerminalReporter` 是首个实现,引擎不再直接 `fmt.Printf`
|
||||
- **WorkDir 从 Engine 下沉到 Session** — 引擎不再持有工作目录,WorkDir 跟随 Session 走。一个引擎实例可同时服务多个不同工作区的会话(多工作区复用单引擎)
|
||||
- **Run 签名重构** — `Run(ctx, userPrompt)` → `Run(ctx, session, reporter)`,会话成为一等公民
|
||||
- **引擎循环改造** — 每轮从 Session 的 Working Memory 构建上下文,工具执行结果实时 `Append` 回 Session,ReAct 循环结束后挂起等待人类下一条指令
|
||||
|
||||
#### 踩坑记录
|
||||
|
||||
| 问题 | 原因 | 解决 |
|
||||
|---|---|---|
|
||||
| 多会话并发操作同一目录文件冲突 | 两个 Session 的 WorkDir 相同,工具同时读写 | WorkDir 绑定 Session,不同会话指向不同工作区 |
|
||||
| 截断 Working Memory 后 API 报 400 | 丢弃了携带 ToolCall 的 Assistant 消息,但留下了对应的 ToolResult | `GetWorkingMemory` 检测并丢弃首部的孤儿 ToolResult |
|
||||
| `fmt.Printf` 无法适配飞书/钉钉/WebUI 等输出目标 | 引擎与终端输出硬耦合 | 抽象 Reporter 接口,`TerminalReporter` 仅为首个实现 |
|
||||
|
||||
#### 经验教训
|
||||
|
||||
1. **WorkDir 属于会话而非引擎** — 将工作目录从 Engine 移到 Session,一个引擎实例就能同时服务多个隔离的工作区(`project_front` / `project_back`),架构不变代码不变
|
||||
2. **Working Memory 不是全量历史** — 大模型 API 有 context window 上限,截取最近 N 条消息既控制成本又保持对话连贯。截断时必须保证 ToolCall / ToolResult 成对存在,否则 API 直接报错
|
||||
3. **Reporter 是引擎可移植的关键** — 引擎只负责"推理 + 调工具",不关心输出到哪里。CLI、飞书、WebUI 只需各自实现 Reporter 接口,引擎零改动
|
||||
|
||||
### v1.5 — Edit 工具 + 四级容错替换 + 多工具并发执行
|
||||
|
||||
#### 变更
|
||||
|
||||
- **新增 EditFileTool** — 实现四级容错降级替换算法(L1 精确 → L2 换行符归一 → L3 Trim Space → L4 逐行去缩进滑动窗口),解决大模型代码修改时缩进丢失、换行符不一致等幻觉问题
|
||||
- **工具集扩展** — 工具集从 3 个(read / write / bash)扩展到 4 个(+ edit)
|
||||
- **多工具并发执行** — 引擎从串行改为并行:预分配结果切片 + `sync.WaitGroup` + 按索引无锁写入,模型一次请求多个工具时同时执行
|
||||
|
||||
#### 踩坑记录
|
||||
|
||||
| 问题 | 原因 | 解决 |
|
||||
|---|---|---|
|
||||
| 大模型生成的代码缩进不一致 | 模型推理时对源文件缩进感知不准,产生多一个空格或少一个 tab | 编辑工具内建多级模糊匹配 |
|
||||
| 同一段代码在文件中出现多次 | 模型给的 old_text 上下文不够 | 算法检测多匹配后返回错误给模型自愈 |
|
||||
| Windows 换行符 `\r\n` vs `\n` 不一致 | 模型通常输出 `\n`,Windows 文件可能是 `\r\n` | L2 换行符归一化:统一转 `\n` |
|
||||
| Goroutine 闭包捕获 loop 变量 | Go 的 loop 变量复用同一地址 | 将 `i`/`toolCall` 作为参数传入 goroutine |
|
||||
|
||||
#### 经验教训
|
||||
|
||||
1. **Agent 工具要做"容错输入,严格输出"** — 接受模型可能不完美的输入(多级模糊匹配),但输出清晰的错误信息帮模型自我纠正
|
||||
2. **工具语义要匹配模型的能力边界** — `edit_file`(给 old_text + new_text)比重写整个文件更适合 Agent,不要求模型完整认知整个文件
|
||||
3. **并发安全可以零成本** — 预分配切片 + 按索引写入 + 主 goroutine 串行读取,比加锁方案更简洁高效
|
||||
|
||||
### v1.6 — System Prompt 工程化 + 渐进式技能发现
|
||||
|
||||
#### 变更
|
||||
|
||||
- **PromptComposer** — 新增 `internal/prompt` 包取代硬编码 system prompt,运行时动态组装:核心身份 → `AGENTS.md` 项目规范 → Skill 目录
|
||||
- **AGENTS.md** — 项目根目录的 Markdown 文件自动被识别并注入 system prompt,让非代码层面的架构规范可被 Agent 感知
|
||||
- **渐进式技能发现** — `SkillLoader` 扫描 `skills/<name>/SKILL.md`,system prompt 只注入技能目录(名称 + 一行描述),模型按需调用 `read_skill` 加载完整指令
|
||||
- **ReadSkillTool** — 工具集扩展到 5 个,接收技能名称返回完整 Skill.md 正文
|
||||
- **包重命名** — `internal/context` → `internal/prompt`,消除与标准库 `context` 包的命名冲突
|
||||
|
||||
#### 踩坑记录
|
||||
|
||||
| 问题 | 原因 | 解决 |
|
||||
|---|---|---|
|
||||
| 包名与标准库冲突 | `internal/context` 与 `context` 包同名,导入时被迫黑别名 `ctxpkg` | 重命名为 `prompt`,导入无歧义 |
|
||||
| prompt 全量注入浪费上下文 | List() 只返回摘要,Build() 仍需知道技能的完整存在 | 摘要注入 system prompt,正文通过 read_skill 按需加载,典型场景节省 70%+ context |
|
||||
|
||||
#### 经验教训
|
||||
|
||||
1. **上下文管理是 Agent 的核心杠杆** — system prompt 从 30 行硬编码字符串演变为动态组装系统,每项内容(身份 / 项目规范 / 技能)的增删都不需要改引擎代码
|
||||
2. **"先摘要后按需"适用于 Agent 的所有知识注入** — 无论是技能、文档还是 API 参考,把完整内容塞进 context 是最简单的做法,但渐进式加载才是可扩展的方案
|
||||
|
||||
### 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 死循环修复
|
||||
|
||||
#### 变更
|
||||
|
||||
+63
-50
@@ -4,63 +4,76 @@ import (
|
||||
"context"
|
||||
"log"
|
||||
"os"
|
||||
"fmt"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"go-tiny-claw/internal/engine"
|
||||
"go-tiny-claw/internal/schema"
|
||||
"go-tiny-claw/internal/provider"
|
||||
"go-tiny-claw/internal/schema"
|
||||
"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{}
|
||||
// 1. 初始化真实的 Provider大脑
|
||||
// 这里你可以任意切换 NewZhipuClaudeProvider 或 NewZhipuOpenAIProvider,效果完全一致!
|
||||
llmProvider := provider.DeepseekOpenAIProvider("deepseek-v4-flash")
|
||||
|
||||
// 3. 实例化并运行引擎,开启 EnableThinking = true (开启慢思考阶段!)
|
||||
eng := engine.NewAgentEngine(llmProvider, registry, workDir, true)
|
||||
registry := tools.NewRegistry()
|
||||
|
||||
// 设定测试任务
|
||||
prompt := "我想去北京跑步,帮我查查天气适合吗?"
|
||||
// 挂载工具全家桶
|
||||
// registry.Register(tools.NewReadFileTool(workDir))
|
||||
// registry.Register(tools.NewWriteFileTool(workDir))
|
||||
// registry.Register(tools.NewBashTool(workDir))
|
||||
// registry.Register(tools.NewEditFileTool(workDir))
|
||||
// registry.Register(tools.NewReadSkillTool(workDir))
|
||||
|
||||
err := eng.Run(context.Background(), prompt)
|
||||
if err != nil {
|
||||
log.Fatalf("引擎运行崩溃: %v", err)
|
||||
}
|
||||
}
|
||||
workDir, _ := os.Getwd()
|
||||
|
||||
registry.Register(tools.NewReadFileTool(workDir + "/tmp/project_front"))
|
||||
|
||||
// 实例化引擎,开启 EnableThinking = true
|
||||
eng := engine.NewAgentEngine(llmProvider, registry, false)
|
||||
reporter := engine.NewTerminalReporter()
|
||||
|
||||
var wg sync.WaitGroup
|
||||
|
||||
// ================= 模拟并发场景 1:飞书前端群 =================
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
sessionA := engine.GlobalSessionMgr.GetOrCreate("chat_front_001", workDir+"/tmp/project_front")
|
||||
|
||||
// 回合 1:获取机密
|
||||
log.Println("\n>>> 🙋♂️ [Session A / Turn 1]: 帮我看看 README.md 里记录了什么密钥?我的操作系统是windows")
|
||||
sessionA.Append(schema.Message{Role: schema.RoleUser, Content: "帮我看看 README.md 里记录了什么密钥?"})
|
||||
_ = eng.Run(context.Background(), sessionA, reporter)
|
||||
|
||||
// 故意制造大量“废话”对话,刷掉记忆 (假设 Working Memory Limit=6)
|
||||
for i := 0; i < 6; i++ {
|
||||
sessionA.Append(schema.Message{Role: schema.RoleUser, Content: "这只是一句闲聊占位符。"})
|
||||
sessionA.Append(schema.Message{Role: schema.RoleAssistant, Content: "好的,收到闲聊。"})
|
||||
}
|
||||
|
||||
// 回合 2:验证记忆截断 (此时第一轮的密钥已经被挤出 Working Memory 了!)
|
||||
log.Println("\n>>> 🙋♂️ [Session A / Turn 2]: 请直接告诉我,刚才第一轮你查到的那个密钥是什么?")
|
||||
sessionA.Append(schema.Message{Role: schema.RoleUser, Content: "请直接告诉我,刚才第一轮你查到的那个密钥是什么?不准调用工具!"})
|
||||
_ = eng.Run(context.Background(), sessionA, reporter)
|
||||
}()
|
||||
|
||||
// ================= 模拟并发场景 2:飞书后端群 =================
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
// 稍微错开一点时间发起请求
|
||||
time.Sleep(1 * time.Second)
|
||||
|
||||
sessionB := engine.GlobalSessionMgr.GetOrCreate("chat_back_002", workDir+"/tmp/project_back")
|
||||
|
||||
log.Println("\n>>> 🙋♂️ [Session B]: 别人查到了一个密钥,你这里能看到吗?")
|
||||
sessionB.Append(schema.Message{Role: schema.RoleUser, Content: "别人查到了一个密钥,你这里能看到吗?不准调用工具!"})
|
||||
_ = eng.Run(context.Background(), sessionB, reporter)
|
||||
}()
|
||||
|
||||
wg.Wait()
|
||||
}
|
||||
|
||||
@@ -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=
|
||||
|
||||
+219
-97
@@ -4,7 +4,9 @@ import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log"
|
||||
"sync"
|
||||
|
||||
"go-tiny-claw/internal/prompt"
|
||||
"go-tiny-claw/internal/provider"
|
||||
"go-tiny-claw/internal/schema"
|
||||
"go-tiny-claw/internal/tools"
|
||||
@@ -16,26 +18,31 @@ type AgentEngine struct {
|
||||
registry tools.Registry
|
||||
|
||||
// WorkDir (工作区): 借鉴 OpenClaw 的理念,Agent 必须有一个明确的物理边界
|
||||
WorkDir string
|
||||
// WorkDir string
|
||||
EnableThinking bool // 【新增】慢思考模式开关
|
||||
composer *prompt.PromptComposer
|
||||
}
|
||||
|
||||
func NewAgentEngine(p provider.LLMProvider, r tools.Registry, workDir string, enableThinking bool) *AgentEngine {
|
||||
// 移除了 Engine 层级的 WorkDir,因为 WorkDir 现在应该跟随 Session 走
|
||||
func NewAgentEngine(p provider.LLMProvider, r tools.Registry, enableThinking bool) *AgentEngine {
|
||||
return &AgentEngine{
|
||||
provider: p,
|
||||
registry: r,
|
||||
WorkDir: workDir,
|
||||
provider: p,
|
||||
registry: r,
|
||||
EnableThinking: enableThinking,
|
||||
}
|
||||
}
|
||||
|
||||
func (e *AgentEngine) String() string {
|
||||
return fmt.Sprintf("AgentEngine{thinking: %v, registry: %s}", 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)
|
||||
}
|
||||
}
|
||||
@@ -51,112 +58,227 @@ 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)
|
||||
func (e *AgentEngine) Run(ctx context.Context, session *Session, reporter Reporter) error {
|
||||
log.Printf("[Engine] 唤醒会话 [%s],锁定工作区: %s\n", session.ID, session.WorkDir)
|
||||
|
||||
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,
|
||||
},
|
||||
}
|
||||
// 根据当前 Session 的工作区,动态组装最新的 System Prompt
|
||||
composer := prompt.NewPromptComposer(session.WorkDir)
|
||||
systemMsg := composer.Build()
|
||||
|
||||
turnCount := 0
|
||||
const maxTurns = 10
|
||||
for {
|
||||
availableTools := e.registry.GetAvailableTools()
|
||||
|
||||
for {
|
||||
turnCount++
|
||||
if turnCount > maxTurns {
|
||||
log.Printf("[Engine] 已达最大轮数 (%d),强制终止。\n", maxTurns)
|
||||
break
|
||||
}
|
||||
log.Printf("\n========== [Turn %d] 开始 ==========\n", turnCount)
|
||||
dumpMessages(contextHistory)
|
||||
// 1. 【上下文组装】: System Prompt + 截取最近的 6 条消息作为 Working Memory
|
||||
// 在实际业务中,由于工具返回结果可能很长,短期工作记忆往往设为 6-10 条足以维系连贯对话
|
||||
workingMemory := session.GetWorkingMemory(6)
|
||||
|
||||
// 获取当前挂载的所有工具定义
|
||||
availableTools := e.registry.GetAvailableTools()
|
||||
dumpTools(availableTools)
|
||||
var contextHistory []schema.Message
|
||||
contextHistory = append(contextHistory, systemMsg)
|
||||
contextHistory = append(contextHistory, workingMemory...)
|
||||
|
||||
// ====================================================================
|
||||
// Phase 1: 慢思考阶段 (Thinking) - 仅第一轮执行初始规划
|
||||
// ====================================================================
|
||||
if e.EnableThinking && turnCount == 1 {
|
||||
log.Println("[Engine][Phase 1] 剥夺工具访问权,强制进入慢思考与规划阶段...")
|
||||
// 2. ================= Phase 1: Thinking =================
|
||||
if e.EnableThinking {
|
||||
if reporter != nil {
|
||||
reporter.OnThinking(ctx)
|
||||
}
|
||||
|
||||
// 核心机制:传入的 availableTools 为 nil!
|
||||
// 大模型看不到任何 JSON Schema,被迫只能输出纯文本的思考过程。
|
||||
thinkResp, err := e.provider.Generate(ctx, contextHistory, nil)
|
||||
if err != nil {
|
||||
return fmt.Errorf("Thinking 阶段生成失败: %w", err)
|
||||
}
|
||||
thinkResp, err := e.provider.Generate(ctx, contextHistory, nil)
|
||||
if err != nil {
|
||||
return fmt.Errorf("Thinking 阶段失败: %w", err)
|
||||
}
|
||||
if thinkResp.Content != "" {
|
||||
// 将思考过程持久化到 Session 中!
|
||||
session.Append(*thinkResp)
|
||||
// 把它追加到当前这一轮的临时上下文中,供 Action 阶段使用
|
||||
contextHistory = append(contextHistory, *thinkResp)
|
||||
}
|
||||
}
|
||||
|
||||
// 如果模型输出了思考过程,我们将其作为 Assistant 消息追加到上下文中
|
||||
if thinkResp.Content != "" {
|
||||
fmt.Printf("🧠 [内部思考 Trace]: %s\n", thinkResp.Content)
|
||||
contextHistory = append(contextHistory, *thinkResp)
|
||||
}
|
||||
// 3. ================= Phase 2: Action =================
|
||||
actionResp, err := e.provider.Generate(ctx, contextHistory, availableTools)
|
||||
if err != nil {
|
||||
return fmt.Errorf("Action 阶段失败: %w", err)
|
||||
}
|
||||
|
||||
// 插入过渡指令:让模型知道现在可以调用工具了
|
||||
contextHistory = append(contextHistory, schema.Message{
|
||||
Role: schema.RoleUser,
|
||||
Content: "根据你的推理,现在请使用可用的工具来完成任务。执行具体行动。",
|
||||
})
|
||||
}
|
||||
// 将大模型的行动响应持久化到 Session 中
|
||||
session.Append(*actionResp)
|
||||
contextHistory = append(contextHistory, *actionResp)
|
||||
|
||||
// ====================================================================
|
||||
// Phase 2: 行动阶段 (Action) - 恢复工具,顺着规划执行
|
||||
// ====================================================================
|
||||
log.Println("[Engine][Phase 2] 恢复工具挂载,等待模型采取行动...")
|
||||
if actionResp.Content != "" && reporter != nil {
|
||||
reporter.OnMessage(ctx, actionResp.Content)
|
||||
}
|
||||
|
||||
// 此时的 contextHistory 中已经包含了上一阶段模型自己的 Thinking Trace + 过渡指令。
|
||||
// 模型会顺着自己的逻辑,结合恢复的 availableTools 发起精准的工具调用。
|
||||
actionResp, err := e.provider.Generate(ctx, contextHistory, availableTools)
|
||||
if err != nil {
|
||||
return fmt.Errorf("Action 阶段生成失败: %w", err)
|
||||
}
|
||||
if len(actionResp.ToolCalls) == 0 {
|
||||
// 如果没有工具调用,说明本次任务已完成,打破 ReAct 循环,挂起等待人类的下一条指令
|
||||
break
|
||||
}
|
||||
|
||||
contextHistory = append(contextHistory, *actionResp)
|
||||
// 4. ================= 并发执行底层工具 =================
|
||||
observationMsgs := make([]schema.Message, len(actionResp.ToolCalls))
|
||||
var wg sync.WaitGroup
|
||||
|
||||
if actionResp.Content != "" {
|
||||
fmt.Printf("🤖 [对外回复]: %s\n", actionResp.Content)
|
||||
}
|
||||
for i, toolCall := range actionResp.ToolCalls {
|
||||
wg.Add(1)
|
||||
|
||||
// ====================================================================
|
||||
// 退出与执行逻辑 (与上一讲保持一致)
|
||||
// ====================================================================
|
||||
if len(actionResp.ToolCalls) == 0 {
|
||||
log.Println("[Engine] 模型未请求调用工具,任务宣告完成。")
|
||||
break
|
||||
}
|
||||
go func(idx int, call schema.ToolCall) {
|
||||
defer wg.Done()
|
||||
|
||||
log.Printf("[Engine] 模型请求调用 %d 个工具...\n", len(actionResp.ToolCalls))
|
||||
if reporter != nil {
|
||||
reporter.OnToolCall(ctx, call.Name, string(call.Arguments))
|
||||
}
|
||||
|
||||
for _, toolCall := range actionResp.ToolCalls {
|
||||
log.Printf(" -> 🛠️ 执行工具: %s, 参数: %s\n", toolCall.Name, string(toolCall.Arguments))
|
||||
result := e.registry.Execute(ctx, call)
|
||||
|
||||
result := e.registry.Execute(ctx, toolCall)
|
||||
if reporter != nil {
|
||||
displayOutput := result.Output
|
||||
if len(displayOutput) > 200 {
|
||||
displayOutput = displayOutput[:200] + "... (已截断)"
|
||||
}
|
||||
reporter.OnToolResult(ctx, call.Name, displayOutput, result.IsError)
|
||||
}
|
||||
|
||||
if result.IsError {
|
||||
log.Printf(" -> ❌ 工具执行报错: %s\n", result.Output)
|
||||
} else {
|
||||
log.Printf(" -> ✅ 工具执行成功 (返回 %d 字节)\n", len(result.Output))
|
||||
}
|
||||
observationMsgs[idx] = schema.Message{
|
||||
Role: schema.RoleUser,
|
||||
Content: result.Output,
|
||||
ToolCallID: call.ID,
|
||||
}
|
||||
}(i, toolCall)
|
||||
}
|
||||
|
||||
// 将工具执行的观察结果追加到 Context,准备进入下一轮
|
||||
observationMsg := schema.Message{
|
||||
Role: schema.RoleUser,
|
||||
Content: result.Output,
|
||||
ToolCallID: toolCall.ID,
|
||||
}
|
||||
contextHistory = append(contextHistory, observationMsg)
|
||||
}
|
||||
}
|
||||
wg.Wait()
|
||||
|
||||
return nil
|
||||
// 将所有的工具执行结果(Observation)持久化到 Session 中,开启下一轮的复盘与推理
|
||||
session.Append(observationMsgs...)
|
||||
|
||||
// systemMsg := e.composer.Build()
|
||||
|
||||
// contextHistory := []schema.Message{
|
||||
// systemMsg, // 注入动态组装的内核、AGENTS.md 与 Skills
|
||||
// {Role: schema.RoleUser, Content: userPrompt},
|
||||
// }
|
||||
|
||||
// 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)
|
||||
|
||||
// // 获取当前挂载的所有工具定义
|
||||
// availableTools := e.registry.GetAvailableTools()
|
||||
// dumpTools(availableTools)
|
||||
|
||||
// // ====================================================================
|
||||
// // 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)
|
||||
// }
|
||||
|
||||
// // 如果模型输出了思考过程,我们将其作为 Assistant 消息追加到上下文中
|
||||
// if thinkResp.Content != "" {
|
||||
// fmt.Printf("🧠 [内部思考 Trace]: %s\n", thinkResp.Content)
|
||||
// contextHistory = append(contextHistory, *thinkResp)
|
||||
// }
|
||||
|
||||
// // 插入过渡指令:让模型知道现在可以调用工具了
|
||||
// contextHistory = append(contextHistory, schema.Message{
|
||||
// Role: schema.RoleUser,
|
||||
// Content: "根据你的推理,现在请使用可用的工具来完成任务。执行具体行动。",
|
||||
// })
|
||||
// }
|
||||
|
||||
// // ====================================================================
|
||||
// // 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 = append(contextHistory, *actionResp)
|
||||
|
||||
// if actionResp.Content != "" {
|
||||
// fmt.Printf("🤖 [对外回复]: %s\n", actionResp.Content)
|
||||
// }
|
||||
|
||||
// // ====================================================================
|
||||
// // 退出与执行逻辑 (与上一讲保持一致)
|
||||
// // ====================================================================
|
||||
// if len(actionResp.ToolCalls) == 0 {
|
||||
// log.Println("[Engine] 模型未请求调用工具,任务宣告完成。")
|
||||
// break
|
||||
// }
|
||||
|
||||
// log.Printf("[Engine] 模型请求并发调用 %d 个工具...\n", len(actionResp.ToolCalls))
|
||||
|
||||
// // 【核心改造开始】: 从串行 (Sequential) 演进为并行 (Parallel)
|
||||
|
||||
// // 1. 预分配一个固定长度的切片,用于安全地存放各个并发工具的执行结果(Observation)
|
||||
// // 长度与 ToolCalls 的数量完全一致
|
||||
// observationMsgs := make([]schema.Message, len(actionResp.ToolCalls))
|
||||
|
||||
// // 2. 声明 WaitGroup 用于阻塞等待所有协程完成
|
||||
// var wg sync.WaitGroup
|
||||
|
||||
// // 3. 遍历模型请求的所有工具,为每一个工具单独 Fork 出一个 Goroutine
|
||||
// for i, toolCall := range actionResp.ToolCalls {
|
||||
// wg.Add(1) // 增加计数器
|
||||
|
||||
// // 开启协程。注意:一定要将索引 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)
|
||||
// }
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
package engine
|
||||
|
||||
import "context"
|
||||
|
||||
// Reporter 定义了 Agent 引擎向外界输出信息的规范。
|
||||
// 这使得引擎可以无缝切换终端 (CLI)、飞书、钉钉甚至 WebUI 等不同的展现层。
|
||||
type Reporter interface {
|
||||
// OnThinking 当模型开始进行慢思考 (Reasoning) 时调用
|
||||
OnThinking(ctx context.Context)
|
||||
|
||||
// OnToolCall 当模型决定并发调用工具时调用
|
||||
OnToolCall(ctx context.Context, toolName string, args string)
|
||||
|
||||
// OnToolResult 当工具在底层执行完毕并返回结果时调用
|
||||
OnToolResult(ctx context.Context, toolName string, result string, isError bool)
|
||||
|
||||
// OnMessage 当模型宣告任务完成,向用户输出最终纯文本回答时调用
|
||||
OnMessage(ctx context.Context, content string)
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
package engine
|
||||
|
||||
import (
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"go-tiny-claw/internal/schema"
|
||||
)
|
||||
|
||||
// Session 代表了一次持续的人机交互过程。它负责维护该会话的完整历史。
|
||||
type Session struct {
|
||||
ID string
|
||||
WorkDir string // 该会话绑定的物理工作区
|
||||
CreatedAt time.Time
|
||||
UpdatedAt time.Time
|
||||
|
||||
// 存放此 Session 中所有的用户输入、大模型回复和工具调用结果
|
||||
history []schema.Message
|
||||
mu sync.RWMutex // 读写锁,防止并发读写历史时发生 Data Race
|
||||
}
|
||||
|
||||
func NewSession(id string, workDir string) *Session {
|
||||
return &Session{
|
||||
ID: id,
|
||||
WorkDir: workDir,
|
||||
CreatedAt: time.Now(),
|
||||
UpdatedAt: time.Now(),
|
||||
history: make([]schema.Message, 0),
|
||||
}
|
||||
}
|
||||
|
||||
// Append 线程安全地向 Session 中追加消息
|
||||
func (s *Session) Append(msgs ...schema.Message) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
s.history = append(s.history, msgs...)
|
||||
s.UpdatedAt = time.Now()
|
||||
|
||||
// 【持久化预留点】:在真实的工业级实现中(如 Claude Code),
|
||||
// 我们会在这里将 s.history 以 JSONL 的格式 Append 到 workDir/.claw/sessions/xxx.jsonl 中。
|
||||
// s.SaveToDisk()
|
||||
}
|
||||
|
||||
// GetWorkingMemory 是驾驭工程的核心!
|
||||
// 它不返回全量历史,而是从后往前截取最近的 N 条消息,形成 Agent 的“短期工作记忆”。
|
||||
func (s *Session) GetWorkingMemory(limit int) []schema.Message {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
|
||||
total := len(s.history)
|
||||
if total <= limit || limit <= 0 {
|
||||
// 如果历史总量小于限制,或者不设限,全量返回 (需要深拷贝以防外部修改)
|
||||
res := make([]schema.Message, total)
|
||||
copy(res, s.history)
|
||||
return res
|
||||
}
|
||||
|
||||
// 截取最近的 limit 条消息
|
||||
res := make([]schema.Message, limit)
|
||||
copy(res, s.history[total-limit:])
|
||||
|
||||
// 【驾驭防线】:大模型 API 强制要求历史消息的连续性!
|
||||
// 如果我们截断的第一条消息恰好是一个 ToolResult (RoleUser 且含有 ToolCallID),
|
||||
// 但发出这个请求的 ToolCall 被我们截断抛弃了,大模型 API 会直接报 400 Bad Request。
|
||||
// 因此,如果切片首条属于“孤儿”工具响应,我们必须将其强行舍弃,顺延到下一条正常的 User/Assistant 消息。
|
||||
for len(res) > 0 {
|
||||
if res[0].Role == schema.RoleUser && res[0].ToolCallID != "" {
|
||||
res = res[1:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
return res
|
||||
}
|
||||
|
||||
// ==========================================
|
||||
// 全局 Session Manager: 用于多用户/多终端隔离
|
||||
// ==========================================
|
||||
|
||||
type SessionManager struct {
|
||||
sessions map[string]*Session
|
||||
mu sync.RWMutex
|
||||
}
|
||||
|
||||
var GlobalSessionMgr = &SessionManager{
|
||||
sessions: make(map[string]*Session),
|
||||
}
|
||||
|
||||
// GetOrCreate 获取或创建一个会话
|
||||
func (sm *SessionManager) GetOrCreate(id string, workDir string) *Session {
|
||||
sm.mu.Lock()
|
||||
defer sm.mu.Unlock()
|
||||
|
||||
if sess, exists := sm.sessions[id]; exists {
|
||||
return sess
|
||||
}
|
||||
sess := NewSession(id, workDir)
|
||||
sm.sessions[id] = sess
|
||||
return sess
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package engine
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type TerminalReporter struct{}
|
||||
|
||||
func NewTerminalReporter() *TerminalReporter {
|
||||
return &TerminalReporter{}
|
||||
}
|
||||
|
||||
func (r *TerminalReporter) OnThinking(ctx context.Context) {
|
||||
fmt.Printf("\n[🤔 思考中] 模型正在推理...\n")
|
||||
}
|
||||
|
||||
func (r *TerminalReporter) OnToolCall(ctx context.Context, toolName string, args string) {
|
||||
fmt.Printf("[🛠️ 调用工具] %s\n", toolName)
|
||||
// 清理参数中的换行符和特殊字符
|
||||
displayArgs := strings.ReplaceAll(args, "\n", "\\n")
|
||||
displayArgs = strings.ReplaceAll(displayArgs, "\r", "\\r")
|
||||
if len(displayArgs) > 150 {
|
||||
displayArgs = displayArgs[:150] + "... (已截断)"
|
||||
}
|
||||
fmt.Printf(" 参数: %s\n", displayArgs)
|
||||
}
|
||||
|
||||
func (r *TerminalReporter) OnToolResult(ctx context.Context, toolName string, result string, isError bool) {
|
||||
if isError {
|
||||
fmt.Printf("[❌ 执行失败] %s\n", toolName)
|
||||
// 显示错误信息
|
||||
if result != "" {
|
||||
fmt.Printf(" 错误: %s\n", result)
|
||||
}
|
||||
} else {
|
||||
fmt.Printf("[✅ 执行成功] %s\n", toolName)
|
||||
}
|
||||
}
|
||||
|
||||
func (r *TerminalReporter) OnMessage(ctx context.Context, content string) {
|
||||
if content == "" {
|
||||
return
|
||||
}
|
||||
fmt.Printf("\n🤖 Agent 回复:\n%s\n\n", content)
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
package prompt
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
|
||||
"go-tiny-claw/internal/schema"
|
||||
)
|
||||
|
||||
// Compactor 负责监控和压缩上下文内存,防止大模型发生 OOM
|
||||
type Compactor struct {
|
||||
MaxChars int // 触发压缩的最大字符数阈值 (水位线,可参考使用的大模型的token窗口大小)
|
||||
RetainLastMsgs int // Working Memory 保护区:最近的 N 条消息
|
||||
}
|
||||
|
||||
func NewCompactor(maxChars int, retainLastMsgs int) *Compactor {
|
||||
return &Compactor{
|
||||
MaxChars: maxChars,
|
||||
RetainLastMsgs: retainLastMsgs,
|
||||
}
|
||||
}
|
||||
|
||||
// Compact 接收准备发送给大模型的消息数组。
|
||||
// 如果总长度超标,对远期历史区进行全量掩码 (Masking),对短期保护区进行超长局部截断 (Truncation)。
|
||||
func (c *Compactor) Compact(msgs []schema.Message) []schema.Message {
|
||||
currentLength := c.estimateLength(msgs)
|
||||
|
||||
// 如果没有超过水位线,直接返回原数组 (大多数情况下的正常路径)
|
||||
if currentLength < c.MaxChars {
|
||||
return msgs
|
||||
}
|
||||
|
||||
log.Printf("[Compactor] ⚠️ 内存告警:当前上下文长度 (%d 字符) 超过阈值 (%d),触发压缩清理...\n", currentLength, c.MaxChars)
|
||||
|
||||
var compacted []schema.Message
|
||||
msgCount := len(msgs)
|
||||
|
||||
// 计算受保护的 Working Memory 起始索引
|
||||
protectStartIndex := msgCount - c.RetainLastMsgs
|
||||
if protectStartIndex < 0 {
|
||||
protectStartIndex = 0
|
||||
}
|
||||
|
||||
for i, msg := range msgs {
|
||||
// 1. 系统提示词 (System Prompt) 绝对不能动,直接保留
|
||||
if msg.Role == schema.RoleSystem {
|
||||
compacted = append(compacted, msg)
|
||||
continue
|
||||
}
|
||||
|
||||
// 我们必须拷贝一份新消息,因为在并发环境中直接修改原引用可能导致底层数据结构被污染
|
||||
newMsg := msg
|
||||
|
||||
isInWorkingMemory := i >= protectStartIndex
|
||||
|
||||
// 【核心驾驭逻辑】: 双重降级防线
|
||||
if msg.Role == schema.RoleUser && msg.ToolCallID != "" {
|
||||
// 对于工具的返回结果 (Observation/ToolResult)
|
||||
if !isInWorkingMemory {
|
||||
// 【第一道防线:远期历史】如果是早期对话,执行无情替换 (Full Masking)
|
||||
if len(msg.Content) > 200 {
|
||||
newMsg.Content = fmt.Sprintf("...[为了节省内存,早期的工具输出已被系统强制清理。原始长度: %d 字节]...", len(msg.Content))
|
||||
}
|
||||
} else {
|
||||
// 【第二道防线:短期记忆】即使处于近期保护区,只要单条内容过大,也必须截断防 OOM (Head-Tail Truncation)
|
||||
// 我们保留前 500 字符和后 500 字符(掐头去尾法,大模型通常只需要看开头报错和结尾总结)
|
||||
const maxKeep = 1000
|
||||
if len(msg.Content) > maxKeep {
|
||||
head := msg.Content[:500]
|
||||
tail := msg.Content[len(msg.Content)-500:]
|
||||
newMsg.Content = fmt.Sprintf("%s\n\n...[内容过长,中间 %d 字节已被系统截断]...\n\n%s", head, len(msg.Content)-maxKeep, tail)
|
||||
}
|
||||
}
|
||||
} else if msg.Role == schema.RoleAssistant && msg.Content != "" {
|
||||
// 对于大模型的冗长推理废话 (Thinking Trace)
|
||||
if !isInWorkingMemory && len(msg.Content) > 200 {
|
||||
newMsg.Content = "...[早期的推理思考过程已折叠]..."
|
||||
}
|
||||
}
|
||||
|
||||
// 注意:我们绝不会去动 msg.ToolCalls,因为这是模型行动的证据,是维系逻辑链的关键!
|
||||
compacted = append(compacted, newMsg)
|
||||
}
|
||||
|
||||
newLength := c.estimateLength(compacted)
|
||||
log.Printf("[Compactor] ✅ 压缩完成。上下文长度从 %d 降至 %d 字符。\n", currentLength, newLength)
|
||||
|
||||
return compacted
|
||||
}
|
||||
|
||||
// estimateLength 粗略计算当前上下文的总字符长度
|
||||
func (c *Compactor) estimateLength(msgs []schema.Message) int {
|
||||
length := 0
|
||||
for _, msg := range msgs {
|
||||
length += len(msg.Content)
|
||||
for _, tc := range msg.ToolCalls {
|
||||
length += len(tc.Name) + len(tc.Arguments)
|
||||
}
|
||||
}
|
||||
return length
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
package prompt
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"go-tiny-claw/internal/schema"
|
||||
)
|
||||
|
||||
// PromptComposer 负责根据工作区环境动态生成 System Prompt
|
||||
type PromptComposer struct {
|
||||
workDir string
|
||||
skillLoader *SkillLoader
|
||||
}
|
||||
|
||||
func NewPromptComposer(workDir string) *PromptComposer {
|
||||
return &PromptComposer{
|
||||
workDir: workDir,
|
||||
skillLoader: NewSkillLoader(workDir),
|
||||
}
|
||||
}
|
||||
|
||||
// Build 组装并返回一条完整的 RoleSystem 消息
|
||||
func (c *PromptComposer) Build() schema.Message {
|
||||
var promptBuilder strings.Builder
|
||||
|
||||
// 1. 极简内核 (Minimal Core)
|
||||
promptBuilder.WriteString(`# 核心身份
|
||||
你名叫 go-tiny-claw,一个由驾驭工程驱动的骨灰级研发助手。
|
||||
你具备极简主义哲学,拒绝废话。你能通过系统提供的内置工具,创建、读取、修改和执行工作区中的代码。
|
||||
|
||||
# 核心纪律 (CRITICAL)
|
||||
1. 如需检查文件是否存在,请使用 bash 的 ls 或 test -f,而不是对目录使用 read_file。
|
||||
2. 创建新文件时,务必使用 write_file,并同时提供 path 和 content 参数。
|
||||
3. 编辑文件前务必先读取现有文件,以理解上下文。
|
||||
4. 无论何时你需要写代码或创建文件,都要直接使用 write_file 工具。
|
||||
5. 遇到工具执行报错时,仔细阅读 stderr,尝试自己修正命令并重试。
|
||||
6. 始终用中文回复,以便传达你的进展和想法。
|
||||
`)
|
||||
|
||||
// 2. 外部化状态:加载项目专属规范 (AGENTS.md)
|
||||
agentsMDPath := filepath.Join(c.workDir, "AGENTS.md")
|
||||
content, err := os.ReadFile(agentsMDPath)
|
||||
if err == nil {
|
||||
promptBuilder.WriteString("\n# 项目专属指南 (来自 AGENTS.md)\n")
|
||||
promptBuilder.WriteString("以下是当前工作区特有的架构规范与注意事项,你的行为必须绝对符合以下要求:\n")
|
||||
promptBuilder.WriteString("```markdown\n")
|
||||
promptBuilder.WriteString(string(content))
|
||||
promptBuilder.WriteString("\n```\n")
|
||||
}
|
||||
|
||||
// 3. 渐进式技能发现:仅注入目录(名称 + 触发条件),正文按需加载
|
||||
skills := c.skillLoader.List()
|
||||
if len(skills) > 0 {
|
||||
promptBuilder.WriteString("\n# 可用专业技能\n")
|
||||
promptBuilder.WriteString("你在以下场景可以调用 read_skill 加载完整的技能指令:\n\n")
|
||||
for _, s := range skills {
|
||||
promptBuilder.WriteString("- **" + s.Name + "**:" + s.Description + "\n")
|
||||
}
|
||||
promptBuilder.WriteString("\n当任务匹配上述技能的描述时,请先调用 read_skill 加载完整的执行指南,再严格按照指南操作。\n")
|
||||
}
|
||||
|
||||
return schema.Message{
|
||||
Role: schema.RoleSystem,
|
||||
Content: promptBuilder.String(),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
package prompt
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io/fs"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Skill 定义了从 SKILL.md 中解析出的标准化技能结构
|
||||
type Skill struct {
|
||||
Name string
|
||||
Description string
|
||||
Body string
|
||||
}
|
||||
|
||||
// SkillSummary 是技能的轻量目录项(仅元信息,不含 Body)
|
||||
type SkillSummary struct {
|
||||
Name string
|
||||
Description string
|
||||
}
|
||||
|
||||
// SkillLoader 负责从本地文件系统中加载技能模板
|
||||
type SkillLoader struct {
|
||||
workDir string
|
||||
}
|
||||
|
||||
func NewSkillLoader(workDir string) *SkillLoader {
|
||||
return &SkillLoader{workDir: workDir}
|
||||
}
|
||||
|
||||
// List 扫描 skills 目录,返回所有技能的轻量目录(仅名称和描述)
|
||||
func (s *SkillLoader) List() []SkillSummary {
|
||||
skillBaseDir := filepath.Join(s.workDir, "skills")
|
||||
if _, err := os.Stat(skillBaseDir); os.IsNotExist(err) {
|
||||
return nil
|
||||
}
|
||||
|
||||
var summaries []SkillSummary
|
||||
|
||||
filepath.WalkDir(skillBaseDir, func(path string, d fs.DirEntry, err error) error {
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
if d.IsDir() || d.Name() != "SKILL.md" {
|
||||
return nil
|
||||
}
|
||||
|
||||
content, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
skill := parseSkillMD(string(content))
|
||||
summaries = append(summaries, SkillSummary{
|
||||
Name: skill.Name,
|
||||
Description: skill.Description,
|
||||
})
|
||||
return nil
|
||||
})
|
||||
|
||||
return summaries
|
||||
}
|
||||
|
||||
// Load 按技能名称加载完整的 Skill(含 Body)
|
||||
func (s *SkillLoader) Load(name string) (*Skill, error) {
|
||||
skillBaseDir := filepath.Join(s.workDir, "skills")
|
||||
if _, err := os.Stat(skillBaseDir); os.IsNotExist(err) {
|
||||
return nil, fmt.Errorf("skills 目录不存在")
|
||||
}
|
||||
|
||||
var found *Skill
|
||||
|
||||
filepath.WalkDir(skillBaseDir, func(path string, d fs.DirEntry, err error) error {
|
||||
if err != nil || found != nil {
|
||||
return nil
|
||||
}
|
||||
if d.IsDir() || d.Name() != "SKILL.md" {
|
||||
return nil
|
||||
}
|
||||
|
||||
content, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
skill := parseSkillMD(string(content))
|
||||
if skill.Name == name {
|
||||
found = &skill
|
||||
}
|
||||
return nil
|
||||
})
|
||||
|
||||
if found == nil {
|
||||
return nil, fmt.Errorf("未找到技能: %s", name)
|
||||
}
|
||||
return found, nil
|
||||
}
|
||||
|
||||
// parseSkillMD 解析带有 YAML Frontmatter 的 Markdown 内容
|
||||
func parseSkillMD(content string) Skill {
|
||||
skill := Skill{
|
||||
Name: "Unknown Skill",
|
||||
Description: "No description provided.",
|
||||
Body: content,
|
||||
}
|
||||
|
||||
if strings.HasPrefix(content, "---\n") || strings.HasPrefix(content, "---\r\n") {
|
||||
parts := strings.SplitN(content, "---", 3)
|
||||
if len(parts) == 3 {
|
||||
frontmatter := parts[1]
|
||||
skill.Body = strings.TrimSpace(parts[2])
|
||||
|
||||
lines := strings.Split(frontmatter, "\n")
|
||||
for _, line := range lines {
|
||||
line = strings.TrimSpace(line)
|
||||
if strings.HasPrefix(line, "name:") {
|
||||
skill.Name = strings.TrimSpace(strings.TrimPrefix(line, "name:"))
|
||||
} else if strings.HasPrefix(line, "description:") {
|
||||
skill.Description = strings.TrimSpace(strings.TrimPrefix(line, "description:"))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return skill
|
||||
}
|
||||
+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
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
package tools
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
|
||||
"go-tiny-claw/internal/prompt"
|
||||
"go-tiny-claw/internal/schema"
|
||||
)
|
||||
|
||||
type ReadSkillTool struct {
|
||||
loader *prompt.SkillLoader
|
||||
}
|
||||
|
||||
func NewReadSkillTool(workDir string) *ReadSkillTool {
|
||||
return &ReadSkillTool{
|
||||
loader: prompt.NewSkillLoader(workDir),
|
||||
}
|
||||
}
|
||||
|
||||
func (t *ReadSkillTool) Name() string {
|
||||
return "read_skill"
|
||||
}
|
||||
|
||||
func (t *ReadSkillTool) Definition() schema.ToolDefinition {
|
||||
return schema.ToolDefinition{
|
||||
Name: t.Name(),
|
||||
Description: "按技能名称加载完整的技能指令。在开始任务前可先用 read_skill 获取该技能的详细执行指南。支持技能: git-workflow",
|
||||
InputSchema: map[string]interface{}{
|
||||
"type": "object",
|
||||
"properties": map[string]interface{}{
|
||||
"name": map[string]interface{}{
|
||||
"type": "string",
|
||||
"description": "要加载的技能名称,如 git-workflow",
|
||||
},
|
||||
},
|
||||
"required": []string{"name"},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
type readSkillArgs struct {
|
||||
Name string `json:"name"`
|
||||
}
|
||||
|
||||
func (t *ReadSkillTool) Execute(ctx context.Context, args json.RawMessage) (string, error) {
|
||||
var input readSkillArgs
|
||||
if err := json.Unmarshal(args, &input); err != nil {
|
||||
return "", fmt.Errorf("参数解析失败: %w", err)
|
||||
}
|
||||
|
||||
skill, err := t.loader.Load(input.Name)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
return fmt.Sprintf("技能: %s\n描述: %s\n\n--- 技能正文 ---\n%s", skill.Name, skill.Description, skill.Body), 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,
|
||||
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
---
|
||||
name: git-workflow
|
||||
description: 当人类用户要求你“提交代码”、“保存变更”或执行 Git 相关操作时,必须使用此技能。
|
||||
---
|
||||
|
||||
# 提交流程 SOP
|
||||
|
||||
1. 先使用 `bash` 调用 `git status` 确认当前有哪些文件发生了改动。
|
||||
2. 你的 commit message 必须使用 Emoji 开头,例如:`🚀 feat: 增加新功能` 或 `🐛 fix: 修复 Bug`。
|
||||
3. 严禁使用 `git commit -am "update"` 这种敷衍的提交。
|
||||
Reference in New Issue
Block a user