| 63 | } |
| 64 | |
| 65 | func (t *UpdateWorkingMemoryTool) Execute(ctx context.Context, input map[string]any, tc *tools.ToolContext) (any, error) { |
| 66 | // 从 input 中获取 memory 内容 |
| 67 | memoryContent, ok := input["memory"].(string) |
| 68 | if !ok { |
| 69 | return map[string]any{ |
| 70 | "success": false, |
| 71 | "error": "memory field is required and must be a string", |
| 72 | }, nil |
| 73 | } |
| 74 | |
| 75 | // 从 ToolContext 获取 threadID 和 resourceID |
| 76 | threadID := tc.ThreadID |
| 77 | resourceID := tc.ResourceID |
| 78 | |
| 79 | if threadID == "" && resourceID == "" { |
| 80 | return map[string]any{ |
| 81 | "success": false, |
| 82 | "error": "threadID and resourceID cannot both be empty. Please ensure they are set in the context.", |
| 83 | }, nil |
| 84 | } |
| 85 | |
| 86 | // 如果配置了 Schema,尝试美化 JSON 格式 |
| 87 | if t.schema != nil && t.schema.Type == "object" { |
| 88 | // 尝试解析并重新格式化 |
| 89 | var data any |
| 90 | if err := json.Unmarshal([]byte(memoryContent), &data); err == nil { |
| 91 | formatted, err := json.MarshalIndent(data, "", " ") |
| 92 | if err == nil { |
| 93 | memoryContent = string(formatted) |
| 94 | } |
| 95 | } |
| 96 | } |
| 97 | |
| 98 | // 更新 Working Memory |
| 99 | if err := t.manager.Update(ctx, threadID, resourceID, memoryContent); err != nil { |
| 100 | return map[string]any{ |
| 101 | "success": false, |
| 102 | "error": fmt.Sprintf("failed to update working memory: %v", err), |
| 103 | }, nil |
| 104 | } |
| 105 | |
| 106 | return map[string]any{ |
| 107 | "success": true, |
| 108 | "thread_id": threadID, |
| 109 | "resource_id": resourceID, |
| 110 | "scope": string(t.manager.GetScope()), |
| 111 | }, nil |
| 112 | } |
| 113 | |
| 114 | func (t *UpdateWorkingMemoryTool) Prompt() string { |
| 115 | prompt := `Update your working memory to track important information across the conversation. |