-
Notifications
You must be signed in to change notification settings - Fork 2
/
memory_context.go
425 lines (376 loc) · 12.9 KB
/
memory_context.go
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
// Package raggo provides advanced context-aware retrieval and memory management
// capabilities for RAG (Retrieval-Augmented Generation) systems.
package raggo
import (
"context"
"fmt"
"strings"
"time"
"github.com/teilomillet/gollm"
)
// MemoryContextOptions configures the behavior of the contextual memory system.
// It provides fine-grained control over memory storage, retrieval, and relevance
// assessment through a set of configurable parameters.
type MemoryContextOptions struct {
// TopK determines how many relevant memories to retrieve for context
// Higher values provide more context but may introduce noise
TopK int
// MinScore sets the minimum similarity threshold for memory retrieval
// Higher values ensure more relevant but fewer memories
MinScore float64
// Collection specifies the vector database collection for storing memories
Collection string
// DBType specifies the vector database type (e.g., "chromem", "milvus")
DBType string
// DBAddress specifies the vector database address (e.g., "./.chromem/name" or "localhost:19530")
DBAddress string
// IncludeScore determines whether to include relevance scores in results
IncludeScore bool
// StoreLastN limits memory storage to the N most recent interactions
// Use 0 for unlimited storage
StoreLastN int
// StoreRAGInfo enables storage of RAG-enhanced context information
// This provides richer context by storing processed and enhanced memories
StoreRAGInfo bool
}
// MemoryContext provides intelligent context management for RAG systems by:
// - Storing and retrieving relevant past interactions
// - Enriching queries with historical context
// - Managing memory lifecycle and relevance
//
// It integrates with vector databases for efficient similarity search and
// supports configurable memory management strategies.
type MemoryContext struct {
retriever *Retriever
options MemoryContextOptions
lastStoreTime time.Time
lastMemoryLen int
}
// MemoryTopK configures the number of relevant memories to retrieve.
// Higher values provide more comprehensive context but may impact performance.
//
// Example:
//
// ctx, err := raggo.NewMemoryContext(apiKey,
// raggo.MemoryTopK(5), // Retrieve top 5 relevant memories
// )
func MemoryTopK(k int) func(*MemoryContextOptions) {
return func(o *MemoryContextOptions) {
o.TopK = k
}
}
// MemoryMinScore sets the similarity threshold for memory retrieval.
// Memories with scores below this threshold are considered irrelevant.
//
// Example:
//
// ctx, err := raggo.NewMemoryContext(apiKey,
// raggo.MemoryMinScore(0.7), // Only retrieve highly similar memories
// )
func MemoryMinScore(score float64) func(*MemoryContextOptions) {
return func(o *MemoryContextOptions) {
o.MinScore = score
}
}
// MemoryCollection specifies the vector database collection for storing memories.
// Different collections can be used to separate contexts for different use cases.
//
// Example:
//
// ctx, err := raggo.NewMemoryContext(apiKey,
// raggo.MemoryCollection("support_chat"), // Store support chat memories
// )
func MemoryCollection(collection string) func(*MemoryContextOptions) {
return func(o *MemoryContextOptions) {
o.Collection = collection
}
}
// MemoryVectorDB configures the vector database type and address.
// This allows choosing between different vector store implementations and their locations.
//
// Example:
//
// ctx, err := raggo.NewMemoryContext(apiKey,
// raggo.MemoryVectorDB("chromem", "./.chromem/chat"), // Use Chromem store
// )
func MemoryVectorDB(dbType, address string) func(*MemoryContextOptions) {
return func(o *MemoryContextOptions) {
o.DBType = dbType
o.DBAddress = address
}
}
// MemoryScoreInclusion controls whether similarity scores are included in results.
// Useful for debugging or implementing custom relevance filtering.
//
// Example:
//
// ctx, err := raggo.NewMemoryContext(apiKey,
// raggo.MemoryScoreInclusion(true), // Include similarity scores
// )
func MemoryScoreInclusion(include bool) func(*MemoryContextOptions) {
return func(o *MemoryContextOptions) {
o.IncludeScore = include
}
}
// MemoryStoreLastN limits memory storage to the N most recent interactions.
// This helps manage memory usage and maintain relevant context windows.
//
// Example:
//
// ctx, err := raggo.NewMemoryContext(apiKey,
// raggo.MemoryStoreLastN(100), // Keep last 100 interactions
// )
func MemoryStoreLastN(n int) func(*MemoryContextOptions) {
return func(o *MemoryContextOptions) {
o.StoreLastN = n
}
}
// MemoryStoreRAGInfo enables storage of RAG-enhanced context information.
// This provides richer context by storing processed and enhanced memories.
//
// Example:
//
// ctx, err := raggo.NewMemoryContext(apiKey,
// raggo.MemoryStoreRAGInfo(true), // Store enhanced context
// )
func MemoryStoreRAGInfo(store bool) func(*MemoryContextOptions) {
return func(o *MemoryContextOptions) {
o.StoreRAGInfo = store
}
}
// NewMemoryContext creates a new memory context manager with the specified options.
// It initializes the underlying vector store and configures memory management.
//
// The function supports multiple configuration options through functional parameters:
// - TopK: Number of relevant memories to retrieve
// - MinScore: Similarity threshold for relevance
// - Collection: Vector store collection name
// - StoreLastN: Recent memory retention limit
// - StoreRAGInfo: Enhanced context storage
//
// Example:
//
// ctx, err := raggo.NewMemoryContext(apiKey,
// raggo.MemoryTopK(5),
// raggo.MemoryMinScore(0.7),
// raggo.MemoryCollection("chat_memory"),
// raggo.MemoryStoreLastN(100),
// raggo.MemoryStoreRAGInfo(true),
// )
// if err != nil {
// log.Fatal(err)
// }
// defer ctx.Close()
func NewMemoryContext(apiKey string, opts ...func(*MemoryContextOptions)) (*MemoryContext, error) {
// Default options
options := MemoryContextOptions{
TopK: 3,
MinScore: 0.7,
Collection: "memory_store",
DBType: "milvus", // Default to Milvus
DBAddress: "localhost:19530", // Default Milvus address
IncludeScore: false,
StoreLastN: 0,
StoreRAGInfo: false,
}
// Apply custom options
for _, opt := range opts {
opt(&options)
}
// Initialize retriever with config
retriever, err := NewRetriever(
WithRetrieveCollection(options.Collection),
WithTopK(options.TopK),
WithMinScore(options.MinScore),
WithRetrieveEmbedding("openai", "text-embedding-3-small", apiKey),
WithRetrieveDB(options.DBType, options.DBAddress),
)
if err != nil {
return nil, fmt.Errorf("failed to initialize retriever: %w", err)
}
// Ensure collection exists with proper schema
ctx := context.Background()
db := retriever.GetVectorDB()
exists, err := db.HasCollection(ctx, options.Collection)
if err != nil {
return nil, fmt.Errorf("failed to check collection: %w", err)
}
if !exists {
// Create collection with proper schema
schema := Schema{
Name: options.Collection,
Description: "Memory context collection for RAG",
Fields: []Field{
{Name: "ID", DataType: "int64", PrimaryKey: true, AutoID: true},
{Name: "Embedding", DataType: "float_vector", Dimension: 1536}, // text-embedding-3-small dimension
{Name: "Text", DataType: "varchar", MaxLength: 65535},
{Name: "Metadata", DataType: "varchar", MaxLength: 65535},
},
}
if err := db.CreateCollection(ctx, options.Collection, schema); err != nil {
return nil, fmt.Errorf("failed to create collection: %w", err)
}
// Create index for vector search
index := Index{
Type: "HNSW",
Metric: "COSINE",
Parameters: map[string]interface{}{
"M": 16,
"efConstruction": 256,
},
}
if err := db.CreateIndex(ctx, options.Collection, "Embedding", index); err != nil {
return nil, fmt.Errorf("failed to create index: %w", err)
}
if err := db.LoadCollection(ctx, options.Collection); err != nil {
return nil, fmt.Errorf("failed to load collection: %w", err)
}
}
return &MemoryContext{
retriever: retriever,
options: options,
lastStoreTime: time.Time{},
lastMemoryLen: 0,
}, nil
}
// shouldStore determines whether to store the given memory based on configured rules.
// It checks:
// - StoreLastN limits
// - Time-based storage policies
// - Memory content validity
func (m *MemoryContext) shouldStore(memory []gollm.MemoryMessage) bool {
newLen := len(memory)
timeSinceLastStore := time.Since(m.lastStoreTime)
messagesDiff := newLen - m.lastMemoryLen
return messagesDiff >= m.options.StoreLastN/2 ||
timeSinceLastStore > 5*time.Minute
}
// StoreMemory explicitly stores messages in the memory context.
// It processes and indexes the messages for later retrieval.
//
// Example:
//
// err := ctx.StoreMemory(context.Background(), []gollm.MemoryMessage{
// {Role: "user", Content: "How does feature X work?"},
// {Role: "assistant", Content: "Feature X works by..."},
// })
func (m *MemoryContext) StoreMemory(ctx context.Context, messages []gollm.MemoryMessage) error {
if len(messages) == 0 {
return nil
}
var memoryContent string
for _, msg := range messages {
memoryContent += fmt.Sprintf("%s: %s\n", msg.Role, msg.Content)
}
// TODO: Implement document storage through the vector store
// For now, we'll just store the content through the retriever
_, err := m.retriever.Retrieve(ctx, memoryContent)
if err != nil {
return fmt.Errorf("failed to store memory: %w", err)
}
return nil
}
// StoreLastN stores only the most recent N messages from the memory.
// This helps maintain a sliding window of relevant context.
//
// Example:
//
// err := ctx.StoreLastN(context.Background(), messages, 10) // Keep last 10 messages
func (m *MemoryContext) StoreLastN(ctx context.Context, memory []gollm.MemoryMessage, n int) error {
if !m.shouldStore(memory) {
return nil
}
start := len(memory) - n
if start < 0 {
start = 0
}
err := m.StoreMemory(ctx, memory[start:])
if err == nil {
m.lastStoreTime = time.Now()
m.lastMemoryLen = len(memory)
}
return err
}
// EnhancePrompt enriches a prompt with relevant context from memory.
// It retrieves and integrates past interactions to provide better context.
//
// Example:
//
// enhanced, err := ctx.EnhancePrompt(context.Background(), prompt, messages)
func (m *MemoryContext) EnhancePrompt(ctx context.Context, prompt *gollm.Prompt, memory []gollm.MemoryMessage) (*gollm.Prompt, error) {
relevantContext, err := m.retrieveContext(ctx, prompt.Input)
if err != nil {
return prompt, fmt.Errorf("failed to retrieve context: %w", err)
}
enhancedPrompt := gollm.NewPrompt(
prompt.Input,
gollm.WithSystemPrompt(prompt.SystemPrompt, gollm.CacheTypeEphemeral),
gollm.WithContext(strings.Join(relevantContext, "\n")),
)
if m.options.StoreRAGInfo && len(relevantContext) > 0 {
contextMsg := gollm.MemoryMessage{
Role: "system",
Content: "Retrieved Context:\n" + strings.Join(relevantContext, "\n"),
}
memory = append(memory, contextMsg)
}
return enhancedPrompt, nil
}
// retrieveContext retrieves relevant context from stored memories.
// It uses vector similarity search to find the most relevant past interactions.
func (m *MemoryContext) retrieveContext(ctx context.Context, input string) ([]string, error) {
results, err := m.retriever.Retrieve(ctx, input)
if err != nil {
return nil, fmt.Errorf("failed to search context: %w", err)
}
var relevantContext []string
for _, result := range results {
if result.Content != "" {
if m.options.IncludeScore {
relevantContext = append(relevantContext, fmt.Sprintf("[Score: %.2f] %s", result.Score, result.Content))
} else {
relevantContext = append(relevantContext, result.Content)
}
}
}
return relevantContext, nil
}
// Close releases resources held by the memory context.
// Always defer Close() after creating a new memory context.
func (m *MemoryContext) Close() error {
return m.retriever.Close()
}
// GetRetriever returns the underlying retriever for advanced configuration.
// This provides access to low-level retrieval settings and operations.
func (m *MemoryContext) GetRetriever() *Retriever {
return m.retriever
}
// GetOptions returns the current context options configuration.
// Useful for inspecting or copying the current settings.
func (m *MemoryContext) GetOptions() MemoryContextOptions {
return m.options
}
// UpdateOptions allows updating context options at runtime.
// This enables dynamic reconfiguration of memory management behavior.
//
// Example:
//
// ctx.UpdateOptions(
// raggo.MemoryTopK(10), // Increase context breadth
// raggo.MemoryMinScore(0.8), // Raise relevance threshold
// )
func (m *MemoryContext) UpdateOptions(opts ...func(*MemoryContextOptions)) {
options := m.GetOptions()
for _, opt := range opts {
opt(&options)
}
m.options = options
// Create new retriever with updated config
if retriever, err := NewRetriever(
WithRetrieveCollection(options.Collection),
WithTopK(options.TopK),
WithMinScore(options.MinScore),
); err == nil {
m.retriever = retriever
}
}