Help us shape the future of Go! Take the 2026 Go Developer Survey

memory

package
v1.4.0 Latest Latest
Warning

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

Go to latest
Published: Oct 31, 2026 License: MIT Imports: 15 Imported by: 0

Documentation

Overview

Package memory provides long-term memory that persists across sessions, with keyword, vector and hybrid retrieval.

Index

Constants

This section is empty.

Variables

View Source
var ErrNotFound = errors.New("memory not found")

ErrNotFound is returned when an entry does not exist.

Functions

func Cosine

func Cosine(a, b []float32) float64

Cosine returns the cosine similarity of two vectors, or 0 when their lengths differ or either is zero.

func Format

func Format(hits []Hit) string

Format renders hits as a bulleted list for inclusion in a prompt.

func ScopedTools

func ScopedTools(m Memory, scope ScopeFunc) []tool.Tool

ScopedTools is like Tools, with the scope of each call chosen by scope, so one agent can serve several users.

func Tokenize

func Tokenize(text string) []string

Tokenize lower-cases text and splits it into terms. Runs of letters and digits form words; CJK characters produce unigrams and bigrams.

func Tools

func Tools(m Memory, scope string) []tool.Tool

Tools returns tools that let a model manage memory: memory_remember, memory_recall and memory_forget. Entries are written with the given scope, and recall and deletion are restricted to it. With a non-empty scope, deletion requires Memory to implement ScopedForgetter; otherwise the forget tool returns an error.

Types

type Embedder

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

Embedder converts texts to vectors.

type Entry

type Entry struct {
	ID        string            `json:"id"`
	Content   string            `json:"content"`
	Tags      []string          `json:"tags,omitempty"`
	Scope     string            `json:"scope,omitempty"`
	Metadata  map[string]string `json:"metadata,omitempty"`
	Embedding []float32         `json:"embedding,omitempty"`
	CreatedAt time.Time         `json:"created_at"`
	UpdatedAt time.Time         `json:"updated_at"`
}

Entry is one remembered fact.

type Filter

type Filter struct {
	// Scope matches entries with exactly this scope when non-empty.
	Scope string
	// Tags matches entries that carry all of these tags.
	Tags []string
}

Filter selects entries.

func (Filter) Match

func (f Filter) Match(e *Entry) bool

Match reports whether e satisfies the filter.

type Hit

type Hit struct {
	Entry *Entry
	Score float64
}

Hit is a retrieved entry with its relevance score.

func RecallIn

func RecallIn(ctx context.Context, m Memory, scope, query string, limit int) ([]Hit, error)

RecallIn recalls up to limit entries in scope. An empty scope searches all entries and a non-positive limit uses the default.

type Hybrid

type Hybrid struct {
	Retrievers []Retriever
	// K is the RRF constant. Defaults to 60.
	K float64
	// OnError receives the error of each retriever that fails while at
	// least one other succeeds. If nil, the errors are logged as warnings
	// with slog.Default, so a retriever that is permanently broken does not
	// go unnoticed.
	OnError func(err error)
}

Hybrid fuses several retrievers with reciprocal rank fusion.

A retriever that fails does not fail the recall: Hybrid returns the fused hits of the others and reports the failure to OnError, or logs it when OnError is nil. Retrieve returns an error only when every retriever fails.

func (*Hybrid) Retrieve

func (h *Hybrid) Retrieve(ctx context.Context, q Query) ([]Hit, error)

Retrieve implements Retriever.

Query.MinScore is passed to each underlying retriever and compared with its own scores, not with the fused score. Scores have different scales (BM25 scores are unbounded while cosine similarity is at most 1), so one threshold rarely suits every retriever; prefer filtering in the retrievers themselves, for example with a wrapping Retriever.

type Keyword

type Keyword struct {
	Store Store
	// K1 and B are the BM25 parameters. Zero selects the defaults, 1.2 and
	// 0.75; a negative value selects 0, so B < 0 turns off document length
	// normalization.
	K1, B float64
}

Keyword ranks entries with BM25 over their content and tags. It handles CJK text by indexing single characters and character bigrams.

func (*Keyword) Retrieve

func (k *Keyword) Retrieve(ctx context.Context, q Query) ([]Hit, error)

Retrieve implements Retriever.

type Manager

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

Manager implements Memory over a Store and a Retriever.

func New

func New(store Store, opts ...Option) *Manager

New returns a Manager. Without options it uses keyword retrieval.

func (*Manager) Forget

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

Forget deletes an entry.

func (*Manager) ForgetInScope

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

ForgetInScope deletes an entry only when it belongs to scope. An empty scope allows deletion of any entry, as with Forget. A non-empty scope requires the store to implement ScopedDeleter.

func (*Manager) Recall

func (m *Manager) Recall(ctx context.Context, query string, opts ...RecallOption) ([]Hit, error)

Recall returns entries relevant to query.

func (*Manager) Remember

func (m *Manager) Remember(ctx context.Context, content string, opts ...RememberOption) (*Entry, error)

Remember stores content.

func (*Manager) Store

func (m *Manager) Store() Store

Store returns the underlying store.

type Memory

type Memory interface {
	Remember(ctx context.Context, content string, opts ...RememberOption) (*Entry, error)
	Recall(ctx context.Context, query string, opts ...RecallOption) ([]Hit, error)
	Forget(ctx context.Context, id string) error
}

Memory is long-term agent memory.

type MemoryStore

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

MemoryStore keeps entries in process memory. The zero value is ready to use.

func NewMemoryStore

func NewMemoryStore() *MemoryStore

NewMemoryStore returns an empty in-memory store.

func (*MemoryStore) Delete

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

Delete implements Store.

func (*MemoryStore) DeleteInScope

func (s *MemoryStore) DeleteInScope(_ context.Context, id, scope string) error

DeleteInScope atomically checks the scope and deletes an entry. An empty scope allows deletion of any entry.

func (*MemoryStore) Get

func (s *MemoryStore) Get(_ context.Context, id string) (*Entry, error)

Get implements Store.

func (*MemoryStore) List

func (s *MemoryStore) List(_ context.Context, f Filter) ([]*Entry, error)

List implements Store.

func (*MemoryStore) Put

func (s *MemoryStore) Put(_ context.Context, e *Entry) error

Put implements Store.

type Option

type Option func(*Manager)

Option configures a Manager.

func WithEmbedder

func WithEmbedder(e Embedder) Option

WithEmbedder embeds entries on write and enables hybrid retrieval unless a retriever is set explicitly.

func WithQueryEmbedder

func WithQueryEmbedder(e Embedder) Option

WithQueryEmbedder embeds recall queries with e, while WithEmbedder still embeds stored entries. Use it with embedders that distinguish queries from documents, such as Gemini's retrieval task types; both must produce vectors in the same space. It applies to the default hybrid retriever, not to one set with WithRetriever.

func WithRetriever

func WithRetriever(r Retriever) Option

WithRetriever sets the retriever.

type Query

type Query struct {
	Text   string
	Limit  int
	Filter Filter
	// MinScore drops hits scoring below it. Scores are retriever specific.
	MinScore float64
}

Query is a retrieval request.

type RecallOption

type RecallOption func(*Query)

RecallOption configures Recall.

func InScope

func InScope(scope string) RecallOption

InScope restricts recall to a scope.

func Limit

func Limit(n int) RecallOption

Limit sets the maximum number of hits. The default is 5.

func MinScore

func MinScore(s float64) RecallOption

MinScore drops hits scoring below s.

func Tagged

func Tagged(tags ...string) RecallOption

Tagged restricts recall to entries with all tags.

type RememberOption

type RememberOption func(*Entry)

RememberOption configures Remember.

func WithID

func WithID(id string) RememberOption

WithID sets the entry ID, replacing an existing entry with the same ID.

func WithMetadata

func WithMetadata(key, value string) RememberOption

WithMetadata attaches a metadata value.

func WithScope

func WithScope(scope string) RememberOption

WithScope sets the scope, such as a user or project identifier.

func WithTags

func WithTags(tags ...string) RememberOption

WithTags attaches tags.

type Retriever

type Retriever interface {
	Retrieve(ctx context.Context, q Query) ([]Hit, error)
}

Retriever finds entries relevant to a query.

type ScopeFunc

type ScopeFunc func(ctx context.Context) (string, error)

ScopeFunc returns the scope of the memories a call reads and writes, for example the user of a multi-tenant server, taken from ctx. An error fails the call, so a run whose user is unknown reads and writes nothing.

func FixedScope

func FixedScope(scope string) ScopeFunc

FixedScope returns a ScopeFunc that always returns scope.

type ScopedDeleter

type ScopedDeleter interface {
	DeleteInScope(ctx context.Context, id, scope string) error
}

ScopedDeleter is implemented by a Store that can atomically check the scope of an entry and delete it, such as MemoryStore. An empty scope deletes any entry.

type ScopedForgetter

type ScopedForgetter interface {
	ForgetInScope(ctx context.Context, id, scope string) error
}

ScopedForgetter is implemented by a Memory that can delete an entry only when it belongs to a scope, such as Manager.

type Store

type Store interface {
	// Put inserts or replaces an entry by ID.
	Put(ctx context.Context, e *Entry) error
	// Get returns an entry or ErrNotFound.
	Get(ctx context.Context, id string) (*Entry, error)
	Delete(ctx context.Context, id string) error
	// List returns matching entries, oldest first.
	List(ctx context.Context, f Filter) ([]*Entry, error)
}

Store persists memory entries.

type Vector

type Vector struct {
	Store    Store
	Embedder Embedder
}

Vector ranks entries by cosine similarity between embeddings. Entries without an embedding are skipped.

func (*Vector) Retrieve

func (v *Vector) Retrieve(ctx context.Context, q Query) ([]Hit, error)

Retrieve implements Retriever.

Directories

Path Synopsis
Package memorytest checks memory.Store implementations against the contract the built-in stores follow.
Package memorytest checks memory.Store implementations against the contract the built-in stores follow.

Jump to

Keyboard shortcuts

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