WrapModelCall 包装模型调用,注入记忆到 system prompt
(ctx context.Context, req *ModelRequest, handler ModelCallHandler)
| 111 | |
| 112 | // WrapModelCall 包装模型调用,注入记忆到 system prompt |
| 113 | func (m *AgentMemoryMiddleware) WrapModelCall(ctx context.Context, req *ModelRequest, handler ModelCallHandler) (*ModelResponse, error) { |
| 114 | // 如果还没加载记忆,先加载 |
| 115 | if !m.memoryLoaded { |
| 116 | err := m.OnAgentStart(ctx, "default") |
| 117 | if err != nil { |
| 118 | amLog.Error(ctx, "failed to load memory", map[string]any{"error": err.Error()}) |
| 119 | } |
| 120 | } |
| 121 | |
| 122 | // 保存原始 system prompt |
| 123 | originalSystemPrompt := req.SystemPrompt |
| 124 | |
| 125 | // 构建记忆部分 |
| 126 | memorySection := fmt.Sprintf(m.systemPromptTemplate, m.memoryContent) |
| 127 | |
| 128 | // 注入到 system prompt 开头 |
| 129 | if originalSystemPrompt != "" { |
| 130 | req.SystemPrompt = memorySection + "\n\n" + originalSystemPrompt |
| 131 | } else { |
| 132 | req.SystemPrompt = memorySection |
| 133 | } |
| 134 | |
| 135 | // 追加长期记忆使用文档 |
| 136 | longTermMemoryPrompt := m.buildLongTermMemoryPrompt() |
| 137 | req.SystemPrompt = req.SystemPrompt + "\n\n" + longTermMemoryPrompt |
| 138 | |
| 139 | amLog.Debug(ctx, "injected agent memory", map[string]any{"total_chars": len(req.SystemPrompt)}) |
| 140 | |
| 141 | // 调用处理器 |
| 142 | resp, err := handler(ctx, req) |
| 143 | |
| 144 | // 恢复原始 system prompt,避免在重用请求对象时累积 |
| 145 | req.SystemPrompt = originalSystemPrompt |
| 146 | |
| 147 | return resp, err |
| 148 | } |
| 149 | |
| 150 | // buildLongTermMemoryPrompt 构建长期记忆使用指南 |
| 151 | func (m *AgentMemoryMiddleware) buildLongTermMemoryPrompt() string { |