memory

package
v0.6.1 Latest Latest
Warning

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

Go to latest
Published: Feb 3, 2026 License: MIT Imports: 16 Imported by: 0

Documentation

Overview

Package memory handles fact extraction and people management.

This package coordinates the Archivist agent (LLM-powered extraction) with storage repositories to maintain the user's long-term memory.

Key Functions:

  • ProcessSession: Extract facts from archived topic
  • applyFactUpdates: Apply add/update/delete operations from Archivist
  • applyPeopleUpdates: Manage social graph (delegates to people_ops.go)

Archivist Integration:

  • Archivist agent returns Result{Facts, People}
  • This package applies changes to storage
  • Embeddings created for new/updated items

Data Flow:

Archived Topic → Archivist LLM → Result{Facts, People}
                  ↓
               Apply Updates
                  ↓
         Create Embeddings → Store in DB

Fact Types:

  • identity: Core user facts (name, preferences)
  • importance: User-defined importance score (0-100)
  • Facts with importance ≥ 90 always included in profile

People System:

  • People are organized in circles: Work_Inner, Work_Outer, Family, Other
  • Merge operations deduplicate duplicate person records
  • Each person has embedding for semantic search

Thread Safety:

  • Service methods are NOT thread-safe
  • Caller must ensure single ProcessSession per topic at a time

Configuration:

  • Memory.MaxProfileFacts: Maximum facts in profile (default 50)
  • Memory.ConsolidationThreshold: Similarity for fact dedup (default 0.85)

Index

Constants

View Source
const (
	OperationAdd    = "add"
	OperationUpdate = "update"
	OperationDelete = "delete"
)

Константы для операций

Variables

This section is empty.

Functions

func RecordFactOperation added in v0.3.0

func RecordFactOperation(userID int64, operation string)

RecordFactOperation записывает операцию с фактом.

func RecordMemoryExtraction added in v0.3.0

func RecordMemoryExtraction(durationSeconds float64)

RecordMemoryExtraction записывает время извлечения фактов.

func RecordTopicProcessing added in v0.3.0

func RecordTopicProcessing(durationSeconds float64)

RecordTopicProcessing записывает время обработки топика.

func SetTopicsTotal added in v0.3.0

func SetTopicsTotal(userID int64, count int)

SetTopicsTotal устанавливает количество топиков для пользователя.

Types

type FactStats added in v0.3.0

type FactStats struct {
	Created int
	Updated int
	Deleted int
	// People stats (v0.5.1)
	PeopleAdded   int
	PeopleUpdated int
	PeopleMerged  int
	// Usage tracking from API calls
	PromptTokens     int
	CompletionTokens int
	EmbeddingTokens  int
	Cost             *float64
}

FactStats contains statistics about fact processing.

func (*FactStats) AddChatUsage added in v0.3.0

func (s *FactStats) AddChatUsage(promptTokens, completionTokens int, cost *float64)

AddChatUsage adds usage from a chat completion response.

func (*FactStats) AddEmbeddingUsage added in v0.3.0

func (s *FactStats) AddEmbeddingUsage(tokens int, cost *float64)

AddEmbeddingUsage adds usage from an embedding response.

type MemoryUpdate

type MemoryUpdate struct {
	Added []struct {
		Relation   string `json:"relation"`
		Content    string `json:"content"`
		Category   string `json:"category"`
		Type       string `json:"type"`
		Importance int    `json:"importance"`
		Reason     string `json:"reason"`
	} `json:"added"`
	Updated []struct {
		ID         int64  `json:"id"`
		Content    string `json:"content"`
		Type       string `json:"type,omitempty"`
		Importance int    `json:"importance"`
		Reason     string `json:"reason"`
	} `json:"updated"`
	Removed []struct {
		ID     int64  `json:"id"`
		Reason string `json:"reason"`
	} `json:"removed"`
}

MemoryUpdate represents the changes returned by the LLM

type PeopleStats added in v0.5.1

type PeopleStats struct {
	Added           int
	Updated         int
	Merged          int
	EmbeddingTokens int
	EmbeddingCost   *float64
}

PeopleStats contains statistics about people processing.

type Service

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

func NewService

func NewService(logger *slog.Logger, cfg *config.Config, factRepo storage.FactRepository, userRepo storage.UserRepository, factHistoryRepo storage.FactHistoryRepository, orClient openrouter.Client, translator *i18n.Translator) *Service

func (*Service) ProcessSession

func (s *Service) ProcessSession(ctx context.Context, userID int64, messages []storage.Message, referenceDate time.Time, topicID int64) error

func (*Service) ProcessSessionWithStats added in v0.3.0

func (s *Service) ProcessSessionWithStats(ctx context.Context, userID int64, messages []storage.Message, referenceDate time.Time, topicID int64) (FactStats, error)

ProcessSessionWithStats processes a session and returns statistics about fact changes.

func (*Service) SetAgentLogger added in v0.4.8

func (s *Service) SetAgentLogger(logger *agentlog.Logger)

func (*Service) SetArchivistAgent added in v0.5.0

func (s *Service) SetArchivistAgent(a agent.Agent)

SetArchivistAgent sets the fact extraction agent.

func (*Service) SetPeopleRepository added in v0.5.1

func (s *Service) SetPeopleRepository(pr storage.PeopleRepository)

SetPeopleRepository sets the people repository for person extraction.

func (*Service) SetTopicRepository added in v0.4.8

func (s *Service) SetTopicRepository(tr storage.TopicRepository)

func (*Service) SetVectorSearcher

func (s *Service) SetVectorSearcher(vs VectorSearcher)

type VectorSearcher

type VectorSearcher interface {
	FindSimilarFacts(ctx context.Context, userID int64, embedding []float32, threshold float32) ([]storage.Fact, error)
}

Jump to

Keyboard shortcuts

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