v1.2 真实模型接入 + Thinking 死循环修复
- 新增 OpenAIProvider / ClaudeProvider,接入 Deepseek 真实 API - 修复 Deepseek thinking 模式 reasoning_content 回传问题 - 修复 Thinking 阶段过渡指令每轮重复插入导致的死循环 - 新增 maxTurns 保护、dumpMessages/dumpTools 调试输出
This commit is contained in:
@@ -65,6 +65,30 @@ func main() {
|
|||||||
|
|
||||||
## 版本历史
|
## 版本历史
|
||||||
|
|
||||||
|
### v1.2 — 真实模型接入与 Thinking 死循环修复
|
||||||
|
|
||||||
|
#### 变更
|
||||||
|
|
||||||
|
- **接入真实大模型** — 新增 `OpenAIProvider` 和 `ClaudeProvider`,分别基于 OpenAI V3 SDK 和 Anthropic SDK 连接 Deepseek API,替换原有的 Mock Provider
|
||||||
|
- **Deepseek thinking 模式适配** — 修正 `reasoning_content` 字段丢失导致的 API 400 错误,在 `schema.Message` 中新增字段并在请求中回传
|
||||||
|
- **Thinking 死循环修复** — 过渡指令只在首轮插入,防止模型每轮重复调用工具
|
||||||
|
- **最大轮数保护** — 新增 `maxTurns = 10` 上限,防止意外死循环
|
||||||
|
- **调试输出** — 新增 `dumpMessages` 和 `dumpTools`,每轮打印上下文消息和工具列表
|
||||||
|
|
||||||
|
#### 踩坑记录
|
||||||
|
|
||||||
|
| 问题 | 原因 | 解决 |
|
||||||
|
|---|---|---|
|
||||||
|
| API 400: `reasoning_content must be passed back` | Deepseek thinking 模式返回了 `reasoning_content` 字段,回传请求时未携带 | 从响应 RawJSON 中提取该字段,用 `param.Override` 注入原始 JSON 回传 |
|
||||||
|
| 模型在 Phase 2 不调用工具 | Phase 1 的思考内容作为 Assistant 消息追加后,模型认为对话已结束 | 在思考后插入一条 User 角色过渡指令:"根据推理,使用工具完成任务" |
|
||||||
|
| 引擎死循环跑到 maxTurns | 过渡指令每轮都插入,模型每轮都被要求调用工具 | 过渡指令只在 `turnCount == 1` 时插入,后续轮次模型根据观察结果自行判断 |
|
||||||
|
|
||||||
|
#### 经验教训
|
||||||
|
|
||||||
|
1. **上下文即状态** — Agent 的所有行为都由上下文驱动。插入一条消息就能改变模型行为,不需要改代码逻辑
|
||||||
|
2. **非标准 API 字段需手动处理** — 大模型厂商的扩展字段(如 `reasoning_content`)不在 SDK 类型中,需要从 RawJSON 手动提取并用注入方式回传
|
||||||
|
3. **过渡指令的作用域很重要** — "使用工具"这种指令适合在首轮引导,重复出现会导致模型无法自行判断任务是否完成
|
||||||
|
|
||||||
### v1.1 — 慢思考模式 (Thinking Phase)
|
### v1.1 — 慢思考模式 (Thinking Phase)
|
||||||
|
|
||||||
将 ReAct 循环从单阶段升级为双阶段架构:
|
将 ReAct 循环从单阶段升级为双阶段架构:
|
||||||
|
|||||||
+35
-43
@@ -4,71 +4,63 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"log"
|
"log"
|
||||||
"os"
|
"os"
|
||||||
|
"fmt"
|
||||||
|
|
||||||
"go-tiny-claw/internal/engine"
|
"go-tiny-claw/internal/engine"
|
||||||
"go-tiny-claw/internal/schema"
|
"go-tiny-claw/internal/schema"
|
||||||
|
"go-tiny-claw/internal/provider"
|
||||||
)
|
)
|
||||||
|
|
||||||
// 升级版 Mock Provider
|
|
||||||
type mockProvider struct {
|
|
||||||
turn int
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *mockProvider) Generate(ctx context.Context, msgs []schema.Message, tools []schema.ToolDefinition) (*schema.Message, error) {
|
|
||||||
// 如果工具列表为空,说明这是引擎发起的 Phase 1: Thinking 阶段
|
|
||||||
if len(tools) == 0 {
|
|
||||||
return &schema.Message{
|
|
||||||
Role: schema.RoleAssistant,
|
|
||||||
Content: "【推理中】目标是检查文件。我不能直接盲猜,我需要先调用 bash 工具执行 ls 命令,看看当前目录下有什么,然后再做定夺。",
|
|
||||||
}, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// 如果工具列表不为空,说明这是 Phase 2: Action 阶段
|
|
||||||
m.turn++
|
|
||||||
if m.turn == 1 {
|
|
||||||
// 第一轮 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
|
|
||||||
}
|
|
||||||
|
|
||||||
|
// 伪造的工具注册表 (用于测试 Provider 的工具提取能力)
|
||||||
type mockRegistry struct{}
|
type mockRegistry struct{}
|
||||||
|
|
||||||
func (m *mockRegistry) GetAvailableTools() []schema.ToolDefinition {
|
func (m *mockRegistry) GetAvailableTools() []schema.ToolDefinition {
|
||||||
// 为了让 Phase 2 能检测到工具,这里返回一个伪造的工具定义数组
|
return []schema.ToolDefinition{
|
||||||
return []schema.ToolDefinition{{Name: "bash"}}
|
{
|
||||||
|
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 {
|
func (m *mockRegistry) Execute(ctx context.Context, call schema.ToolCall) schema.ToolResult {
|
||||||
|
log.Printf(" -> [Mock 工具执行] 获取 %s 的天气中...\n", call.Name)
|
||||||
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: "API 返回:今天是晴天,气温 25 度。",
|
||||||
IsError: false,
|
IsError: false,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
|
|
||||||
|
fmt.Printf("11111")
|
||||||
workDir, _ := os.Getwd()
|
workDir, _ := os.Getwd()
|
||||||
|
|
||||||
p := &mockProvider{}
|
// 1. 初始化真实的 Provider大脑 (指向智谱 GLM-4.5)
|
||||||
r := &mockRegistry{}
|
// 这里你可以任意切换 NewZhipuClaudeProvider 或 NewZhipuOpenAIProvider,效果完全一致!
|
||||||
|
llmProvider := provider.DeepseekOpenAIProvider("deepseek-v4-flash")
|
||||||
|
// 2. 注入伪造的工具注册表
|
||||||
|
registry := &mockRegistry{}
|
||||||
|
|
||||||
// 实例化引擎,开启 EnableThinking = true
|
// 3. 实例化并运行引擎,开启 EnableThinking = true (开启慢思考阶段!)
|
||||||
eng := engine.NewAgentEngine(p, r, workDir, true)
|
eng := engine.NewAgentEngine(llmProvider, registry, workDir, true)
|
||||||
|
|
||||||
err := eng.Run(context.Background(), "帮我检查当前目录的文件")
|
// 设定测试任务
|
||||||
|
prompt := "我想去北京跑步,帮我查查天气适合吗?"
|
||||||
|
|
||||||
|
err := eng.Run(context.Background(), prompt)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatalf("引擎崩溃: %v", err)
|
log.Fatalf("引擎运行崩溃: %v", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,2 +1,21 @@
|
|||||||
module go-tiny-claw
|
module go-tiny-claw
|
||||||
|
|
||||||
|
go 1.23.0
|
||||||
|
|
||||||
|
require (
|
||||||
|
github.com/anthropics/anthropic-sdk-go v1.43.0 // indirect
|
||||||
|
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
|
||||||
|
github.com/tidwall/pretty v1.2.1 // indirect
|
||||||
|
github.com/tidwall/sjson v1.2.5 // indirect
|
||||||
|
github.com/wk8/go-ordered-map/v2 v2.1.8 // indirect
|
||||||
|
golang.org/x/sync v0.16.0 // indirect
|
||||||
|
gopkg.in/yaml.v3 v3.0.1 // indirect
|
||||||
|
)
|
||||||
|
|||||||
@@ -0,0 +1,34 @@
|
|||||||
|
github.com/anthropics/anthropic-sdk-go v1.43.0 h1:ShY3C7lafzHP0ze1dCxL3ZFZzvkGfXJN91DfZTG8zLM=
|
||||||
|
github.com/anthropics/anthropic-sdk-go v1.43.0/go.mod h1:5cEaslQ6A9ajdL5YUvhNW57LKxEz0OAZ7WEzgZWLD7k=
|
||||||
|
github.com/bahlo/generic-list-go v0.2.0 h1:5sz/EEAK+ls5wF+NeqDpk5+iNdMDXrh3z3nPnH1Wvgk=
|
||||||
|
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/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/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/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=
|
||||||
|
github.com/tidwall/match v1.1.1 h1:+Ho715JplO36QYgwN9PGYNhgZvoUSc9X2c80KVTi+GA=
|
||||||
|
github.com/tidwall/match v1.1.1/go.mod h1:eRSPERbgtNPcGhD8UCthc6PmLEQXEWd3PRB5JTxsfmM=
|
||||||
|
github.com/tidwall/pretty v1.2.0/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU=
|
||||||
|
github.com/tidwall/pretty v1.2.1 h1:qjsOFOWWQl+N3RsoF5/ssm1pHmJJwhjlSbZ51I6wMl4=
|
||||||
|
github.com/tidwall/pretty v1.2.1/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU=
|
||||||
|
github.com/tidwall/sjson v1.2.5 h1:kLy8mja+1c9jlljvWTlSazM7cKDRfJuR/bOJhcY5NcY=
|
||||||
|
github.com/tidwall/sjson v1.2.5/go.mod h1:Fvgq9kS/6ociJEDnK0Fk1cpYF4FIW6ZF7LAe+6jwd28=
|
||||||
|
github.com/wk8/go-ordered-map/v2 v2.1.8 h1:5h/BUHu93oj4gIdvHHHGsScSTMijfx5PeYkE/fJgbpc=
|
||||||
|
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=
|
||||||
|
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||||
|
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||||
|
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||||
+38
-3
@@ -29,6 +29,28 @@ func NewAgentEngine(p provider.LLMProvider, r tools.Registry, workDir string, en
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// dumpMessages 打印当前上下文中的所有消息 (调试用)
|
||||||
|
func dumpMessages(msgs []schema.Message) {
|
||||||
|
for i, msg := range msgs {
|
||||||
|
content := msg.Content
|
||||||
|
if len(content) > 80 {
|
||||||
|
content = content[:80] + "..."
|
||||||
|
}
|
||||||
|
log.Printf(" [%02d] %-10s | %s", i, msg.Role, content)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// dumpTools 打印当前可用的工具列表
|
||||||
|
func dumpTools(tools []schema.ToolDefinition) {
|
||||||
|
if len(tools) == 0 {
|
||||||
|
log.Printf(" [Tools] (无可用工具)\n")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
for i, t := range tools {
|
||||||
|
log.Printf(" [Tool %d] %s — %s", i, t.Name, t.Description)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// internal/engine/loop.go (续)
|
// 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)
|
||||||
@@ -46,18 +68,25 @@ func (e *AgentEngine) Run(ctx context.Context, userPrompt string) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
turnCount := 0
|
turnCount := 0
|
||||||
|
const maxTurns = 10
|
||||||
|
|
||||||
for {
|
for {
|
||||||
turnCount++
|
turnCount++
|
||||||
|
if turnCount > maxTurns {
|
||||||
|
log.Printf("[Engine] 已达最大轮数 (%d),强制终止。\n", maxTurns)
|
||||||
|
break
|
||||||
|
}
|
||||||
log.Printf("\n========== [Turn %d] 开始 ==========\n", turnCount)
|
log.Printf("\n========== [Turn %d] 开始 ==========\n", turnCount)
|
||||||
|
dumpMessages(contextHistory)
|
||||||
|
|
||||||
// 获取当前挂载的所有工具定义
|
// 获取当前挂载的所有工具定义
|
||||||
availableTools := e.registry.GetAvailableTools()
|
availableTools := e.registry.GetAvailableTools()
|
||||||
|
dumpTools(availableTools)
|
||||||
|
|
||||||
// ====================================================================
|
// ====================================================================
|
||||||
// Phase 1: 慢思考阶段 (Thinking) - 剥夺工具,强制规划
|
// Phase 1: 慢思考阶段 (Thinking) - 仅第一轮执行初始规划
|
||||||
// ====================================================================
|
// ====================================================================
|
||||||
if e.EnableThinking {
|
if e.EnableThinking && turnCount == 1 {
|
||||||
log.Println("[Engine][Phase 1] 剥夺工具访问权,强制进入慢思考与规划阶段...")
|
log.Println("[Engine][Phase 1] 剥夺工具访问权,强制进入慢思考与规划阶段...")
|
||||||
|
|
||||||
// 核心机制:传入的 availableTools 为 nil!
|
// 核心机制:传入的 availableTools 为 nil!
|
||||||
@@ -72,6 +101,12 @@ func (e *AgentEngine) Run(ctx context.Context, userPrompt string) error {
|
|||||||
fmt.Printf("🧠 [内部思考 Trace]: %s\n", thinkResp.Content)
|
fmt.Printf("🧠 [内部思考 Trace]: %s\n", thinkResp.Content)
|
||||||
contextHistory = append(contextHistory, *thinkResp)
|
contextHistory = append(contextHistory, *thinkResp)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 插入过渡指令:让模型知道现在可以调用工具了
|
||||||
|
contextHistory = append(contextHistory, schema.Message{
|
||||||
|
Role: schema.RoleUser,
|
||||||
|
Content: "根据你的推理,现在请使用可用的工具来完成任务。执行具体行动。",
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
// ====================================================================
|
// ====================================================================
|
||||||
@@ -79,7 +114,7 @@ func (e *AgentEngine) Run(ctx context.Context, userPrompt string) error {
|
|||||||
// ====================================================================
|
// ====================================================================
|
||||||
log.Println("[Engine][Phase 2] 恢复工具挂载,等待模型采取行动...")
|
log.Println("[Engine][Phase 2] 恢复工具挂载,等待模型采取行动...")
|
||||||
|
|
||||||
// 此时的 contextHistory 中已经包含了上一阶段模型自己的 Thinking Trace。
|
// 此时的 contextHistory 中已经包含了上一阶段模型自己的 Thinking Trace + 过渡指令。
|
||||||
// 模型会顺着自己的逻辑,结合恢复的 availableTools 发起精准的工具调用。
|
// 模型会顺着自己的逻辑,结合恢复的 availableTools 发起精准的工具调用。
|
||||||
actionResp, err := e.provider.Generate(ctx, contextHistory, availableTools)
|
actionResp, err := e.provider.Generate(ctx, contextHistory, availableTools)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|||||||
@@ -0,0 +1,144 @@
|
|||||||
|
// internal/provider/claude.go
|
||||||
|
package provider
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
// "os"
|
||||||
|
|
||||||
|
"github.com/anthropics/anthropic-sdk-go"
|
||||||
|
"github.com/anthropics/anthropic-sdk-go/option"
|
||||||
|
"go-tiny-claw/internal/schema"
|
||||||
|
)
|
||||||
|
|
||||||
|
type ClaudeProvider struct {
|
||||||
|
client anthropic.Client
|
||||||
|
model string
|
||||||
|
}
|
||||||
|
|
||||||
|
func DeepseekClaudeProvider(model string) *ClaudeProvider {
|
||||||
|
apiKey := "sk-1f44696abe644bd684f09cc43f12c557"
|
||||||
|
if apiKey == "" {
|
||||||
|
panic("请设置 ZHIPU_API_KEY 环境变量")
|
||||||
|
}
|
||||||
|
baseURL := "https://api.deepseek.com/anthropic"
|
||||||
|
return &ClaudeProvider{
|
||||||
|
client: anthropic.NewClient(option.WithAPIKey(apiKey), option.WithBaseURL(baseURL)),
|
||||||
|
model: model,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *ClaudeProvider) Generate(ctx context.Context, msgs []schema.Message, availableTools []schema.ToolDefinition) (*schema.Message, error) {
|
||||||
|
var anthropicMsgs []anthropic.MessageParam
|
||||||
|
var systemPrompt string
|
||||||
|
|
||||||
|
// 1. 消息翻译
|
||||||
|
for _, msg := range msgs {
|
||||||
|
switch msg.Role {
|
||||||
|
case schema.RoleSystem:
|
||||||
|
systemPrompt = msg.Content
|
||||||
|
case schema.RoleUser:
|
||||||
|
if msg.ToolCallID != "" {
|
||||||
|
anthropicMsgs = append(anthropicMsgs, anthropic.NewUserMessage(
|
||||||
|
anthropic.NewToolResultBlock(msg.ToolCallID, msg.Content, false),
|
||||||
|
))
|
||||||
|
} else {
|
||||||
|
anthropicMsgs = append(anthropicMsgs, anthropic.NewUserMessage(
|
||||||
|
anthropic.NewTextBlock(msg.Content),
|
||||||
|
))
|
||||||
|
}
|
||||||
|
case schema.RoleAssistant:
|
||||||
|
var blocks []anthropic.ContentBlockParamUnion
|
||||||
|
if msg.Content != "" {
|
||||||
|
blocks = append(blocks, anthropic.NewTextBlock(msg.Content))
|
||||||
|
}
|
||||||
|
|
||||||
|
// 将历史工具调用转回 Claude 特有的 ToolUseBlockParam
|
||||||
|
for _, tc := range msg.ToolCalls {
|
||||||
|
var inputMap map[string]interface{}
|
||||||
|
_ = json.Unmarshal(tc.Arguments, &inputMap)
|
||||||
|
blocks = append(blocks, anthropic.ContentBlockParamUnion{
|
||||||
|
OfToolUse: &anthropic.ToolUseBlockParam{
|
||||||
|
ID: tc.ID,
|
||||||
|
Name: tc.Name,
|
||||||
|
Input: inputMap,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
if len(blocks) > 0 {
|
||||||
|
anthropicMsgs = append(anthropicMsgs, anthropic.NewAssistantMessage(blocks...))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. 工具 Schema 翻译
|
||||||
|
var anthropicTools []anthropic.ToolUnionParam
|
||||||
|
for _, toolDef := range availableTools {
|
||||||
|
// ToolInputSchemaParam 是结构体,需要通过 Properties 字段精准填充
|
||||||
|
var properties map[string]any
|
||||||
|
var required []string
|
||||||
|
|
||||||
|
if m, ok := toolDef.InputSchema.(map[string]interface{}); ok {
|
||||||
|
if p, ok := m["properties"].(map[string]interface{}); ok {
|
||||||
|
properties = p
|
||||||
|
}
|
||||||
|
if r, ok := m["required"].([]string); ok {
|
||||||
|
required = r
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
tp := anthropic.ToolParam{
|
||||||
|
Name: toolDef.Name,
|
||||||
|
Description: anthropic.String(toolDef.Description),
|
||||||
|
InputSchema: anthropic.ToolInputSchemaParam{
|
||||||
|
Properties: properties,
|
||||||
|
Required: required,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
anthropicTools = append(anthropicTools, anthropic.ToolUnionParam{OfTool: &tp})
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3. 构建请求并发送
|
||||||
|
params := anthropic.MessageNewParams{
|
||||||
|
Model: anthropic.Model(p.model),
|
||||||
|
MaxTokens: 4096,
|
||||||
|
Messages: anthropicMsgs,
|
||||||
|
}
|
||||||
|
|
||||||
|
if systemPrompt != "" {
|
||||||
|
params.System = []anthropic.TextBlockParam{
|
||||||
|
{Text: systemPrompt},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(anthropicTools) > 0 {
|
||||||
|
params.Tools = anthropicTools
|
||||||
|
}
|
||||||
|
|
||||||
|
resp, err := p.client.Messages.New(ctx, params)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("Claude/Zhipu API 请求失败: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 4. 反向解析
|
||||||
|
resultMsg := &schema.Message{
|
||||||
|
Role: schema.RoleAssistant,
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, block := range resp.Content {
|
||||||
|
switch block.Type {
|
||||||
|
case "text":
|
||||||
|
resultMsg.Content += block.Text
|
||||||
|
case "tool_use":
|
||||||
|
argsBytes, _ := json.Marshal(block.Input)
|
||||||
|
resultMsg.ToolCalls = append(resultMsg.ToolCalls, schema.ToolCall{
|
||||||
|
ID: block.ID,
|
||||||
|
Name: block.Name,
|
||||||
|
Arguments: argsBytes,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return resultMsg, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,193 @@
|
|||||||
|
// internal/provider/openai.go
|
||||||
|
package provider
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
// "os"
|
||||||
|
|
||||||
|
"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"
|
||||||
|
)
|
||||||
|
|
||||||
|
type OpenAIProvider struct {
|
||||||
|
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"
|
||||||
|
|
||||||
|
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
|
||||||
|
|
||||||
|
// 1. 翻译上下文消息
|
||||||
|
for _, msg := range msgs {
|
||||||
|
switch msg.Role {
|
||||||
|
case schema.RoleSystem:
|
||||||
|
openaiMsgs = append(openaiMsgs, openai.SystemMessage(msg.Content))
|
||||||
|
|
||||||
|
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))
|
||||||
|
}
|
||||||
|
|
||||||
|
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
|
||||||
|
}
|
||||||
|
|
||||||
|
astParam := openai.ChatCompletionAssistantMessageParam{}
|
||||||
|
|
||||||
|
if msg.Content != "" {
|
||||||
|
astParam.Content = openai.ChatCompletionAssistantMessageParamContentUnion{
|
||||||
|
OfString: openai.String(msg.Content),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 【重要】如果历史包含 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
|
||||||
|
}
|
||||||
|
|
||||||
|
openaiMsgs = append(openaiMsgs, openai.ChatCompletionMessageParamUnion{
|
||||||
|
OfAssistant: &astParam,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. 翻译工具定义 (v3 新 API 特性适配)
|
||||||
|
var openaiTools []openai.ChatCompletionToolUnionParam
|
||||||
|
for _, toolDef := range availableTools {
|
||||||
|
var params shared.FunctionParameters
|
||||||
|
|
||||||
|
// 尝试直接断言,如果不成功则通过 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)
|
||||||
|
}
|
||||||
|
|
||||||
|
openaiTools = append(openaiTools, openai.ChatCompletionFunctionTool(
|
||||||
|
shared.FunctionDefinitionParam{
|
||||||
|
Name: toolDef.Name,
|
||||||
|
Description: openai.String(toolDef.Description),
|
||||||
|
Parameters: params,
|
||||||
|
},
|
||||||
|
))
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3. 构建请求并发送
|
||||||
|
params := openai.ChatCompletionNewParams{
|
||||||
|
Model: p.model,
|
||||||
|
Messages: openaiMsgs,
|
||||||
|
}
|
||||||
|
|
||||||
|
// 【慢思考机制支撑】仅当 availableTools 存在时才挂载 Tools
|
||||||
|
if len(openaiTools) > 0 {
|
||||||
|
params.Tools = openaiTools
|
||||||
|
}
|
||||||
|
|
||||||
|
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")
|
||||||
|
}
|
||||||
|
|
||||||
|
// 4. 将 API Response 反向翻译为内部 schema.Message
|
||||||
|
choice := resp.Choices[0].Message
|
||||||
|
resultMsg := &schema.Message{
|
||||||
|
Role: schema.RoleAssistant,
|
||||||
|
Content: choice.Content,
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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 字符串字节
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return resultMsg, nil
|
||||||
|
}
|
||||||
@@ -16,6 +16,9 @@ type Message struct {
|
|||||||
Role Role `json:"role"`
|
Role Role `json:"role"`
|
||||||
Content string `json:"content"` // 存放纯文本内容
|
Content string `json:"content"` // 存放纯文本内容
|
||||||
|
|
||||||
|
// ReasoningContent Deepseek thinking 模式的内部推理链,回传时必须保留
|
||||||
|
ReasoningContent string `json:"reasoning_content,omitempty"`
|
||||||
|
|
||||||
// 如果模型决定调用工具,此字段将被填充 (支持并行调用多个工具)
|
// 如果模型决定调用工具,此字段将被填充 (支持并行调用多个工具)
|
||||||
ToolCalls []ToolCall `json:"tool_calls,omitempty"`
|
ToolCalls []ToolCall `json:"tool_calls,omitempty"`
|
||||||
|
|
||||||
|
|||||||
@@ -50,7 +50,7 @@ func main() {
|
|||||||
p := &mockProvider{}
|
p := &mockProvider{}
|
||||||
r := &mockRegistry{}
|
r := &mockRegistry{}
|
||||||
|
|
||||||
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 {
|
||||||
|
|||||||
Reference in New Issue
Block a user