memory

package
v0.0.0-...-edaca3c Latest Latest
Warning

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

Go to latest
Published: Jul 22, 2026 License: MIT Imports: 20 Imported by: 0

Documentation

Index

Constants

View Source
const MaxSTMEpisodeAge = 24 * time.Hour
View Source
const PreferenceKeyVerbose = "verbose"

Variables

This section is empty.

Functions

func BuildLTMStoreName

func BuildLTMStoreName(agentID string, userID string) string

func BuildSTMStoreName

func BuildSTMStoreName(agentID string, userID string) string

func BuildSTMTimeIndexName

func BuildSTMTimeIndexName(agentID string, userID string) string

func CategoryPathVectors

func CategoryPathVectors(ctx context.Context, catPath string, embedder ai.Embeddings) ([][]float32, error)

func ComputeVectorHash

func ComputeVectorHash(embedderDim int, texts ...string) string

ComputeVectorHash computes a predictable string hash representing the text content. We optionally include dimensions, but explicitly exclude embedderName so that compatible models (same dims) don't trigger re-vectorization unless content actually changes.

func CosineSimilarity

func CosineSimilarity(a, b []float32) float32

CosineSimilarity computes the mathematical cosine similarity between two vectors.

func Distance

func Distance(a, b []float32, normalized bool) float32

func DotProduct

func DotProduct(a, b []float32) float32

1. THE LIVE SEARCH LOOP (Blazing Fast - No Sqrts, No Divisions) Use this inside your nested category loops to rank your documents.

func EuclideanDistance

func EuclideanDistance(a, b []float32) float32

EuclideanDistance computes the Euclidean distance between two vectors.

func ExtractSTMCreatedAt

func ExtractSTMCreatedAt(payload map[string]any) (int64, bool)

func FastEuclidean

func FastEuclidean(normalizedVectorA, NormalizedVectorB []float32) float32

FastEuclidean outputs the exact same distance metric as traditional Euclidean calculation, but runs up to 4x faster on normalized vectors by utilizing DotProduct internally.

func MigrateFromVector

func MigrateFromVector[T any](ctx context.Context, source ai.VectorStore[T], target MemoryStore[T]) error

MigrateFromVector imports all Centroids and Vectors from a legacy ai.VectorStore (which uses pure math K-Means flat clustering) into the ai/memory MemoryStore as flat Categories and Items.

This allows users to do bulk ingestion using the ultra-fast offline math pipeline, and then migrate the finished taxonomy into the rich Memory DAG for LLM enrichment.

func NormalizeCategoryToken

func NormalizeCategoryToken(text string) string

func NormalizeVector

func NormalizeVector(v []float32) []float32

2. THE ONE-TIME PRE-NORMALIZER Run this ONLY when indexing or slicing local GGUF vectors (like Nomic 256 slices).

func PruneSTMOlderThan

func PruneSTMOlderThan(ctx context.Context, stm btree.BtreeInterface[string, any], stmByTime btree.BtreeInterface[string, any], now time.Time, maxAge time.Duration) (int, error)

func STMTimeIndexKey

func STMTimeIndexKey(createdAt int64, itemID string) string

Types

type Category

type Category struct {
	ID sop.UUID `json:"id"`
	// ParentIDs points to parent Categories, allowing a Directed Acyclic Graph (DAG) / Polyhierarchy.
	// Use-case: A category like "Database Migrations" can belong to both "Release Management"
	// and "Database Administration". Adding the explicit UseCase here gives the LLM
	// the ability to review, validate, and improve these graph edges during deep sleep cycles.
	ParentIDs       []CategoryParent `json:"parents,omitempty"`
	CenterVector    []float32        `json:"center_vector"`               // Mathematical center of this chunk/category
	ChildrenIDs     []sop.UUID       `json:"children_ids,omitempty"`      // IDs of Sub-Categories
	Radius          float32          `json:"radius,omitempty"`            // Size of the cluster
	ItemCount       int              `json:"item_count,omitempty"`        // Number of vectors/items in this bucket
	Name            string           `json:"name,omitempty"`              // Human-readable concept name
	Path            string           `json:"path,omitempty"`              // Full contextual taxonomy path (e.g. "tools / execute_script")
	Description     string           `json:"description,omitempty"`       // Broader context
	SummaryMaxCount int              `json:"summary_max_count,omitempty"` // Maximum number of summaries for items in this category
	VectorHash      string           `json:"vector_hash,omitempty"`       // Hash of EmbedderName + Content to deduplicate vectorization
}

Category represents the semantic Map/Hierarchy (formerly Centroid). Singular form matching Item.

func FindClosestCategories

func FindClosestCategories(vec []float32, categories []*Category, n int) []*Category

FindClosestCategories finds the nearest N categories to the target vector using Euclidean distance.

func FindClosestCategory

func FindClosestCategory(vec []float32, categories []Category) (*Category, float32)

func FindClosestCategoryFromPtrs

func FindClosestCategoryFromPtrs(vec []float32, categories []*Category) (*Category, float32)

FindClosestCategory finds the nearest single category to the target vector using Euclidean distance.

type CategoryParent

type CategoryParent struct {
	ParentID sop.UUID `json:"parent_id"`
	UseCase  string   `json:"use_case,omitempty"` // The explicit justification (can be empty "" for the primary/obvious parent)
}

CategoryParent represents a relationship to a parent category, capturing the explicit operational use-case for this edge in the DAG.

type ChunkData

type ChunkData struct {
	Text        string   `json:"text,omitempty"`        // Small snippet or chunk directly answerable
	Description string   `json:"description,omitempty"` // Contextual description or rationale
	DocumentID  sop.UUID `json:"document_id,omitempty"` // Pointer to the heavyweight Document/Blob (can be NilUUID)
}

ChunkData is a standard struct designed for the generic T in Item[T], specifically formulated for two-stage Retrieval-Augmented Generation (RAG).

type Database

type Database interface {
	ai.Database
	OpenKnowledgeBase(ctx context.Context, name string, tx sop.Transaction, llm ai.Generator, embedder ai.Embeddings, documentMode bool, enableTextSearch ...bool) (*KnowledgeBase[map[string]any], error)
	NewBtree(ctx context.Context, name string, t sop.Transaction) (btree.BtreeInterface[string, any], error)
}

Database is an interface that allows the memory layer to orchestrate its own batched transactions.

type DistanceKey

type DistanceKey struct {
	ParentID sop.UUID // NilUUID for Level 1 Macro-Categories
	Distance float32  // Mathematical distance relative to the bounding anchor
	ID       sop.UUID // ID of the Category
}

DistanceKey represents a distance-based index for sorting categories by distance to the Domain Reference CenterVector.

func (DistanceKey) Compare

func (k DistanceKey) Compare(other any) int

Compare implements btree.Comparer for DistanceKey to enable fast distance-based in indexing, grouped by taxonomy depth and parent node.

type DocIDs

type DocIDs []string

DocIDs stores one or more source document references for an item. It accepts both a single string and a JSON array, which keeps older exports compatible.

func (DocIDs) First

func (d DocIDs) First() string

func (DocIDs) MarshalJSON

func (d DocIDs) MarshalJSON() ([]byte, error)

func (DocIDs) String

func (d DocIDs) String() string

func (*DocIDs) UnmarshalJSON

func (d *DocIDs) UnmarshalJSON(data []byte) error

type Document

type Document struct {
	ID          sop.UUID `json:"id"`
	Title       string   `json:"title,omitempty"`
	URL         string   `json:"url,omitempty"`
	Source      string   `json:"source,omitempty"`
	ContentType string   `json:"content_type,omitempty"` // e.g. "text/markdown", "text/plain"
	Content     string   `json:"content,omitempty"`
	Data        []byte   `json:"data,omitempty"` // For pure blobs, pdf binaries, etc
}

Document represents a large source asset (markdown file, text blob, PDF parsed text, etc). It acts as the canonical reading interface to prevent bloated indexes and context-loss in RAG. Multiple Items (with unique Vectors/Summaries) can point back to this same Document.

type ExportData

type ExportData[T any] struct {
	Config     *KnowledgeBaseConfig `json:"config,omitempty"`
	Categories []*Category          `json:"categories"`
	Documents  []*Document          `json:"documents,omitempty"`
	Items      []ExportItem[T]      `json:"items"`
}

ExportData defines the structure of the KnowledgeBase JSON payload.

type ExportItem

type ExportItem[T any] struct {
	CategoryPath     string      `json:"category"`
	DocID            DocIDs      `json:"doc_id,omitempty"`
	Data             T           `json:"data"`
	Summaries        []string    `json:"summaries,omitempty"`
	SummariesVectors [][]float32 `json:"summaries_vectors,omitempty"`
	Positions        []VectorKey `json:"positions,omitempty"`
	VectorHash       string      `json:"vector_hash,omitempty"`
}

ExportItem dictates what fields from the item are serialized.

type Item

type Item[T any] struct {
	ID         sop.UUID    `json:"id"`
	CategoryID sop.UUID    `json:"category_id"`
	DocID      DocIDs      `json:"doc_id,omitempty"`      // UUID of uploaded documents OR string URI for external docs
	Summaries  []string    `json:"summaries,omitempty"`   // 1 or more distinct, clean sentences for vector indexing
	Data       T           `json:"data"`                  // The application data or structured thought
	Positions  []VectorKey `json:"positions,omitempty"`   // Direct links to its Vectors for O(1) cleanup during Category moves
	VectorHash string      `json:"vector_hash,omitempty"` // Hash of EmbedderName + Content to avoid re-vectorizing unchanged items
}

Item represents the actual content (The "Thought" or Document). Singular form as requested. It is fundamentally mapped to one or more Vector embeddings.

func (*Item[T]) IsConfig

func (item *Item[T]) IsConfig() bool

Returns true if Item is considered the KnowledgeBase's Config item.

func (*Item[T]) IsExternalDocument

func (item *Item[T]) IsExternalDocument() bool

IsExternalDocument returns true if the DocID is populated but is not a valid SOP UUID (e.g. an HTTP/File URI).

func (*Item[T]) IsInternalDocument

func (item *Item[T]) IsInternalDocument() bool

IsInternalDocument returns true if the DocID is a valid SOP UUID, meaning the document is stored natively in the KB.

type ItemKey

type ItemKey struct {
	CategoryID sop.UUID
	ItemID     sop.UUID
}

ItemKey composites the Category and Item identity for physical clustering

func (ItemKey) Compare

func (k ItemKey) Compare(other any) int

Compare implements btree.Comparer for ItemKey to ensure fast B-Tree physical clustering.

type KBDigestHit

type KBDigestHit struct {
	DocID      []string
	Score      float32
	Category   string
	Text       string
	Query      string
	SearchType string
}

func DigestKnowledgeBase

func DigestKnowledgeBase(ctx context.Context, kb *KnowledgeBase[map[string]any], embedder ai.Embeddings, req KBDigestRequest) ([]KBDigestHit, error)

type KBDigestRequest

type KBDigestRequest struct {
	Queries            []string
	PerQueryLimit      int
	MaxResults         int
	MinScore           float32
	UseClosestCategory bool
	KeywordFallback    bool
}

type KnowledgeBase

type KnowledgeBase[T any] struct {
	Store   MemoryStore[T]
	Manager *MemoryManager[T]

	// MaxMathCategoryDistance specifies the max Euclidean distance to cluster centroids
	// to avoid calling the LLM for category categorization. Set to 0.0 or less to disable
	// and always rely on "pristine" LLM categorization.
	MaxMathCategoryDistance float32
	// contains filtered or unexported fields
}

KnowledgeBase provides a clean, unified API for developers. It orchestrates both the storage tables and the LLM memory management.

func (*KnowledgeBase[T]) Close

func (kb *KnowledgeBase[T]) Close(ctx context.Context) error

Close commits any transaction owned by this KnowledgeBase.

func (*KnowledgeBase[T]) DeleteCategories

func (kb *KnowledgeBase[T]) DeleteCategories(ctx context.Context, categoryIDs []sop.UUID) error

func (*KnowledgeBase[T]) DeleteItems

func (kb *KnowledgeBase[T]) DeleteItems(ctx context.Context, itemKeys []ItemKey) error

func (*KnowledgeBase[T]) ExportJSON

func (kb *KnowledgeBase[T]) ExportJSON(ctx context.Context, writer io.Writer) error

ExportJSON serializes the KnowledgeBase contents into a JSON stream.

func (*KnowledgeBase[T]) GetConfig

func (kb *KnowledgeBase[T]) GetConfig(ctx context.Context) (*KnowledgeBaseConfig, error)

GetConfig retrieves the metadata configuration for this KnowledgeBase.

func (*KnowledgeBase[T]) ImportJSON

func (kb *KnowledgeBase[T]) ImportJSON(ctx context.Context, reader io.Reader, persona string, onEnrich ...func(*ExportItem[T])) error

ImportJSON deserializes a JSON stream and ingests it into the KnowledgeBase.

func (*KnowledgeBase[T]) IngestThought

func (kb *KnowledgeBase[T]) IngestThought(
	ctx context.Context,
	text string,
	category string,
	persona string,
	vector []float32,
	data T,
) error

IngestThought securely categorizes and stores a thought. If category is omitted (""), the LLM dynamically categorizes the text, unless it is close enough to an existing category centroid and MaxMathCategoryDistance > 0.

func (*KnowledgeBase[T]) IngestThoughts

func (kb *KnowledgeBase[T]) IngestThoughts(ctx context.Context, thoughts []Thought[T], persona string) error

IngestThoughts securely categorizes and stores an array of thoughts, optimizing latency by clustering queries and sending a batch request to the LLM generator.

func (*KnowledgeBase[T]) Initialize

func (kb *KnowledgeBase[T]) Initialize(ctx context.Context) error

Initialize ensures the knowledge base has an embedder attached based on its persisted config. It uses the configured embedder name and dimension when available, falling back to a simple embedder.

func (*KnowledgeBase[T]) ListCategories

func (kb *KnowledgeBase[T]) ListCategories(ctx context.Context, param ListCategoriesParam) ([]Category, int, error)

func (*KnowledgeBase[T]) ListItems

func (kb *KnowledgeBase[T]) ListItems(ctx context.Context, param ListItemsParam) ([]Item[T], int, error)

func (*KnowledgeBase[T]) Name

func (kb *KnowledgeBase[T]) Name() string

Returns this KnowledgeBase's name.

func (*KnowledgeBase[T]) RefreshSemanticVectors

func (kb *KnowledgeBase[T]) RefreshSemanticVectors(ctx context.Context) error

func (*KnowledgeBase[T]) Search

func (kb *KnowledgeBase[T]) Search(ctx context.Context, requests []SearchRequest[T]) ([][]ai.Hit[T], error)

Search provides one reusable entry point for single or batch retrieval. Precedence: 1. If CategoryPath specified: try CategoryByPath, fallback to CategoryByDistance 2. If no category yet and Text present: use CategoryText embedding to get resolved in CategoryByDistance + TextSearch categories. (BOTH) 3. If no category found: short circuit and return empty 4. Use found categories to do vector search 5. Return matching items

func (*KnowledgeBase[T]) SearchByPath

func (kb *KnowledgeBase[T]) SearchByPath(ctx context.Context, params []PathSearchParam) ([]Item[T], error)

SearchByPath performs hierarchical category path search with dual-mode operation:

MODE 1 - Lexical Fast-Path (O(1)): If exact CategoryPath exists in CategoriesByPath B-Tree, uses direct lookup.

MODE 2 - Semantic Path Navigation (O(D * log N)) - WORLD'S FIRST 🚀: When lexical match fails, performs breakthrough semantic hierarchical drill-down:

  1. Split path: "Engineering/Databases/SQL" → ["Engineering", "Databases", "SQL"]
  2. Root level: Embed first part, search CategoriesByDistance using DomainReference anchor
  3. Nested levels: Embed each part, search CategoriesByDistance using parent CenterVector
  4. Navigate hierarchically through semantic similarity using Triangle Inequality pruning

Revolutionary capabilities:

  • Natural language paths: "ML training optimization" finds "Machine Learning/Model Training"
  • Typo-resistant: "Databse" semantically matches "Databases"
  • Cross-lingual: Chinese paths match English category structure
  • Zero additional storage: Leverages existing CategoriesByDistance infrastructure
  • ACID-compliant: Full transactional guarantees during semantic navigation

This is the only vector database in the world with hierarchical semantic path search. See ai/DYNAMIC_VECTOR_STORE_DESIGN.md Section 12 for full algorithm details.

func (*KnowledgeBase[T]) SetConfig

func (kb *KnowledgeBase[T]) SetConfig(ctx context.Context, config *KnowledgeBaseConfig) error

SetConfig saves the metadata configuration for this KnowledgeBase.

func (*KnowledgeBase[T]) SetTransaction

func (kb *KnowledgeBase[T]) SetTransaction(tx sop.Transaction)

SetTransaction attaches a transaction that should be committed or rolled back when the KnowledgeBase is closed. This is primarily used by the convenience constructor for the filesystem-backed default path.

func (*KnowledgeBase[T]) TriggerSleepCycle

func (kb *KnowledgeBase[T]) TriggerSleepCycle(ctx context.Context) error

TriggerSleepCycle forces the LLM to scan, reflect, and re-organize dense categories.

func (*KnowledgeBase[T]) UpsertCategories

func (kb *KnowledgeBase[T]) UpsertCategories(ctx context.Context, params []UpsertCategoryParam) error

func (*KnowledgeBase[T]) UpsertItems

func (kb *KnowledgeBase[T]) UpsertItems(ctx context.Context, params []UpsertItemParam[T]) error

type KnowledgeBaseConfig

type KnowledgeBaseConfig struct {
	Type                string            `json:"type,omitempty"`
	IsPersona           bool              `json:"is_persona,omitempty"`
	IsExclusive         bool              `json:"is_exclusive,omitempty"`
	Description         string            `json:"description,omitempty"`
	SystemPrompt        string            `json:"system_prompt,omitempty"`
	Embedder            string            `json:"embedder,omitempty"`
	EmbedderDimension   int               `json:"embedder_dimension,omitempty"`
	AllowAutoEnrichment bool              `json:"allowAutoEnrichment,omitempty"`
	AllowedTools        []string          `json:"allowed_tools,omitempty"`
	ToolQueries         []PathSearchParam `json:"tool_queries,omitempty"`
	LastModified        int64             `json:"last_modified,omitempty"`   // Unix timestamp
	LastVectorized      int64             `json:"last_vectorized,omitempty"` // Unix timestamp
	RoutingPrefix       string            `json:"routing_prefix,omitempty"`
	DomainReference     []float32         `json:"domain_reference,omitempty"`
	// DocumentMode flags whether this KB operates in traditional payload mode (Item.Data holds data),
	// or in decoupled RAG references mode where Item.Data points to the canonical large Document(MD).
	DocumentMode      bool `json:"document_mode,omitempty"`
	TextSearchEnabled bool `json:"text_search_enabled,omitempty"` // Controls if keyword/BM25 search is indexed and available
}

type LLM

type LLM[T any] interface {
	// GenerateCategory invokes the model to synthesize a new Category
	// based off the underlying data structure's payload.
	GenerateCategory(ctx context.Context, payload T) (*Category, error)
}

LLM provides an interface to interact with a semantic language model, simulating agentic reasoning to automatically generate Categories for data when it lacks semantic structuring.

type ListCategoriesParam

type ListCategoriesParam struct {
	ParentPath string   `json:"parent_path"` // Optional: restrict list to a specific parent node
	ParentID   sop.UUID `json:"parent_id"`   // Optional: explicit restriction by ID
	Limit      int      `json:"limit"`
	Offset     int      `json:"offset"`
}

type ListItemsParam

type ListItemsParam struct {
	CategoryPath string   `json:"category_path"` // Optional: restrict list to a specific category
	CategoryID   sop.UUID `json:"category_id"`   // Optional: restrict list by explicit ID
	Limit        int      `json:"limit"`
	Offset       int      `json:"offset"`
}

type MemoryManager

type MemoryManager[T any] struct {
	// contains filtered or unexported fields
}

MemoryManager orchestrates the Semantic Anchoring and Asynchronous Sleep Cycle. It interfaces directly with an LLM and an Embedder to completely bypass mathematical (K-Means) clustering in favor of Semantic taxonomies.

func NewMemoryManager

func NewMemoryManager[T any](store MemoryStore[T], llm ai.Generator, embedder ai.Embeddings) *MemoryManager[T]

NewMemoryManager creates a new biomimetic memory orchestrator.

func (*MemoryManager[T]) EnsureCategory

func (m *MemoryManager[T]) EnsureCategory(ctx context.Context, categoryPath string) (sop.UUID, error)

EnsureCategory guarantees a Semantic Anchor physically exists in the B-Tree for a string noun.

func (*MemoryManager[T]) FindClosestCategory

func (m *MemoryManager[T]) FindClosestCategory(ctx context.Context, vector []float32) (*Category, float32, error)

FindClosestCategory evaluates the spatial coordinates logically mapped into categories. This executes mathematically without LLM inference, serving as the fast-path.

func (*MemoryManager[T]) GenerateCategories

func (m *MemoryManager[T]) GenerateCategories(ctx context.Context, texts []string, personaContext string) ([]string, error)

GenerateCategories uses the LLM to deduce a 2-4 word taxonomy category for a batch of raw thoughts.

func (*MemoryManager[T]) GenerateCategory

func (m *MemoryManager[T]) GenerateCategory(ctx context.Context, text string, personaContext string) (string, error)

GenerateCategory uses the LLM to deduce a 2-4 word taxonomy category for a raw thought.

func (*MemoryManager[T]) GenerateSummaries

func (m *MemoryManager[T]) GenerateSummaries(ctx context.Context, dataStr string) ([]string, error)

func (*MemoryManager[T]) GenerateSummariesBatch

func (m *MemoryManager[T]) GenerateSummariesBatch(ctx context.Context, payloads []string) ([][]string, error)

GenerateSummariesBatch splits a batch of data payloads into logical vectors via LLM

func (*MemoryManager[T]) SleepCycle

func (m *MemoryManager[T]) SleepCycle(ctx context.Context) error

SleepCycle performs Asynchronous Memory Consolidation.

type MemoryStore

type MemoryStore[T any] interface {

	// Returns this Memory Store's name.
	Name() string

	// Upsert adds or updates a single item in the store.
	Upsert(ctx context.Context, item Item[T], vec []float32) error

	// UpsertByCategoryPath explicitly assigns a category ignoring spatial routing.
	UpsertByCategoryPath(ctx context.Context, categoryName string, item Item[T], vecs [][]float32) error

	// UpsertByCategoryID inserts data bypassing Category lookup.
	// vecs are DocumentTexts (768 dim), classificationVecs are CategoryTexts (256 dim) for DistanceToCategory.
	UpsertByCategoryID(ctx context.Context, catID sop.UUID, catCenterVector []float32, item Item[T], vecs [][]float32, classificationVecs [][]float32) error

	// UpsertBatch adds or updates multiple items in the store efficiently.
	UpsertBatch(ctx context.Context, items []Item[T], vecs [][]float32) error

	// FindClosestCategory explores the category tree using spatial distance to find the closest matching category.
	FindClosestCategory(ctx context.Context, vector []float32) (*Category, float32, error)

	// SemanticCategoryByPath resolves a category path expressed as pre-embedded vectors into the
	// closest matching Categories at each level of the hierarchy.
	//
	// Given a path "a/b/c" whose parts have been embedded into vectors [va, vb, vc]:
	//   - Level 0 (root): searches CategoriesByDistance with ParentID=NilUUID, anchor=DomainReference
	//   - Level N:        searches CategoriesByDistance with ParentID=prev.ID, anchor=prev.CenterVector
	// The function keeps all best-distance ties per level and returns the final best candidates.
	SemanticCategoryByPath(ctx context.Context, pathVectors [][]float32) ([]*Category, error)

	// Get retrieves a item by its logical ID.
	Get(ctx context.Context, key ItemKey) (*Item[T], error)
	// Delete removes an item by its logical ID.
	Delete(ctx context.Context, key ItemKey) error

	// Query searches for the nearest neighbors to the given vector coordinates.
	// filters is a function that returns true if the item should be included.
	Query(ctx context.Context, vec []float32, opts *SearchOptions[T]) ([]ai.Hit[T], error)

	// QueryItems searches stored items for the already-resolved category.
	// This lets the KnowledgeBase path reuse resolved categories instead of resolving them again.
	QueryItems(ctx context.Context, vec []float32, category *Category, opts *SearchOptions[T]) ([]ai.Hit[T], error)

	// QueryBatch searches for the nearest neighbors for a slice of query vectors.
	QueryBatch(ctx context.Context, vecs [][]float32, opts *SearchOptions[T]) ([][]ai.Hit[T], error)

	// QueryText performs a BM25 or keyword text search on the stored text representation of the thoughts.
	QueryText(ctx context.Context, text string, opts *SearchOptions[T]) ([]ai.Hit[T], error)

	// QueryTextBatch performs a BM25 or keyword text search for an array of queries.
	QueryTextBatch(ctx context.Context, texts []string, opts *SearchOptions[T]) ([][]ai.Hit[T], error)

	// Count returns the total number of items in the store.
	Count(ctx context.Context) (int64, error)

	// Categories returns a B-Tree interface to manually read/update hierarchical categories.
	Categories(ctx context.Context) (btree.BtreeInterface[sop.UUID, *Category], error)

	// CategoriesByPath returns a B-Tree interface to manually read/update path-indexed categories.
	CategoriesByPath(ctx context.Context) (btree.BtreeInterface[string, sop.UUID], error)

	// CategoriesByDistance returns a B-Tree interface for reading/updating distance-indexed categories.
	CategoriesByDistance(ctx context.Context) (btree.BtreeInterface[DistanceKey, byte], error)

	// AddCategory adds a new category to the store dynamically.
	// This allows for runtime expansion of the concept space without full rebalancing.
	AddCategory(ctx context.Context, c *Category) (sop.UUID, error)

	// AddCategoryParent connects an existing category to an additional parent, supporting
	// the polyhierarchy DAG structure. This is often leveraged during LLM Sleep Cycles.
	AddCategoryParent(ctx context.Context, categoryID sop.UUID, parent CategoryParent) error

	// Consolidate reads accumulated vectors from short-term memory (TempVectors),
	// dynamically routes them into existing Categories using AssignAndIndex logic,
	// and clears them from short-term memory.
	Consolidate(ctx context.Context) error

	// UpdateEmbedderInfo updates the configuration defining which embedder was used
	// to index the vectors, persisting it in the system configuration of the store.
	UpdateEmbedderInfo(ctx context.Context, provider string, model string, dimensions int) error

	// SetDomainReference sets the anchor vector for O(log N) category indexing.
	SetDomainReference(vec []float32)

	// DomainReference returns the anchor vector for O(log N) category indexing.
	DomainReference() []float32

	// SetLLM sets the LLM interface used to generate categories dynamically.
	SetLLM(llm LLM[T])

	// Vectors returns the Vectors B-Tree for advanced manipulation (Mathematical layout).
	Vectors(ctx context.Context) (btree.BtreeInterface[VectorKey, Vector], error)

	// Content returns the Content B-Tree for advanced manipulation (The actual Item Data).
	Items(ctx context.Context) (btree.BtreeInterface[ItemKey, Item[T]], error)

	// Documents returns the Documents B-Tree for reading the raw canonical documents.
	Documents(ctx context.Context) (btree.BtreeInterface[sop.UUID, Document], error)

	// UpsertDocument adds or updates a full canonical document.
	UpsertDocument(ctx context.Context, doc Document) error

	// GetDocument retrieves a full document by its ID.
	GetDocument(ctx context.Context, id sop.UUID) (*Document, error)

	// Version returns the Vector store's version number, which is a unix elapsed time.
	Version(ctx context.Context) (int64, error)
}

MemoryStore is the m-way tree dynamic capability database interface.

func NewStore

func NewStore[T any](
	name string,
	db Database,
	categories btree.BtreeInterface[sop.UUID, *Category],
	categoriesByPath btree.BtreeInterface[string, sop.UUID],
	categoriesByDistance btree.BtreeInterface[DistanceKey, byte],
	vectors btree.BtreeInterface[VectorKey, Vector],
	items btree.BtreeInterface[ItemKey, Item[T]],
	documents btree.BtreeInterface[sop.UUID, Document],
) MemoryStore[T]

NewStore creates a new instance of MemoryStore.

type MemoryUnit

type MemoryUnit struct {
	AgentID    string
	UserID     string
	AllowedKBs []string // LTM scoping boundaries

	// Tracks the last time an episode was logged to STM for idle sleep cycles
	LastEpisodeTS atomic.Int64
	// contains filtered or unexported fields
}

MemoryUnit encapsulates the cognitive state and boundaries of an Agent instance.

func NewMemoryUnit

func NewMemoryUnit(agentID string) *MemoryUnit

func (*MemoryUnit) BindSession

func (m *MemoryUnit) BindSession(ctx context.Context)

func (*MemoryUnit) CloseShortTermMemory

func (m *MemoryUnit) CloseShortTermMemory()

func (*MemoryUnit) LogEpisodeToSTM

func (m *MemoryUnit) LogEpisodeToSTM(ctx context.Context, intent string, astPayload any, outcome string, executeErr error)

LogEpisodeToSTM directly writes to the Agent's physical STM structure

func (*MemoryUnit) LongTermMemoryName

func (m *MemoryUnit) LongTermMemoryName() string

func (*MemoryUnit) OpenLongTermMemory

func (m *MemoryUnit) OpenLongTermMemory(ctx context.Context, systemDB Database, trans sop.Transaction, llm ai.Generator, embedder ai.Embeddings) (*KnowledgeBase[map[string]any], error)

func (*MemoryUnit) OpenShortTermMemory

func (m *MemoryUnit) OpenShortTermMemory(ctx context.Context, systemDB Database, trans sop.Transaction) (any, error)

func (*MemoryUnit) STMStore

func (m *MemoryUnit) STMStore() *ShortTermMemoryStore

func (*MemoryUnit) ShortTermMemory

func (m *MemoryUnit) ShortTermMemory() any

func (*MemoryUnit) ShortTermMemoryName

func (m *MemoryUnit) ShortTermMemoryName() string

func (*MemoryUnit) ShortTermMemoryTimeIndexName

func (m *MemoryUnit) ShortTermMemoryTimeIndexName() string

func (*MemoryUnit) StartMemoryWorkers

func (m *MemoryUnit) StartMemoryWorkers(ctx context.Context, systemDB Database) error

StartMemoryWorkers launches the dedicated background worker that reads episodes from the channel and flushes them to STM.

type PathSearchParam

type PathSearchParam struct {
	CategoryPath string `json:"category_path"` // e.g. "Root/Engineering/Architecture" (semantic or lexical)
	SearchText   string `json:"search_text"`   // Text to prefix search on item content/title
}

PathSearchParam specifies a hierarchical category path search. BREAKTHROUGH: Supports semantic path navigation using CategoriesByDistance B-Tree. When exact lexical path is not found, the system performs hierarchical semantic drill-down: 1. Split path by "/" (e.g., "Engineering/Databases/SQL" → ["Engineering", "Databases", "SQL"]) 2. Root level: embed first part, search CategoriesByDistance using DomainReference as anchor 3. Nested levels: embed each part, search CategoriesByDistance using parent CenterVector as anchor 4. Navigate hierarchically through semantic similarity with O(D * log N) performance This enables typo-resistant, cross-lingual, natural language path queries. See ai/DYNAMIC_VECTOR_STORE_DESIGN.md Section 12 for full details.

type Preference

type Preference struct {
	Key          string   `json:"key"`
	BoolValue    *bool    `json:"bool_value,omitempty"`
	StringValue  string   `json:"string_value,omitempty"`
	NumberValue  *float64 `json:"number_value,omitempty"`
	UpdatedAtUTC int64    `json:"updated_at_utc,omitempty"`
	Source       string   `json:"source,omitempty"`
}

Preference stores a durable user preference that can be persisted in LTM, projected into MRU, and finally copied into request-scoped runtime state. Typed value lanes avoid ambiguous any-typed payloads at the memory boundary.

func NewBoolPreference

func NewBoolPreference(key string, value bool) Preference

NewBoolPreference creates a typed boolean preference record.

func (Preference) Bool

func (p Preference) Bool() (bool, bool)

Bool returns the stored boolean value and whether the preference is boolean-typed.

type SearchOptions

type SearchOptions[T any] struct {
	Limit int
	// CategoryPath can serve as a cheaper SearchByPath-style alternative to TextSearch
	// when the use-case has a stable, meaningful category taxonomy to route through.
	CategoryPath string
	// CategoryVector can be used to search for items within a given category.
	// The Category whose CenterVector is closest to this vector will be used as the search Category.
	CategoryVector []float32
	Filter         func(T) bool
}

SearchOptions provides optional parameters for querying the vector store

type SearchRequest

type SearchRequest[T any] struct {
	Text           string
	Vector         []float32
	CategoryPath   string
	CategoryVector []float32
	Limit          int
	Filter         func(T) bool
}

SearchRequest is the reusable public contract for single and batch retrieval.

type ShortTermMemoryStore

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

func NewShortTermMemoryStore

func NewShortTermMemoryStore(agentID string, maxAge time.Duration) *ShortTermMemoryStore

func (*ShortTermMemoryStore) Attach

func (*ShortTermMemoryStore) Close

func (s *ShortTermMemoryStore) Close()

func (*ShortTermMemoryStore) Open

func (s *ShortTermMemoryStore) Open(ctx context.Context, systemDB Database, tx sop.Transaction) error

func (*ShortTermMemoryStore) Primary

func (*ShortTermMemoryStore) PruneExpired

func (s *ShortTermMemoryStore) PruneExpired(ctx context.Context, now time.Time) (int, error)

func (*ShortTermMemoryStore) RemoveEpisode

func (s *ShortTermMemoryStore) RemoveEpisode(ctx context.Context, itemID string, payload map[string]any) error

func (*ShortTermMemoryStore) SetUserID

func (s *ShortTermMemoryStore) SetUserID(userID string)

func (*ShortTermMemoryStore) StartPeriodicCommitter

func (s *ShortTermMemoryStore) StartPeriodicCommitter(ctx context.Context, systemDB Database, queue <-chan map[string]any) error

func (*ShortTermMemoryStore) StoreName

func (s *ShortTermMemoryStore) StoreName() string

func (*ShortTermMemoryStore) TimeIndexName

func (s *ShortTermMemoryStore) TimeIndexName() string

func (*ShortTermMemoryStore) UpsertEpisode

func (s *ShortTermMemoryStore) UpsertEpisode(ctx context.Context, payload map[string]any) error

type Thought

type Thought[T any] struct {
	Summaries    []string
	CategoryPath string
	DocID        DocIDs
	Data         T
	Vectors      [][]float32
	Positions    []VectorKey
	VectorHash   string
}

Thought represents the individual entity of data in a batch categorization execution.

type UpsertCategoryParam

type UpsertCategoryParam struct {
	ParentPaths []string   `json:"parent_paths"` // Declarative DAG routing (e.g. ["Root/Engineering", "Root/DevOps"])
	ParentIDs   []sop.UUID `json:"parent_ids"`   // Explicit DAG routing fallback
	Category    *Category  `json:"category"`     // Pointer to the Category to upsert
}

type UpsertItemParam

type UpsertItemParam[T any] struct {
	CategoryPath string      `json:"category_path"` // e.g. "Root/Engineering/Architecture"
	CategoryID   sop.UUID    `json:"category_id"`   // Direct ID fallback if path is empty
	Item         *Item[T]    `json:"item"`          // Pointer to avoid heavy allocation during batch
	Vectors      [][]float32 `json:"vectors"`       // Optional explicit embeddings
}

type Vector

type Vector struct {
	ID         sop.UUID  `json:"id"`
	Data       []float32 `json:"data"`        // Math coordinate
	ItemID     sop.UUID  `json:"item_id"`     // Points to the actual Item
	CategoryID sop.UUID  `json:"category_id"` // Critical for category-partitioned semantic searches
}

Vector represents the pointer/index fragment mapping the math to the Item.

type VectorKey

type VectorKey struct {
	CategoryID         sop.UUID // Points to the hierarchical Category ID
	DistanceToCategory float32
	VectorID           sop.UUID // Points to the specific Vector ID
}

VectorKey is the key for the Vectors B-Tree. It dictates how vectors are sorted mathematically relative to their parent Category.

Jump to

Keyboard shortcuts

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