WrapModelCall 包装模型调用,注入 Working Memory 到 system prompt
(ctx context.Context, req *ModelRequest, handler ModelCallHandler)
| 89 | |
| 90 | // WrapModelCall 包装模型调用,注入 Working Memory 到 system prompt |
| 91 | func (m *WorkingMemoryMiddleware) WrapModelCall(ctx context.Context, req *ModelRequest, handler ModelCallHandler) (*ModelResponse, error) { |
| 92 | // 从请求元数据中获取 threadID 和 resourceID |
| 93 | // 注意:这些值应该由 Agent 在调用时设置 |
| 94 | var threadID, resourceID string |
| 95 | if req.Metadata != nil { |
| 96 | if tid, ok := req.Metadata["thread_id"].(string); ok { |
| 97 | threadID = tid |
| 98 | } |
| 99 | if rid, ok := req.Metadata["resource_id"].(string); ok { |
| 100 | resourceID = rid |
| 101 | } |
| 102 | } |
| 103 | |
| 104 | // 如果没有 threadID 或 resourceID,使用默认值 |
| 105 | if threadID == "" && resourceID == "" { |
| 106 | // 可以根据 AgentID 生成默认的 threadID |
| 107 | if req.Metadata != nil { |
| 108 | if agentID, ok := req.Metadata["agent_id"].(string); ok && agentID != "" { |
| 109 | threadID = agentID |
| 110 | } |
| 111 | } |
| 112 | if threadID == "" { |
| 113 | threadID = "default" |
| 114 | } |
| 115 | } |
| 116 | |
| 117 | // 加载 Working Memory |
| 118 | workingMemoryContent, err := m.manager.Get(ctx, threadID, resourceID) |
| 119 | if err != nil { |
| 120 | wmLog.Error(ctx, "failed to load working memory", map[string]any{"error": err.Error()}) |
| 121 | workingMemoryContent = "" |
| 122 | } |
| 123 | |
| 124 | // 保存原始 system prompt |
| 125 | originalSystemPrompt := req.SystemPrompt |
| 126 | |
| 127 | // 构建 Working Memory 部分 |
| 128 | if workingMemoryContent != "" { |
| 129 | memorySection := fmt.Sprintf(m.systemPromptTemplate, workingMemoryContent) |
| 130 | |
| 131 | // 注入到 system prompt 开头 |
| 132 | if originalSystemPrompt != "" { |
| 133 | req.SystemPrompt = memorySection + "\n\n" + originalSystemPrompt |
| 134 | } else { |
| 135 | req.SystemPrompt = memorySection |
| 136 | } |
| 137 | |
| 138 | wmLog.Debug(ctx, "injected working memory", map[string]any{"chars": len(workingMemoryContent), "thread": threadID, "resource": resourceID}) |
| 139 | } else { |
| 140 | wmLog.Debug(ctx, "no working memory found", map[string]any{"thread": threadID, "resource": resourceID}) |
| 141 | } |
| 142 | |
| 143 | // 追加 Working Memory 使用文档 |
| 144 | workingMemoryPrompt := m.buildWorkingMemoryPrompt() |
| 145 | req.SystemPrompt = req.SystemPrompt + "\n\n" + workingMemoryPrompt |
| 146 | |
| 147 | // 调用处理器 |
| 148 | resp, err := handler(ctx, req) |
nothing calls this directly
no test coverage detected