memory

package
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: May 15, 2026 License: MIT Imports: 19 Imported by: 0

Documentation

Index

Constants

View Source
const DocumentDefaultCollection = "default"

DocumentDefaultCollection is the fallback collection name.

Variables

This section is empty.

Functions

func DefaultDBPath added in v0.2.1

func DefaultDBPath() string

DefaultDBPath returns the default path for the memory database.

func LightweightTreeAsText added in v0.2.1

func LightweightTreeAsText(tree map[string]TopicTree, topFacts []Node) string

func LightweightTreeAsTextWithHighlight added in v0.2.1

func LightweightTreeAsTextWithHighlight(tree map[string]TopicTree, topFacts []Node, relevantKeys map[string]float32) string

func LightweightTreeAsTextWithLimit added in v0.2.1

func LightweightTreeAsTextWithLimit(tree map[string]TopicTree, topFacts []Node, maxSummaryChars int) string

Types

type ChatClient added in v0.2.1

type ChatClient interface {
	Chat(ctx context.Context, system, prompt string) (string, error)
}

ChatClient is the minimal interface the Graph needs to call an LLM. It wraps a blocking chat call — callers can adapt streaming providers.

func NewChatClient added in v0.2.1

func NewChatClient(p provider.Provider, model string) ChatClient

NewChatClient creates a blocking ChatClient from an ogcode Provider. model is the specific model ID to use; if empty the provider's default (Models()[0]) is used.

type CollectionStats added in v0.2.1

type CollectionStats struct {
	Collections int `json:"collections"`
	Documents   int `json:"documents"`
	Nodes       int `json:"nodes"`
	Edges       int `json:"edges"`
}

CollectionStats is returned by Stats.

type ConceptTree added in v0.2.1

type ConceptTree struct {
	Name            string   `json:"name"`
	Facts           []Node   `json:"facts"`
	RelatedConcepts []string `json:"related,omitempty"`
}

ConceptTree is the readable tree for one concept.

type Document added in v0.2.1

type Document struct {
	ID         int64  `json:"id"`
	Collection string `json:"collection"`
	Content    string `json:"content"`
	CreatedAt  int64  `json:"createdAt"`
}

Document is an unstructured text fragment tied to a collection.

type Edge added in v0.2.1

type Edge struct {
	ID        int64   `json:"id"`
	SessionID string  `json:"sessionId"`
	FromKey   string  `json:"fromKey"` // concept key
	ToKey     string  `json:"toKey"`   // concept key (cross-topic allowed)
	RelType   string  `json:"relType"` // e.g. "related", "prerequisite", "opposite"
	Weight    float32 `json:"weight"`
	CreatedAt int64   `json:"createdAt"`
}

Edge represents a named relationship between two nodes.

type EmbedClient added in v0.2.1

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

EmbedClient returns embedding vectors for input strings.

func NewEmbedClient added in v0.2.1

func NewEmbedClient(e provider.Embedder) EmbedClient

NewEmbedClient creates an EmbedClient from an ogcode Embedder.

type Graph added in v0.2.1

type Graph struct {
	Store *Store
	Chat  ChatClient
	Embed EmbedClient
}

Graph orchestrates the knowledge graph lifecycle.

func (*Graph) AddFact added in v0.2.1

func (g *Graph) AddFact(ctx context.Context, opts GraphOptions) (*Node, error)

AddFact stores a new fact and reorganizes the graph. Embedding is required.

func (*Graph) BuildLightweightTree added in v0.2.1

func (g *Graph) BuildLightweightTree(ctx context.Context, sessionID string, f NodeFilter, queryVec []float32, limit int) (map[string]TopicTree, []Node, error)

BuildLightweightTree builds a lightweight tree ready for LLM consumption.

func (*Graph) BuildTree added in v0.2.1

func (g *Graph) BuildTree(ctx context.Context, sessionID string) (map[string]TopicTree, error)

BuildTree constructs the hierarchical memory tree for a session.

func (*Graph) BuildTreeFiltered added in v0.2.1

func (g *Graph) BuildTreeFiltered(ctx context.Context, sessionID string, f NodeFilter) (map[string]TopicTree, error)

BuildTreeFiltered constructs the tree filtered by given bounds.

func (*Graph) Recall added in v0.2.1

func (g *Graph) Recall(ctx context.Context, opts RecallOptions) (*RecallResult, error)

type GraphOptions added in v0.2.1

type GraphOptions struct {
	SessionID string
	Question  string
	Response  string
	UserTopic string
}

GraphOptions tunes Graph inference behavior.

type GraphOpts added in v0.2.1

type GraphOpts struct {
	// ChatProvider is the provider used for topic/concept inference and recall.
	// It may be the same as EmbedProvider or different.
	ChatProvider provider.Provider
	// ChatModel is the specific model ID to use for inference. If empty, the
	// provider's first available model is used.
	ChatModel string
	// EmbedProvider is the provider used for text embeddings. Must satisfy provider.Embedder.
	EmbedProvider provider.Provider
}

GraphOpts holds dependencies for initializing agentic memory.

type Memory

type Memory struct {
	Store *Store
	Graph *Graph
	// contains filtered or unexported fields
}

Memory provides the agentic memory lifecycle: read, recall, and write. It wraps a local SQLite-backed knowledge graph with optional LLM inference.

func New

func New(store *Store, opts *GraphOpts) *Memory

New creates a Memory backed by local SQLite graph store. If chatProvider is nil but embedProvider is non-nil, AddFact can still store facts without LLM topic inference.

func (*Memory) CreateCollection added in v0.2.1

func (m *Memory) CreateCollection(ctx context.Context, name string) (int64, error)

CreateCollection inserts a new collection.

func (*Memory) DeleteCollection added in v0.2.1

func (m *Memory) DeleteCollection(ctx context.Context, name string) error

DeleteCollection removes a collection including its documents.

func (*Memory) Enabled

func (m *Memory) Enabled() bool

Enabled returns whether agentic memory is active.

func (*Memory) ReadMemory

func (m *Memory) ReadMemory(ctx context.Context, sessionID string) string

ReadMemory fetches the full session knowledge graph as text.

func (*Memory) RecallMemory

func (m *Memory) RecallMemory(ctx context.Context, sessionID, question string, recentMessages []string) string

RecallMemory performs semantic recall for a specific question. recentMessages contains the last N raw conversation turns (role: text) used to resolve references like "the previous API" or "continue" before embedding.

func (*Memory) RefreshAll added in v0.2.1

func (m *Memory) RefreshAll(ctx context.Context) error

RefreshAll recomputes all document embeddings; useful after provider changes.

func (*Memory) SemanticSearch added in v0.2.1

func (m *Memory) SemanticSearch(ctx context.Context, collection, query string, topK int) ([]SearchResult, error)

SemanticSearch runs a vector search across a collection.

func (*Memory) Stats added in v0.2.1

func (m *Memory) Stats(ctx context.Context) (col, doc, nodes, edges int, err error)

Stats returns total counts across all collections and graph tables.

func (*Memory) UpsertDocument added in v0.2.1

func (m *Memory) UpsertDocument(ctx context.Context, collection, content string) (int64, error)

UpsertDocument stores or updates a document and computes its embedding using the currently configured embedder.

func (*Memory) WriteMemory

func (m *Memory) WriteMemory(ctx context.Context, sessionID, question, response string)

WriteMemory persists a conversation turn.

type Node added in v0.2.1

type Node struct {
	ID         int64    `json:"id"`
	SessionID  string   `json:"sessionId"`
	Type       NodeType `json:"type"`
	Key        string   `json:"key"`
	Content    string   `json:"content,omitempty"`   // question + " [ANSWER] " + response for facts
	Question   string   `json:"question,omitempty"`  // original question
	Response   string   `json:"response,omitempty"`  // original answer
	TopicName  string   `json:"topicName,omitempty"` // only set for concept/fact nodes
	Summary    string   `json:"summary,omitempty"`   // LLM-generated one-line summary per fact
	Labels     []string `json:"labels,omitempty"`    // LLM-generated labels per fact
	Order      int      `json:"order,omitempty"`     // position in conversation (1-indexed)
	CreatedAt  int64    `json:"createdAt"`
	AccessedAt int64    `json:"accessedAt"`
}

Node is the fundamental unit in the knowledge graph.

type NodeFilter added in v0.2.1

type NodeFilter struct {
	Type      NodeType
	Since     int64  // unix milliseconds; 0 = no lower bound
	Until     int64  // unix milliseconds; 0 = no upper bound
	FromOrder int    // 1-indexed inclusive; 0 = no lower bound
	ToOrder   int    // 1-indexed inclusive; 0 = no upper bound
	TopicName string // empty = any topic
}

NodeFilter captures all optional bounds on a node query.

type NodeType added in v0.2.1

type NodeType string

NodeType distinguishes the three levels in the hierarchy.

const (
	TypeTopic   NodeType = "topic"
	TypeConcept NodeType = "concept"
	TypeFact    NodeType = "fact"
)

type Placement added in v0.2.1

type Placement struct {
	Topic   string
	Concept string
}

type RecallOptions added in v0.2.1

type RecallOptions struct {
	SessionID      string
	Question       string
	RecentMessages []string // last N raw conversation turns for reference resolution
	MaxRounds      int      // max refinement rounds, default 3
	Threshold      float32  // confidence threshold to stop early, default 0.7
	Limit          int      // max facts in lightweight tree, default 50
	MinScore       float32  // minimum cosine similarity to include fact
	Since          int64
	Until          int64
	FromOrder      int
	ToOrder        int
}

type RecallResult added in v0.2.1

type RecallResult struct {
	Answer     string
	Confidence float32
	Rounds     int
	FactsUsed  int
}

type RelatedConcept added in v0.2.1

type RelatedConcept struct {
	ToConcept string
	Weight    float32
}

type SearchResult added in v0.2.1

type SearchResult struct {
	Doc   Document `json:"doc"`
	Score float32  `json:"score"`
}

SearchResult pairs a Document with a relevance score.

type SessionMeta added in v0.2.1

type SessionMeta struct {
	ID           string `json:"id"`
	Name         string `json:"name,omitempty"`
	CreatedAt    int64  `json:"createdAt"`
	LastAccessAt int64  `json:"lastAccessAt"`
	NodeCount    int    `json:"nodeCount"`
	TopicCount   int    `json:"topicCount"`
	ConceptCount int    `json:"conceptCount"`
	FactCount    int    `json:"factCount"`
}

SessionMeta is the metadata for a session.

type Store added in v0.2.1

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

Store is the SQLite-backed knowledge graph. All methods are safe for concurrent use; writes are serialized through a mutex.

func Open added in v0.2.1

func Open(path string) (*Store, error)

Open opens (or creates) the memory database at path.

func (*Store) AddEdge added in v0.2.1

func (s *Store) AddEdge(e Edge) error

AddEdge creates a relationship between two concepts.

func (*Store) AddNode added in v0.2.1

func (s *Store) AddNode(n Node) (*Node, error)

AddNode inserts a node. If a node with the same (session_id, key) exists, it is updated (upsert). Returns the node with its ID set.

func (*Store) Close added in v0.2.1

func (s *Store) Close() error

Close releases the database handle.

func (*Store) DB added in v0.2.1

func (s *Store) DB() *sql.DB

DB returns the underlying sql.DB for advanced queries.

func (*Store) DeleteEdge added in v0.2.1

func (s *Store) DeleteEdge(sessionID, fromKey, toKey string) error

DeleteEdge removes an edge by from_key + to_key.

func (*Store) DeleteNode added in v0.2.1

func (s *Store) DeleteNode(sessionID, key string) error

DeleteNode removes a node by session_id + key.

func (*Store) DeleteSession added in v0.2.1

func (s *Store) DeleteSession(sessionID string) error

DeleteSession removes a session and all its data (cascading via FK triggers if present).

func (*Store) Embeddings added in v0.2.1

func (s *Store) Embeddings(sessionID string) (map[string][]float32, error)

Embeddings returns all (key, embedding) pairs for a session.

func (*Store) EnsureSession added in v0.2.1

func (s *Store) EnsureSession(sessionID string) error

EnsureSession creates a session if it does not exist, and updates lastAccessAt.

func (*Store) GetFirstFact added in v0.2.1

func (s *Store) GetFirstFact(sessionID string) (*Node, error)

func (*Store) GetLastFact added in v0.2.1

func (s *Store) GetLastFact(sessionID string) (*Node, error)

func (*Store) GetNode added in v0.2.1

func (s *Store) GetNode(sessionID, key string) (*Node, error)

GetNode retrieves a node by session_id + key.

func (*Store) GetNodeAt added in v0.2.1

func (s *Store) GetNodeAt(sessionID string, order int) (*Node, error)

GetNodeAt returns the Nth fact (1-indexed) in a session.

func (*Store) ListEdges added in v0.2.1

func (s *Store) ListEdges(sessionID string) ([]Edge, error)

ListEdges returns all edges for a session.

func (*Store) ListNodes added in v0.2.1

func (s *Store) ListNodes(sessionID string, filterType NodeType) ([]Node, error)

ListNodes returns all nodes for a session, optionally filtered by type.

func (*Store) ListNodesFiltered added in v0.2.1

func (s *Store) ListNodesFiltered(sessionID string, f NodeFilter) ([]Node, error)

ListNodesFiltered returns nodes matching the given bounds.

func (*Store) ListSessions added in v0.2.1

func (s *Store) ListSessions() ([]SessionMeta, error)

ListSessions returns all sessions ordered by last access.

func (*Store) SetEmbedding added in v0.2.1

func (s *Store) SetEmbedding(sessionID, key string, emb []float32) error

SetEmbedding upserts the embedding for a node key.

func (*Store) Stats added in v0.2.1

func (s *Store) Stats(sessionID string) (topics, concepts, facts int, err error)

Stats returns per-type counts for a session.

func (*Store) UpdateNodeEnrichment added in v0.2.1

func (s *Store) UpdateNodeEnrichment(sessionID, key, summary string, labels []string) error

UpdateNodeEnrichment updates labels and summary for a fact node.

type TopicTree added in v0.2.1

type TopicTree struct {
	Name     string        `json:"name"`
	Concepts []ConceptTree `json:"concepts"`
}

TopicTree is the readable tree for one topic.

Jump to

Keyboard shortcuts

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