memory

package
v1.6.0 Latest Latest
Warning

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

Go to latest
Published: Mar 6, 2026 License: MIT Imports: 13 Imported by: 0

Documentation

Index

Constants

View Source
const (
	MemoryTypeEpisodic   = memorycore.MemoryEpisodic   // Event-based memories
	MemoryTypeSemantic   = memorycore.MemorySemantic   // Factual knowledge
	MemoryTypeWorking    = memorycore.MemoryWorking    // Short-term context
	MemoryTypeProcedural = memorycore.MemoryProcedural // How-to knowledge
)

Memory type constants — convenience aliases for memorycore.MemoryKind values.

Variables

View Source
var ErrMemoryNotFound = fmt.Errorf("memory not found")

未找到内存时返回 Err Memory Not Found 。

Functions

This section is empty.

Types

type BatchVectorStore added in v1.0.0

type BatchVectorStore interface {
	rag.LowLevelVectorStore
	BatchStore(ctx context.Context, items []VectorItem) error
}

BatchVectorStore extends LowLevelVectorStore with batch operations. This is memory-specific and not part of the shared rag interface.

type CompletionFunc added in v1.5.0

type CompletionFunc func(ctx context.Context, systemPrompt, userPrompt string) (string, error)

CompletionFunc abstracts LLM completion for the observer.

type ConsolidationStrategy

type ConsolidationStrategy interface {
	// 判断是否应该整合
	ShouldConsolidate(ctx context.Context, memory any) bool

	// 执行整合
	Consolidate(ctx context.Context, memories []any) error
}

ConsolidationStrategy 整合策略接口

type DBClient added in v1.5.0

type DBClient interface {
	Exec(ctx context.Context, query string, args ...any) error
	Query(ctx context.Context, query string, args ...any) (DBRows, error)
}

DBClient abstracts SQL database operations. Compatible with agent.PostgreSQLClient — the composition root wires the same adapter used by PostgreSQLCheckpointStore.

type DBRows added in v1.5.0

type DBRows interface {
	Next() bool
	Scan(dest ...any) error
	Close() error
}

DBRows abstracts database row iteration.

type DecayConfig

type DecayConfig struct {
	RecencyWeight   float64       `json:"recency_weight"`   // Weight for recency score (0-1)
	RelevanceWeight float64       `json:"relevance_weight"` // Weight for relevance score (0-1)
	UtilityWeight   float64       `json:"utility_weight"`   // Weight for utility score (0-1)
	DecayThreshold  float64       `json:"decay_threshold"`  // Score below which memories are pruned
	DecayInterval   time.Duration `json:"decay_interval"`   // How often to run decay
	MaxMemories     int           `json:"max_memories"`     // Maximum memories to retain
	HalfLife        time.Duration `json:"half_life"`        // Time for recency score to halve
}

DecayConfig配置了智能衰变机制.

func DefaultDecayConfig

func DefaultDecayConfig() DecayConfig

默认DecayConfig 返回合理的默认值 。

type DecayResult

type DecayResult struct {
	Timestamp   time.Time `json:"timestamp"`
	TotalBefore int       `json:"total_before"`
	TotalAfter  int       `json:"total_after"`
	PrunedCount int       `json:"pruned_count"`
	PrunedIDs   []string  `json:"pruned_ids,omitempty"`
}

衰变Result包含衰变操作的结果.

type DecayStats

type DecayStats struct {
	TotalMemories    int     `json:"total_memories"`
	AverageScore     float64 `json:"average_score"`
	AverageRecency   float64 `json:"average_recency"`
	AverageRelevance float64 `json:"average_relevance"`
	AverageUtility   float64 `json:"average_utility"`
}

DecayStats包含了关于记忆库的统计数据.

type Embedder

type Embedder interface {
	Embed(ctx context.Context, text string) ([]float32, error)
}

嵌入器生成文字嵌入.

type EnhancedMemoryConfig

type EnhancedMemoryConfig struct {
	// 短期记忆配置
	ShortTermTTL     time.Duration `json:"short_term_ttl"`      // 短期记忆 TTL
	ShortTermMaxSize int           `json:"short_term_max_size"` // 最大条目数

	// 工作记忆配置
	WorkingMemorySize int `json:"working_memory_size"` // 工作记忆容量

	// 长期记忆配置
	LongTermEnabled bool `json:"long_term_enabled"` // 是否启用长期记忆
	VectorDimension int  `json:"vector_dimension"`  // 向量维度

	// 情节记忆配置
	EpisodicEnabled   bool          `json:"episodic_enabled"`   // 是否启用情节记忆
	EpisodicRetention time.Duration `json:"episodic_retention"` // 情节记忆保留时间

	// 语义记忆配置
	SemanticEnabled bool `json:"semantic_enabled"` // 是否启用语义记忆

	// 观测记忆配置
	ObservationEnabled bool           `json:"observation_enabled"` // 是否启用观测记忆
	ObserverConfig     ObserverConfig `json:"observer_config"`     // Observer 配置

	// 记忆整合配置
	ConsolidationEnabled  bool          `json:"consolidation_enabled"`  // 是否启用记忆整合
	ConsolidationInterval time.Duration `json:"consolidation_interval"` // 整合间隔
}

EnhancedMemoryConfig 增强记忆配置

func DefaultEnhancedMemoryConfig

func DefaultEnhancedMemoryConfig() EnhancedMemoryConfig

DefaultEnhancedMemoryConfig 默认配置

type EnhancedMemorySystem

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

EnhancedMemorySystem 增强的多层记忆系统 实现短期、工作、长期、情节、语义和观测记忆

func NewDefaultEnhancedMemorySystem

func NewDefaultEnhancedMemorySystem(config EnhancedMemoryConfig, logger *zap.Logger) *EnhancedMemorySystem

NewDefault Enhanced MemorySystem 创建了带有memory默认商店的增强记忆系统. 它旨在地方发展、测试和快速启动。

func NewEnhancedMemorySystem

func NewEnhancedMemorySystem(
	shortTerm MemoryStore,
	working MemoryStore,
	longTerm rag.LowLevelVectorStore,
	episodic EpisodicStore,
	semantic KnowledgeGraph,
	observationStore ObservationStore,
	config EnhancedMemoryConfig,
	logger *zap.Logger,
) *EnhancedMemorySystem

NewEnhancedMemorySystem 创建增强记忆系统

func (*EnhancedMemorySystem) AddConsolidationStrategy

func (m *EnhancedMemorySystem) AddConsolidationStrategy(strategy ConsolidationStrategy) error

添加整合战略增加了整合战略.

func (*EnhancedMemorySystem) AddDefaultConsolidationStrategies

func (m *EnhancedMemorySystem) AddDefaultConsolidationStrategies() error

添加 Default Construction 战略安装了一套最低限度的安全内置策略 : - 短期至短期 - 工作记忆,每个代理 - 可选地促进已经包含向量的长期存储的短期记忆

func (*EnhancedMemorySystem) AddKnowledge

func (m *EnhancedMemorySystem) AddKnowledge(ctx context.Context, entity *Entity) error

AddKnowledge 添加知识(实体和关系)

func (*EnhancedMemorySystem) AddKnowledgeRelation

func (m *EnhancedMemorySystem) AddKnowledgeRelation(ctx context.Context, relation *Relation) error

AddKnowledgeRelation 添加知识关系

func (*EnhancedMemorySystem) BuildObservationContext added in v1.5.0

func (m *EnhancedMemorySystem) BuildObservationContext(ctx context.Context, agentID string, limit int) (string, error)

BuildObservationContext 构建观测上下文摘要,可直接拼接到 system prompt。

func (*EnhancedMemorySystem) ClearWorking

func (m *EnhancedMemorySystem) ClearWorking(ctx context.Context, agentID string) error

ClearWorking 清除工作记忆

func (*EnhancedMemorySystem) ConsolidateOnce

func (m *EnhancedMemorySystem) ConsolidateOnce(ctx context.Context) error

合并后启动一次合并运行(对手工运行和测试有用)。

func (*EnhancedMemorySystem) EnableObservationPipeline added in v1.5.0

func (m *EnhancedMemorySystem) EnableObservationPipeline(completeFn CompletionFunc)

EnableObservationPipeline 启用观测管线(Observer + Reflector), 需要 LLM CompletionFunc 来驱动压缩与精炼。

func (*EnhancedMemorySystem) GetRecentObservations added in v1.5.0

func (m *EnhancedMemorySystem) GetRecentObservations(ctx context.Context, agentID string, limit int) ([]Observation, error)

GetRecentObservations 从 Store 加载最近的观测记录。

func (*EnhancedMemorySystem) LoadShortTerm

func (m *EnhancedMemorySystem) LoadShortTerm(ctx context.Context, agentID string, limit int) ([]types.MemoryEntry, error)

LoadShortTerm 加载短期记忆

func (*EnhancedMemorySystem) LoadWorking

func (m *EnhancedMemorySystem) LoadWorking(ctx context.Context, agentID string) ([]types.MemoryEntry, error)

LoadWorking 加载工作记忆

func (*EnhancedMemorySystem) ProcessObservation added in v1.5.0

func (m *EnhancedMemorySystem) ProcessObservation(ctx context.Context, agentID string, messages []types.Message) (*Observation, error)

ProcessObservation 对一批对话消息执行观测:Observer 压缩 -> Reflector 精炼 -> Store 持久化。

func (*EnhancedMemorySystem) QueryEpisodes

func (m *EnhancedMemorySystem) QueryEpisodes(ctx context.Context, query EpisodicQuery) ([]types.EpisodicEvent, error)

QueryEpisodes 查询情节

func (*EnhancedMemorySystem) QueryKnowledge

func (m *EnhancedMemorySystem) QueryKnowledge(ctx context.Context, entityID string) (*Entity, error)

QueryKnowledge 查询知识

func (*EnhancedMemorySystem) RecordEpisode

func (m *EnhancedMemorySystem) RecordEpisode(ctx context.Context, event *types.EpisodicEvent) error

RecordEpisode 记录情节

func (*EnhancedMemorySystem) SaveLongTerm

func (m *EnhancedMemorySystem) SaveLongTerm(ctx context.Context, agentID string, content string, vector []float64, metadata map[string]any) error

SaveLongTerm 保存长期记忆(向量化)

func (*EnhancedMemorySystem) SaveShortTerm

func (m *EnhancedMemorySystem) SaveShortTerm(ctx context.Context, agentID string, content string, metadata map[string]any) error

SaveShortTerm 保存短期记忆

func (*EnhancedMemorySystem) SaveShortTermWithVector

func (m *EnhancedMemorySystem) SaveShortTermWithVector(
	ctx context.Context,
	agentID string,
	content string,
	vector []float64,
	metadata map[string]any,
) error

保存ShortTermWith Vector 保存一个短期内存条目并附加元数据中的向量. 内建的合并战略可以促进此类条目的长期记忆。

func (*EnhancedMemorySystem) SaveWorking

func (m *EnhancedMemorySystem) SaveWorking(ctx context.Context, agentID string, content string, metadata map[string]any) error

SaveWorking 保存工作记忆

func (*EnhancedMemorySystem) SearchLongTerm

func (m *EnhancedMemorySystem) SearchLongTerm(ctx context.Context, agentID string, queryVector []float64, topK int) ([]rag.LowLevelSearchResult, error)

SearchLongTerm 搜索长期记忆 When a LongTermRetriever is set, it is used instead of raw vector search.

func (*EnhancedMemorySystem) SetLongTermRetriever added in v1.6.0

func (m *EnhancedMemorySystem) SetLongTermRetriever(r LongTermRetriever)

SetLongTermRetriever injects a higher-quality retriever (e.g. HybridRetriever from the RAG pipeline) for long-term memory search.

func (*EnhancedMemorySystem) StartConsolidation

func (m *EnhancedMemorySystem) StartConsolidation(ctx context.Context) error

StartConsolidation 启动记忆整合

func (*EnhancedMemorySystem) StopConsolidation

func (m *EnhancedMemorySystem) StopConsolidation() error

StopConsolidation 停止记忆整合

type Entity

type Entity struct {
	ID         string         `json:"id"`
	Type       string         `json:"type"`
	Name       string         `json:"name"`
	Properties map[string]any `json:"properties"`
	CreatedAt  time.Time      `json:"created_at"`
	UpdatedAt  time.Time      `json:"updated_at"`
}

Entity 实体

type Episode

type Episode struct {
	ID           string         `json:"id"`
	Timestamp    time.Time      `json:"timestamp"`
	Context      string         `json:"context"`
	Action       string         `json:"action"`
	Result       string         `json:"result"`
	Emotion      string         `json:"emotion,omitempty"`
	Importance   float64        `json:"importance"`
	Participants []string       `json:"participants,omitempty"`
	Metadata     map[string]any `json:"metadata,omitempty"`
}

第一部代表一集/活动.

type EpisodicMemory

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

EpisodicMemory存储基于事件的经验.

func NewEpisodicMemory

func NewEpisodicMemory(maxSize int, logger *zap.Logger) *EpisodicMemory

NewEpisodic Memory创建了一款新的偶联记忆商店.

func (*EpisodicMemory) Recall

func (m *EpisodicMemory) Recall(limit int) []*Episode

召回最近的一些事件。

func (*EpisodicMemory) Search

func (m *EpisodicMemory) Search(query string, limit int) []*Episode

按上下文进行搜索 。

func (*EpisodicMemory) Store

func (m *EpisodicMemory) Store(ep *Episode)

存储新剧集。

type EpisodicQuery

type EpisodicQuery struct {
	AgentID   string
	Type      string
	StartTime time.Time
	EndTime   time.Time
	Limit     int
}

EpisodicQuery 情节查询

type EpisodicStore

type EpisodicStore interface {
	// 记录事件
	RecordEvent(ctx context.Context, event *types.EpisodicEvent) error

	// 查询事件
	QueryEvents(ctx context.Context, query EpisodicQuery) ([]types.EpisodicEvent, error)

	// 获取时间线
	GetTimeline(ctx context.Context, agentID string, start, end time.Time) ([]types.EpisodicEvent, error)
}

EpisodicStore 情节记忆存储接口

type Fact

type Fact struct {
	ID         string    `json:"id"`
	Subject    string    `json:"subject"`
	Predicate  string    `json:"predicate"`
	Object     string    `json:"object"`
	Confidence float64   `json:"confidence"`
	Source     string    `json:"source,omitempty"`
	Embedding  []float32 `json:"embedding,omitempty"`
	CreatedAt  time.Time `json:"created_at"`
	UpdatedAt  time.Time `json:"updated_at"`
}

事实代表了事实知识。

type InMemoryEpisodicStore

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

InMemoryEpisodicStore 基于内存的情节记忆存储实现。 适用于本地开发、测试和小规模部署场景。

func NewInMemoryEpisodicStore

func NewInMemoryEpisodicStore(logger *zap.Logger) *InMemoryEpisodicStore

NewInMemoryEpisodicStore 创建内存情节记忆存储。

func (*InMemoryEpisodicStore) GetTimeline

func (s *InMemoryEpisodicStore) GetTimeline(ctx context.Context, agentID string, start, end time.Time) ([]types.EpisodicEvent, error)

GetTimeline 获取指定 agent 在时间范围内的事件时间线。 结果按时间正序排列(最早的在前)。

func (*InMemoryEpisodicStore) QueryEvents

QueryEvents 按条件查询情节事件。 支持按 agentID、事件类型和时间范围过滤,结果按时间倒序排列。

func (*InMemoryEpisodicStore) RecordEvent

func (s *InMemoryEpisodicStore) RecordEvent(ctx context.Context, event *types.EpisodicEvent) error

RecordEvent 记录一个情节事件。

type InMemoryKnowledgeGraph

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

InMemoryKnowledgeGraph 基于内存的知识图谱实现。 适用于本地开发、测试和小规模部署场景。

func NewInMemoryKnowledgeGraph

func NewInMemoryKnowledgeGraph(logger *zap.Logger) *InMemoryKnowledgeGraph

NewInMemoryKnowledgeGraph 创建内存知识图谱。

func (*InMemoryKnowledgeGraph) AddEntity

func (g *InMemoryKnowledgeGraph) AddEntity(ctx context.Context, entity *Entity) error

AddEntity 添加实体到知识图谱。

func (*InMemoryKnowledgeGraph) AddRelation

func (g *InMemoryKnowledgeGraph) AddRelation(ctx context.Context, relation *Relation) error

AddRelation 添加关系到知识图谱。

func (*InMemoryKnowledgeGraph) FindPath

func (g *InMemoryKnowledgeGraph) FindPath(ctx context.Context, fromID, toID string, maxDepth int) ([][]string, error)

FindPath 在知识图谱中查找从 fromID 到 toID 的路径。 maxDepth 限制搜索深度,返回所有找到的路径(每条路径为实体 ID 序列)。

func (*InMemoryKnowledgeGraph) QueryEntity

func (g *InMemoryKnowledgeGraph) QueryEntity(ctx context.Context, id string) (*Entity, error)

QueryEntity 按 ID 查询实体。

func (*InMemoryKnowledgeGraph) QueryRelations

func (g *InMemoryKnowledgeGraph) QueryRelations(ctx context.Context, entityID string, relationType string) ([]Relation, error)

QueryRelations 查询与指定实体相关的关系。 如果 relationType 非空,则只返回匹配类型的关系。

type InMemoryMemoryStore

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

InMemory MemoryStore是一款在TTL支持下的简单记忆Store执行. 它用于地方发展、测试和小规模部署。

func NewInMemoryMemoryStore

func NewInMemoryMemoryStore(config InMemoryMemoryStoreConfig, logger *zap.Logger) *InMemoryMemoryStore

func (*InMemoryMemoryStore) Clear

func (s *InMemoryMemoryStore) Clear(ctx context.Context) error

func (*InMemoryMemoryStore) Delete

func (s *InMemoryMemoryStore) Delete(ctx context.Context, key string) error

func (*InMemoryMemoryStore) List

func (s *InMemoryMemoryStore) List(ctx context.Context, pattern string, limit int) ([]any, error)

func (*InMemoryMemoryStore) Load

func (s *InMemoryMemoryStore) Load(ctx context.Context, key string) (any, error)

func (*InMemoryMemoryStore) Save

func (s *InMemoryMemoryStore) Save(ctx context.Context, key string, value any, ttl time.Duration) error

type InMemoryMemoryStoreConfig

type InMemoryMemoryStoreConfig struct {
	// Max Entries是本商店条目的全球封顶.
	// 0表示无限.
	MaxEntries int

	// 现在用于测试。 默认时间 。 现在。
	Now func() time.Time
}

type InMemoryObservationStore added in v1.5.0

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

InMemoryObservationStore is a simple in-memory implementation for dev/test.

func NewInMemoryObservationStore added in v1.5.0

func NewInMemoryObservationStore() *InMemoryObservationStore

func (*InMemoryObservationStore) LoadByDateRange added in v1.5.0

func (s *InMemoryObservationStore) LoadByDateRange(_ context.Context, agentID string, start, end time.Time) ([]Observation, error)

func (*InMemoryObservationStore) LoadRecent added in v1.5.0

func (s *InMemoryObservationStore) LoadRecent(_ context.Context, agentID string, limit int) ([]Observation, error)

func (*InMemoryObservationStore) Save added in v1.5.0

type InMemoryVectorStore

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

InMemoryVectorStore是增强MemorySystem的基本矢量执行. 它支持通过平等进行元数据过滤和同位素相似性搜索.

func NewInMemoryVectorStore

func NewInMemoryVectorStore(config InMemoryVectorStoreConfig, logger *zap.Logger) *InMemoryVectorStore

func (*InMemoryVectorStore) BatchStore

func (s *InMemoryVectorStore) BatchStore(ctx context.Context, items []VectorItem) error

BatchStore 原子地批量存储多个向量项。 整个批次在同一把锁内完成,保证并发读取者不会看到部分写入的状态。

func (*InMemoryVectorStore) Delete

func (s *InMemoryVectorStore) Delete(ctx context.Context, id string) error

func (*InMemoryVectorStore) Search

func (s *InMemoryVectorStore) Search(ctx context.Context, query []float64, topK int, filter map[string]any) ([]rag.LowLevelSearchResult, error)

func (*InMemoryVectorStore) Store

func (s *InMemoryVectorStore) Store(ctx context.Context, id string, vector []float64, metadata map[string]any) error

type InMemoryVectorStoreConfig

type InMemoryVectorStoreConfig struct {
	// 尺寸在 > 0时验证存储/搜索向量。
	Dimension int

	// MaxEntries limits the number of stored vectors. 0 means unlimited.
	// When the limit is reached, the oldest entry is evicted.
	MaxEntries int

	// 现在用于测试。 默认时间 。 现在。
	Now func() time.Time
}

type IntelligentDecay

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

IntelligentDecay以智能衰变管理内存.

func NewIntelligentDecay

func NewIntelligentDecay(config DecayConfig, logger *zap.Logger) *IntelligentDecay

新智能Decay创建了新的智能衰变管理器.

func (*IntelligentDecay) Add

func (d *IntelligentDecay) Add(item *MemoryItem)

添加一个内存项 。

func (*IntelligentDecay) Decay

衰变运行了一次衰变过程.

func (*IntelligentDecay) Get

func (d *IntelligentDecay) Get(id string) *MemoryItem

获取一个内存项目并更新访问元数据 。

func (*IntelligentDecay) GetStats

func (d *IntelligentDecay) GetStats() DecayStats

GetStats 返回关于记忆库的统计数据.

func (*IntelligentDecay) Search

func (d *IntelligentDecay) Search(queryVector []float64, topK int) []*MemoryItem

搜索通过对查询向量的关联找到记忆 。

func (*IntelligentDecay) Start

func (d *IntelligentDecay) Start(ctx context.Context) error

启动自动衰变进程 。

func (*IntelligentDecay) Stop

func (d *IntelligentDecay) Stop()

停止自动衰变过程 。

func (*IntelligentDecay) UpdateRelevance

func (d *IntelligentDecay) UpdateRelevance(id string, relevance float64) error

更新关联更新一个内存的相关分数.

type KnowledgeGraph

type KnowledgeGraph interface {
	// 添加实体
	AddEntity(ctx context.Context, entity *Entity) error

	// 添加关系
	AddRelation(ctx context.Context, relation *Relation) error

	// 查询实体
	QueryEntity(ctx context.Context, id string) (*Entity, error)

	// 查询关系
	QueryRelations(ctx context.Context, entityID string, relationType string) ([]Relation, error)

	// 路径查询
	FindPath(ctx context.Context, fromID, toID string, maxDepth int) ([][]string, error)
}

KnowledgeGraph 知识图谱接口

type LayeredMemory

type LayeredMemory struct {
	Episodic   *EpisodicMemory
	Semantic   *SemanticMemory
	Working    *WorkingMemory
	Procedural *ProceduralMemory
	// contains filtered or unexported fields
}

分层记忆结合了所有的内存类型.

func NewLayeredMemory

func NewLayeredMemory(config LayeredMemoryConfig, logger *zap.Logger) *LayeredMemory

NewLayered Memory创造了一个新的分层记忆系统.

func (*LayeredMemory) Export

func (lm *LayeredMemory) Export() ([]byte, error)

导出全部内存到 JSON 。

type LayeredMemoryConfig

type LayeredMemoryConfig struct {
	EpisodicMaxSize  int
	WorkingCapacity  int
	WorkingTTL       time.Duration
	Embedder         Embedder
	ProceduralConfig ProceduralConfig
}

分层的MemoryConfig配置分层内存.

type LongTermRetriever added in v1.6.0

type LongTermRetriever interface {
	Retrieve(ctx context.Context, query string, queryEmbedding []float64) ([]rag.RetrievalResult, error)
}

LongTermRetriever provides a higher-quality retrieval path for long-term memory search. When set, it replaces the raw LowLevelVectorStore.Search with a RAG pipeline (e.g. BM25+Vector+Rerank fusion).

type MaxPerAgentPrunerStrategy

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

MaxPerAgentPrunerStrategy为给定的密钥前缀保留每个代理的最新N条目. 它要求每个内存值都携带"键"和"agent id"字段(或可解析键).

func NewMaxPerAgentPrunerStrategy

func NewMaxPerAgentPrunerStrategy(prefix string, store MemoryStore, max int, logger *zap.Logger) *MaxPerAgentPrunerStrategy

func (*MaxPerAgentPrunerStrategy) Consolidate

func (s *MaxPerAgentPrunerStrategy) Consolidate(ctx context.Context, memories []any) error

func (*MaxPerAgentPrunerStrategy) ShouldConsolidate

func (s *MaxPerAgentPrunerStrategy) ShouldConsolidate(ctx context.Context, memory any) bool

type MemoryConsolidator

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

MemoryConsolidator 记忆整合器

func NewMemoryConsolidator

func NewMemoryConsolidator(system *EnhancedMemorySystem, logger *zap.Logger) *MemoryConsolidator

NewMemoryConsolidator 创建记忆整合器

func (*MemoryConsolidator) AddStrategy

func (c *MemoryConsolidator) AddStrategy(strategy ConsolidationStrategy)

AddStrategy 添加整合策略

func (*MemoryConsolidator) Start

func (c *MemoryConsolidator) Start(ctx context.Context) error

Start 启动整合器

func (*MemoryConsolidator) Stop

func (c *MemoryConsolidator) Stop() error

Stop 停止整合器

type MemoryEntry

type MemoryEntry struct {
	ID          string                `json:"id"`
	Type        memorycore.MemoryKind `json:"type"`
	Content     string                `json:"content"`
	Embedding   []float32             `json:"embedding,omitempty"`
	Importance  float64               `json:"importance"`
	AccessCount int                   `json:"access_count"`
	CreatedAt   time.Time             `json:"created_at"`
	LastAccess  time.Time             `json:"last_access"`
	ExpiresAt   *time.Time            `json:"expires_at,omitempty"`
	Metadata    map[string]any        `json:"metadata,omitempty"`
	Relations   []string              `json:"relations,omitempty"`
}

MemoryEntry 代表单个内存条目.

type MemoryItem

type MemoryItem struct {
	ID           string         `json:"id"`
	Content      string         `json:"content"`
	Vector       []float64      `json:"vector,omitempty"`
	CreatedAt    time.Time      `json:"created_at"`
	LastAccessed time.Time      `json:"last_accessed"`
	AccessCount  int            `json:"access_count"`
	Relevance    float64        `json:"relevance"` // User-defined relevance (0-1)
	Utility      float64        `json:"utility"`   // Computed utility based on usage
	Tags         []string       `json:"tags,omitempty"`
	Metadata     map[string]any `json:"metadata,omitempty"`
}

内存项目代表着一个带有衰变元数据的内存项目.

func (*MemoryItem) CompositeScore

func (m *MemoryItem) CompositeScore(config DecayConfig) float64

复合分数计算出复合衰减分数.

func (*MemoryItem) RecencyScore

func (m *MemoryItem) RecencyScore(halfLife time.Duration) float64

RecencyScore使用指数衰减计算Recency分数.

type MemoryStore

type MemoryStore interface {
	Save(ctx context.Context, key string, value any, ttl time.Duration) error
	Load(ctx context.Context, key string) (any, error)
	Delete(ctx context.Context, key string) error
	List(ctx context.Context, pattern string, limit int) ([]any, error)
	Clear(ctx context.Context) error
}

MemoryStore 通用记忆存储接口

type Observation added in v1.5.0

type Observation struct {
	ID        string         `json:"id"`
	AgentID   string         `json:"agent_id"`
	Date      string         `json:"date"`
	Content   string         `json:"content"`
	CreatedAt time.Time      `json:"created_at"`
	Metadata  map[string]any `json:"metadata,omitempty"`
}

Observation is a single dated observation compressed from conversation history.

type ObservationStore added in v1.5.0

type ObservationStore interface {
	Save(ctx context.Context, obs Observation) error
	LoadRecent(ctx context.Context, agentID string, limit int) ([]Observation, error)
	LoadByDateRange(ctx context.Context, agentID string, start, end time.Time) ([]Observation, error)
}

ObservationStore persists and retrieves observations.

type Observer added in v1.5.0

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

Observer compresses conversation history into dated observation logs.

func NewObserver added in v1.5.0

func NewObserver(config ObserverConfig, complete CompletionFunc, logger *zap.Logger) *Observer

NewObserver creates an observer agent.

func (*Observer) Observe added in v1.5.0

func (o *Observer) Observe(ctx context.Context, agentID string, messages []types.Message) (*Observation, error)

Observe compresses a batch of messages into an observation.

type ObserverConfig added in v1.5.0

type ObserverConfig struct {
	MaxMessagesPerBatch       int           `json:"max_messages_per_batch"`
	MinMessagesForObservation int           `json:"min_messages_for_observation"`
	ObservationInterval       time.Duration `json:"observation_interval"`
}

ObserverConfig controls observation generation behavior.

func DefaultObserverConfig added in v1.5.0

func DefaultObserverConfig() ObserverConfig

DefaultObserverConfig returns sensible defaults.

type PostgreSQLObservationStore added in v1.5.0

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

PostgreSQLObservationStore persists observations in PostgreSQL. Reuses the project's agent.PostgreSQLClient interface for consistency with PostgreSQLCheckpointStore.

func NewPostgreSQLObservationStore added in v1.5.0

func NewPostgreSQLObservationStore(ctx context.Context, db DBClient) (*PostgreSQLObservationStore, error)

NewPostgreSQLObservationStore creates a store and initializes the schema.

func (*PostgreSQLObservationStore) LoadByDateRange added in v1.5.0

func (s *PostgreSQLObservationStore) LoadByDateRange(ctx context.Context, agentID string, start, end time.Time) ([]Observation, error)

func (*PostgreSQLObservationStore) LoadRecent added in v1.5.0

func (s *PostgreSQLObservationStore) LoadRecent(ctx context.Context, agentID string, limit int) ([]Observation, error)

func (*PostgreSQLObservationStore) Save added in v1.5.0

type ProceduralConfig

type ProceduralConfig struct {
	MaxProcedures int `json:"max_procedures"`
}

程序Config配置程序内存.

type ProceduralMemory

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

程序记忆存储如何知识。

func NewProceduralMemory

func NewProceduralMemory(config ProceduralConfig, logger *zap.Logger) *ProceduralMemory

新程序记忆创造出一个新的程序记忆.

func (*ProceduralMemory) FindByTrigger

func (m *ProceduralMemory) FindByTrigger(trigger string) []*Procedure

FindByTrigger通过触发找到程序.

func (*ProceduralMemory) Get

func (m *ProceduralMemory) Get(id string) (*Procedure, bool)

获取一个程序 通过身份。

func (*ProceduralMemory) Store

func (m *ProceduralMemory) Store(proc *Procedure)

存储存储程序。

type Procedure

type Procedure struct {
	ID          string   `json:"id"`
	Name        string   `json:"name"`
	Description string   `json:"description"`
	Steps       []string `json:"steps"`
	Triggers    []string `json:"triggers"`
	SuccessRate float64  `json:"success_rate"`
	Executions  int      `json:"executions"`
}

程序是一种学习过的程序。

type PromoteShortTermVectorToLongTermStrategy

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

促进短期记忆到长期存储 当它们已经携带元数据中的向量时。

func NewPromoteShortTermVectorToLongTermStrategy

func NewPromoteShortTermVectorToLongTermStrategy(system *EnhancedMemorySystem, logger *zap.Logger) *PromoteShortTermVectorToLongTermStrategy

func (*PromoteShortTermVectorToLongTermStrategy) Consolidate

func (s *PromoteShortTermVectorToLongTermStrategy) Consolidate(ctx context.Context, memories []any) error

func (*PromoteShortTermVectorToLongTermStrategy) ShouldConsolidate

func (s *PromoteShortTermVectorToLongTermStrategy) ShouldConsolidate(ctx context.Context, memory any) bool

type Reflector added in v1.5.0

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

Reflector refines draft observations by checking consistency and accuracy.

func NewReflector added in v1.5.0

func NewReflector(complete CompletionFunc, logger *zap.Logger) *Reflector

NewReflector creates a reflector.

func (*Reflector) Reflect added in v1.5.0

func (r *Reflector) Reflect(ctx context.Context, existing []Observation, draft *Observation) (*Observation, error)

Reflect refines a draft observation against existing observations.

type Relation

type Relation struct {
	ID         string         `json:"id"`
	FromID     string         `json:"from_id"`
	ToID       string         `json:"to_id"`
	Type       string         `json:"type"`
	Properties map[string]any `json:"properties"`
	Weight     float64        `json:"weight"`
	CreatedAt  time.Time      `json:"created_at"`
}

Relation 关系

type SemanticMemory

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

语义记忆存储事实知识.

func NewSemanticMemory

func NewSemanticMemory(embedder Embedder, logger *zap.Logger) *SemanticMemory

NewSemantic Memory创建了一个新的语义记忆商店.

func (*SemanticMemory) GetFact

func (m *SemanticMemory) GetFact(id string) (*Fact, bool)

Get Fact通过身份证检索一个事实.

func (*SemanticMemory) Query

func (m *SemanticMemory) Query(subject string) []*Fact

按主题查询事实。

func (*SemanticMemory) StoreFact

func (m *SemanticMemory) StoreFact(ctx context.Context, fact *Fact) error

StoreFact存储了一个事实。

type VectorItem

type VectorItem struct {
	ID       string
	Vector   []float64
	Metadata map[string]any
}

VectorItem 向量项

type WorkingItem

type WorkingItem struct {
	Key       string    `json:"key"`
	Value     any       `json:"value"`
	Priority  int       `json:"priority"`
	CreatedAt time.Time `json:"created_at"`
	ExpiresAt time.Time `json:"expires_at"`
}

工作 项目是工作记忆中的一个项目。

type WorkingMemory

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

WorkMemory提供短期上下文存储.

func NewWorkingMemory

func NewWorkingMemory(capacity int, ttl time.Duration, logger *zap.Logger) *WorkingMemory

新工作记忆创造出新的工作记忆.

func (*WorkingMemory) Clear

func (m *WorkingMemory) Clear()

清除过期的项目 。

func (*WorkingMemory) Get

func (m *WorkingMemory) Get(key string) (any, bool)

从工作记忆中获取一个值 。

func (*WorkingMemory) GetAll

func (m *WorkingMemory) GetAll() []WorkingItem

Get All 返回所有未过期的项目 。

func (*WorkingMemory) Set

func (m *WorkingMemory) Set(key string, value any, priority int)

设定工作内存中的值 。

Jump to

Keyboard shortcuts

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