-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmemory_integration.go
More file actions
434 lines (368 loc) · 12.1 KB
/
memory_integration.go
File metadata and controls
434 lines (368 loc) · 12.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
package sdk
import (
"context"
"encoding/json"
"fmt"
"time"
)
// StoreReasoningTrace stores a ReAct reasoning trace in episodic memory.
func StoreReasoningTrace(ctx context.Context, mm *MemoryManager, trace ReasoningTrace, agentID, executionID string) error {
if mm == nil {
return nil // No memory manager, skip storage
}
// Serialize trace to JSON for storage
traceJSON, err := json.Marshal(trace)
if err != nil {
return fmt.Errorf("failed to serialize reasoning trace: %w", err)
}
// Create content string with key information
content := fmt.Sprintf("Reasoning Step %d: %s | Action: %s | Observation: %s | Reflection: %s",
trace.Step, trace.Thought, trace.Action, trace.Observation, trace.Reflection)
// Store with metadata
metadata := map[string]any{
"type": "reasoning_trace",
"agent_id": agentID,
"execution_id": executionID,
"step": trace.Step,
"action": trace.Action,
"confidence": trace.Confidence,
"timestamp": trace.Timestamp,
"trace_json": string(traceJSON),
}
_, err = mm.Store(ctx, content, metadata, trace.Confidence)
return err
}
// StorePlan stores a plan in episodic memory.
func StorePlan(ctx context.Context, mm *MemoryManager, plan *Plan) error {
if mm == nil {
return nil // No memory manager, skip storage
}
// Serialize plan to JSON
planJSON, err := json.Marshal(plan)
if err != nil {
return fmt.Errorf("failed to serialize plan: %w", err)
}
// Create content string with plan summary
content := fmt.Sprintf("Plan %s: %s | Steps: %d | Status: %s",
plan.ID, plan.Goal, len(plan.Steps), plan.Status)
// Calculate importance based on plan status and complexity
importance := 0.5
switch plan.Status {
case PlanStatusCompleted:
importance = 0.8
case PlanStatusFailed:
importance = 0.6 // Failed plans are important for learning
}
importance += float64(len(plan.Steps)) * 0.02 // More complex plans are more important
if importance > 1.0 {
importance = 1.0
}
// Store with metadata
metadata := map[string]any{
"type": "plan",
"agent_id": plan.AgentID,
"plan_id": plan.ID,
"goal": plan.Goal,
"status": string(plan.Status),
"steps": len(plan.Steps),
"version": plan.Version,
"created_at": plan.CreatedAt,
"updated_at": plan.UpdatedAt,
"plan_json": string(planJSON),
}
_, err = mm.Store(ctx, content, metadata, importance)
return err
}
// StorePlanStep stores a single plan step in memory.
func StorePlanStep(ctx context.Context, mm *MemoryManager, step *PlanStep, planID, agentID string) error {
if mm == nil {
return nil
}
// Create content string
content := fmt.Sprintf("Plan Step %d: %s | Status: %s | Result: %v",
step.Index, step.Description, step.Status, step.Result)
// Calculate importance
importance := 0.5
switch step.Status {
case PlanStepStatusCompleted:
importance = 0.7
case PlanStepStatusFailed:
importance = 0.8 // Failed steps are important for learning
}
if step.Verification != nil {
importance = (importance + step.Verification.Score) / 2
}
// Store with metadata
metadata := map[string]any{
"type": "plan_step",
"agent_id": agentID,
"plan_id": planID,
"step_id": step.ID,
"step_index": step.Index,
"description": step.Description,
"status": string(step.Status),
"tools_used": step.ToolsNeeded,
}
// Add duration if available
if !step.StartTime.IsZero() && !step.EndTime.IsZero() {
metadata["duration"] = step.EndTime.Sub(step.StartTime).Seconds()
}
if step.Error != "" {
metadata["error"] = step.Error
}
_, err := mm.Store(ctx, content, metadata, importance)
return err
}
// RecallSimilarTraces retrieves reasoning traces similar to the given query.
func RecallSimilarTraces(ctx context.Context, mm *MemoryManager, query string, limit int) ([]ReasoningTrace, error) {
if mm == nil {
return nil, nil
}
// Recall memories with type filter
memories, err := mm.Recall(ctx, query, MemoryTierEpisodic, limit)
if err != nil {
return nil, fmt.Errorf("failed to recall traces: %w", err)
}
traces := make([]ReasoningTrace, 0, len(memories))
for _, mem := range memories {
// Check if this is a reasoning trace
if memType, ok := mem.Metadata["type"].(string); ok && memType == "reasoning_trace" {
// Try to deserialize from stored JSON
if traceJSON, ok := mem.Metadata["trace_json"].(string); ok {
var trace ReasoningTrace
if err := json.Unmarshal([]byte(traceJSON), &trace); err == nil {
traces = append(traces, trace)
}
}
}
}
return traces, nil
}
// RecallSimilarPlans retrieves plans similar to the given query.
func RecallSimilarPlans(ctx context.Context, mm *MemoryManager, query string, limit int) ([]*Plan, error) {
if mm == nil {
return nil, nil
}
// Recall memories with type filter
memories, err := mm.Recall(ctx, query, MemoryTierEpisodic, limit)
if err != nil {
return nil, fmt.Errorf("failed to recall plans: %w", err)
}
plans := make([]*Plan, 0, len(memories))
for _, mem := range memories {
// Check if this is a plan
if memType, ok := mem.Metadata["type"].(string); ok && memType == "plan" {
// Try to deserialize from stored JSON
if planJSON, ok := mem.Metadata["plan_json"].(string); ok {
var plan Plan
if err := json.Unmarshal([]byte(planJSON), &plan); err == nil {
plans = append(plans, &plan)
}
}
}
}
return plans, nil
}
// RecallRecentTraces retrieves the most recent reasoning traces.
func RecallRecentTraces(ctx context.Context, mm *MemoryManager, agentID string, limit int) ([]ReasoningTrace, error) {
if mm == nil {
return nil, nil
}
// Get all memories for this agent
memories, err := mm.Recall(ctx, fmt.Sprintf("agent:%s reasoning", agentID), MemoryTierEpisodic, limit*2)
if err != nil {
return nil, fmt.Errorf("failed to recall recent traces: %w", err)
}
traces := make([]ReasoningTrace, 0, limit)
for _, mem := range memories {
if memType, ok := mem.Metadata["type"].(string); ok && memType == "reasoning_trace" {
if traceJSON, ok := mem.Metadata["trace_json"].(string); ok {
var trace ReasoningTrace
if err := json.Unmarshal([]byte(traceJSON), &trace); err == nil {
traces = append(traces, trace)
if len(traces) >= limit {
break
}
}
}
}
}
return traces, nil
}
// RecallRecentPlans retrieves the most recent plans for an agent.
func RecallRecentPlans(ctx context.Context, mm *MemoryManager, agentID string, limit int) ([]*Plan, error) {
if mm == nil {
return nil, nil
}
// Get all memories for this agent
memories, err := mm.Recall(ctx, fmt.Sprintf("agent:%s plan", agentID), MemoryTierEpisodic, limit*2)
if err != nil {
return nil, fmt.Errorf("failed to recall recent plans: %w", err)
}
plans := make([]*Plan, 0, limit)
for _, mem := range memories {
if memType, ok := mem.Metadata["type"].(string); ok && memType == "plan" {
if planJSON, ok := mem.Metadata["plan_json"].(string); ok {
var plan Plan
if err := json.Unmarshal([]byte(planJSON), &plan); err == nil {
plans = append(plans, &plan)
if len(plans) >= limit {
break
}
}
}
}
}
return plans, nil
}
// RecallSuccessfulPlans retrieves completed plans similar to the query.
func RecallSuccessfulPlans(ctx context.Context, mm *MemoryManager, query string, limit int) ([]*Plan, error) {
plans, err := RecallSimilarPlans(ctx, mm, query, limit*2)
if err != nil {
return nil, err
}
// Filter for successful plans
successful := make([]*Plan, 0, limit)
for _, plan := range plans {
if plan.Status == PlanStatusCompleted {
successful = append(successful, plan)
if len(successful) >= limit {
break
}
}
}
return successful, nil
}
// RecallFailedPlans retrieves failed plans to learn from mistakes.
func RecallFailedPlans(ctx context.Context, mm *MemoryManager, query string, limit int) ([]*Plan, error) {
plans, err := RecallSimilarPlans(ctx, mm, query, limit*2)
if err != nil {
return nil, err
}
// Filter for failed plans
failed := make([]*Plan, 0, limit)
for _, plan := range plans {
if plan.Status == PlanStatusFailed {
failed = append(failed, plan)
if len(failed) >= limit {
break
}
}
}
return failed, nil
}
// StoreReflection stores a reflection result in memory.
func StoreReflection(ctx context.Context, mm *MemoryManager, reflection ReflectionResult, agentID, executionID string, stepIndex int) error {
if mm == nil {
return nil
}
// Calculate importance from quality
importance := 0.5
switch reflection.Quality {
case "good":
importance = 0.7
case "needs_improvement":
importance = 0.8 // Important to learn from
case "invalid":
importance = 0.9 // Very important to avoid repeating
}
// Create content string
content := fmt.Sprintf("Reflection on Step %d: Quality=%s | Issues: %v | Suggestions: %v",
stepIndex, reflection.Quality, reflection.Issues, reflection.Suggestions)
// Store with metadata
metadata := map[string]any{
"type": "reflection",
"agent_id": agentID,
"execution_id": executionID,
"step_index": stepIndex,
"quality": reflection.Quality,
"should_replan": reflection.ShouldReplan,
"timestamp": time.Now(),
}
_, err := mm.Store(ctx, content, metadata, importance)
return err
}
// RecallReflections retrieves reflection results for analysis.
func RecallReflections(ctx context.Context, mm *MemoryManager, agentID string, limit int) ([]ReflectionResult, error) {
if mm == nil {
return nil, nil
}
memories, err := mm.Recall(ctx, fmt.Sprintf("agent:%s reflection", agentID), MemoryTierEpisodic, limit)
if err != nil {
return nil, fmt.Errorf("failed to recall reflections: %w", err)
}
reflections := make([]ReflectionResult, 0, len(memories))
for _, mem := range memories {
if memType, ok := mem.Metadata["type"].(string); ok && memType == "reflection" {
reflection := ReflectionResult{}
if quality, ok := mem.Metadata["quality"].(string); ok {
reflection.Quality = quality
}
if shouldReplan, ok := mem.Metadata["should_replan"].(bool); ok {
reflection.ShouldReplan = shouldReplan
}
reflections = append(reflections, reflection)
}
}
return reflections, nil
}
// CreateEpisodicMemory creates an episodic memory for an agent execution.
func CreateEpisodicMemory(ctx context.Context, mm *MemoryManager, execution *AgentExecution, title string) error {
if mm == nil {
return nil
}
// Collect all memory IDs from this execution
memoryIDs := make([]string, 0)
// Store each step as a memory and collect IDs
for _, step := range execution.Steps {
content := fmt.Sprintf("Step %d: %s -> %s", step.Index, step.Input, step.Output)
metadata := map[string]any{
"type": "execution_step",
"agent_id": execution.AgentID,
"execution_id": execution.ID,
"step_index": step.Index,
"state": string(step.State),
}
entry, err := mm.Store(ctx, content, metadata, 0.6)
if err == nil && entry != nil {
memoryIDs = append(memoryIDs, entry.ID)
}
}
// Store episodic memory as a high-level memory entry
episodeContent := fmt.Sprintf("Execution Episode: %s | Steps: %d | Status: %s | Output: %s",
title, len(execution.Steps), execution.Status, execution.FinalOutput)
episodeMetadata := map[string]any{
"type": "episode",
"agent_id": execution.AgentID,
"execution_id": execution.ID,
"title": title,
"status": string(execution.Status),
"step_count": len(execution.Steps),
"memory_ids": memoryIDs,
"timestamp": execution.StartTime,
"duration": execution.EndTime.Sub(execution.StartTime).Seconds(),
}
_, err := mm.Store(ctx, episodeContent, episodeMetadata, 0.7)
return err
}
// GetExecutionContext retrieves relevant context for an execution from memory.
func GetExecutionContext(ctx context.Context, mm *MemoryManager, query string, agentID string) (string, error) {
if mm == nil {
return "", nil
}
// Recall relevant memories
memories, err := mm.Recall(ctx, query, MemoryTierEpisodic, 5)
if err != nil {
return "", err
}
if len(memories) == 0 {
return "", nil
}
// Build context string
var contextBuilder string
contextBuilder += "Relevant past experiences:\n"
for i, mem := range memories {
contextBuilder += fmt.Sprintf("%d. %s (importance: %.2f)\n", i+1, mem.Content, mem.Importance)
}
return contextBuilder, nil
}