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: 17 Imported by: 0

Documentation

Overview

Package memory provides unified memory management for the StyleAgent framework. It coordinates session memory, task memory, and distilled task storage through a single interface.

Package memory provides unified memory management for the StyleAgent framework.

Package memory provides unified memory management for the StyleAgent framework. This is the production-grade MemoryManager that integrates with PostgreSQL + pgvector storage.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type DistilledTaskData

type DistilledTaskData struct {
	TaskID    string
	Input     string
	Output    string
	Context   map[string]interface{}
	Vector    []float64
	CreatedAt time.Time
}

DistilledTaskData holds distilled task information with local vector.

type MemoryConfig

type MemoryConfig struct {
	// Enabled enables memory features.
	Enabled bool

	// Storage type: "memory" or "postgres".
	Storage string

	// MaxHistory is the maximum number of turns to keep in context.
	MaxHistory int

	// MaxSessions is the maximum number of sessions to store.
	MaxSessions int

	// MaxTasks is the maximum number of tasks to store.
	MaxTasks int

	// MaxDistilledTasks is the maximum number of distilled tasks to store.
	// Implements LRU eviction when limit is reached.
	MaxDistilledTasks int

	// SessionTTL is the time-to-live for sessions.
	SessionTTL time.Duration

	// TaskTTL is time-to-live for tasks.
	TaskTTL time.Duration

	// DistilledTaskTTL is time-to-live for distilled tasks.
	DistilledTaskTTL time.Duration

	// VectorDim is the dimension of the vector (for local embedding).
	VectorDim int

	// EnablePostgres enables PostgreSQL storage.
	EnablePostgres bool

	// PostgresDSN is the PostgreSQL connection string.
	PostgresDSN string
}

MemoryConfig holds configuration for MemoryManager.

func DefaultMemoryConfig

func DefaultMemoryConfig() *MemoryConfig

DefaultMemoryConfig returns default configuration for MemoryManager.

type MemoryManager

type MemoryManager interface {
	// CreateSession creates a new session and returns the session ID.
	CreateSession(ctx context.Context, userID string) (string, error)

	// AddMessage adds a message to the session.
	AddMessage(ctx context.Context, sessionID, role, content string) error

	// GetMessages retrieves all messages from the session.
	GetMessages(ctx context.Context, sessionID string) ([]Message, error)

	// DeleteSession deletes a session and all its messages immediately.
	// This is different from TTL-based cleanup, which waits for expiration.
	DeleteSession(ctx context.Context, sessionID string) error

	// BuildContext builds input with conversation history context.
	BuildContext(ctx context.Context, input string, sessionID string) (string, error)

	// CreateTask creates a new task and returns the task ID.
	CreateTask(ctx context.Context, sessionID, userID, input string) (string, error)

	// UpdateTaskOutput updates the task output.
	UpdateTaskOutput(ctx context.Context, taskID, output string) error

	// DistillTask extracts key information from task for future reference.
	DistillTask(ctx context.Context, taskID string) (*models.Task, error)

	// StoreDistilledTask stores a distilled task with local vector embedding.
	// The vector is generated locally using simple hash-based algorithms.
	StoreDistilledTask(ctx context.Context, taskID string, distilled *models.Task) error

	// SearchSimilarTasks searches for similar tasks using local cosine similarity.
	SearchSimilarTasks(ctx context.Context, query string, limit int) ([]*models.Task, error)

	// Start starts the memory manager and background workers.
	Start(ctx context.Context) error

	// Stop stops the memory manager and cleans up resources.
	Stop(ctx context.Context) error
}

MemoryManager provides unified memory management. It coordinates session memory, task memory, and distilled task storage.

func NewMemoryManager

func NewMemoryManager(config *MemoryConfig) (MemoryManager, error)

NewMemoryManager creates a new MemoryManager with the given configuration. For production use with new distillation engine, use NewMemoryManagerWithDistiller.

func NewMemoryManagerWithDistiller

func NewMemoryManagerWithDistiller(config *MemoryConfig, embedder embedding.EmbeddingService, expRepo distillation.ExperienceRepository) (MemoryManager, error)

NewMemoryManagerWithDistiller creates a new MemoryManager with the new distillation engine. This is the recommended method for production use.

Args:

config - memory configuration.
embedder - embedding service for generating vectors.
expRepo - experience repository for storage and retrieval.

Returns:

MemoryManager - configured memory manager instance.
error - any error encountered.

type Message

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

Message represents a chat message.

type ProductionMemoryManager

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

ProductionMemoryManager implements MemoryManager interface with production-grade storage. It integrates with PostgreSQL + pgvector for persistent storage and intelligent retrieval.

func NewProductionMemoryManager

func NewProductionMemoryManager(
	dbPool *postgres.Pool,
	embeddingClient *embedding.EmbeddingClient,
	config *MemoryConfig,
) (*ProductionMemoryManager, error)

NewProductionMemoryManager creates a new production-grade MemoryManager. Args: dbPool - PostgreSQL connection pool embeddingClient - Embedding service client config - Memory manager configuration Returns new ProductionMemoryManager instance.

func (*ProductionMemoryManager) AddMessage

func (m *ProductionMemoryManager) AddMessage(ctx context.Context, sessionID, role, content string) error

AddMessage adds a message to the session. Args: ctx - database operation context. sessionID - session identifier. role - message role (user/assistant/system). content - message content. Returns error if operation fails. Note: This stores conversations WITHOUT vector embedding (per design standard). conversations table is for history tracking only, retrieval uses knowledge/experience tables.

func (*ProductionMemoryManager) BuildContext

func (m *ProductionMemoryManager) BuildContext(ctx context.Context, input string, sessionID string) (string, error)

BuildContext builds input with conversation history context. Args: ctx - database operation context. input - current user input. sessionID - session identifier. Returns context string or error if building fails.

func (*ProductionMemoryManager) CreateSession

func (m *ProductionMemoryManager) CreateSession(ctx context.Context, userID string) (string, error)

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

func (*ProductionMemoryManager) CreateTask

func (m *ProductionMemoryManager) CreateTask(ctx context.Context, sessionID, userID, input string) (string, error)

CreateTask creates a new task and returns the task ID. Args: ctx - database operation context. sessionID - session identifier. userID - user identifier. input - task input. Returns task ID or error if creation fails. Note: This creates task_result WITHOUT embedding (embedding only for experiences). task_results table stores execution history, experiences store reusable knowledge.

func (*ProductionMemoryManager) DeleteSession

func (m *ProductionMemoryManager) DeleteSession(ctx context.Context, sessionID string) error

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

func (*ProductionMemoryManager) DistillTask

func (m *ProductionMemoryManager) DistillTask(ctx context.Context, taskID string) (*models.Task, error)

DistillTask extracts key information from task for future reference. Args: ctx - database operation context. taskID - task identifier. Returns distilled task or error if distillation fails. Note: This retrieves stored task result and converts to Task format.

func (*ProductionMemoryManager) GetMessages

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

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

func (*ProductionMemoryManager) SearchSimilarTasks

func (m *ProductionMemoryManager) SearchSimilarTasks(ctx context.Context, query string, limit int) ([]*models.Task, error)

SearchSimilarTasks searches for similar tasks using intelligent retrieval. Args: ctx - database operation context. query - search query. limit - maximum number of results. Returns list of similar tasks or error if search fails. Note: This returns experiences (agent knowledge) rather than execution tasks.

func (*ProductionMemoryManager) SetTenantID

func (m *ProductionMemoryManager) SetTenantID(tenantID string) error

SetTenantID sets the current tenant ID for multi-tenant operations. Args: tenantID - tenant identifier. Returns error if tenant ID is invalid.

func (*ProductionMemoryManager) Start

Start starts the memory manager and background workers. This method creates a new context for the memory manager and starts the write buffer goroutine. The context is used for graceful shutdown.

Thread-safety: Uses mutex to ensure only one goroutine can start the manager.

Args: ctx - context for cancellation. Returns error if starting fails.

func (*ProductionMemoryManager) Stop

Stop stops the memory manager and cleans up resources. This method cancels the memory manager context and waits for all background goroutines to finish.

Thread-safety: Uses mutex to ensure only one goroutine can stop the manager.

Args: ctx - context for cancellation (used for timeout). Returns error if stopping fails.

func (*ProductionMemoryManager) StoreDistilledTask

func (m *ProductionMemoryManager) StoreDistilledTask(ctx context.Context, taskID string, distilled *models.Task) error

StoreDistilledTask stores a distilled task with async embedding chain. Args: ctx - database operation context. taskID - task identifier. distilled - distilled task data. Returns error if storage fails. Note: Per design standard, this uses asynchronous embedding chain: 1. Write to DB with embedding_status = 'pending' 2. Write to embedding_queue with dedupe_key (for deduplication) 3. Background Worker processes embedding tasks 4. Worker updates DB with embedding and status = 'completed'

func (*ProductionMemoryManager) UpdateTaskOutput

func (m *ProductionMemoryManager) UpdateTaskOutput(ctx context.Context, taskID, output string) error

UpdateTaskOutput updates the task output. Args: ctx - database operation context. taskID - task identifier. output - task output. Returns error if update fails.

type SessionData

type SessionData struct {
	SessionID    string
	UserID       string
	CreatedAt    time.Time
	UpdatedAt    time.Time
	MessageCount int
}

SessionData holds session information with optional caching.

Directories

Path Synopsis
Package distillation provides memory distillation functionality for agent experience extraction.
Package distillation provides memory distillation functionality for agent experience extraction.

Jump to

Keyboard shortcuts

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