v1.1 慢思考模式 (Thinking Phase)
将 ReAct 循环从单阶段升级为 Thinking + Action 双阶段架构: - Phase 1:剥夺工具访问权,强制模型先输出纯文本推理规划 - Phase 2:恢复工具挂载,模型按推理结果精准执行 - 新增 EnableThinking 开关,兼容旧模式
This commit is contained in:
@@ -63,6 +63,20 @@ func main() {
|
|||||||
- **注册工具**: 实现 `Registry` 接口即可挂载自定义工具集(bash、文件操作、代码搜索等)
|
- **注册工具**: 实现 `Registry` 接口即可挂载自定义工具集(bash、文件操作、代码搜索等)
|
||||||
- **自定义 Schema**: 基于 `schema` 包的数据结构可灵活扩展消息格式和工具定义
|
- **自定义 Schema**: 基于 `schema` 包的数据结构可灵活扩展消息格式和工具定义
|
||||||
|
|
||||||
|
## 版本历史
|
||||||
|
|
||||||
|
### v1.1 — 慢思考模式 (Thinking Phase)
|
||||||
|
|
||||||
|
将 ReAct 循环从单阶段升级为双阶段架构:
|
||||||
|
|
||||||
|
- **Phase 1 (Thinking)** — 剥夺工具访问权,强制模型先进行纯文本推理规划
|
||||||
|
- **Phase 2 (Action)** — 恢复工具挂载,模型顺着推理结果执行精准的工具调用
|
||||||
|
- 新增 `EnableThinking` 开关,兼容旧模式
|
||||||
|
|
||||||
|
### v1.0 — ReAct 循环基础
|
||||||
|
|
||||||
|
实现标准的单阶段 ReAct 循环:思考 → 调工具 → 观察 → 继续,直到任务完成。
|
||||||
|
|
||||||
## License
|
## License
|
||||||
|
|
||||||
MIT
|
MIT
|
||||||
|
|||||||
+46
-44
@@ -9,64 +9,66 @@ import (
|
|||||||
"go-tiny-claw/internal/schema"
|
"go-tiny-claw/internal/schema"
|
||||||
)
|
)
|
||||||
|
|
||||||
// ==========================================
|
// 升级版 Mock Provider
|
||||||
// 1. 伪造的大模型 Provider
|
|
||||||
// ==========================================
|
|
||||||
type mockProvider struct {
|
type mockProvider struct {
|
||||||
turn int
|
turn int
|
||||||
}
|
}
|
||||||
|
|
||||||
// 模拟大模型的响应:第一轮请求执行 bash,第二轮输出最终结果
|
func (m *mockProvider) Generate(ctx context.Context, msgs []schema.Message, tools []schema.ToolDefinition) (*schema.Message, error) {
|
||||||
func (m *mockProvider) Generate(ctx context.Context, msgs []schema.Message, _ []schema.ToolDefinition) (*schema.Message, error) {
|
// 如果工具列表为空,说明这是引擎发起的 Phase 1: Thinking 阶段
|
||||||
m.turn++
|
if len(tools) == 0 {
|
||||||
if m.turn == 1 {
|
return &schema.Message{
|
||||||
return &schema.Message{
|
Role: schema.RoleAssistant,
|
||||||
Role: schema.RoleAssistant,
|
Content: "【推理中】目标是检查文件。我不能直接盲猜,我需要先调用 bash 工具执行 ls 命令,看看当前目录下有什么,然后再做定夺。",
|
||||||
Content: "让我来看看当前目录下有什么文件。",
|
}, nil
|
||||||
ToolCalls: []schema.ToolCall{
|
}
|
||||||
{ID: "call_123", Name: "bash", Arguments: []byte(`{"command": "ls -la"}`)},
|
|
||||||
},
|
|
||||||
}, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
return &schema.Message{
|
// 如果工具列表不为空,说明这是 Phase 2: Action 阶段
|
||||||
Role: schema.RoleAssistant,
|
m.turn++
|
||||||
Content: "我看到了文件列表,里面包含 main.go,任务完成!",
|
if m.turn == 1 {
|
||||||
}, nil
|
// 第一轮 Action:顺着刚才的 Thinking,精准调用工具
|
||||||
|
return &schema.Message{
|
||||||
|
Role: schema.RoleAssistant,
|
||||||
|
Content: "我要执行我刚才计划的步骤了。",
|
||||||
|
ToolCalls: []schema.ToolCall{
|
||||||
|
{ID: "call_123", Name: "bash", Arguments: []byte(`{"command": "ls -la"}`)},
|
||||||
|
},
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// 第二轮 Action:直接总结退出
|
||||||
|
return &schema.Message{
|
||||||
|
Role: schema.RoleAssistant,
|
||||||
|
Content: "根据工具返回的结果,我看到了 main.go,任务圆满完成!",
|
||||||
|
}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// ==========================================
|
|
||||||
// 2. 伪造的 Tool Registry
|
|
||||||
// ==========================================
|
|
||||||
type mockRegistry struct{}
|
type mockRegistry struct{}
|
||||||
|
|
||||||
func (m *mockRegistry) GetAvailableTools() []schema.ToolDefinition { return nil }
|
func (m *mockRegistry) GetAvailableTools() []schema.ToolDefinition {
|
||||||
|
// 为了让 Phase 2 能检测到工具,这里返回一个伪造的工具定义数组
|
||||||
|
return []schema.ToolDefinition{{Name: "bash"}}
|
||||||
|
}
|
||||||
|
|
||||||
func (m *mockRegistry) Execute(ctx context.Context, call schema.ToolCall) schema.ToolResult {
|
func (m *mockRegistry) Execute(ctx context.Context, call schema.ToolCall) schema.ToolResult {
|
||||||
// 直接返回一段伪造的终端输出
|
return schema.ToolResult{
|
||||||
return schema.ToolResult{
|
ToolCallID: call.ID,
|
||||||
ToolCallID: call.ID,
|
Output: "-rw-r--r-- 1 user group 234 Oct 24 10:00 main.go\n",
|
||||||
Output: "-rw-r--r-- 1 user group 234 Oct 24 10:00 main.go\n",
|
IsError: false,
|
||||||
IsError: false,
|
}
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// ==========================================
|
|
||||||
// 3. 组装运行
|
|
||||||
// ==========================================
|
|
||||||
func main() {
|
func main() {
|
||||||
// 获取当前执行目录作为 WorkDir 物理边界
|
workDir, _ := os.Getwd()
|
||||||
workDir, _ := os.Getwd()
|
|
||||||
|
|
||||||
p := &mockProvider{}
|
p := &mockProvider{}
|
||||||
r := &mockRegistry{}
|
r := &mockRegistry{}
|
||||||
|
|
||||||
// 实例化核心引擎
|
// 实例化引擎,开启 EnableThinking = true
|
||||||
eng := engine.NewAgentEngine(p, r, workDir)
|
eng := engine.NewAgentEngine(p, r, workDir, true)
|
||||||
|
|
||||||
// 发起任务指令
|
err := eng.Run(context.Background(), "帮我检查当前目录的文件")
|
||||||
err := eng.Run(context.Background(), "帮我检查当前目录的文件")
|
if err != nil {
|
||||||
if err != nil {
|
log.Fatalf("引擎崩溃: %v", err)
|
||||||
log.Fatalf("引擎崩溃: %v", err)
|
}
|
||||||
}
|
|
||||||
}
|
}
|
||||||
+82
-63
@@ -17,92 +17,111 @@ type AgentEngine struct {
|
|||||||
|
|
||||||
// WorkDir (工作区): 借鉴 OpenClaw 的理念,Agent 必须有一个明确的物理边界
|
// WorkDir (工作区): 借鉴 OpenClaw 的理念,Agent 必须有一个明确的物理边界
|
||||||
WorkDir string
|
WorkDir string
|
||||||
|
EnableThinking bool // 【新增】慢思考模式开关
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewAgentEngine(p provider.LLMProvider, r tools.Registry, workDir string) *AgentEngine {
|
func NewAgentEngine(p provider.LLMProvider, r tools.Registry, workDir string, enableThinking bool) *AgentEngine {
|
||||||
return &AgentEngine{
|
return &AgentEngine{
|
||||||
provider: p,
|
provider: p,
|
||||||
registry: r,
|
registry: r,
|
||||||
WorkDir: workDir,
|
WorkDir: workDir,
|
||||||
|
EnableThinking: enableThinking,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Run 启动 Agent 的生命周期
|
// internal/engine/loop.go (续)
|
||||||
func (e *AgentEngine) Run(ctx context.Context, userPrompt string) error {
|
func (e *AgentEngine) Run(ctx context.Context, userPrompt string) error {
|
||||||
log.Printf("[Engine] 引擎启动,锁定工作区: %s\n", e.WorkDir)
|
log.Printf("[Engine] 引擎启动,锁定工作区: %s\n", e.WorkDir)
|
||||||
|
log.Printf("[Engine] 慢思考模式 (Thinking Phase): %v\n", e.EnableThinking)
|
||||||
|
|
||||||
// 1. 初始化会话的 Context (上下文内存)
|
contextHistory := []schema.Message{
|
||||||
// 在真实的场景中,这里会由动态 Prompt 组装器加载 AGENTS.md。目前我们先硬编码。
|
{
|
||||||
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.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,
|
||||||
Role: schema.RoleUser,
|
},
|
||||||
Content: userPrompt,
|
}
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
turnCount := 0
|
turnCount := 0
|
||||||
|
|
||||||
// 2. The Main Loop: 心跳开始 (标准的 ReAct 循环)
|
for {
|
||||||
for {
|
turnCount++
|
||||||
turnCount++
|
log.Printf("\n========== [Turn %d] 开始 ==========\n", turnCount)
|
||||||
log.Printf("========== [Turn %d] 开始 ==========\n", turnCount)
|
|
||||||
|
|
||||||
// 获取当前挂载的所有工具定义
|
// 获取当前挂载的所有工具定义
|
||||||
availableTools := e.registry.GetAvailableTools()
|
availableTools := e.registry.GetAvailableTools()
|
||||||
|
|
||||||
// 向大模型发起推理请求 (包含 Reasoning)
|
// ====================================================================
|
||||||
log.Println("[Engine] 正在思考 (Reasoning)...")
|
// Phase 1: 慢思考阶段 (Thinking) - 剥夺工具,强制规划
|
||||||
responseMsg, err := e.provider.Generate(ctx, contextHistory, availableTools)
|
// ====================================================================
|
||||||
if err != nil {
|
if e.EnableThinking {
|
||||||
return fmt.Errorf("模型生成失败: %w", err)
|
log.Println("[Engine][Phase 1] 剥夺工具访问权,强制进入慢思考与规划阶段...")
|
||||||
}
|
|
||||||
|
|
||||||
// 将模型的响应完整追加到上下文历史中
|
// 核心机制:传入的 availableTools 为 nil!
|
||||||
contextHistory = append(contextHistory, *responseMsg)
|
// 大模型看不到任何 JSON Schema,被迫只能输出纯文本的思考过程。
|
||||||
|
thinkResp, err := e.provider.Generate(ctx, contextHistory, nil)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("Thinking 阶段生成失败: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
// 如果模型回复了纯文本,打印出来 (这通常是它的思考过程,或是最终结果)
|
// 如果模型输出了思考过程,我们将其作为 Assistant 消息追加到上下文中
|
||||||
if responseMsg.Content != "" {
|
if thinkResp.Content != "" {
|
||||||
fmt.Printf("🤖 模型: %s\n", responseMsg.Content)
|
fmt.Printf("🧠 [内部思考 Trace]: %s\n", thinkResp.Content)
|
||||||
}
|
contextHistory = append(contextHistory, *thinkResp)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// 3. 退出条件判断
|
// ====================================================================
|
||||||
// 如果模型没有请求任何工具调用,说明它认为任务已经完成,跳出循环。
|
// Phase 2: 行动阶段 (Action) - 恢复工具,顺着规划执行
|
||||||
if len(responseMsg.ToolCalls) == 0 {
|
// ====================================================================
|
||||||
log.Println("[Engine] 任务完成,退出循环。")
|
log.Println("[Engine][Phase 2] 恢复工具挂载,等待模型采取行动...")
|
||||||
break
|
|
||||||
}
|
|
||||||
|
|
||||||
// 4. 执行行动 (Action) 与 获取观察结果 (Observation)
|
// 此时的 contextHistory 中已经包含了上一阶段模型自己的 Thinking Trace。
|
||||||
log.Printf("[Engine] 模型请求调用 %d 个工具...\n", len(responseMsg.ToolCalls))
|
// 模型会顺着自己的逻辑,结合恢复的 availableTools 发起精准的工具调用。
|
||||||
|
actionResp, err := e.provider.Generate(ctx, contextHistory, availableTools)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("Action 阶段生成失败: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
for _, toolCall := range responseMsg.ToolCalls {
|
contextHistory = append(contextHistory, *actionResp)
|
||||||
log.Printf(" -> 🛠️ 执行工具: %s, 参数: %s\n", toolCall.Name, string(toolCall.Arguments))
|
|
||||||
|
|
||||||
// 通过 Registry 路由并执行底层工具
|
if actionResp.Content != "" {
|
||||||
result := e.registry.Execute(ctx, toolCall)
|
fmt.Printf("🤖 [对外回复]: %s\n", actionResp.Content)
|
||||||
|
}
|
||||||
|
|
||||||
if result.IsError {
|
// ====================================================================
|
||||||
log.Printf(" -> ❌ 工具执行报错: %s\n", result.Output)
|
// 退出与执行逻辑 (与上一讲保持一致)
|
||||||
} else {
|
// ====================================================================
|
||||||
log.Printf(" -> ✅ 工具执行成功 (返回 %d 字节)\n", len(result.Output))
|
if len(actionResp.ToolCalls) == 0 {
|
||||||
}
|
log.Println("[Engine] 模型未请求调用工具,任务宣告完成。")
|
||||||
|
break
|
||||||
|
}
|
||||||
|
|
||||||
// 将工具执行的观察结果 (Observation) 封装为 User Message 追加到上下文中
|
log.Printf("[Engine] 模型请求调用 %d 个工具...\n", len(actionResp.ToolCalls))
|
||||||
// 注意:ToolCallID 必须携带!这是维系大模型推理链条的关键
|
|
||||||
observationMsg := schema.Message{
|
|
||||||
Role: schema.RoleUser,
|
|
||||||
Content: result.Output,
|
|
||||||
ToolCallID: toolCall.ID,
|
|
||||||
}
|
|
||||||
contextHistory = append(contextHistory, observationMsg)
|
|
||||||
}
|
|
||||||
|
|
||||||
// 循环回到开头,模型将带着新加入的 Observation 继续它的下一轮思考...
|
for _, toolCall := range actionResp.ToolCalls {
|
||||||
}
|
log.Printf(" -> 🛠️ 执行工具: %s, 参数: %s\n", toolCall.Name, string(toolCall.Arguments))
|
||||||
|
|
||||||
return nil
|
result := e.registry.Execute(ctx, toolCall)
|
||||||
|
|
||||||
|
if result.IsError {
|
||||||
|
log.Printf(" -> ❌ 工具执行报错: %s\n", result.Output)
|
||||||
|
} else {
|
||||||
|
log.Printf(" -> ✅ 工具执行成功 (返回 %d 字节)\n", len(result.Output))
|
||||||
|
}
|
||||||
|
|
||||||
|
// 将工具执行的观察结果追加到 Context,准备进入下一轮
|
||||||
|
observationMsg := schema.Message{
|
||||||
|
Role: schema.RoleUser,
|
||||||
|
Content: result.Output,
|
||||||
|
ToolCallID: toolCall.ID,
|
||||||
|
}
|
||||||
|
contextHistory = append(contextHistory, observationMsg)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user