Documentation
¶
Index ¶
- Constants
- type PruningAlgorithm
- type ScoringAlgorithm
- type SelectionAlgorithm
- type Service
- func (s *Service) ExtractAndSaveMemories(ctx context.Context, query string, usedMemories []*memory.AgentMemory, ...) error
- func (s *Service) PruneMemories(ctx context.Context) (int, error)
- func (s *Service) SearchAndSelectMemories(ctx context.Context, query string, limit int) ([]*memory.AgentMemory, error)
- func (s *Service) WithPruningAlgorithm(algo PruningAlgorithm) *Service
- func (s *Service) WithScoringAlgorithm(algo ScoringAlgorithm) *Service
- func (s *Service) WithSelectionAlgorithm(algo SelectionAlgorithm) *Service
Constants ¶
const (
// EmbeddingDimension is the dimension of embedding vectors
EmbeddingDimension = 256
)
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type PruningAlgorithm ¶ added in v0.8.0
type PruningAlgorithm func( memories []*memory.AgentMemory, now time.Time, ) []types.AgentMemoryID
PruningAlgorithm selects memories to be deleted based on score and usage patterns Takes all memories for an agent and current time Returns list of memory IDs that should be deleted
var DefaultPruningAlgorithm PruningAlgorithm = func( memories []*memory.AgentMemory, now time.Time, ) []types.AgentMemoryID { // Algorithm parameters (const within function) const ( criticalThreshold = -8.0 // Critical score threshold for immediate deletion harmfulThreshold = -5.0 // Harmful score threshold harmfulMaxDays = 90 // Max days unused for harmful memories moderateThreshold = -3.0 // Moderate score threshold moderateMaxDays = 180 // Max days unused for moderate memories ) var toDelete []types.AgentMemoryID for _, mem := range memories { shouldDelete := false if mem.Score <= criticalThreshold { shouldDelete = true } if !shouldDelete && mem.Score <= harmfulThreshold { daysSinceUsed := calculateDaysSinceUsed(mem, now) if daysSinceUsed >= harmfulMaxDays { shouldDelete = true } } if !shouldDelete && mem.Score <= moderateThreshold { daysSinceUsed := calculateDaysSinceUsed(mem, now) if daysSinceUsed >= moderateMaxDays { shouldDelete = true } } if shouldDelete { toDelete = append(toDelete, mem.ID) } } return toDelete }
DefaultPruningAlgorithm is the default implementation of pruning algorithm Parameters are defined as constants within the function Uses conservative approach with 3-tier criteria: 1. Critical: Score <= -8.0 (immediate deletion) 2. Harmful + Stale: Score <= -5.0 AND unused for 90+ days 3. Moderate + Very Stale: Score <= -3.0 AND unused for 180+ days
type ScoringAlgorithm ¶ added in v0.8.0
type ScoringAlgorithm func( memories map[types.AgentMemoryID]*memory.AgentMemory, reflection *memory.Reflection, ) map[types.AgentMemoryID]float64
ScoringAlgorithm updates memory scores based on reflection feedback Pure function with no side effects - receives memories and reflection, returns score updates
var DefaultScoringAlgorithm ScoringAlgorithm = func( memories map[types.AgentMemoryID]*memory.AgentMemory, reflection *memory.Reflection, ) map[types.AgentMemoryID]float64 { // Algorithm parameters (const within function) const ( helpfulScoreDelta = 2.0 // positive feedback for helpful memories harmfulScoreDelta = -3.0 // negative feedback for harmful memories emaAlpha = 0.3 // EMA smoothing factor (weight for new feedback) scoreMin = -10.0 // minimum score value scoreMax = 10.0 // maximum score value ) updates := make(map[types.AgentMemoryID]float64) for _, memID := range reflection.HelpfulMemories { if mem, exists := memories[memID]; exists { delta := helpfulScoreDelta newScore := emaAlpha*delta + (1-emaAlpha)*mem.Score newScore = clamp(newScore, scoreMin, scoreMax) updates[memID] = newScore } } for _, memID := range reflection.HarmfulMemories { if mem, exists := memories[memID]; exists { delta := harmfulScoreDelta newScore := emaAlpha*delta + (1-emaAlpha)*mem.Score newScore = clamp(newScore, scoreMin, scoreMax) updates[memID] = newScore } } return updates }
DefaultScoringAlgorithm is the default implementation of scoring algorithm using EMA Algorithm parameters are defined as constants within the function
func NewAggressiveScoringAlgorithm ¶ added in v0.8.0
func NewAggressiveScoringAlgorithm() ScoringAlgorithm
NewAggressiveScoringAlgorithm creates a scoring algorithm with more aggressive feedback Example of how to create custom scoring algorithms with different parameters
type SelectionAlgorithm ¶ added in v0.8.0
type SelectionAlgorithm func( candidates []*memory.AgentMemory, queryEmbedding []float32, limit int, ) []*memory.AgentMemory
SelectionAlgorithm ranks and filters memories for prompt selection Takes candidates retrieved from vector search, query embedding, and desired limit Returns top-ranked memories based on multi-dimensional scoring
var DefaultSelectionAlgorithm SelectionAlgorithm = func( candidates []*memory.AgentMemory, queryEmbedding []float32, limit int, ) []*memory.AgentMemory { // Algorithm parameters (const within function) const ( minQualityScore = -5.0 // Minimum quality score threshold similarityWeight = 0.5 // Weight for similarity score qualityWeight = 0.3 // Weight for quality score recencyWeight = 0.2 // Weight for recency score recencyHalfLifeDays = 30.0 // Half-life for recency decay in days scoreMin = -10.0 scoreMax = 10.0 ) now := time.Now() type rankedMemory struct { memory *memory.AgentMemory finalScore float64 } var ranked []rankedMemory for _, mem := range candidates { if mem.Score < minQualityScore { continue } similarity := calculateCosineSimilarity(queryEmbedding, mem.QueryEmbedding) quality := (mem.Score - scoreMin) / (scoreMax - scoreMin) recency := calculateRecencyScore(mem.LastUsedAt, now, recencyHalfLifeDays) finalScore := similarityWeight*similarity + qualityWeight*quality + recencyWeight*recency ranked = append(ranked, rankedMemory{ memory: mem, finalScore: finalScore, }) } sort.Slice(ranked, func(i, j int) bool { return ranked[i].finalScore > ranked[j].finalScore }) resultSize := limit if len(ranked) < resultSize { resultSize = len(ranked) } results := make([]*memory.AgentMemory, resultSize) for i := 0; i < resultSize; i++ { results[i] = ranked[i].memory } return results }
DefaultSelectionAlgorithm is the default implementation of selection algorithm Parameters are defined as constants within the function
type Service ¶
type Service struct {
// contains filtered or unexported fields
}
Service provides agent memory management with scoring, selection, and pruning Each service instance is bound to a specific agent
func New ¶
func New(agentID string, llmClient gollem.LLMClient, repo interfaces.Repository) *Service
New creates a new memory service bound to a specific agent with default algorithms
func (*Service) ExtractAndSaveMemories ¶ added in v0.8.0
func (s *Service) ExtractAndSaveMemories( ctx context.Context, query string, usedMemories []*memory.AgentMemory, history *gollem.History, ) error
ExtractAndSaveMemories extracts new claims from execution history and saves them This method uses LLM to generate reflection and extract claims from execution history Responsibilities: Extract claims, update scores, generate embeddings, save memories Does NOT perform pruning - caller should call PruneMemories separately when needed
func (*Service) PruneMemories ¶ added in v0.8.0
PruneMemories removes low-quality memories based on score and usage patterns This is a separate operation from ExtractAndSaveMemories for clear separation of concerns Caller controls when to prune (e.g., periodically, after N executions, manually)
func (*Service) SearchAndSelectMemories ¶ added in v0.8.0
func (s *Service) SearchAndSelectMemories( ctx context.Context, query string, limit int, ) ([]*memory.AgentMemory, error)
SearchAndSelectMemories searches for relevant memories and selects top N using injection algorithm This is the main method agents should call before execution to get relevant memories
func (*Service) WithPruningAlgorithm ¶ added in v0.8.0
func (s *Service) WithPruningAlgorithm(algo PruningAlgorithm) *Service
WithPruningAlgorithm replaces the pruning algorithm
func (*Service) WithScoringAlgorithm ¶ added in v0.8.0
func (s *Service) WithScoringAlgorithm(algo ScoringAlgorithm) *Service
WithScoringAlgorithm replaces the scoring algorithm
func (*Service) WithSelectionAlgorithm ¶ added in v0.8.0
func (s *Service) WithSelectionAlgorithm(algo SelectionAlgorithm) *Service
WithSelectionAlgorithm replaces the selection algorithm