memory

package
v0.1.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 14, 2026 License: Apache-2.0 Imports: 9 Imported by: 0

Documentation

Overview

Package memory provides API abstractions for memory distillation operations.

Package memory provides implementation for memory distillation operations.

Package memory provides error definitions for memory operations.

Package memory provides high-level APIs for memory management.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrInvalidUserID is returned when user ID is empty.
	ErrInvalidUserID = errors.New("invalid user ID")

	// ErrInvalidSessionID is returned when session ID is empty.
	ErrInvalidSessionID = errors.New("invalid session ID")

	// ErrInvalidRole is returned when role is empty.
	ErrInvalidRole = errors.New("invalid role")

	// ErrInvalidContent is returned when content is empty.
	ErrInvalidContent = errors.New("invalid content")

	// ErrInvalidTaskID is returned when task ID is empty.
	ErrInvalidTaskID = errors.New("invalid task ID")

	// ErrInvalidQuery is returned when query is empty.
	ErrInvalidQuery = errors.New("invalid query")

	// ErrInvalidLimit is returned when limit is less than or equal to zero.
	ErrInvalidLimit = errors.New("invalid limit")

	// ErrSessionNotFound is returned when session does not exist.
	ErrSessionNotFound = errors.New("session not found")

	// ErrTaskNotFound is returned when task does not exist.
	ErrTaskNotFound = errors.New("task not found")

	// ErrInvalidConversationID is returned when conversation ID is empty.
	ErrInvalidConversationID = errors.New("invalid conversation ID")

	// ErrNoMessages is returned when no messages are provided for distillation.
	ErrNoMessages = errors.New("no messages provided")

	// ErrInvalidTenantID is returned when tenant ID is empty.
	ErrInvalidTenantID = errors.New("invalid tenant ID")

	// ErrInvalidConfig is returned when configuration is invalid.
	ErrInvalidConfig = errors.New("invalid configuration")

	// ErrDistillationFailed is returned when distillation process fails.
	ErrDistillationFailed = errors.New("distillation failed")

	// ErrEmbeddingFailed is returned when embedding generation fails.
	ErrEmbeddingFailed = errors.New("embedding generation failed")

	// ErrVectorSearchFailed is returned when vector search fails.
	ErrVectorSearchFailed = errors.New("vector search failed")

	// ErrInvalidMemoryID is returned when memory ID is empty.
	ErrInvalidMemoryID = errors.New("invalid memory ID")

	// ErrMemoryNotFound is returned when memory does not exist.
	ErrMemoryNotFound = errors.New("memory not found")

	// ErrMemoryUpdateFailed is returned when memory update fails.
	ErrMemoryUpdateFailed = errors.New("memory update failed")

	// ErrMemoryDeleteFailed is returned when memory deletion fails.
	ErrMemoryDeleteFailed = errors.New("memory deletion failed")
)

Functions

This section is empty.

Types

type ConversationMessage

type ConversationMessage struct {
	// Role is the message role (user/assistant/system).
	Role string `json:"role"`
	// Content is the message content.
	Content string `json:"content"`
}

ConversationMessage represents a message in a conversation.

type DistillationConfig

type DistillationConfig struct {
	// MinImportance is the minimum importance score.
	MinImportance float64 `json:"min_importance"`
	// ConflictThreshold is the similarity threshold for conflict detection.
	ConflictThreshold float64 `json:"conflict_threshold"`
	// MaxMemoriesPerDistillation is the maximum memories per distillation.
	MaxMemoriesPerDistillation int `json:"max_memories_per_distillation"`
	// MaxSolutionsPerTenant is the global cap on solution memories.
	MaxSolutionsPerTenant int `json:"max_solutions_per_tenant"`
	// EnableCodeFilter enables code block filtering.
	EnableCodeFilter bool `json:"enable_code_filter"`
	// EnableStacktraceFilter enables stacktrace filtering.
	EnableStacktraceFilter bool `json:"enable_stacktrace_filter"`
	// EnableLogFilter enables log filtering.
	EnableLogFilter bool `json:"enable_log_filter"`
	// EnableMarkdownTableFilter enables markdown table filtering.
	EnableMarkdownTableFilter bool `json:"enable_markdown_table_filter"`
	// EnableCrossTurnExtraction enables cross-turn conversation extraction.
	EnableCrossTurnExtraction bool `json:"enable_cross_turn_extraction"`
	// EnableLengthBonus enables length bonus in importance scoring.
	EnableLengthBonus bool `json:"enable_length_bonus"`
	// LengthThreshold is the threshold for length bonus.
	LengthThreshold int `json:"length_threshold"`
	// LengthBonus is the bonus value for length threshold.
	LengthBonus float64 `json:"length_bonus"`
	// TopNBeforeConflict enables top-N filtering before conflict detection.
	TopNBeforeConflict bool `json:"top_n_before_conflict"`
	// ConflictSearchLimit is the limit for vector search in conflict detection.
	ConflictSearchLimit int `json:"conflict_search_limit"`
	// PrecisionOverRecall prioritizes precision over recall.
	PrecisionOverRecall bool `json:"precision_over_recall"`
}

DistillationConfig holds configuration for the distillation process.

type DistillationMetrics

type DistillationMetrics struct {
	// AttemptTotal is the total number of distillation attempts.
	AttemptTotal int64 `json:"attempt_total"`
	// SuccessTotal is the total number of successful distillations.
	SuccessTotal int64 `json:"success_total"`
	// FilteredNoise is the number of memories filtered as noise.
	FilteredNoise int64 `json:"filtered_noise"`
	// FilteredSecurity is the number of memories filtered for security.
	FilteredSecurity int64 `json:"filtered_security"`
	// ConflictResolved is the number of conflicts resolved.
	ConflictResolved int64 `json:"conflict_resolved"`
	// MemoriesCreated is the total number of memories created.
	MemoriesCreated int64 `json:"memories_created"`
}

DistillationMetrics holds metrics for the distillation process.

type DistillationService

type DistillationService interface {
	// DistillConversation distills memories from a conversation.
	// Args:
	// ctx - operation context.
	// conversationID - unique identifier for the conversation.
	// messages - conversation messages.
	// tenantID - tenant ID for multi-tenancy.
	// userID - user ID for the conversation.
	// Returns distilled memories or error.
	DistillConversation(ctx context.Context, conversationID string, messages []ConversationMessage, tenantID, userID string) ([]*DistilledMemory, error)

	// GetMetrics returns the current distillation metrics.
	// Returns the metrics.
	GetMetrics() *DistillationMetrics

	// ResetMetrics resets the distillation metrics.
	ResetMetrics()

	// GetConfig returns the current distillation configuration.
	// Returns the configuration.
	GetConfig() *DistillationConfig

	// UpdateConfig updates the distillation configuration.
	// Args:
	// config - new configuration.
	// Returns error if update fails.
	UpdateConfig(config *DistillationConfig) error

	// UpdateMemory updates an existing distilled memory.
	// Args:
	// ctx - operation context.
	// memoryID - the memory ID to update.
	// updates - map of fields to update (content, importance, metadata, etc.).
	// Returns error if update fails.
	UpdateMemory(ctx context.Context, memoryID string, updates map[string]interface{}) error

	// DeleteMemory deletes a distilled memory.
	// Args:
	// ctx - operation context.
	// memoryID - the memory ID to delete.
	// Returns error if deletion fails.
	DeleteMemory(ctx context.Context, memoryID string) error

	// SearchMemories searches for memories by query text (using vector search).
	// Args:
	// ctx - operation context.
	// query - the search query.
	// tenantID - tenant ID for multi-tenancy.
	// limit - maximum number of results.
	// Returns matching memories or error.
	SearchMemories(ctx context.Context, query string, tenantID string, limit int) ([]*DistilledMemory, error)
}

DistillationService provides memory distillation operations.

type DistillationServiceImpl

type DistillationServiceImpl struct {
	// contains filtered or unexported fields
}

DistillationServiceImpl implements the DistillationService interface.

func NewDistillationService

func NewDistillationService(distiller *distillation.Distiller) *DistillationServiceImpl

NewDistillationService creates a new DistillationService instance.

Args: distiller - internal distiller instance.

Returns new distillation service instance.

func NewDistillationServiceWithEmbedder

func NewDistillationServiceWithEmbedder(config *DistillationConfig, embedder embedding.EmbeddingService, repo ExperienceRepository) (*DistillationServiceImpl, error)

NewDistillationServiceWithEmbedder creates a new DistillationService with embedder and repository.

Args: config - distillation configuration. embedder - embedding service for generating vectors. repo - experience repository for storage and retrieval.

Returns new distillation service instance or error.

func (*DistillationServiceImpl) DeleteMemory

func (s *DistillationServiceImpl) DeleteMemory(ctx context.Context, memoryID string) error

DeleteMemory deletes a distilled memory.

Args: ctx - operation context. memoryID - the memory ID to delete. Returns error if deletion fails.

func (*DistillationServiceImpl) DistillConversation

func (s *DistillationServiceImpl) DistillConversation(ctx context.Context, conversationID string, messages []ConversationMessage, tenantID, userID string) ([]*DistilledMemory, error)

DistillConversation distills memories from a conversation.

Args: ctx - operation context. conversationID - unique identifier for the conversation. messages - conversation messages. tenantID - tenant ID for multi-tenancy. userID - user ID for the conversation.

Returns distilled memories or error.

func (*DistillationServiceImpl) GetConfig

GetConfig returns the current distillation configuration.

Returns the configuration.

func (*DistillationServiceImpl) GetDistiller

func (s *DistillationServiceImpl) GetDistiller() interface{}

GetDistiller returns the internal distiller instance (for advanced usage).

func (*DistillationServiceImpl) GetMetrics

GetMetrics returns the current distillation metrics.

Returns the metrics.

func (*DistillationServiceImpl) ResetMetrics

func (s *DistillationServiceImpl) ResetMetrics()

ResetMetrics resets the distillation metrics.

func (*DistillationServiceImpl) SearchMemories

func (s *DistillationServiceImpl) SearchMemories(ctx context.Context, query string, tenantID string, limit int) ([]*DistilledMemory, error)

SearchMemories searches for memories by query text (using vector search).

Args: ctx - operation context. query - the search query. tenantID - tenant ID for multi-tenancy. limit - maximum number of results. Returns matching memories or error.

func (*DistillationServiceImpl) UpdateConfig

func (s *DistillationServiceImpl) UpdateConfig(config *DistillationConfig) error

UpdateConfig updates the distillation configuration.

Args: config - new configuration.

Returns error if update fails.

func (*DistillationServiceImpl) UpdateMemory

func (s *DistillationServiceImpl) UpdateMemory(ctx context.Context, memoryID string, updates map[string]interface{}) error

UpdateMemory updates an existing distilled memory.

Args: ctx - operation context. memoryID - the memory ID to update. updates - map of fields to update (content, importance, metadata, etc.). Returns error if update fails.

type DistilledMemory

type DistilledMemory struct {
	// ID is the unique identifier.
	ID string `json:"id"`
	// Type is the memory type.
	Type MemoryType `json:"type"`
	// Content is the memory content.
	Content string `json:"content"`
	// Importance is the importance score.
	Importance float64 `json:"importance"`
	// Source is the source conversation ID.
	Source string `json:"source"`
	// TenantID is the tenant identifier.
	TenantID string `json:"tenant_id"`
	// UserID is the user identifier.
	UserID string `json:"user_id"`
	// CreatedAt is the creation timestamp.
	CreatedAt time.Time `json:"created_at"`
	// ExpiresAt is the expiration timestamp.
	ExpiresAt *time.Time `json:"expires_at"`
	// Metadata is additional metadata.
	Metadata map[string]interface{} `json:"metadata"`
}

DistilledMemory represents a distilled memory from agent experience.

type Experience

type Experience struct {
	// Problem is the problem description.
	Problem string `json:"problem"`
	// Solution is the solution description.
	Solution string `json:"solution"`
	// Confidence is the confidence score.
	Confidence float64 `json:"confidence"`
	// ExtractionMethod is how the experience was extracted.
	ExtractionMethod ExtractionMethod `json:"extraction_method"`
}

Experience represents a problem-solution pair extracted from conversation.

type ExperienceRepository

type ExperienceRepository interface {
	// SearchByVector searches for similar experiences by vector.
	// Args:
	// ctx - operation context.
	// vector - the vector to search.
	// tenantID - tenant ID for multi-tenancy.
	// limit - maximum number of results.
	// Returns similar experiences or error.
	SearchByVector(ctx context.Context, vector []float64, tenantID string, limit int) ([]*Experience, error)

	// GetByMemoryType retrieves experiences by memory type.
	// Args:
	// ctx - operation context.
	// tenantID - tenant ID for multi-tenancy.
	// memoryType - the memory type to filter by.
	// Returns experiences or error.
	GetByMemoryType(ctx context.Context, tenantID string, memoryType MemoryType) ([]*Experience, error)

	// Update updates an existing experience.
	// Args:
	// ctx - operation context.
	// experience - the experience to update.
	// Returns error if update fails.
	Update(ctx context.Context, experience *Experience) error

	// Delete deletes an experience by ID.
	// Args:
	// ctx - operation context.
	// id - the experience ID.
	// Returns error if deletion fails.
	Delete(ctx context.Context, id string) error

	// Create creates a new experience.
	// Args:
	// ctx - operation context.
	// experience - the experience to create.
	// Returns error if creation fails.
	Create(ctx context.Context, experience *Experience) error

	// GetInternalRepository returns the internal repository for advanced usage.
	// This is used to bridge the API and internal interfaces.
	GetInternalRepository() interface{}
}

ExperienceRepository defines the interface for experience storage and retrieval.

type ExtractionMethod

type ExtractionMethod string

ExtractionMethod represents how an experience was extracted.

const (
	// ExtractionDirect represents direct user-assistant pair extraction.
	ExtractionDirect ExtractionMethod = "direct"
	// ExtractionCrossTurn represents multi-turn conversation extraction.
	ExtractionCrossTurn ExtractionMethod = "cross-turn"
)

type MemoryType

type MemoryType string

MemoryType represents the type of distilled memory.

const (
	// MemoryKnowledge represents factual information and knowledge.
	MemoryKnowledge MemoryType = "knowledge"
	// MemoryPreference represents user preferences.
	MemoryPreference MemoryType = "preference"
	// MemoryInteraction represents interaction patterns and solutions.
	MemoryInteraction MemoryType = "interaction"
	// MemoryProfile represents user profile and behavioral patterns.
	MemoryProfile MemoryType = "profile"
)

type Message

type Message struct {
	Role    string `json:"role"`
	Content string `json:"content"`
	Time    string `json:"time"`
}

Message represents a conversation message.

type ResolutionStrategy

type ResolutionStrategy string

ResolutionStrategy represents how to resolve memory conflicts.

const (
	// ReplaceOld replaces old memory with new.
	ReplaceOld ResolutionStrategy = "replace"
	// KeepBoth keeps both versions.
	KeepBoth ResolutionStrategy = "version"
	// Merge merges memories (future implementation).
	Merge ResolutionStrategy = "merge"
)

type Service

type Service struct {
	// contains filtered or unexported fields
}

Service provides memory management operations.

func NewService

func NewService(memoryMgr memory.MemoryManager) *Service

NewService creates a new memory service instance. Args: memoryMgr - internal memory manager instance. Returns new memory service instance.

func (*Service) AddMessage

func (s *Service) AddMessage(ctx context.Context, sessionID, role, content string) error

AddMessage adds a message to the session. Args: ctx - operation context. sessionID - session identifier. role - message role (user/assistant/system). content - message content. Returns error if operation fails.

func (*Service) CreateSession

func (s *Service) CreateSession(ctx context.Context, userID string) (string, error)

CreateSession creates a new conversation session. Args: ctx - operation context. userID - user identifier for the session. Returns session ID or error if creation fails.

func (*Service) DeleteSession

func (s *Service) DeleteSession(ctx context.Context, sessionID string) error

DeleteSession deletes a session and all its messages. Args: ctx - operation context. sessionID - session identifier. Returns error if deletion fails.

func (*Service) DistillTask

func (s *Service) DistillTask(ctx context.Context, taskID string) error

DistillTask extracts key information from a task for future reference. Args: ctx - operation context. taskID - task identifier. Returns error if distillation fails.

func (*Service) GetMessages

func (s *Service) GetMessages(ctx context.Context, sessionID string) ([]*Message, error)

GetMessages retrieves all messages from the session. Args: ctx - operation context. sessionID - session identifier. Returns list of messages or error if retrieval fails.

func (*Service) SearchSimilarTasks

func (s *Service) SearchSimilarTasks(ctx context.Context, query string, limit int) ([]*Task, error)

SearchSimilarTasks searches for similar tasks using vector similarity. Args: ctx - operation context. query - search query text. limit - maximum number of results to return. Returns list of similar tasks or error if search fails.

type Task

type Task struct {
	TaskID  string `json:"task_id"`
	Input   string `json:"input"`
	Output  string `json:"output"`
	Context string `json:"context"`
}

Task represents a distilled task with its extracted information.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL