core

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Jun 28, 2026 License: MIT Imports: 7 Imported by: 0

Documentation

Overview

Package core provides the core types and interfaces for omnimemory.

Index

Constants

View Source
const (
	PriorityThin  = 0  // Lightweight implementations (in-memory, mock)
	PriorityThick = 10 // Full SDK implementations (PostgreSQL, external services)
)

Priority levels for provider registration.

View Source
const DefaultEmbeddingDimension = 1536

DefaultEmbeddingDimension is the default dimension for OpenAI text-embedding-3-small.

Variables

View Source
var (
	ErrNotFound         = errors.New("memory not found")
	ErrInvalidInput     = errors.New("invalid input")
	ErrProviderNotFound = errors.New("provider not found")
	ErrNoProviders      = errors.New("no providers configured")
	ErrEmbeddingFailed  = errors.New("embedding generation failed")
	ErrTenantRequired   = errors.New("tenant_id is required")
	ErrSubjectRequired  = errors.New("subject_id is required")
	ErrContentRequired  = errors.New("content is required")
)

Common errors returned by omnimemory operations.

Functions

func CosineSimilarity

func CosineSimilarity(a, b []float64) float64

CosineSimilarity computes the cosine similarity between two vectors.

func EuclideanDistance

func EuclideanDistance(a, b []float64) float64

EuclideanDistance computes the Euclidean distance between two vectors.

func RegisterProvider

func RegisterProvider(name ProviderName, factory ProviderFactory, priority int)

RegisterProvider registers a provider factory with the global registry.

Types

type AddRequest

type AddRequest struct {
	Context
	Type     MemoryType     `json:"type"`
	Content  string         `json:"content"`
	Metadata map[string]any `json:"metadata,omitempty"`
	TTL      time.Duration  `json:"ttl,omitempty"`
}

AddRequest is the request for adding a new memory.

func (*AddRequest) Validate

func (r *AddRequest) Validate() error

Validate validates the add request.

type Client

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

Client is a multi-provider memory client with fallback support.

func NewClient

func NewClient(config ClientConfig) (*Client, error)

NewClient creates a new Client with the given configuration.

func (*Client) Add

func (c *Client) Add(ctx context.Context, req *AddRequest) (*Memory, error)

Add adds a new memory.

func (*Client) Close

func (c *Client) Close() error

Close closes all providers.

func (*Client) Delete

func (c *Client) Delete(ctx context.Context, req *DeleteRequest) error

Delete deletes a memory by ID.

func (*Client) Get

func (c *Client) Get(ctx context.Context, req *GetRequest) (*Memory, error)

Get retrieves a memory by ID.

func (*Client) List

func (c *Client) List(ctx context.Context, req *ListRequest) (*ListResponse, error)

List lists memories with optional filters.

func (*Client) Primary

func (c *Client) Primary() ProviderName

Primary returns the primary provider name.

func (*Client) Providers

func (c *Client) Providers() []ProviderName

Providers returns all provider names.

func (*Client) Recall

func (c *Client) Recall(ctx context.Context, req *RecallRequest) (*RecallResponse, error)

Recall retrieves relevant memories for a given query.

func (*Client) Search

func (c *Client) Search(ctx context.Context, req *SearchRequest) (*SearchResponse, error)

Search performs semantic search on memories.

func (*Client) SetHook

func (c *Client) SetHook(hook ObservabilityHook)

SetHook sets the observability hook.

func (*Client) Update

func (c *Client) Update(ctx context.Context, req *UpdateRequest) (*Memory, error)

Update updates an existing memory.

type ClientConfig

type ClientConfig struct {
	// Providers is the list of provider configurations.
	// The first provider is the primary, others are fallbacks.
	Providers []ProviderConfig `json:"providers"`

	// DefaultTTL is the default time-to-live for memories.
	DefaultTTL time.Duration `json:"default_ttl,omitempty"`

	// Embedder is the embedding generator.
	Embedder Embedder `json:"-"`

	// Logger is the logger for the client.
	Logger *slog.Logger `json:"-"`
}

ClientConfig is the configuration for creating a Client.

type Context

type Context struct {
	TenantID       string `json:"tenant_id"`
	SubjectID      string `json:"subject_id"`   // Who the memory is about
	PrincipalID    string `json:"principal_id"` // Who is making the request
	AgentID        string `json:"agent_id,omitempty"`
	SessionID      string `json:"session_id,omitempty"`      // Current session identifier
	ConversationID string `json:"conversation_id,omitempty"` // Conversation within a session
	Scope          Scope  `json:"scope,omitempty"`
}

Context provides multi-tenancy context for all operations.

func (*Context) Validate

func (c *Context) Validate() error

Validate validates the context.

type DeleteRequest

type DeleteRequest struct {
	Context
	ID string `json:"id"`
}

DeleteRequest is the request for deleting a memory.

func (*DeleteRequest) Validate

func (r *DeleteRequest) Validate() error

Validate validates the delete request.

type Embedder

type Embedder interface {
	// Embed generates an embedding for a single text.
	Embed(ctx context.Context, text string) ([]float64, error)

	// EmbedBatch generates embeddings for multiple texts.
	EmbedBatch(ctx context.Context, texts []string) ([][]float64, error)

	// Dimension returns the embedding dimension.
	Dimension() int
}

Embedder generates embeddings for text.

type EmbedderConfig

type EmbedderConfig struct {
	// Provider is the embedding provider (openai, anthropic, cohere, etc.)
	Provider string `json:"provider"`

	// APIKey is the API key for the provider.
	APIKey string `json:"api_key"`

	// Model is the embedding model to use.
	Model string `json:"model"`

	// Dimension is the embedding dimension (if configurable).
	Dimension int `json:"dimension,omitempty"`

	// Endpoint is the custom API endpoint (optional).
	Endpoint string `json:"endpoint,omitempty"`
}

EmbedderConfig is the configuration for creating an Embedder.

type ExtractorProvider

type ExtractorProvider interface {
	Provider

	// ExtractObservations extracts observations from a conversation.
	ExtractObservations(ctx context.Context, conversation string) ([]Observation, error)

	// ExtractFacts extracts facts from text.
	ExtractFacts(ctx context.Context, text string) ([]Fact, error)
}

ExtractorProvider extends Provider with extraction capabilities.

type Fact

type Fact struct {
	Subject   string         `json:"subject"`
	Predicate string         `json:"predicate"`
	Object    string         `json:"object"`
	Source    string         `json:"source,omitempty"`
	Timestamp time.Time      `json:"timestamp"`
	Metadata  map[string]any `json:"metadata,omitempty"`
}

Fact represents a verified piece of information extracted from text.

type GetRequest

type GetRequest struct {
	Context
	ID string `json:"id"`
}

GetRequest is the request for getting a memory by ID.

func (*GetRequest) Validate

func (r *GetRequest) Validate() error

Validate validates the get request.

type ListRequest

type ListRequest struct {
	Context
	Types  []MemoryType `json:"types,omitempty"`
	Scopes []Scope      `json:"scopes,omitempty"`
	Limit  int          `json:"limit,omitempty"`
	Offset int          `json:"offset,omitempty"`
}

ListRequest is the request for listing memories.

type ListResponse

type ListResponse struct {
	Memories   []*Memory `json:"memories"`
	TotalCount int       `json:"total_count"`
	HasMore    bool      `json:"has_more"`
}

ListResponse is the response for listing memories.

type Memory

type Memory struct {
	ID        string         `json:"id"`
	TenantID  string         `json:"tenant_id"`
	SubjectID string         `json:"subject_id"` // Who this memory is about
	AgentID   string         `json:"agent_id,omitempty"`
	SessionID string         `json:"session_id,omitempty"` // Session that created this memory
	Scope     Scope          `json:"scope"`
	Type      MemoryType     `json:"type"`
	Content   string         `json:"content"`
	Embedding []float64      `json:"embedding,omitempty"`
	Metadata  map[string]any `json:"metadata,omitempty"`
	CreatedAt time.Time      `json:"created_at"`
	UpdatedAt time.Time      `json:"updated_at"`
	ExpiresAt *time.Time     `json:"expires_at,omitempty"`
}

Memory is the primary storage unit for omnimemory.

type MemoryType

type MemoryType string

MemoryType defines the category of memory content.

const (
	// MemoryTypeObservation represents an observed behavior or interaction.
	MemoryTypeObservation MemoryType = "observation"
	// MemoryTypeFact represents a verified piece of information.
	MemoryTypeFact MemoryType = "fact"
	// MemoryTypePreference represents a user preference.
	MemoryTypePreference MemoryType = "preference"
	// MemoryTypeSummary represents a summarized conversation or topic.
	MemoryTypeSummary MemoryType = "summary"
	// MemoryTypeTrait represents a personality trait or characteristic.
	MemoryTypeTrait MemoryType = "trait"
	// MemoryTypeRelationship represents a relationship between entities.
	MemoryTypeRelationship MemoryType = "relationship"
)

func (MemoryType) String

func (t MemoryType) String() string

String returns the string representation of the memory type.

func (MemoryType) Valid

func (t MemoryType) Valid() bool

Valid returns true if the memory type is a valid type value.

type ObservabilityHook

type ObservabilityHook func(provider string, op string, duration time.Duration, err error)

ObservabilityHook is called for provider operations.

type Observation

type Observation struct {
	Content   string         `json:"content"`
	Source    string         `json:"source,omitempty"`
	Timestamp time.Time      `json:"timestamp"`
	Metadata  map[string]any `json:"metadata,omitempty"`
}

Observation represents an observed behavior or interaction extracted from conversation.

type Provider

type Provider interface {
	// Add adds a new memory.
	Add(ctx context.Context, req *AddRequest) (*Memory, error)

	// Get retrieves a memory by ID.
	Get(ctx context.Context, req *GetRequest) (*Memory, error)

	// Update updates an existing memory.
	Update(ctx context.Context, req *UpdateRequest) (*Memory, error)

	// Delete deletes a memory by ID.
	Delete(ctx context.Context, req *DeleteRequest) error

	// List lists memories with optional filters.
	List(ctx context.Context, req *ListRequest) (*ListResponse, error)

	// Search performs semantic search on memories.
	Search(ctx context.Context, req *SearchRequest) (*SearchResponse, error)

	// Recall retrieves relevant memories for a given query.
	Recall(ctx context.Context, req *RecallRequest) (*RecallResponse, error)

	// Close closes the provider and releases resources.
	Close() error

	// Name returns the provider name.
	Name() string
}

Provider is the interface that all memory providers must implement.

func GetProvider

func GetProvider(name ProviderName, config ProviderConfig, embedder Embedder) (Provider, error)

GetProvider creates a provider instance from the global registry.

type ProviderConfig

type ProviderConfig struct {
	Name     ProviderName   `json:"name"`
	DSN      string         `json:"dsn,omitempty"`
	APIKey   string         `json:"api_key,omitempty"`
	Endpoint string         `json:"endpoint,omitempty"`
	Options  map[string]any `json:"options,omitempty"`
}

ProviderConfig is the configuration for initializing a provider.

type ProviderError

type ProviderError struct {
	Provider string
	Op       string
	Err      error
}

ProviderError wraps an error with provider context.

func NewProviderError

func NewProviderError(provider, op string, err error) *ProviderError

NewProviderError creates a new ProviderError.

func (*ProviderError) Error

func (e *ProviderError) Error() string

func (*ProviderError) Unwrap

func (e *ProviderError) Unwrap() error

type ProviderFactory

type ProviderFactory func(config ProviderConfig, embedder Embedder) (Provider, error)

ProviderFactory is a function that creates a new Provider from config.

type ProviderName

type ProviderName string

ProviderName identifies a provider type.

const (
	ProviderNameMemory   ProviderName = "memory"
	ProviderNamePostgres ProviderName = "postgres"
	ProviderNameKVS      ProviderName = "kvs"
	ProviderNameMem0     ProviderName = "mem0"
	ProviderNameGraphiti ProviderName = "graphiti"
	ProviderNameTwilio   ProviderName = "twilio"

	// AWS providers
	ProviderNameAWSDynamoDB   ProviderName = "aws-dynamodb"
	ProviderNameAWSS3         ProviderName = "aws-s3"
	ProviderNameAWSOpenSearch ProviderName = "aws-opensearch"
)

func ListProviders

func ListProviders() []ProviderName

ListProviders returns all registered provider names from the global registry.

func (ProviderName) String

func (n ProviderName) String() string

String returns the string representation of the provider name.

func (ProviderName) Valid

func (n ProviderName) Valid() bool

Valid returns true if the provider name is valid.

type RecallRequest

type RecallRequest struct {
	Context
	Query        string       `json:"query"`
	MaxResults   int          `json:"max_results,omitempty"`
	IncludeTypes []MemoryType `json:"include_types,omitempty"`
}

RecallRequest is the request for recalling relevant memories.

func (*RecallRequest) Validate

func (r *RecallRequest) Validate() error

Validate validates the recall request.

type RecallResponse

type RecallResponse struct {
	Memories []*Memory `json:"memories"`
	Summary  string    `json:"summary,omitempty"`
}

RecallResponse is the response for recalling memories.

type Registry

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

Registry manages provider registrations.

func (*Registry) Get

func (r *Registry) Get(name ProviderName, config ProviderConfig, embedder Embedder) (Provider, error)

Get creates a provider instance from this registry.

func (*Registry) Has

func (r *Registry) Has(name ProviderName) bool

Has returns true if a provider is registered.

func (*Registry) List

func (r *Registry) List() []ProviderName

List returns all registered provider names sorted by priority (highest first).

func (*Registry) Register

func (r *Registry) Register(name ProviderName, factory ProviderFactory, priority int)

Register registers a provider factory with this registry.

func (*Registry) Unregister

func (r *Registry) Unregister(name ProviderName)

Unregister removes a provider from the registry.

type Scope

type Scope string

Scope defines the visibility and ownership level of a memory.

const (
	// ScopeUser represents personal memories for one user.
	ScopeUser Scope = "user"
	// ScopeAgent represents what an agent has learned.
	ScopeAgent Scope = "agent"
	// ScopeTenant represents org-level shared memories.
	ScopeTenant Scope = "tenant"
	// ScopeTeam represents group/project level memories.
	ScopeTeam Scope = "team"
	// ScopeSession represents short-lived conversation memories.
	ScopeSession Scope = "session"
	// ScopeDomain represents domain-specific memories (support, sales, etc.).
	ScopeDomain Scope = "domain"
)

func (Scope) String

func (s Scope) String() string

String returns the string representation of the scope.

func (Scope) Valid

func (s Scope) Valid() bool

Valid returns true if the scope is a valid scope value.

type SearchRequest

type SearchRequest struct {
	Context
	Query     string       `json:"query"`
	Types     []MemoryType `json:"types,omitempty"`
	Scopes    []Scope      `json:"scopes,omitempty"`
	Limit     int          `json:"limit,omitempty"`
	Threshold float64      `json:"threshold,omitempty"` // Similarity threshold
}

SearchRequest is the request for semantic search.

func (*SearchRequest) Validate

func (r *SearchRequest) Validate() error

Validate validates the search request.

type SearchResponse

type SearchResponse struct {
	Results []*SearchResult `json:"results"`
}

SearchResponse is the response for semantic search.

type SearchResult

type SearchResult struct {
	Memory *Memory `json:"memory"`
	Score  float64 `json:"score"`
}

SearchResult is a single search result with similarity score.

type UpdateRequest

type UpdateRequest struct {
	Context
	ID       string         `json:"id"`
	Content  string         `json:"content,omitempty"`
	Metadata map[string]any `json:"metadata,omitempty"`
}

UpdateRequest is the request for updating a memory.

func (*UpdateRequest) Validate

func (r *UpdateRequest) Validate() error

Validate validates the update request.

type ValidationError

type ValidationError struct {
	Field   string
	Message string
}

ValidationError represents a validation error with field context.

func NewValidationError

func NewValidationError(field, message string) *ValidationError

NewValidationError creates a new ValidationError.

func (*ValidationError) Error

func (e *ValidationError) Error() string

Directories

Path Synopsis
Package providertest provides conformance tests for memory provider implementations.
Package providertest provides conformance tests for memory provider implementations.

Jump to

Keyboard shortcuts

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