memory

package
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Feb 4, 2025 License: MIT Imports: 15 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// MetadataKeySource indicates the source/creator of the memory
	MetadataKeySource = "source"
	// MetadataKeyTimestamp indicates when the memory was created
	MetadataKeyTimestamp = "timestamp"
	// MetadataKeyType indicates the type of memory (e.g., "entity", "task", "general")
	MetadataKeyType = "type"
	// MetadataKeyShared indicates if the memory is shared between agents
	MetadataKeyShared = "shared"
	// MetadataKeyTaskID links memory to a specific task
	MetadataKeyTaskID = "task_id"
	// MetadataKeyAgentID links memory to a specific agent
	MetadataKeyAgentID = "agent_id"
	// MetadataKeyProcessType indicates the process type (sequential, hierarchical)
	MetadataKeyProcessType = "process_type"
)

Standard metadata keys

Variables

This section is empty.

Functions

This section is empty.

Types

type BaseMemory

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

BaseMemory provides a basic implementation of the Memory interface

func NewBaseMemory

func NewBaseMemory(storage Storage, config *MemoryConfig) *BaseMemory

NewBaseMemory creates a new base memory instance

func (*BaseMemory) Reset

func (m *BaseMemory) Reset() error

Reset clears all stored memories

func (*BaseMemory) Save

func (m *BaseMemory) Save(value string, metadata map[string]interface{}, source string, scope MemoryScope, expiresAt *time.Time) error

Save stores a memory with optional metadata and expiration

func (*BaseMemory) Search

func (m *BaseMemory) Search(query *MemoryQuery) ([]MemoryResult, error)

Search queries memories based on the provided query parameters

func (*BaseMemory) Subscribe

func (m *BaseMemory) Subscribe(target string, callback func(MemoryNotification)) error

Subscribe registers a callback for memory notifications

func (*BaseMemory) Unsubscribe

func (m *BaseMemory) Unsubscribe(target string) error

Unsubscribe removes a notification callback

type Config

type Config struct {
	Backend     backend.Backend
	VectorStore vector.Store
	History     *conversation.History
}

Config holds configuration for the memory manager

type ContextualMemory

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

ContextualMemory provides context-aware memory access

func NewContextualMemory

func NewContextualMemory(stm *ShortTermMemory, ltm *LongTermMemory, em EntityMemory) *ContextualMemory

NewContextualMemory creates a new contextual memory instance

func (*ContextualMemory) GetAgentContext

func (m *ContextualMemory) GetAgentContext(ctx context.Context, agentName string, query string) (map[string]interface{}, error)

GetAgentContext retrieves context relevant to a specific agent

func (*ContextualMemory) GetProcessContext

func (m *ContextualMemory) GetProcessContext(ctx context.Context, processType string, query string) (map[string]interface{}, error)

GetProcessContext retrieves context relevant to a specific process type

func (*ContextualMemory) GetRelevantContext

func (m *ContextualMemory) GetRelevantContext(ctx context.Context, query *MemoryQuery) (map[string]interface{}, error)

GetRelevantContext retrieves context based on a structured query

func (*ContextualMemory) GetSharedMemories

func (m *ContextualMemory) GetSharedMemories(ctx context.Context, agentID string, query string) ([]*SharedMemoryContext, error)

GetSharedMemories retrieves shared memories accessible to an agent

func (*ContextualMemory) GetTaskContext

func (m *ContextualMemory) GetTaskContext(ctx context.Context, taskID string, query string) (map[string]interface{}, error)

GetTaskContext retrieves context relevant to a specific task

func (*ContextualMemory) Reset

func (m *ContextualMemory) Reset(ctx context.Context) error

Reset clears all memory components

func (*ContextualMemory) SaveWithContext

func (m *ContextualMemory) SaveWithContext(ctx context.Context, value interface{}, query *MemoryQuery) error

SaveWithContext stores information with contextual metadata

func (*ContextualMemory) ShareMemory

func (m *ContextualMemory) ShareMemory(ctx context.Context, source string, value interface{}, targets []string, metadata map[string]interface{}) error

ShareMemory shares a memory context with other agents

type ContextualMemoryItem

type ContextualMemoryItem struct {
	Data      interface{}            `json:"data"`
	Source    string                 `json:"source"` // short_term, long_term, entity
	Metadata  map[string]interface{} `json:"metadata"`
	Agent     string                 `json:"agent,omitempty"`
	Timestamp time.Time              `json:"timestamp"`
	Relevance float64                `json:"relevance,omitempty"`
}

ContextualMemoryItem represents a combined memory item

type Embedder

type Embedder interface {
	Embed(text string) ([]float32, error)
	Dimension() int
}

Embedder interface for generating embeddings

type EntityMemory

type EntityMemory interface {
	// SaveEntity stores an entity with its relationships
	SaveEntity(ctx context.Context, item EntityMemoryItem) error

	// SearchEntities performs a search over stored entities
	SearchEntities(ctx context.Context, query string) ([]EntityMemoryItem, error)

	// SearchByType searches for entities of a specific type
	SearchByType(ctx context.Context, entityType EntityType, query string) ([]EntityMemoryItem, error)

	// GetEntity retrieves a specific entity by name
	GetEntity(ctx context.Context, name string) (*EntityMemoryItem, error)
}

EntityMemory defines the interface for entity-based memory

type EntityMemoryItem

type EntityMemoryItem struct {
	// Name uniquely identifies the entity
	Name string

	// Type indicates the entity type
	Type EntityType

	// Description provides entity details
	Description string

	// Properties contains entity properties
	Properties map[string]interface{}

	// Relationships maps relationship types to related entity names
	Relationships map[string][]string

	// Metadata contains additional metadata
	Metadata map[string]interface{}

	// Agent indicates which agent created/owns this entity
	Agent string

	// Timestamp indicates when the entity was created/updated
	Timestamp time.Time
}

EntityMemoryItem represents an entity in memory with relationships

type EntityMemoryStruct

type EntityMemoryStruct struct {
	*BaseMemory
	// contains filtered or unexported fields
}

EntityMemoryStruct represents a memory component for storing entity information

func NewEntityMemoryStruct

func NewEntityMemoryStruct(storage Storage, config *MemoryConfig) *EntityMemoryStruct

NewEntityMemoryStruct creates a new entity memory instance

func (*EntityMemoryStruct) GetEntity

func (m *EntityMemoryStruct) GetEntity(ctx context.Context, name string) (*EntityMemoryItem, error)

GetEntity retrieves a specific entity by name

func (*EntityMemoryStruct) Reset

func (m *EntityMemoryStruct) Reset(ctx context.Context) error

Reset clears all stored items

func (*EntityMemoryStruct) Save

func (m *EntityMemoryStruct) Save(value string, metadata map[string]interface{}, source string, scope MemoryScope, expiresAt *time.Time) error

Save stores a value in entity memory

func (*EntityMemoryStruct) SaveEntity

func (m *EntityMemoryStruct) SaveEntity(ctx context.Context, item EntityMemoryItem) error

SaveEntity stores an entity in memory

func (*EntityMemoryStruct) Search

func (m *EntityMemoryStruct) Search(query *MemoryQuery) ([]MemoryResult, error)

Search performs a search over stored items

func (*EntityMemoryStruct) SearchByType

func (m *EntityMemoryStruct) SearchByType(ctx context.Context, entityType EntityType, query string) ([]EntityMemoryItem, error)

SearchByType searches for entities of a specific type

func (*EntityMemoryStruct) SearchEntities

func (m *EntityMemoryStruct) SearchEntities(ctx context.Context, query string) ([]EntityMemoryItem, error)

SearchEntities performs a search over stored entities

type EntityType

type EntityType string

EntityType represents the type of an entity in memory

const (
	EntityTypePerson   EntityType = "person"
	EntityTypePlace    EntityType = "place"
	EntityTypeConcept  EntityType = "concept"
	EntityTypeOrg      EntityType = "organization"
	EntityTypeArtifact EntityType = "artifact"
)

type LongTermMemory

type LongTermMemory struct {
	*BaseMemory
}

LongTermMemory manages persistent data and insights

func NewLongTermMemory

func NewLongTermMemory(storage Storage, config *MemoryConfig) *LongTermMemory

NewLongTermMemory creates a new long-term memory instance

func (*LongTermMemory) Reset

func (m *LongTermMemory) Reset(ctx context.Context) error

Reset clears all stored items

func (*LongTermMemory) Save

func (m *LongTermMemory) Save(value string, metadata map[string]interface{}, source string, scope MemoryScope, expiresAt *time.Time) error

Save stores a value in long-term memory

func (*LongTermMemory) Search

func (m *LongTermMemory) Search(query *MemoryQuery) ([]MemoryResult, error)

Search performs a search over stored items

type LongTermMemoryItem

type LongTermMemoryItem struct {
	ID        int64                  `json:"id"`
	Data      interface{}            `json:"data"`
	Metadata  map[string]interface{} `json:"metadata"`
	Agent     string                 `json:"agent,omitempty"`
	Timestamp time.Time              `json:"timestamp"`
}

LongTermMemoryItem represents an item in long-term memory

type Manager

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

Manager coordinates memory components and provides a high-level interface

func NewManager

func NewManager(config Config) (*Manager, error)

NewManager creates a new memory manager

func (*Manager) AddMessage

func (m *Manager) AddMessage(ctx context.Context, msg conversation.Message) error

AddMessage adds a message to conversation history

func (*Manager) Close

func (m *Manager) Close() error

Close closes the memory manager and its components

func (*Manager) DeleteThread

func (m *Manager) DeleteThread(ctx context.Context, threadID string) error

DeleteThread deletes a conversation thread

func (*Manager) DeleteVector

func (m *Manager) DeleteVector(ctx context.Context, id string) error

DeleteVector deletes a vector by ID

func (*Manager) GetThread

func (m *Manager) GetThread(threadID string) (*conversation.Thread, error)

GetThread retrieves a conversation thread

func (*Manager) GetThreadMessages

func (m *Manager) GetThreadMessages(ctx context.Context, threadID string, limit int) ([]conversation.Message, error)

GetThreadMessages retrieves messages from a thread

func (*Manager) LoadVector

func (m *Manager) LoadVector(ctx context.Context, id string) (vector.Vector, map[string]interface{}, error)

LoadVector retrieves a vector by ID

func (*Manager) SearchConversations

func (m *Manager) SearchConversations(ctx context.Context, query string, limit int) ([]*conversation.Thread, error)

SearchConversations searches for conversations matching the query

func (*Manager) SearchVectors

func (m *Manager) SearchVectors(ctx context.Context, queryVec vector.Vector, limit int) ([]vector.SearchResult, error)

SearchVectors searches for similar vectors

func (*Manager) StoreVector

func (m *Manager) StoreVector(ctx context.Context, id string, vec vector.Vector, metadata map[string]interface{}) error

StoreVector stores a vector with metadata

type Memory

type Memory interface {
	// Save stores a memory with optional metadata and expiration
	Save(value string, metadata map[string]interface{}, source string, scope MemoryScope, expiresAt *time.Time) error

	// Search queries memories based on the provided query parameters
	Search(query *MemoryQuery) ([]MemoryResult, error)

	// Subscribe registers a callback for memory notifications
	Subscribe(target string, callback func(MemoryNotification)) error

	// Unsubscribe removes a notification callback
	Unsubscribe(target string) error

	// Reset clears all stored memories
	Reset() error
}

Memory defines the interface for memory operations

type MemoryAccessLevel

type MemoryAccessLevel string

MemoryAccessLevel defines how agents can interact with shared memories

const (
	// AccessReadOnly means agent can only read the memory
	AccessReadOnly MemoryAccessLevel = "read"

	// AccessReadWrite means agent can read and modify the memory
	AccessReadWrite MemoryAccessLevel = "write"
)

type MemoryConfig

type MemoryConfig struct {
	MaxResults          int           `json:"max_results"`
	RelevanceThreshold  float64       `json:"relevance_threshold"`
	DefaultTTL          time.Duration `json:"default_ttl"`
	EnableNotifications bool          `json:"enable_notifications"`

	// Storage configuration for different memory types
	ShortTermStorage *StorageConfig `json:"short_term_storage,omitempty"`
	LongTermStorage  *StorageConfig `json:"long_term_storage,omitempty"`
	EntityStorage    *StorageConfig `json:"entity_storage,omitempty"`
}

MemoryConfig defines configuration options for memory components

func DefaultMemoryConfig

func DefaultMemoryConfig() *MemoryConfig

DefaultMemoryConfig returns the default memory configuration

type MemoryNotification

type MemoryNotification struct {
	Source    string                 `json:"source"`
	Target    string                 `json:"target"`
	Value     string                 `json:"value"`
	Metadata  map[string]interface{} `json:"metadata"`
	Scope     MemoryScope            `json:"scope"`
	Type      MemoryType             `json:"type"`
	Timestamp time.Time              `json:"timestamp"`
}

MemoryNotification represents a notification about memory updates

type MemoryPermission

type MemoryPermission struct {
	// AgentID identifies the agent
	AgentID string `json:"agent_id"`

	// Scope defines visibility scope
	Scope MemoryScope `json:"scope"`

	// AccessLevel defines interaction level
	AccessLevel MemoryAccessLevel `json:"access_level"`

	// AllowedTypes specifies which memory types this agent can access
	AllowedTypes []MemoryType `json:"allowed_types,omitempty"`
}

MemoryPermission defines access control for shared memories

type MemoryQuery

type MemoryQuery struct {
	Query       string                 `json:"query"`
	Type        MemoryType             `json:"type"`
	Scope       MemoryScope            `json:"scope"`
	TaskID      string                 `json:"task_id,omitempty"`
	AgentName   string                 `json:"agent_name,omitempty"`
	ProcessType string                 `json:"process_type,omitempty"`
	Metadata    map[string]interface{} `json:"metadata,omitempty"`
	MaxResults  int                    `json:"max_results"`
	MinScore    float64                `json:"min_score"`
}

MemoryQuery represents a query for retrieving memories

type MemoryResult

type MemoryResult struct {
	Value     string                 `json:"value"`
	Score     float64                `json:"score"`
	Metadata  map[string]interface{} `json:"metadata"`
	Scope     MemoryScope            `json:"scope"`
	Type      MemoryType             `json:"type"`
	ExpiresAt *time.Time             `json:"expires_at,omitempty"`
}

MemoryResult represents a result from a memory query

type MemoryScope

type MemoryScope string

MemoryScope defines the scope of memory storage

const (
	// ScopeShortTerm represents short-term memory storage
	ScopeShortTerm MemoryScope = "short_term"
	// ScopeLongTerm represents long-term memory storage
	ScopeLongTerm MemoryScope = "long_term"
	// ScopeEntity represents entity memory storage
	ScopeEntity MemoryScope = "entity"
	// TaskScope indicates memory is only relevant to a specific task
	TaskScope MemoryScope = "task"
	// ProcessScope indicates memory is relevant to the entire process/workflow
	ProcessScope MemoryScope = "process"
	// GlobalScope indicates memory is globally accessible
	GlobalScope MemoryScope = "global"
)

type MemoryType

type MemoryType string

MemoryType defines the type of memory storage

const (
	// TaskMemory represents memory related to task execution
	TaskMemory MemoryType = "task"
	// AgentMemory represents memory specific to an agent
	AgentMemory MemoryType = "agent"
	// ProcessMemory represents memory related to process execution
	ProcessMemory MemoryType = "process"
	// GeneralMemory represents general purpose memory
	GeneralMemory MemoryType = "general"
)

type OpenAIEmbedder

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

OpenAIEmbedder implements Embedder interface using OpenAI's embeddings API

func NewOpenAIEmbedder

func NewOpenAIEmbedder(apiKey string) *OpenAIEmbedder

NewOpenAIEmbedder creates a new OpenAI embedder instance

func (*OpenAIEmbedder) Dimension

func (e *OpenAIEmbedder) Dimension() int

Dimension returns the dimension of the embeddings

func (*OpenAIEmbedder) Embed

func (e *OpenAIEmbedder) Embed(text string) ([]float32, error)

Embed generates embeddings for the given text using OpenAI's API

type RAGItem

type RAGItem struct {
	StorageItem *StorageItem
	Embedding   []float32
}

RAGItem represents a single item in RAG storage

type RAGStorage

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

RAGStorage implements Storage interface using vector embeddings for semantic search

func NewRAGStorage

func NewRAGStorage(embedder Embedder) *RAGStorage

NewRAGStorage creates a new RAG storage instance

func (*RAGStorage) Reset

func (s *RAGStorage) Reset(ctx context.Context) error

Reset clears all stored items

func (*RAGStorage) Save

func (s *RAGStorage) Save(ctx context.Context, item *StorageItem) error

Save stores an item in RAG storage

func (*RAGStorage) Search

func (s *RAGStorage) Search(ctx context.Context, query string, maxResults int) ([]*StorageItem, error)

Search finds memories matching the query

type SQLiteStorage

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

SQLiteStorage implements Storage interface using SQLite database

func NewSQLiteStorage

func NewSQLiteStorage(path string) (*SQLiteStorage, error)

NewSQLiteStorage creates a new SQLite storage instance

func (*SQLiteStorage) Close

func (s *SQLiteStorage) Close() error

Close closes the database connection

func (*SQLiteStorage) Reset

func (s *SQLiteStorage) Reset(ctx context.Context) error

Reset clears all stored items

func (*SQLiteStorage) Save

func (s *SQLiteStorage) Save(ctx context.Context, item *StorageItem) error

Save stores an item in SQLite storage

func (*SQLiteStorage) Search

func (s *SQLiteStorage) Search(ctx context.Context, query string, maxResults int) ([]*StorageItem, error)

Search finds memories matching the query

type SharedMemory

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

SharedMemory manages memory sharing between agents

func NewSharedMemory

func NewSharedMemory(storage Storage, config *MemoryConfig) *SharedMemory

NewSharedMemory creates a new shared memory instance

func (*SharedMemory) Access

func (m *SharedMemory) Access(ctx context.Context, agentID string, query string, memoryType MemoryType) ([]*SharedMemoryContext, error)

Access retrieves shared memories accessible to the given agent

func (*SharedMemory) SetPermissions

func (m *SharedMemory) SetPermissions(agentID string, permissions *MemoryPermission)

SetPermissions sets memory access permissions for an agent

func (*SharedMemory) Share

func (m *SharedMemory) Share(ctx context.Context, memory *SharedMemoryContext) error

Share stores a memory that can be accessed by other agents

func (*SharedMemory) UpdateRelevance

func (m *SharedMemory) UpdateRelevance(ctx context.Context, memory *SharedMemoryContext, relevance float64) error

UpdateRelevance updates the relevance score of a shared memory

type SharedMemoryContext

type SharedMemoryContext struct {
	// Source indicates which agent shared this memory
	Source string `json:"source"`

	// Target specifies which agents can access this memory (empty means all)
	Target []string `json:"target,omitempty"`

	// Scope defines the context scope (task, process, general)
	Scope MemoryType `json:"scope"`

	// Value is the actual memory content
	Value interface{} `json:"value"`

	// Metadata contains additional context
	Metadata map[string]interface{} `json:"metadata"`

	// Timestamp indicates when this was shared
	Timestamp time.Time `json:"timestamp"`

	// Relevance indicates how relevant this context is (0-1)
	Relevance float64 `json:"relevance,omitempty"`
}

SharedMemoryContext represents shared memory between agents

type ShortTermMemory

type ShortTermMemory struct {
	*BaseMemory
}

ShortTermMemory represents a memory component for transient data

func NewShortTermMemory

func NewShortTermMemory(storage Storage, config *MemoryConfig) *ShortTermMemory

NewShortTermMemory creates a new short-term memory instance

func (*ShortTermMemory) Reset

func (m *ShortTermMemory) Reset(ctx context.Context) error

Reset clears all stored items

func (*ShortTermMemory) Save

func (m *ShortTermMemory) Save(value string, metadata map[string]interface{}, source string, scope MemoryScope, expiresAt *time.Time) error

Save stores a value in short-term memory

func (*ShortTermMemory) Search

func (m *ShortTermMemory) Search(query *MemoryQuery) ([]MemoryResult, error)

Search performs a search over stored items

type ShortTermMemoryItem

type ShortTermMemoryItem struct {
	Data      interface{}            `json:"data"`
	Metadata  map[string]interface{} `json:"metadata"`
	Agent     string                 `json:"agent,omitempty"`
	Timestamp time.Time              `json:"timestamp"`
}

ShortTermMemoryItem represents an item in short-term memory

type SimpleEmbedder

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

SimpleEmbedder provides basic local embeddings without external API

func NewSimpleEmbedder

func NewSimpleEmbedder(dimension int) *SimpleEmbedder

NewSimpleEmbedder creates a new SimpleEmbedder instance

func (*SimpleEmbedder) Dimension

func (e *SimpleEmbedder) Dimension() int

Dimension returns the dimension of the embeddings

func (*SimpleEmbedder) Embed

func (e *SimpleEmbedder) Embed(text string) ([]float32, error)

Embed generates a simple deterministic vector based on the text

type Storage

type Storage interface {
	// Save stores a memory item
	Save(ctx context.Context, item *StorageItem) error

	// Search finds memories matching the query
	Search(ctx context.Context, query string, maxResults int) ([]*StorageItem, error)

	// Reset clears all stored memories
	Reset(ctx context.Context) error
}

Storage defines the interface for memory storage backends

func NewStorage

func NewStorage(ctx context.Context, config *StorageConfig, baseDir string) (Storage, error)

NewStorage creates a new storage instance based on the provided configuration

type StorageConfig

type StorageConfig struct {
	// Provider specifies the storage provider to use
	Provider StorageProvider `json:"provider"`

	// Path is the storage location (e.g. file path, connection string)
	Path string `json:"path"`

	// MaxSize is the maximum number of items to store
	MaxSize int `json:"max_size"`

	// CleanupInterval is how often to remove expired items
	CleanupInterval time.Duration `json:"cleanup_interval"`

	// Additional provider-specific options
	Options map[string]interface{} `json:"options"`
}

StorageConfig defines configuration options for storage backends

type StorageItem

type StorageItem struct {
	Value     string                 `json:"value"`
	Metadata  map[string]interface{} `json:"metadata"`
	Source    string                 `json:"source"`
	Scope     MemoryScope            `json:"scope"`
	Type      MemoryType             `json:"type"`
	Score     float64                `json:"score,omitempty"`
	ExpiresAt *time.Time             `json:"expires_at,omitempty"`
	Timestamp time.Time              `json:"timestamp"`
}

StorageItem represents a stored memory item

type StorageProvider

type StorageProvider string

StorageProvider defines the type of storage provider

const (
	// ProviderLocal uses local storage (SQLite/files)
	ProviderLocal StorageProvider = "local"
	// ProviderRAG uses RAG storage with vector embeddings
	ProviderRAG StorageProvider = "rag"
	// ProviderMem0 uses Mem0 external service
	ProviderMem0 StorageProvider = "mem0"
)

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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