mem0

package module
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: 8 Imported by: 0

README

mem0-go

Go CI Go Lint Go SAST Go Report Card Docs Docs Visualization License

Go client SDK for mem0 - the AI memory layer for agents and apps.

Installation

go get github.com/plexusone/mem0-go

Quick Start

package main

import (
    "context"
    "fmt"
    "log"

    "github.com/plexusone/mem0-go"
)

func main() {
    // Create a client (API key from MEM0_API_KEY env var or WithAPIKey option)
    client, err := mem0.NewClient(mem0.WithAPIKey("your-api-key"))
    if err != nil {
        log.Fatal(err)
    }

    ctx := context.Background()

    // Add a memory
    messages := []mem0.Message{
        {Role: mem0.RoleUser, Content: "I prefer dark mode in all my applications"},
    }

    result, err := client.Memory().Add(ctx, messages, mem0.WithUserID("user-123"))
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("Added memory: %v\n", result)

    // Search memories
    results, err := client.Memory().Search(ctx, "dark mode preferences",
        mem0.WithFilters(mem0.Filters{UserID: "user-123"}),
        mem0.WithTopK(5),
    )
    if err != nil {
        log.Fatal(err)
    }

    for _, r := range results {
        fmt.Printf("Memory: %s (score: %.2f)\n", r.Memory, r.Score)
    }
}

Configuration

Environment Variables
Variable Description
MEM0_API_KEY API key for authentication
MEM0_BASE_URL Custom base URL (default: https://api.mem0.ai)
Client Options
client, err := mem0.NewClient(
    mem0.WithAPIKey("your-api-key"),
    mem0.WithBaseURL("https://custom.example.com"),
    mem0.WithHTTPClient(customHTTPClient),
    mem0.WithBackend(mem0.BackendHosted),
)

API Reference

Memory Interface
type Memory interface {
    Add(ctx context.Context, messages []Message, opts ...AddOption) (*AddResponse, error)
    Get(ctx context.Context, memoryID string) (*MemoryItem, error)
    GetAll(ctx context.Context, opts ...GetAllOption) (*GetAllResult, error)
    Search(ctx context.Context, query string, opts ...SearchOption) ([]SearchResult, error)
    Update(ctx context.Context, memoryID string, text string) (*MemoryItem, error)
    Delete(ctx context.Context, memoryID string) error
    DeleteAll(ctx context.Context, opts ...DeleteAllOption) (*DeleteAllResult, error)
    History(ctx context.Context, memoryID string) ([]HistoryItem, error)
    GetEventStatus(ctx context.Context, eventID string) (*EventStatus, error)
}
Add Options
mem0.WithUserID("user-123")
mem0.WithAgentID("agent-456")
mem0.WithAppID("app-789")
mem0.WithRunID("run-012")
mem0.WithMetadata(map[string]interface{}{"key": "value"})
mem0.WithInfer(true)
Search Options
mem0.WithFilters(mem0.Filters{UserID: "user-123"})
mem0.WithTopK(10)
mem0.WithRerank(true)
mem0.WithThreshold(0.5)
GetAll Options
mem0.WithGetAllFilters(mem0.Filters{UserID: "user-123"})
mem0.WithPage(1)
mem0.WithPageSize(50)
DeleteAll Options
mem0.WithDeleteUserID("user-123")
mem0.WithDeleteAgentID("agent-456")

Error Handling

_, err := client.Memory().Get(ctx, "non-existent-id")
if err != nil {
    if mem0.IsNotFoundError(err) {
        fmt.Println("Memory not found")
    } else if mem0.IsUnauthorizedError(err) {
        fmt.Println("Authentication failed")
    } else if mem0.IsBadRequestError(err) {
        fmt.Println("Invalid request")
    } else if mem0.IsRateLimitedError(err) {
        fmt.Println("Rate limit exceeded")
    }
}

Code Generation

This SDK uses ogen for OpenAPI code generation.

To regenerate the client:

./generate.sh

License

MIT

Documentation

Overview

Example (Basic)
package main

import (
	"context"
	"fmt"
	"log"

	"github.com/plexusone/mem0-go"
)

func main() {
	// Create a client with API key
	client, err := mem0.NewClient(mem0.WithAPIKey("your-api-key"))
	if err != nil {
		log.Fatal(err)
	}

	ctx := context.Background()

	// Add a memory
	messages := []mem0.Message{
		{Role: mem0.RoleUser, Content: "I prefer dark mode in all my applications"},
	}

	result, err := client.Memory().Add(ctx, messages, mem0.WithUserID("user-123"))
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("Added memory with event ID: %s\n", result.EventID)
}
Example (ErrorHandling)
package main

import (
	"context"
	"fmt"
	"log"

	"github.com/plexusone/mem0-go"
)

func main() {
	client, err := mem0.NewClient(mem0.WithAPIKey("your-api-key"))
	if err != nil {
		log.Fatal(err)
	}

	ctx := context.Background()

	// Try to get a non-existent memory
	_, err = client.Memory().Get(ctx, "non-existent-id")
	if err != nil {
		if mem0.IsNotFoundError(err) {
			fmt.Println("Memory not found")
		} else if mem0.IsUnauthorizedError(err) {
			fmt.Println("Authentication failed")
		} else {
			log.Fatal(err)
		}
	}
}
Example (GetAll)
package main

import (
	"context"
	"fmt"
	"log"

	"github.com/plexusone/mem0-go"
)

func main() {
	client, err := mem0.NewClient(mem0.WithAPIKey("your-api-key"))
	if err != nil {
		log.Fatal(err)
	}

	ctx := context.Background()

	// Get all memories for a user with pagination
	result, err := client.Memory().GetAll(ctx,
		mem0.WithGetAllFilters(mem0.Filters{UserID: "user-123"}),
		mem0.WithPage(1),
		mem0.WithPageSize(50),
	)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("Total memories: %d\n", result.Count)
	for _, m := range result.Results {
		fmt.Printf("- %s\n", m.Memory)
	}
}
Example (History)
package main

import (
	"context"
	"fmt"
	"log"

	"github.com/plexusone/mem0-go"
)

func main() {
	client, err := mem0.NewClient(mem0.WithAPIKey("your-api-key"))
	if err != nil {
		log.Fatal(err)
	}

	ctx := context.Background()

	// Get history for a memory
	history, err := client.Memory().History(ctx, "memory-id-123")
	if err != nil {
		log.Fatal(err)
	}

	for _, h := range history {
		fmt.Printf("Event: %s, Old: %s, New: %s\n", h.Event, h.OldMemory, h.NewMemory)
	}
}
Example (Update)
package main

import (
	"context"
	"fmt"
	"log"

	"github.com/plexusone/mem0-go"
)

func main() {
	client, err := mem0.NewClient(mem0.WithAPIKey("your-api-key"))
	if err != nil {
		log.Fatal(err)
	}

	ctx := context.Background()

	// Update an existing memory
	updated, err := client.Memory().Update(ctx, "memory-id-123", "I now prefer light mode")
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("Updated memory: %s\n", updated.Memory)
}
Example (WithMetadata)
package main

import (
	"context"
	"fmt"
	"log"

	"github.com/plexusone/mem0-go"
)

func main() {
	client, err := mem0.NewClient(mem0.WithAPIKey("your-api-key"))
	if err != nil {
		log.Fatal(err)
	}

	ctx := context.Background()

	// Add a memory with metadata
	messages := []mem0.Message{
		{Role: mem0.RoleUser, Content: "My favorite programming language is Go"},
	}

	metadata := map[string]interface{}{
		"source":   "user_profile",
		"verified": true,
	}

	result, err := client.Memory().Add(ctx, messages,
		mem0.WithUserID("user-123"),
		mem0.WithMetadata(metadata),
	)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("Added memory with metadata: %v\n", result.EventID)
}

Index

Examples

Constants

View Source
const (
	// DefaultHostedBaseURL is the default base URL for the hosted mem0 platform.
	DefaultHostedBaseURL = "https://api.mem0.ai"

	// DefaultFOSSBaseURL is the default base URL for a self-hosted mem0 deployment.
	DefaultFOSSBaseURL = "http://localhost:8888"

	// EnvAPIKey is the environment variable name for the API key.
	//nolint:gosec // G101: Environment variable name, not a hardcoded credential
	EnvAPIKey = "MEM0_API_KEY"

	// EnvBaseURL is the environment variable name for the base URL.
	EnvBaseURL = "MEM0_BASE_URL"
)
View Source
const Version = "0.1.0"

Version is the current SDK version.

Variables

View Source
var (
	// ErrNoAPIKey is returned when no API key is provided.
	ErrNoAPIKey = errors.New("mem0: API key is required")

	// ErrInvalidBackend is returned when an unsupported backend is specified.
	ErrInvalidBackend = errors.New("mem0: invalid backend")

	// ErrNotFound is returned when a resource is not found.
	ErrNotFound = errors.New("mem0: resource not found")

	// ErrUnauthorized is returned when authentication fails.
	ErrUnauthorized = errors.New("mem0: unauthorized")

	// ErrBadRequest is returned when the request is invalid.
	ErrBadRequest = errors.New("mem0: bad request")

	// ErrRateLimited is returned when the rate limit is exceeded.
	ErrRateLimited = errors.New("mem0: rate limit exceeded")
)

Functions

func IsBadRequestError

func IsBadRequestError(err error) bool

IsBadRequestError returns true if the error indicates an invalid request.

func IsNotFoundError

func IsNotFoundError(err error) bool

IsNotFoundError returns true if the error indicates a resource was not found.

func IsRateLimitedError

func IsRateLimitedError(err error) bool

IsRateLimitedError returns true if the error indicates rate limiting.

func IsUnauthorizedError

func IsUnauthorizedError(err error) bool

IsUnauthorizedError returns true if the error indicates an authentication failure.

Types

type APIError

type APIError struct {
	StatusCode int
	Detail     string
	Code       string
}

APIError represents an error returned by the mem0 API.

func (*APIError) Error

func (e *APIError) Error() string

Error implements the error interface.

func (*APIError) Unwrap

func (e *APIError) Unwrap() error

Unwrap returns the underlying error based on status code.

type AddOption

type AddOption func(*addOptions)

AddOption configures the Add operation.

func WithAgentID

func WithAgentID(agentID string) AddOption

WithAgentID sets the agent ID for the operation.

func WithAppID

func WithAppID(appID string) AddOption

WithAppID sets the app ID for the operation.

func WithInfer

func WithInfer(infer bool) AddOption

WithInfer sets whether to infer facts from messages.

func WithMetadata

func WithMetadata(metadata map[string]interface{}) AddOption

WithMetadata sets metadata for the operation.

func WithRunID

func WithRunID(runID string) AddOption

WithRunID sets the run ID for the operation.

func WithUserID

func WithUserID(userID string) AddOption

WithUserID sets the user ID for the operation.

type AddResponse

type AddResponse struct {
	EventID string      `json:"event_id,omitempty"`
	Results []AddResult `json:"results,omitempty"`
}

AddResponse represents the full response from adding memories.

type AddResult

type AddResult struct {
	ID      string      `json:"id"`
	Memory  string      `json:"memory"`
	Event   MemoryEvent `json:"event"`
	EventID string      `json:"event_id,omitempty"`
}

AddResult represents the result of adding a memory.

type Backend

type Backend int

Backend selects which mem0 deployment to use.

const (
	// BackendHosted uses the hosted mem0 platform at api.mem0.ai.
	BackendHosted Backend = iota
	// BackendFOSS uses a self-hosted mem0 deployment.
	BackendFOSS
)

type Client

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

Client is the main entry point for the mem0 SDK.

func NewClient

func NewClient(opts ...Option) (*Client, error)

NewClient creates a new mem0 client with the given options. If no API key is provided via options, it will be loaded from the MEM0_API_KEY environment variable.

func (*Client) Config

func (c *Client) Config() *Config

Config returns the client configuration.

func (*Client) Memory

func (c *Client) Memory() Memory

Memory returns the Memory interface for performing memory operations.

type Config

type Config struct {
	APIKey  string
	BaseURL string
	Backend Backend
}

Config holds the client configuration.

func LoadConfigFromEnv

func LoadConfigFromEnv() *Config

LoadConfigFromEnv loads configuration from environment variables.

type DeleteAllOption

type DeleteAllOption func(*deleteAllOptions)

DeleteAllOption configures the DeleteAll operation.

func WithDeleteAgentID

func WithDeleteAgentID(agentID string) DeleteAllOption

WithDeleteAgentID sets the agent ID for delete all.

func WithDeleteAppID

func WithDeleteAppID(appID string) DeleteAllOption

WithDeleteAppID sets the app ID for delete all.

func WithDeleteRunID

func WithDeleteRunID(runID string) DeleteAllOption

WithDeleteRunID sets the run ID for delete all.

func WithDeleteUserID

func WithDeleteUserID(userID string) DeleteAllOption

WithDeleteUserID sets the user ID for delete all.

type DeleteAllResult

type DeleteAllResult struct {
	Message      string `json:"message"`
	DeletedCount int    `json:"deleted_count"`
}

DeleteAllResult represents the result of deleting all memories.

type Entity

type Entity struct {
	Type        EntityType `json:"type"`
	ID          string     `json:"id"`
	MemoryCount int        `json:"memory_count"`
	CreatedAt   time.Time  `json:"created_at"`
	UpdatedAt   time.Time  `json:"updated_at"`
}

Entity represents an entity (user, agent, app, or run).

type EntityType

type EntityType string

EntityType represents the type of entity.

const (
	EntityTypeUser  EntityType = "user"
	EntityTypeAgent EntityType = "agent"
	EntityTypeApp   EntityType = "app"
	EntityTypeRun   EntityType = "run"
)

type EventStatus

type EventStatus struct {
	EventID     string      `json:"event_id"`
	Status      string      `json:"status"`
	Results     []AddResult `json:"results,omitempty"`
	Error       string      `json:"error,omitempty"`
	CreatedAt   time.Time   `json:"created_at"`
	CompletedAt *time.Time  `json:"completed_at,omitempty"`
}

EventStatus represents the status of an asynchronous operation.

type Filters

type Filters struct {
	UserID  string `json:"user_id,omitempty"`
	AgentID string `json:"agent_id,omitempty"`
	AppID   string `json:"app_id,omitempty"`
	RunID   string `json:"run_id,omitempty"`
}

Filters represents filter conditions for memory queries.

type GetAllOption

type GetAllOption func(*getAllOptions)

GetAllOption configures the GetAll operation.

func WithGetAllFilters

func WithGetAllFilters(filters Filters) GetAllOption

WithGetAllFilters sets filters for getting all memories.

func WithPage

func WithPage(page int) GetAllOption

WithPage sets the page number for pagination.

func WithPageSize

func WithPageSize(pageSize int) GetAllOption

WithPageSize sets the page size for pagination.

type GetAllResult

type GetAllResult struct {
	Count    int          `json:"count"`
	Next     string       `json:"next,omitempty"`
	Previous string       `json:"previous,omitempty"`
	Results  []MemoryItem `json:"results"`
}

GetAllResult represents the result of getting all memories with pagination.

type HistoryItem

type HistoryItem struct {
	ID        string      `json:"id"`
	MemoryID  string      `json:"memory_id"`
	OldMemory string      `json:"old_memory,omitempty"`
	NewMemory string      `json:"new_memory"`
	Event     MemoryEvent `json:"event"`
	CreatedAt time.Time   `json:"created_at"`
}

HistoryItem represents a single history entry for a memory.

type Memory

type Memory interface {
	// Add extracts facts from conversation messages and stores them as memories.
	Add(ctx context.Context, messages []Message, opts ...AddOption) (*AddResponse, error)

	// Get retrieves a specific memory by ID.
	Get(ctx context.Context, memoryID string) (*MemoryItem, error)

	// GetAll retrieves all memories with optional filtering and pagination.
	GetAll(ctx context.Context, opts ...GetAllOption) (*GetAllResult, error)

	// Search performs a hybrid search combining semantic, BM25, and entity matching.
	Search(ctx context.Context, query string, opts ...SearchOption) ([]SearchResult, error)

	// Update modifies an existing memory.
	Update(ctx context.Context, memoryID string, text string) (*MemoryItem, error)

	// Delete removes a single memory.
	Delete(ctx context.Context, memoryID string) error

	// DeleteAll removes all memories matching the given filters.
	DeleteAll(ctx context.Context, opts ...DeleteAllOption) (*DeleteAllResult, error)

	// History retrieves the change history for a memory.
	History(ctx context.Context, memoryID string) ([]HistoryItem, error)

	// GetEventStatus retrieves the status of an asynchronous operation.
	GetEventStatus(ctx context.Context, eventID string) (*EventStatus, error)
}

Memory is the core interface for memory operations.

type MemoryEvent

type MemoryEvent string

MemoryEvent represents the type of operation performed on a memory.

const (
	MemoryEventAdd    MemoryEvent = "ADD"
	MemoryEventUpdate MemoryEvent = "UPDATE"
	MemoryEventDelete MemoryEvent = "DELETE"
	MemoryEventNoop   MemoryEvent = "NOOP"
)

type MemoryItem

type MemoryItem struct {
	ID         string                 `json:"id"`
	Memory     string                 `json:"memory"`
	UserID     string                 `json:"user_id,omitempty"`
	AgentID    string                 `json:"agent_id,omitempty"`
	AppID      string                 `json:"app_id,omitempty"`
	RunID      string                 `json:"run_id,omitempty"`
	Hash       string                 `json:"hash,omitempty"`
	Categories []string               `json:"categories,omitempty"`
	Metadata   map[string]interface{} `json:"metadata,omitempty"`
	CreatedAt  time.Time              `json:"created_at"`
	UpdatedAt  time.Time              `json:"updated_at"`
}

MemoryItem represents a single memory record.

type Message

type Message struct {
	Role    Role   `json:"role"`
	Content string `json:"content"`
}

Message represents a conversation message.

type Option

type Option func(*clientOptions)

Option configures the Client.

func WithAPIKey

func WithAPIKey(apiKey string) Option

WithAPIKey sets the API key for authentication.

func WithBackend

func WithBackend(backend Backend) Option

WithBackend sets the backend to use (hosted or FOSS).

func WithBaseURL

func WithBaseURL(baseURL string) Option

WithBaseURL sets a custom base URL for the API.

func WithHTTPClient

func WithHTTPClient(client *http.Client) Option

WithHTTPClient sets a custom HTTP client.

type Role

type Role string

Role represents the role of a message sender.

const (
	RoleUser      Role = "user"
	RoleAssistant Role = "assistant"
	RoleSystem    Role = "system"
)

type SearchOption

type SearchOption func(*searchOptions)

SearchOption configures the Search operation.

func WithFilters

func WithFilters(filters Filters) SearchOption

WithFilters sets filters for the search.

func WithRerank

func WithRerank(rerank bool) SearchOption

WithRerank enables reranking of search results.

func WithThreshold

func WithThreshold(threshold float64) SearchOption

WithThreshold sets the minimum score threshold for results.

func WithTopK

func WithTopK(topK int) SearchOption

WithTopK sets the number of results to return.

type SearchResult

type SearchResult struct {
	MemoryItem
	Score float64 `json:"score"`
}

SearchResult represents a memory search result with a relevance score.

Directories

Path Synopsis
internal
ogenhosted
Code generated by ogen, DO NOT EDIT.
Code generated by ogen, DO NOT EDIT.
Package omnimemory provides a mem0 provider for omnimemory.
Package omnimemory provides a mem0 provider for omnimemory.

Jump to

Keyboard shortcuts

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