# Get Config Source: https://docs.memmachine.ai/api-reference/configuration/get-config /openapi.json get /api/v2/config Get current configuration and resource status. Returns a comprehensive view of all configured resources in the system, including embedders, language models, rerankers, and databases. Each resource includes its current status (ready, failed, or pending) and any error messages if initialization failed. This endpoint is useful for: - Monitoring the health of configured resources - Diagnosing startup failures when resources are unavailable - Verifying that runtime configuration changes have been applied Resources may be in one of three states: - `ready`: The resource is initialized and available for use - `failed`: The resource failed to initialize (error details included) - `pending`: The resource is configured but not yet initialized # Get Episodic Memory Config Source: https://docs.memmachine.ai/api-reference/configuration/get-episodic-memory-config /openapi.json get /api/v2/config/memory/episodic Get episodic memory configuration. Returns the current episodic memory configuration including both long-term and short-term memory settings, and the overall enabled status. # Get Long Term Memory Config Source: https://docs.memmachine.ai/api-reference/configuration/get-long-term-memory-config /openapi.json get /api/v2/config/memory/episodic/long_term Get long-term memory configuration. Returns the current long-term memory configuration including embedder, reranker, vector graph store, and enabled status. # Get Resources Source: https://docs.memmachine.ai/api-reference/configuration/get-resources /openapi.json get /api/v2/config/resources Get status of all configured resources. Returns the status of all embedders, language models, rerankers, and databases configured in the system. This is a subset of the full configuration response, focused specifically on resource health. Each resource entry includes: - `name`: The unique identifier for the resource - `provider`: The type of provider (e.g., 'openai', 'amazon-bedrock') - `status`: Current state ('ready', 'failed', or 'pending') - `error`: Error message if the resource failed to initialize Use this endpoint to quickly check which resources are available before making API calls that depend on specific embedders or models. # Get Semantic Memory Config Source: https://docs.memmachine.ai/api-reference/configuration/get-semantic-memory-config /openapi.json get /api/v2/config/memory/semantic Get semantic memory configuration. Returns the current semantic memory configuration including database, LLM model, embedding model, and enabled status. # Get Short Term Memory Config Source: https://docs.memmachine.ai/api-reference/configuration/get-short-term-memory-config /openapi.json get /api/v2/config/memory/episodic/short_term Get short-term memory configuration. Returns the current short-term memory configuration including LLM model, message capacity, and enabled status. # Update Episodic Memory Config Source: https://docs.memmachine.ai/api-reference/configuration/update-episodic-memory-config /openapi.json put /api/v2/config/memory/episodic Update episodic memory configuration. This endpoint updates the episodic memory configuration at runtime, including both long-term and short-term memory settings. Only the fields you supply are modified; omitted fields retain their current values. The configuration includes: - long_term_memory: Long-term memory settings (embedder, reranker, vector_graph_store) - short_term_memory: Short-term memory settings (llm_model, message_capacity) - long_term_memory_enabled: Whether long-term memory is enabled - short_term_memory_enabled: Whether short-term memory is enabled - enabled: Whether episodic memory is enabled overall # Update Long Term Memory Config Source: https://docs.memmachine.ai/api-reference/configuration/update-long-term-memory-config /openapi.json put /api/v2/config/memory/episodic/long_term Update long-term memory configuration. This endpoint updates the long-term memory configuration at runtime. Only the fields you supply are modified; omitted fields retain their current values. The configuration includes: - embedder: The embedder resource to use for creating embeddings - reranker: The reranker resource to use for search result reranking - vector_graph_store: The database for storing long-term memories - enabled: Whether long-term memory is enabled # Update Memory Config Endpoint Source: https://docs.memmachine.ai/api-reference/configuration/update-memory-config-endpoint /openapi.json put /api/v2/config/memory Update the episodic and/or semantic memory configuration. This endpoint allows updating the memory configuration at runtime after resources (embedders, language models, rerankers) have been added or changed. Without calling this endpoint, newly added resources will not be used by the memory systems. Both `episodic_memory` and `semantic_memory` are optional. Supply one or both depending on which sections need updating. Within each section, only the fields you supply are modified; omitted fields retain their current values. **Typical workflow:** 1. Add a new resource via `POST /config/resources/embedders` or `POST /config/resources/language_models` 2. Call this endpoint to point the memory configuration at the new resource 3. The configuration is persisted to the configuration file **Example - update episodic long-term memory to use a new embedder:** ```json { "episodic_memory": { "long_term_memory": { "embedder": "my-new-embedder" } } } ``` **Example - update semantic memory to use a new LLM and embedder:** ```json { "semantic_memory": { "llm_model": "my-new-model", "embedding_model": "my-new-embedder" } } ``` Returns 400 if no updates are supplied (both sections are null or empty). # Update Semantic Memory Config Source: https://docs.memmachine.ai/api-reference/configuration/update-semantic-memory-config /openapi.json put /api/v2/config/memory/semantic Update semantic memory configuration. This endpoint updates the semantic memory configuration at runtime. Only the fields you supply are modified; omitted fields retain their current values. The configuration includes: - enabled: Whether semantic memory is enabled - database: The database resource to use for storing semantic memories - llm_model: The language model to use for feature extraction - embedding_model: The embedder to use for semantic similarity - ingestion_trigger_messages: Number of messages before triggering ingestion - ingestion_trigger_age_seconds: Age threshold for triggering ingestion # Update Short Term Memory Config Source: https://docs.memmachine.ai/api-reference/configuration/update-short-term-memory-config /openapi.json put /api/v2/config/memory/episodic/short_term Update short-term memory configuration. This endpoint updates the short-term memory configuration at runtime. Only the fields you supply are modified; omitted fields retain their current values. The configuration includes: - llm_model: The language model to use for summarization - message_capacity: Maximum message capacity in characters - enabled: Whether short-term memory is enabled # Configure Episodic Memory Source: https://docs.memmachine.ai/api-reference/episodic-configuration/configure-episodic-memory /openapi.json post /api/v2/memory/episodic/config Configure episodic memory for a project. Allows enabling or disabling episodic memory components for a specific project session. You can independently control: - **enabled**: Master switch for all episodic memory. When disabled, no episodic memories will be stored or retrieved. - **long_term_memory_enabled**: Controls long-term memory storage. Long-term memory provides persistent storage with summarization and vector search capabilities. - **short_term_memory_enabled**: Controls short-term memory storage. Short-term memory maintains recent context for the current session. Only provided (non-null) values are updated. Fields not specified in the request retain their current values. Returns 404 if the project does not exist. # Configure Long Term Memory Source: https://docs.memmachine.ai/api-reference/episodic-configuration/configure-long-term-memory /openapi.json post /api/v2/memory/episodic/long_term/config Configure long-term memory for a project. Allows enabling or disabling long-term episodic memory for a specific project session. Long-term memory provides persistent storage with summarization and vector search capabilities. Returns 404 if the project does not exist. # Configure Short Term Memory Source: https://docs.memmachine.ai/api-reference/episodic-configuration/configure-short-term-memory /openapi.json post /api/v2/memory/episodic/short_term/config Configure short-term memory for a project. Allows enabling or disabling short-term episodic memory for a specific project session. Short-term memory maintains recent context for the current session. Returns 404 if the project does not exist. # Get Episodic Memory Config Source: https://docs.memmachine.ai/api-reference/episodic-configuration/get-episodic-memory-config /openapi.json post /api/v2/memory/episodic/config/get Get episodic memory configuration for a project. Returns the current episodic memory configuration for the specified project, including whether episodic memory, long-term memory, and short-term memory are enabled. Returns 404 if the project does not exist. # Get Long Term Memory Config Source: https://docs.memmachine.ai/api-reference/episodic-configuration/get-long-term-memory-config /openapi.json post /api/v2/memory/episodic/long_term/config/get Get long-term memory configuration for a project. Returns whether long-term episodic memory is enabled for the specified project. Returns 404 if the project does not exist. # Get Short Term Memory Config Source: https://docs.memmachine.ai/api-reference/episodic-configuration/get-short-term-memory-config /openapi.json post /api/v2/memory/episodic/short_term/config/get Get short-term memory configuration for a project. Returns whether short-term episodic memory is enabled for the specified project. Returns 404 if the project does not exist. # Add Memories Source: https://docs.memmachine.ai/api-reference/memories/add-memories /openapi.json post /api/v2/memories Add memory messages to a project. The `types` field in the request specifies which memory types to add to: - If `types` is empty or not provided, memories are added to all types (episodic and semantic) - If `types` only contains `"episodic"`, memories are added only to Episodic memory - If `types` only contains `"semantic"`, memories are added only to Semantic memory - If `types` contains both, memories are added to both types Each memory message represents a discrete piece of information to be stored in the project's memory system. Messages can include content, metadata, timestamps, and other contextual details. The producer field indicates who created the message, while the produced_for field specifies the intended recipient. These fields help provide context for the memory and if provided should be user-friendly names. The endpoint accepts a batch of messages to be added in a single request. # Delete Episodic Memory Source: https://docs.memmachine.ai/api-reference/memories/delete-episodic-memory /openapi.json post /api/v2/memories/episodic/delete Delete episodic memories from a project. This operation permanently removes one or more episodic memories from the specified project. You may provide either `episodic_id` to delete a single memory or `episodic_ids` to delete multiple memories in one request. This action cannot be undone. If any of the specified episodic memories do not exist, a not-found error is returned for those entries. # Delete Semantic Memory Source: https://docs.memmachine.ai/api-reference/memories/delete-semantic-memory /openapi.json post /api/v2/memories/semantic/delete Delete semantic memories from a project. This operation permanently removes one or more semantic memories from the specified project. You may provide either `semantic_id` to delete a single memory or `semantic_ids` to delete multiple memories in one request. This action cannot be undone. If any of the specified semantic memories do not exist, a not-found error is returned for those entries. # List Memories Source: https://docs.memmachine.ai/api-reference/memories/list-memories /openapi.json post /api/v2/memories/list List memories within a project. System returns a paginated list of memories stored in the project. The page_size and page_num fields control pagination. The filter field accepts the structured filter expression language. User-defined metadata keys must be referenced with the `m.` or `metadata.` prefix (for example, `m.source = "chat_v3"`). Unknown or unsupported fields are rejected instead of being ignored. The set_metadata field scopes semantic memories to matching semantic sets. The type field allows specifying which memory type to list. # Search Memories Source: https://docs.memmachine.ai/api-reference/memories/search-memories /openapi.json post /api/v2/memories/search Search memories within a project. System returns the top K relevant memories matching the natural language query. The result is sorted by timestamp to help with context. The filter field accepts the structured filter expression language. User-defined metadata keys must be referenced with the `m.` or `metadata.` prefix (for example, `m.source = "chat_v3"`). Unknown or unsupported fields are rejected instead of being ignored. The set_metadata field scopes semantic memories to matching semantic sets. The types field allows specifying which memory types to include in the search. # Metrics Source: https://docs.memmachine.ai/api-reference/metrics/metrics /platform.openapi.json get /v2/metrics Expose Prometheus metrics. # Create Project Source: https://docs.memmachine.ai/api-reference/projects/create-project /openapi.json post /api/v2/projects Create a new project. This endpoint creates a project under the specified organization using the provided identifiers and configuration. Both `org_id` and `project_id` follow the rules: no slashes; only letters, numbers, underscores, hyphens, colon, and Unicode characters. Each project acts as an isolated memory namespace. All memories (episodes) inserted into a project belong exclusively to that project. Queries, listings, and any background operations such as memory summarization or knowledge extraction only access data within the same project. No cross-project memory access is allowed. If a project with the same ID already exists within the organization, the request will fail with an error. Returns the fully resolved project record, including configuration defaults applied by the system. # Delete Project Source: https://docs.memmachine.ai/api-reference/projects/delete-project /openapi.json post /api/v2/projects/delete Delete a project. Deletes the specified project identified by `org_id` and `project_id`, following the same rules as project creation. This operation removes the project and all associated memories (episodes) permanently from the system. It cannot be undone. If the project does not exist, a not-found error is returned. # Get Episode Count Source: https://docs.memmachine.ai/api-reference/projects/get-episode-count /openapi.json post /api/v2/projects/episode_count/get Retrieve the episode count for a project. An *episode* is the minimal unit of memory stored in the MemMachine system. In most cases, a single episode corresponds to one message or interaction from a user. Episodes are appended as the project accumulates conversational or operational data. This endpoint returns the total number of episodes currently recorded for the specified project. If the project does not exist, a not-found error is returned. # Get Project Source: https://docs.memmachine.ai/api-reference/projects/get-project /openapi.json post /api/v2/projects/get Retrieve a project. Returns the project identified by `org_id` and `project_id`, following the same rules as project creation. Each project acts as an isolated memory namespace. Queries and operations only access memories (episodes) stored within this project. No data from other projects is visible or included in any background processing, such as memory summarization or knowledge extraction. The response includes the project's description and effective configuration. If the project does not exist, a not-found error is returned. # List Projects Source: https://docs.memmachine.ai/api-reference/projects/list-projects /openapi.json post /api/v2/projects/list List projects in the specified organization. Requires `org_id` in the request body. Returns only projects belonging to that organization. Each entry contains the project's organization ID and project ID. Identifiers follow the standard rules: no slashes; only letters, numbers, underscores, hyphens, colon, and Unicode characters. Projects are isolated memory namespaces. Memories (episodes) belong exclusively to their project. All project operations, including queries and any background processes (e.g., memory summarization or knowledge extraction), only operate within the project's own data. No cross-project access is allowed. # Add Embedder Endpoint Source: https://docs.memmachine.ai/api-reference/resources/add-embedder-endpoint /openapi.json post /api/v2/config/resources/embedders Add a new embedder configuration at runtime. Creates a new embedder with the specified configuration and attempts to initialize it immediately. This allows adding embedders without restarting the server. The configuration is persisted to the configuration file. **Security Warning**: API keys and credentials are stored in plain text in the configuration file. Only use this API in protected environments. To avoid storing secrets in plain text, use environment variable references (e.g., `"api_key": "$OPENAI_API_KEY"`) which will be resolved at runtime. Supported providers: - `openai`: OpenAI embedding models (requires api_key, model) - `amazon-bedrock`: AWS Bedrock embedding models (requires region, model_id) - `sentence-transformer`: Local sentence transformer models (requires model) The response indicates whether the embedder was successfully initialized: - `success: true, status: ready`: Embedder is available for use - `success: false, status: failed`: Initialization failed (check error field) If initialization fails, the embedder configuration is still stored and can be retried later using the retry endpoint when the underlying service becomes available. Returns 422 if the provider type or configuration is invalid. # Add Language Model Endpoint Source: https://docs.memmachine.ai/api-reference/resources/add-language-model-endpoint /openapi.json post /api/v2/config/resources/language_models Add a new language model configuration at runtime. Creates a new language model with the specified configuration and attempts to initialize it immediately. This allows adding models without restarting the server. The configuration is persisted to the configuration file. **Security Warning**: API keys and credentials are stored in plain text in the configuration file. Only use this API in protected environments. To avoid storing secrets in plain text, use environment variable references (e.g., `"api_key": "$OPENAI_API_KEY"`) which will be resolved at runtime. Supported providers: - `openai-responses`: OpenAI models using the Responses API (requires api_key, model) - `openai-chat-completions`: OpenAI models using Chat Completions API (requires api_key, model) - `amazon-bedrock`: AWS Bedrock models (requires region, model_id) The response indicates whether the model was successfully initialized: - `success: true, status: ready`: Model is available for use - `success: false, status: failed`: Initialization failed (check error field) If initialization fails, the model configuration is still stored and can be retried later using the retry endpoint when the underlying service becomes available. Returns 422 if the provider type or configuration is invalid. # Delete Embedder Endpoint Source: https://docs.memmachine.ai/api-reference/resources/delete-embedder-endpoint /openapi.json delete /api/v2/config/resources/embedders/{name} Remove an embedder configuration. Permanently removes the specified embedder from the system. This removes both the cached instance and the configuration, so the embedder cannot be used until it is added again. The change is persisted to the configuration file. This operation is useful for: - Removing embedders that are no longer needed - Clearing failed embedders before adding a corrected configuration - Freeing resources used by unused embedders Returns 404 if the embedder does not exist. # Delete Language Model Endpoint Source: https://docs.memmachine.ai/api-reference/resources/delete-language-model-endpoint /openapi.json delete /api/v2/config/resources/language_models/{name} Remove a language model configuration. Permanently removes the specified language model from the system. This removes both the cached instance and the configuration, so the model cannot be used until it is added again. The change is persisted to the configuration file. This operation is useful for: - Removing models that are no longer needed - Clearing failed models before adding a corrected configuration - Freeing resources used by unused models Returns 404 if the language model does not exist. # Retry Embedder Endpoint Source: https://docs.memmachine.ai/api-reference/resources/retry-embedder-endpoint /openapi.json post /api/v2/config/resources/embedders/{name}/retry Retry building a failed embedder. Attempts to reinitialize an embedder that previously failed to build. This is useful when the underlying service (e.g., OpenAI API, AWS Bedrock) was temporarily unavailable during initial startup or configuration. The retry clears any previous error state and attempts a fresh build. If successful, the embedder becomes available for use immediately. The response indicates the result: - `success: true, status: ready`: Embedder is now available - `success: false, status: failed`: Still failing (check error field) Returns 404 if the embedder is not configured. # Retry Language Model Endpoint Source: https://docs.memmachine.ai/api-reference/resources/retry-language-model-endpoint /openapi.json post /api/v2/config/resources/language_models/{name}/retry Retry building a failed language model. Attempts to reinitialize a language model that previously failed to build. This is useful when the underlying service (e.g., OpenAI API, AWS Bedrock) was temporarily unavailable during initial startup or configuration. The retry clears any previous error state and attempts a fresh build. If successful, the model becomes available for use immediately. The response indicates the result: - `success: true, status: ready`: Model is now available - `success: false, status: failed`: Still failing (check error field) Returns 404 if the language model is not configured. # Retry Reranker Endpoint Source: https://docs.memmachine.ai/api-reference/resources/retry-reranker-endpoint /openapi.json post /api/v2/config/resources/rerankers/{name}/retry Retry building a failed reranker. Attempts to reinitialize a reranker that previously failed to build. This is useful when the underlying service or dependencies were temporarily unavailable during initial startup. The retry clears any previous error state and attempts a fresh build. If successful, the reranker becomes available for use immediately. The response indicates the result: - `success: true, status: ready`: Reranker is now available - `success: false, status: failed`: Still failing (check error field) Returns 404 if the reranker is not configured. # Add Semantic Category Source: https://docs.memmachine.ai/api-reference/semantic-memory:-categories/add-semantic-category /openapi.json post /api/v2/memories/semantic/category Add a semantic category to a set. Creates a new category within a specific set. Categories define how features are extracted and organized. Each category has: - A name for identification - A prompt that drives LLM feature extraction - An optional description Returns the unique identifier of the created category. # Add Semantic Category Template Source: https://docs.memmachine.ai/api-reference/semantic-memory:-categories/add-semantic-category-template /openapi.json post /api/v2/memories/semantic/category/template Add a semantic category template to a set type. Creates a category that will be inherited by all sets mapped to this set type. Template categories provide default extraction behavior that can be customized or disabled per-set. Returns the unique identifier of the created category template. # Add Semantic Tag Source: https://docs.memmachine.ai/api-reference/semantic-memory:-categories/add-semantic-tag /openapi.json post /api/v2/memories/semantic/category/tag Add a tag to a semantic category. Creates a new tag within a category. Tags represent specific types of features that can be extracted. Each tag has: - A name for identification - A description explaining what the tag represents Returns the unique identifier of the created tag. # Delete Semantic Category Source: https://docs.memmachine.ai/api-reference/semantic-memory:-categories/delete-semantic-category /openapi.json post /api/v2/memories/semantic/category/delete Delete a semantic category. Permanently removes the category and all associated tags and features. This is a destructive operation that cannot be undone. Returns 404 if the category does not exist. # Delete Semantic Tag Source: https://docs.memmachine.ai/api-reference/semantic-memory:-categories/delete-semantic-tag /openapi.json post /api/v2/memories/semantic/category/tag/delete Delete a semantic tag. Permanently removes the tag from its category. Features tagged with this tag may lose their tag association. Returns 404 if the tag does not exist. # Disable Semantic Category Source: https://docs.memmachine.ai/api-reference/semantic-memory:-categories/disable-semantic-category /openapi.json post /api/v2/memories/semantic/category/disable Disable a semantic category for a set. Prevents a category from being used for feature extraction on a specific set. This is useful for disabling inherited categories without deleting them. The category remains available for other sets. # Get Semantic Category Source: https://docs.memmachine.ai/api-reference/semantic-memory:-categories/get-semantic-category /openapi.json post /api/v2/memories/semantic/category/get Get a semantic category by ID. Retrieves a specific category using its unique identifier. Returns the category name, prompt, and description. Returns 404 if the category does not exist. # Get Semantic Category Set Ids Source: https://docs.memmachine.ai/api-reference/semantic-memory:-categories/get-semantic-category-set-ids /openapi.json post /api/v2/memories/semantic/category/set_ids/get Get set IDs associated with a category. Returns all set IDs that have features in the specified category. Useful for understanding the scope of a category's usage. # List Semantic Category Templates Source: https://docs.memmachine.ai/api-reference/semantic-memory:-categories/list-semantic-category-templates /openapi.json post /api/v2/memories/semantic/category/template/list List semantic category templates for a set type. Returns all categories defined on a set type. These categories are inherited by sets mapped to the set type. # Add Feature Source: https://docs.memmachine.ai/api-reference/semantic-memory:-features/add-feature /openapi.json post /api/v2/memories/semantic/feature Add a semantic feature to a project. Creates a new semantic feature with the specified category, tag, feature name, and value. Optional metadata and episode citations can be attached. Returns the unique identifier of the created feature. # Get Feature Source: https://docs.memmachine.ai/api-reference/semantic-memory:-features/get-feature /openapi.json post /api/v2/memories/semantic/feature/get Get a semantic feature by ID. Retrieves a specific semantic feature using its unique identifier. Optionally includes episode citations if `load_citations` is true. Returns 404 if the feature does not exist. # Update Feature Source: https://docs.memmachine.ai/api-reference/semantic-memory:-features/update-feature /openapi.json post /api/v2/memories/semantic/feature/update Update a semantic feature. Updates an existing semantic feature with new values. Only the fields provided in the request are updated; omitted fields retain their current values. Returns 404 if the feature does not exist. # Configure Semantic Set Source: https://docs.memmachine.ai/api-reference/semantic-memory:-sets/configure-semantic-set /openapi.json post /api/v2/memories/semantic/set/configure Configure a semantic set. Updates the embedder and/or language model used for a specific set. This allows customizing the models used for feature extraction and embedding on a per-set basis. If not configured, sets inherit the default embedder and language model. # Create Semantic Set Type Source: https://docs.memmachine.ai/api-reference/semantic-memory:-sets/create-semantic-set-type /openapi.json post /api/v2/memories/semantic/set_type Create a new semantic set type. A set type defines a template for grouping semantic features based on metadata tags. For example, a set type with tags ["user_id"] creates user-scoped feature groups. Set types can be organization-level (shared across projects) or project-level (scoped to a single project). Returns the unique identifier of the created set type. # Delete Semantic Set Type Source: https://docs.memmachine.ai/api-reference/semantic-memory:-sets/delete-semantic-set-type /openapi.json post /api/v2/memories/semantic/set_type/delete Delete a semantic set type. Permanently removes the specified set type. This does not delete the sets or features associated with the set type. Returns 404 if the set type does not exist. # Get Semantic Set Id Source: https://docs.memmachine.ai/api-reference/semantic-memory:-sets/get-semantic-set-id /openapi.json post /api/v2/memories/semantic/set_id/get Get or create a semantic set ID. Returns the set ID for the given set type configuration and optional metadata. If the set does not exist, it is created. The set ID is deterministically generated based on: - Organization and project scope - Set type (org-level or project-level) - Metadata tags and values # List Semantic Set Ids Source: https://docs.memmachine.ai/api-reference/semantic-memory:-sets/list-semantic-set-ids /openapi.json post /api/v2/memories/semantic/set_id/list List all semantic sets. Returns all sets for the organization/project context. Can be filtered by metadata values. # List Semantic Set Types Source: https://docs.memmachine.ai/api-reference/semantic-memory:-sets/list-semantic-set-types /openapi.json post /api/v2/memories/semantic/set_type/list List all semantic set types. Returns all set types defined for the organization. Each set type includes its metadata tag configuration and scope level. # Health Check Source: https://docs.memmachine.ai/api-reference/system/health-check /openapi.json get /api/v2/health Health check endpoint to verify server is running. # Metrics Source: https://docs.memmachine.ai/api-reference/system/metrics /openapi.json get /api/v2/metrics Expose Prometheus metrics. # Welcome Source: https://docs.memmachine.ai/api_reference/intro MemMachine API Options ## Welcome MemMachine provides flexible ways to interact with its powerful memory layer. We've organized our APIs into two main groups to fit your development needs: the **Python SDK** for direct integration and the **API Playground**, which contains our web-standard APIs. This ensures you can seamlessly integrate MemMachine into your projects, no matter your preferred language or architecture. ## Python SDK (Software Development Kit) The Python SDK is your go-to for directly integrating MemMachine’s capabilities into your Python applications. It's a collection of pre-built modules and functions designed to make interacting with MemMachine feel natural within your Python code. * **Best For:** Python developers building AI agents, data pipelines, or applications where Python is the primary language. * **Benefit:** Offers the most direct and idiomatic way to leverage MemMachine’s features within a Python environment, providing a rich set of tools and easy access to all functionalities. ## TypeScript SDK (Software Development Kit) The TypeScript SDK provides a type-safe, idiomatic way to integrate MemMachine into your web applications and Node.js services. Built on top of a robust REST architecture, it offers full auto-completion and compile-time safety, ensuring that your interaction with the memory engine is both predictable and efficient. * **Best For**: Web developers and software engineers building AI-native applications, chatbots, or backends using TypeScript or JavaScript. * **Benefit**: Leverages modern TypeScript features to provide deep IntelliSense support and schema validation. It simplifies complex memory operations into clean, promise-based methods that fit perfectly into modern async workflows. ## The API Playground The API Playground serves as a central hub for our web-based APIs, encompassing both REST and MCP APIs. If you're working outside of a Python environment, this is where you'll find the tools to connect your application to MemMachine. ### REST API (Representational State Transfer API) The REST API provides a web-standard way to interact with MemMachine using simple HTTP requests. It’s a universal interface that can be accessed from virtually any programming language or platform capable of making web requests. * **Best For:** Developers integrating MemMachine into web applications, mobile apps, or backend services using any programming language (e.g., JavaScript, Java, Go, C#). It’s also great for quick testing and scripting. * **Benefit:** Offers unparalleled flexibility and interoperability. If your application can make an HTTP request, it can talk to MemMachine, making it incredibly easy to integrate across a wide range of systems. ### MCP Toolkit (Model Content Protocol Tools) The MCP API defines a robust, language-agnostic protocol for managing all memory operations. It's designed to provide a highly scalable and stable foundation for MemMachine’s memory, allowing diverse clients to securely and efficiently access it across your infrastructure. * **Best For:** Deploying MemMachine as a standalone service, microservices architectures, or complex setups where the memory layer needs to be centrally managed and accessed by multiple applications or agents, potentially written in different languages. * **Benefit:** Provides a highly scalable and stable foundation for MemMachine’s memory, enabling secure and efficient access for diverse clients across your infrastructure. Choose the API offering that fits your needs best, then investigate the **API Playground** on the left-side menu to see how our offerings can work for you. # Tools Reference Source: https://docs.memmachine.ai/api_reference/mcp MemMachine Model Context Protocol (MCP) Tools The MemMachine Model Context Protocol (MCP) tools provide a dedicated, simplified interface for Large Language Models (LLMs) to interact with the memory system. These endpoints are designed to be concise and perform the core functions of memory management: adding new context, searching for existing context, and deleting memories. These tools work with both **Episodic Memory** (short-term conversation history) and **Semantic Memory** (long-term user profile and facts). ## 1. `add_memory` ### Summary Store important new information about the user or conversation into memory. ### Description Use this automatically whenever the user shares new facts, preferences, plans, emotions, or other details that could be useful for future context. **Crucially, include the full conversation context in the `content` field — not just a snippet.** This tool writes to both short-term (episodic) and long-term (profile) memory, so that future interactions can recall relevant background knowledge even across different sessions. ### Parameters | Name | Type | Required | Description | Default | | - | - | - | - | - | | `content` | `string` | Yes | The complete context or summary to store in memory. | | | `user_id` | `string` | No | The unique identifier of the user whose memory is being updated. This ensures the new memory is stored under the correct profile. | `user-{mac_address}` | | `proj_id` | `string` | No | Project ID. Defaults to `mcp-{user_id}` if `user_id` is provided. | `mcp-{user_id}` or `mcp-{mac_address}` | | `org_id` | `string` | No | Organization ID. | `mcp-universal` | ### Responses | Status Code | Description | | - | - | | `200` | Success | | `422` | Invalid or unprocessable content (e.g., failed to embed). | | `500` | MemMachine is not initialized or internal error. | ## 2. `search_memory` ### Summary Retrieve relevant context, memories, or profile information for a user. ### Description Use this whenever context is missing or unclear, or when you need to recall what has been previously discussed, even if it was from an earlier conversation or session. This searches both **Profile Memory** (long-term user traits and facts) and **Episodic Memory** (past conversations and experiences) for the most relevant results. ### Parameters | Name | Type | Required | Description | Default | | - | - | - | - | - | | `query` | `string` | Yes | The current user message or topic of discussion to search against. | | | `top_k` | `integer` | No | The maximum number of memory entries to retrieve. | `20` | | `user_id` | `string` | No | The unique identifier of the user whose memory is being searched. | `user-{mac_address}` | | `proj_id` | `string` | No | Project ID. Defaults to `mcp-{user_id}` if `user_id` is provided. | `mcp-{user_id}` or `mcp-{mac_address}` | | `org_id` | `string` | No | Organization ID. | `mcp-universal` | ### Responses | Type | Description | | - | - | | `SearchResult` | Returns the relevant context, memories, or profile data on success. | | `McpResponse` | Returns an error status/message on failure (e.g., MemMachine not initialized). | | `422` | Invalid or unprocessable content. | | `500` | MemMachine is not initialized or internal error. | ## 3. `delete_memory` ### Summary Delete specific memories from the user's memory store. ### Description Use this to remove outdated, incorrect, or sensitive information that should no longer be retained. Specify the unique IDs of the memories to delete from episodic or semantic memory stores. **Note**: Episodic memories and semantic memories are deleted separately as they have different ID spaces. You can obtain memory IDs from the `search_memory` results. ### Parameters | Name | Type | Required | Description | Default | | - | - | - | - | - | | `episodic_memory_uids` | `list[string]` | No | List of episodic memory IDs to delete. | `[]` | | `semantic_memory_uids` | `list[string]` | No | List of semantic memory IDs to delete. | `[]` | | `user_id` | `string` | No | The unique identifier of the user whose memories are being deleted. | `user-{mac_address}` | | `proj_id` | `string` | No | Project ID. Defaults to `mcp-{user_id}` if `user_id` is provided. | `mcp-{user_id}` or `mcp-{mac_address}` | | `org_id` | `string` | No | Organization ID. | `mcp-universal` | ### Responses | Status Code | Description | | - | - | | `200` | Success - memories deleted. | | `422` | Invalid or unprocessable content (e.g., invalid IDs). | | `500` | MemMachine is not initialized or internal error. | # Client Introduction Source: https://docs.memmachine.ai/api_reference/python/client The official Python client for communicating with the MemMachine Server. The **MemMachine Python Client SDK** provides a robust, type-safe interface for your applications to interact with the MemMachine Server. It handles the complexity of authentication, connection pooling, retries, and object serialization, allowing you to focus on building intelligent agents. ## Architecture The MemMachine Client SDK acts as a bridge between your application logic (e.g., an AI agent, a chatbot, or a backend service) and the MemMachine Server. ### Communication Flow The following diagram illustrates how the Client SDK integrates into your system architecture: ```mermaid theme={null} graph LR subgraph "Infra [Your Infrastructure]" App["Your Application / Agent"] -->|Python SDK| Client["MemMachine Client"] end subgraph "Net [Network]" Client -->|HTTP/REST| LB["Load Balancer / Ingress"] end subgraph "ServerSide [MemMachine Server]" LB --> Server["MemMachine Server API"] Server -->|Read/Write| Episodic["Episodic Memory Store"] Server -->|Read/Write| Semantic["Semantic Memory Store"] Server -->|Query| LLM["LLM Provider (OpenAI/Bedrock)"] end ``` ### Interaction Sequence The standard workflow involves initializing the client, selecting a project, defining a memory context, and then performing operations. ```mermaid theme={null} sequenceDiagram participant App as Your App participant SDK as MemMachine Client participant API as MemMachine Server participant DB as Database Note over App, SDK: Initialization App->>SDK: Init MemMachineClient(base_url) App->>SDK: create_project(org="my-org", project="agent-1") SDK->>API: POST /api/v2/projects API->>DB: Create Project Record API-->>SDK: 200 OK (Project Config) Note over App, SDK: Runtime Operation App->>SDK: project.memory(user="alice", agent="bot") App->>SDK: memory.add("I like pizza") SDK->>API: POST /api/v2/memories API->>DB: Store Episode & Update Semantic Profile API-->>SDK: 200 OK App->>SDK: memory.search("What does Alice like?") SDK->>API: POST /api/v2/memories/search API->>DB: Vector Search & Retrieval API-->>SDK: 200 OK (Results) SDK-->>App: Return SearchResult Object ``` ## Installation Install the client package via pip: ```bash theme={null} pip install memmachine-client ``` ## Hello World Example This complete example demonstrates the core workflow: connecting to the server, initializing a project workspace, and performing memory operations. ```python title="MemMachineClient Hello World" Expandable theme={null} import time from memmachine_client import MemMachineClient def main(): # 1. Initialize the Client # Ensure your MemMachine server is running at this URL client = MemMachineClient(base_url="http://localhost:8080") # 2. Define a Project Workspace # Projects segregate data within an organization. # 'get_or_create_project' is idempotent; it returns the existing project if it exists. print("Initializing Project...") project = client.get_or_create_project( org_id="acme-corp", project_id="support-bot-v1", description="Memory store for customer support agent" ) print(f"Connected to Project: {project.org_id}/{project.project_id}") # 3. Create a Context-Aware Memory Interface # This interface scopes all operations to a specific user and agent interaction. # - user_id: The end-user (human) # - agent_id: Your AI agent # - session_id: (Optional) A specific conversation thread memory = project.memory( user_id="alice_123", agent_id="support_bot_01", session_id="session_555" ) # 4. Add Memories (Simulating a conversation) print("Adding memories...") # User states a preference memory.add( content="I am strictly vegetarian and I love spicy food.", role="user", metadata={"topic": "food_preference"} ) # Agent acknowledges memory.add( content="Noted, I will recommend vegetarian spicy options.", role="assistant" ) # 5. Search Memories # Retrieve relevant context for a new query print("\nSearching for context...") query = "What should I suggest for dinner?" results = memory.search(query) print(f"Query: {query}") print("Results found:") for idx, item in enumerate(results.get('episodic_memory', [])): print(f"[{idx+1}] {item['content']} (Role: {item['producer_role']})") if __name__ == "__main__": main() ``` The expected output from running the above Hello World script should look like this: ```bash title="Hello World Expected Output" theme={null} python sample.py Initializing Project... Connected to Project: acme-corp/support-bot-v1 Adding memories... Searching for context... Query: What should I suggest for dinner? Results found: [1] I am strictly vegetarian and I love spicy food. (Role: user) [2] Noted, I will recommend vegetarian spicy options. (Role: assistant) [3] I am strictly vegetarian and I love spicy food. (Role: user) [4] Noted, I will recommend vegetarian spicy options. (Role: assistant) ``` ## Explore the API Now that you understand the architecture, dive into the specific namespaces to see what you can build: Initialization, connection management, and global configuration. Manage isolated data boundaries and organizations. Ingest and search the raw stream of interaction data. Organize facts into Sets, Categories, and Tags. Fine-tune LLM, Embedder, and Reranker resources. Monitor server status, metrics, and version compatibility. ## Core Concepts ### `MemMachineClient` The entry point for the SDK. It manages the persistent HTTP session, connection pooling, and global configuration (like timeouts and retries). **Key Parameters:** * `base_url`: The URL of your MemMachine Server (e.g., `http://localhost:8080`). * `api_key`: (Optional) Authentication token if your server requires it. * `timeout`: Request timeout in seconds (default: 30). ### `Project` A **Project** represents an isolated workspace. All data in MemMachine is siloed by `org_id` and `project_id`. * Use `client.create_project()` to initialize or retrieve a project. * Use `client.get_project()` to retrieve an existing project (raises error if not found). ### `Memory` The **Memory** object is a transient interface bound to a specific *context*. It does not hold state itself but ensures that every operation (add, search, delete) is tagged with the correct metadata identifiers: * `user_id`: The human user. * `agent_id`: The AI agent. * `group_id`: (Optional) A group identifier for multi-user contexts. * `session_id`: (Optional) A specific session identifier. **Key Methods:** * `add(content, role, ...)`: Stores a new memory episode. * `search(query, ...)`: Semantically searches for relevant memories. * `delete()`: Deletes memories matching specific criteria. # Client API Source: https://docs.memmachine.ai/api_reference/python/client_api High-level API reference for the Namespaced MemMachineClient `MemMachineClient` is the primary interface for managing episodic and semantic memory. The client is organized into logical **Namespaces** to improve discoverability and match the modular backend architecture. ## Initialization The client manages a persistent HTTP session, handles authentication, and provides global timeout settings for all sub-client requests. ```python theme={null} from memmachine_client import MemMachineClient client = MemMachineClient( base_url="http://localhost:8080", api_key="your-api-key-here", timeout=30.0 ) ``` ### Parameters | **Parameter** | **Type** | **Default** | **Description** | | | - | - | - | - | - | | `base_url` | `str` | `"http://localhost:8080"` | The root URL of your MemMachine server. | | | `api_key` | \`str | None\` | `None` | Optional bearer token for authenticated environments. | | `timeout` | `float` | `30.0` | Global request timeout in seconds. | | *** ## Namespaces The client is divided into specialized sub-clients. Accessing these allows you to perform operations specific to those domains. | **Namespace** | **Accessor** | **Purpose** | | - | - | - | | **Projects** | `client.projects` | Create, delete, and list isolated memory namespaces. | | **Memories** | `client.memories` | Ingest episodic messages and perform hybrid searches. | | **Semantic** | `client.semantic` | Manage the "Knowledge Graph" (Sets, Categories, and Tags). | | **Configuration** | `client.config` | Manage LLMs, Embedders, and runtime memory settings. | | **System** | `client.system` | Monitor health, metrics, and server versioning. | *** ## Core Client Methods While most operations live in namespaces, the root client provides session management and raw request capabilities. ### `request` Make an authenticated HTTP request using the client's internal session. ```python theme={null} response = client.request(method="GET", path="/health") ``` | **Parameter** | **Type** | **Description** | | - | - | - | | `method` | `str` | HTTP verb (e.g., `"POST"`, `"GET"`, `"PUT"`, `"DELETE"`). | | `path` | `str` | The endpoint path (e.g., `"/projects"`). | | `**kwargs` | `any` | Additional arguments passed to the underlying HTTP client. | ### `close` Cleanly shut down the HTTP connection pool. This is called automatically if using the client as a context manager. ```python theme={null} client.close() ``` ### `health_check` A convenience method to verify connectivity to the server. ```python theme={null} status = client.health_check() ``` **Returns:** A dictionary containing `status`, `service`, and `version`. *** ## Usage Patterns ### Context Manager (Recommended) Using a context manager ensures that connections are released even if an error occurs. ```python theme={null} with MemMachineClient(base_url="http://localhost:8080") as client: project = client.projects.get("my_org", "my_proj") # client.close() is called automatically here ``` ### Error Handling The SDK raises custom `RestError` exceptions for API-level validation or logic errors, allowing for granular error catching. ```python theme={null} from memmachine_client.exceptions import RestError try: client.projects.delete("org", "non_existent_proj") except RestError as e: print(f"Server returned {e.code}: {e.message}") ``` # Configuration API Source: https://docs.memmachine.ai/api_reference/python/config_api Reference for managing runtime resources and memory settings The `client.config` namespace provides programmatic access to the system's underlying resources and memory behavior. Use this to manage model providers, vector stores, and the specific toggles for Episodic and Semantic subsystems. ## System Configuration ### `get_full_config` Retrieves the entire current configuration of the MemMachine server, including active resources and default settings. ```python theme={null} config = client.config.get_full_config() print(config["episodic_memory"]["enabled"]) ``` *** ## Memory Subsystem Updates These methods allow you to modify how memory behaves without restarting the server. Only the fields you provide will be updated. ### `update_episodic` Configures the behavior of the episodic memory stream. | **Parameter** | **Type** | **Description** | | - | - | - | | `enabled` | `bool` | Master toggle for all episodic operations. | | `long_term` | `bool` | Enable/disable vector-based retrieval for older memories. | | `short_term` | `bool` | Enable/disable the sliding-window buffer of recent interactions. | ### `update_long_term` Updates the infrastructure used for long-term storage. ```python theme={null} client.config.update_long_term( vector_store="chroma", embedder="openai-small", reranker="cohere-v3" ) ``` | **Parameter** | **Type** | **Description** | | - | - | - | | `vector_store` | `str` | The name of the configured vector store resource. | | `embedder` | `str` | The name of the configured embedder resource. | | `reranker` | `str` | (Optional) The name of a reranker for high-precision search. | *** ## Resource Management ### `add_embedder` Registers a new embedding model provider. ```python theme={null} client.config.add_embedder( name="openai-v3", provider="openai", config={"api_key": "sk-...", "model": "text-embedding-3-small"} ) ``` ### `add_language_model` Registers a new LLM provider for summarization and semantic extraction. | **Parameter** | **Type** | **Description** | | - | - | - | | `name` | `str` | Unique identifier for this resource. | | `provider` | `str` | Provider type (e.g., `"openai"`, `"bedrock"`). | | `config` | `dict` | Provider-specific credentials and settings. | *** ## Resource Health & Recovery ### `retry_reranker` Attempts to re-initialize a reranker resource that has moved into a `FAILED` state. ```python theme={null} response = client.config.retry_reranker(name="cohere-v3") if response.success: print("Reranker is now READY") ``` ### `retry_language_model` Attempts to re-initialize a failed LLM provider. | **Parameter** | **Type** | **Description** | | - | - | - | | `name` | `str` | The name of the language model to retry. | *** Before updating a memory subsystem to use a new resource (like a new Embedder), ensure the resource has been added via `add_embedder` and is in a `READY` state. # Episodic Memory Source: https://docs.memmachine.ai/api_reference/python/episodic_memory Server-side implementation of session-based conversational memory. The **Episodic Memory** module manages the "stream" of interactions for a specific session. It orchestrates the flow of data between the incoming API requests and the underlying vector and relational databases. ## The Ingestion Pipeline When the server receives an `AddMemoriesSpec` from the SDK, it triggers a transformation pipeline within the service layer. ### Data Mapping: SDK to Server The server maps the high-level `MemoryMessage` from the client into a persistent **`EpisodeEntry`**. This process includes: * **Producer Mapping:** The SDK's `producer` field is mapped to the internal `producer_id`. * **Role Assignment:** Validates the `producer_role` (e.g., "user", "assistant"). * **Timestamp Normalization:** Converts various incoming date formats into a standardized `AwareDatetime` (UTC). * **Metadata Casting:** Raw JSON payloads are cast to `dict[str, JsonValue]` for storage compatibility. *** ## Memory Configuration The server allows for granular control over how episodic data is handled through two distinct sub-modules: ### 1. Short-Term Memory (STM) * **Responsibility:** Manages the immediate context window. * **Server Logic:** Controls the retrieval of the most recent N episodes to provide "sliding window" context for LLM prompts. * **Operations:** `configure_short_term_memory` allows the server to toggle STM usage or adjust window sizes. ### 2. Long-Term Memory (LTM) * **Responsibility:** Manages the persistent, vector-indexed history of a session. * **Server Logic:** Handles the "summarization" loop, where older episodic memories are condensed to save space while retaining semantic meaning. * **Operations:** `configure_long_term_memory` enables or disables the backend vector-search retrieval for historical context. *** ## Internal Server Classes ### `EpisodicMemoryParams` This dataclass defines the environment for a memory instance. | Attribute | Type | Description | | :- | :- | :- | | `session_key` | `str` | The `{org_id}/{project_id}` unique identifier. | | `long_term_memory` | `LongTermMemory` | The backend vector store instance for this session. | | `short_term_memory` | `ShortTermMemory` | The backend relational/cache store for the context window. | | `metrics_factory` | `MetricsFactory` | Telemetry provider for monitoring ingestion rates. | ### `EpisodeEntry` (Internal Model) Unlike the SDK's `Episode`, the server's `EpisodeEntry` includes internal tracking fields: ```python theme={null} # Internal server-side structure class EpisodeEntry: content: str producer_id: str produced_for_id: str producer_role: str created_at: datetime metadata: dict[str, JsonValue] episode_type: EpisodeType # Defaults to MESSAGE ``` ## Lifecycle Management Episodic memory instances are **stateful** but **cached**. 1. **Creation:** When an API request arrives for a new session, the `EpisodicMemoryManager` instantiates the episodic sub-system. 2. **Reference Counting:** The server tracks how many active requests are utilizing a specific session instance. 3. **Cleanup:** Once the reference count drops to zero and the `max_life_time` is exceeded, the server flushes caches and closes database connections to conserve resources. # Episodic Memory Manager Source: https://docs.memmachine.ai/api_reference/python/episodic_memory_manager Server-side orchestration and lifecycle management for memory instances. The **Episodic Memory Manager** is a factory and orchestration layer that manages per-session memory instances. Its primary role is to ensure that memory resources (like vector store connections and LLM caches) are reused efficiently and disposed of correctly through a **Reference Counting** mechanism. ## Resource Orchestration In a high-concurrency server environment, creating a new memory instance for every single API request is expensive. The Manager solves this by maintaining an active cache of instances. ### The Lifecycle Flow 1. **Request:** An API call arrives with a `session_key` (derived from `org_id` and `project_id`). 2. **Lookup:** The Manager checks the `instance_cache` to see if a memory object for that session already exists. 3. **Instantiation:** If not found, it uses `EpisodicMemoryParams` to build a new instance. 4. **Reference Increment:** The manager increments the "Active User" count for that instance. 5. **Cleanup:** When the request finishes, the count decrements. If the count hits zero and the `max_life_time` expires, the instance is closed and purged from memory. *** ## Class `EpisodicMemoryManagerParams` These parameters define the "Rules of Engagement" for the server's memory usage. | Attribute | Type | Description | | :- | :- | :- | | `instance_cache_size` | `int` | The maximum number of unique sessions to keep in RAM simultaneously. | | `max_life_time` | `int` | How long (in seconds) an idle session stays in the cache before being evicted. | | `resource_manager` | `ResourceManager` | Provides shared access to the LLM and Embedding providers. | | `session_data_manager` | `SessionDataManager` | Handles the low-level database persistence for session metadata. | *** ## Class `EpisodicMemoryManager` The manager class is responsible for the thread-safe creation and retrieval of memory pillars. ### Key Responsibilities #### 1. Instance Retrieval (`get_instance`) The manager ensures that two concurrent requests for the same `project_id` share the same memory instance, preventing data race conditions and redundant database connections. #### 2. Cross-Namespace Support While primarily focused on Episodic data, the manager also facilitates the retrieval of **Semantic Memory** instances when a hybrid search is required, ensuring that the Knowledge Graph and the Chat History are synchronized. #### 3. Graceful Shutdown When the server receives a shutdown signal, the Manager is responsible for: * Flushing any pending "summarization" loops to the database. * Closing all active vector database connections. * Clearing the instance cache. *** ## Implementation Example (Internal) ```python theme={null} # How the server uses the manager inside service.py async def handle_request(spec): # Manager handles the 'get or create' logic automatically memory_instance = await manager.get_memory_instance( session_key=spec.session_key, params=default_params ) async with memory_instance: return await memory_instance.add(spec.messages) ``` Developer Note: Because the Manager uses reference counting, it is vital to use the memory instance within an async with block or manually call close() to prevent memory leaks in the server process. # Memories API Source: https://docs.memmachine.ai/api_reference/python/memory_api Reference for Episodic memory ingestion and retrieval The `client.memories` namespace provides methods for storing and searching "Episodic" memories—the raw stream of interactions and events associated with a project. ## Ingestion ### `add` Adds a new interaction or observation to the episodic memory store. ```python theme={null} client.memories.add( org_id="my_org", project_id="my_proj", content="The user prefers Python over JavaScript.", role="user", metadata={"source": "chat_v3"} ) ``` | **Parameter** | **Type** | **Default** | **Description** | | - | - | - | - | | `org_id` | `str` | **Required** | Organization identifier. | | `project_id` | `str` | **Required** | Project identifier. | | `content` | `str` | **Required** | The actual text of the memory episode. | | `role` | `str` | `"user"` | The role of the speaker (e.g., `"user"`, `"assistant"`, `"system"`). | | `producer` | `str` | `None` | Identifier of the entity that produced the message. | | `produced_for` | `str` | `None` | Identifier of the entity the message was intended for. | | `timestamp` | `str` | `None` | ISO-8601 timestamp string. Defaults to current server time. | | `metadata` | `dict` | `None` | Arbitrary key-value pairs for filtering and categorization. | *** ## Retrieval & Search ### `search` Performs a hybrid semantic search across the episodic memory store to find relevant context. ```python theme={null} results = client.memories.search( org_id="my_org", project_id="my_proj", query="What are the user's coding preferences?", limit=5, expand_context=2, score_threshold=0.65, agent_mode=True, filter_dict={"m.source": "chat_v3"}, ) ``` | **Parameter** | **Type** | **Default** | **Description** | | - | - | - | - | | `org_id` | `str` | **Required** | Organization identifier. | | `project_id` | `str` | **Required** | Project identifier. | | `query` | `str` | **Required** | The natural language search query. | | `limit` | `int` | `10` | Maximum number of results to return. | | `expand_context` | `int` | `0` | Number of neighboring episodic entries to include around each long-term match. | | `score_threshold` | `float` | `None` | Minimum episodic retrieval score to keep. Not supported when `agent_mode=True`. | | `agent_mode` | `bool` | `False` | Whether to use retrieval-agent search orchestration. | | `filter_dict` | `dict` | `None` | Metadata filters to apply to the search. User metadata keys must be prefixed with `m.` / `metadata.` (for example `{"m.source": "chat_v3"}`). Unknown or misspelled fields return a 400 error. | | `timeout` | `int` | `None` | Request timeout in seconds. Uses client default if omitted. | When constructing filters, always prefix user metadata fields with `m.` or `metadata.`. For example, use `{"m.user_id": "123"}` instead of `{"user_id": "123"}`. Filters that reference unqualified user metadata fields (or misspelled built-in fields) now fail fast with a 400 error instead of being ignored. *** ## Management ### `list_episodic` Retrieves a paginated list of raw memory episodes. | **Parameter** | **Type** | **Default** | **Description** | | - | - | - | - | | `org_id` | `str` | **Required** | Organization identifier. | | `project_id` | `str` | **Required** | Project identifier. | | `limit` | `int` | `50` | Number of items per page. | | `offset` | `int` | `0` | Number of items to skip. | ### `delete_all_episodic` Permanently removes all episodic memories from a specific project. ```python theme={null} client.memories.delete_all_episodic(org_id="my_org", project_id="my_proj") ``` *** ## Configuration ### `configure_episodic_memory` Adjusts the behavior of episodic memory for a project at runtime. | **Parameter** | **Type** | **Default** | **Description** | | - | - | - | - | | `enabled` | `bool` | `True` | Whether to allow episodic memory ingestion/retrieval. | | `long_term_memory_enabled` | `bool` | `True` | Enable vector-based retrieval for older memories. | | `short_term_memory_enabled` | `bool` | `True` | Enable retrieval of the most recent interactions. | *** Advanced semantic structures like Sets, Categories, and Tags have been moved to the client.semantic namespace to provide better structural clarity. # Memory Types & Models Source: https://docs.memmachine.ai/api_reference/python/memory_types Reference for the atomic Enums and Pydantic models used by the MemMachine server. The server utilizes a standardized set of types and models to ensure that data is validated and typed consistently across the **Service** and **Router** layers. These types are the "Source of Truth" for how the server interprets incoming requests. ## API Enumerations Enums are used to route logic within the service layer and categorize data in the persistent stores. ### `MemoryType` Defined in `memmachine_common.api`, this enum determines which store and service logic a request should target. | Member | Value | Description | | :- | :- | :- | | `Episodic` | `"episodic"` | Targets session-based conversational stores. | | `Semantic` | `"semantic"` | Targets the structured knowledge graph and tag stores. | ### `EpisodeType` Used within episodic memory to distinguish between different kinds of events. | Member | Value | Description | | :- | :- | :- | | `MESSAGE` | `"message"` | Represents a standard conversational exchange (User/Assistant). | *** ## Core Specification Models (DTOs) The server relies on Pydantic models defined in `spec.py` to validate and parse incoming data. ### `MemoryMessage` The primary unit of ingestion for Episodic memory. ```python theme={null} class MemoryMessage(BaseModel): content: str # The raw text of the message producer: str # The ID of the human or agent creator produced_for: str # The recipient ID timestamp: datetime # Standardized UTC timestamp role: str # e.g., "user", "assistant", or "system" metadata: dict # Custom JSON metadata ``` ### `SemanticFeature` The standardized output format for knowledge retrieved from the Semantic store. | **Field** | **Type** | **Description** | | - | - | - | | **`id`** | `str` | Unique UUID for the semantic tag. | | **`category_id`** | `str` | The parent category this tag belongs to. | | **`value`** | `str` | The actual knowledge value (e.g., "Likes Spicy Food"). | | **`metadata`** | `dict` | Contextual data regarding the source of the knowledge. | *** ## Content and Serialization ### `ContentType` (Enum) Specifies the format of data stored within an entry. | **Member** | **Value** | **Description** | | - | - | - | | `STRING` | `"string"` | The content is a standard UTF-8 text string. | While the current implementation primarily uses `STRING`, the server architecture is designed to support future serialization of vector embeddings or binary objects without altering the core schema. *** ## Legacy Structures The `GroupConfiguration` and `MemoryContext` objects from v1 are deprecated in the v2 API. The server now uses an **Org/Project/Session** hierarchy for secure data isolation, which is managed via the `_WithOrgAndProj` base model in `spec.py`. # Project API Source: https://docs.memmachine.ai/api_reference/python/project_api Reference for managing isolated memory namespaces The `client.projects` namespace allows you to manage the lifecycle of projects. A Project serves as a strict security and data boundary; memories from one project cannot be accessed by another. ## Project Lifecycle ### `create` Initializes a new project within an organization. If the project already exists, it returns the existing project details. ```python theme={null} project = client.projects.create( org_id="my_org", project_id="my_project", description="Main memory store for our customer support agent", metadata={"environment": "production"} ) ``` | **Parameter** | **Type** | **Description** | | - | - | - | | `org_id` | `str` | Organization identifier. | | `project_id` | `str` | Unique project identifier within the org. | | `description` | `str` | Optional text describing the project. | | `metadata` | `dict` | Optional key-value pairs for organizational labeling. | ### `get` Retrieves the details of an existing project. ```python theme={null} project = client.projects.get(org_id="my_org", project_id="my_project") ``` | **Parameter** | **Type** | **Description** | | - | - | - | | `org_id` | `str` | Organization identifier. | | `project_id` | `str` | Project identifier. | ### `delete` Permanently removes a project and all associated episodic and semantic data. This action is irreversible. All vector embeddings, relational tags, and chat history associated with this project will be destroyed. | **Parameter** | **Type** | **Description** | | - | - | - | | `org_id` | `str` | Organization identifier. | | `project_id` | `str` | Project identifier. | *** ## Project Inspection ### `get_episode_count` Returns the total number of episodic memory entries stored in the project. ```python theme={null} count = client.projects.get_episode_count("my_org", "my_project") print(f"Project has {count} memories.") ``` ### `list_all` Lists all project IDs belonging to a specific organization. ```python theme={null} projects = client.projects.list_all(org_id="my_org") ``` *** ## The Project Object When you use `client.projects.get()` or `create()`, you receive a `Project` instance. This object contains the following attributes: | **Attribute** | **Type** | **Description** | | - | - | - | | `org_id` | `str` | The organization ID this project belongs to. | | `project_id` | `str` | The unique ID for this project. | | `description` | `str` | The project's description. | | `configuration` | `dict` | The specific LLM/Embedder config used by this project. | # Semantic API Source: https://docs.memmachine.ai/api_reference/python/semantic_api Reference for managing structured Knowledge Sets, Categories, and Tags The `client.semantic` namespace manages the structured "Knowledge Graph" of your projects. Unlike episodic memory, which is a stream of events, semantic memory is used for organized facts, user preferences, and entity relationships. ## Semantic Sets Sets are the top-level containers for structured data within a project (e.g., a "User Preferences" set or a "Product Catalog" set). ### `create_set_type` Defines a new type of semantic set that can be instantiated. ```python theme={null} client.semantic.create_set_type( org_id="my_org", project_id="my_proj", name="UserPreferences", description="Stores long-term user habits and settings" ) ``` | **Parameter** | **Type** | **Description** | | - | - | - | | `org_id` | `str` | Organization identifier. | | `project_id` | `str` | Project identifier. | | `name` | `str` | Unique name for the set type. | | `description` | `str` | Optional summary of the set's purpose. | *** ## Categories Categories live inside Sets and define specific schemas for the data being stored. ### `add_category` Adds a new category to an existing semantic set. ```python theme={null} client.semantic.add_category( org_id="my_org", project_id="my_proj", set_id="set_123", name="DietaryRestrictions", template_id="v1_template" ) ``` | **Parameter** | **Type** | **Description** | | - | - | - | | `org_id` | `str` | Organization identifier. | | `project_id` | `str` | Project identifier. | | `set_id` | `str` | The ID of the parent Set. | | `name` | `str` | Name of the category. | | `template_id` | `str` | Optional schema template for validation. | *** ## Tags Tags are the individual "facts" or "labels" stored within a category. ### `add_tag` Adds a specific semantic tag to a category. ```python theme={null} client.semantic.add_tag( org_id="my_org", project_id="my_proj", category_id="cat_456", value="Vegetarian", metadata={"confidence": 0.98} ) ``` | **Parameter** | **Type** | **Description** | | - | - | - | | `org_id` | `str` | Organization identifier. | | `project_id` | `str` | Project identifier. | | `category_id` | `str` | The ID of the parent Category. | | `value` | `str` | The actual tag content (e.g., "Vegetarian"). | | `metadata` | `dict` | Optional key-value pairs for the tag. | *** ## Retrieval ### `get_features` Retrieves all semantic features (sets, categories, and tags) associated with a project or specific filter. | **Parameter** | **Type** | **Default** | **Description** | | - | - | - | - | | `org_id` | `str` | **Required** | Organization identifier. | | `project_id` | `str` | **Required** | Project identifier. | | `filter_dict` | `dict` | `None` | Filter by specific tags or categories. User metadata keys must be prefixed with `m.` / `metadata.`. Unknown or misspelled fields return a 400 error. | *** ## Deletion ### `delete_tag` Removes a specific tag from a category. ```python theme={null} client.semantic.delete_tag( org_id="my_org", project_id="my_proj", tag_id="tag_789" ) ``` Deleting a Set Type will recursively delete all Categories and Tags associated with it. This action cannot be undone. # Semantic Memory Source: https://docs.memmachine.ai/api_reference/python/semantic_memory Server-side implementation of structured knowledge and semantic tagging. The **Semantic Memory** module provides the server-side logic for managing structured knowledge. Unlike Episodic memory, which is chronological, Semantic memory is relational—organizing data into a hierarchy of **Sets**, **Categories**, and **Tags**. ## Knowledge Hierarchy The server implements a three-tier structure to ensure data remains organized and searchable: 1. **Semantic Set:** The top-level container (e.g., "User Profiles", "Product Catalog"). 2. **Category:** A specific attribute or bucket within a set (e.g., "Preferences", "Specifications"). 3. **Tag:** The atomic piece of knowledge (e.g., "Likes: Spicy Food", "Color: Blue"). *** ## Core Server Operations The server handles semantic operations through specialized specification models defined in `spec.py`. ### 1. Set Management Before tags can be added, a **Set Type** must be established. The server uses the `CreateSemanticSetTypeSpec` to define the schema and ownership of a knowledge set. ```python theme={null} # Server-side logic for set creation async def create_semantic_set_type(spec: CreateSemanticSetTypeSpec): # Validates org_id/project_id and initializes the set in the database ``` ### 2. Category Configuration Categories act as templates for data extraction. The server allows for **Category Templates**, which define how a Language Model should extract information from raw text to populate specific semantic tags. ### 3. Tag Ingestion & Consolidation When the SDK calls `client.semantic.add_tag()`, the server processes an `AddSemanticTagSpec`. * **Vectorization:** The server generates an embedding for the tag value. * **Consolidation:** Periodically, the server identifies "large sections" (many similar tags) and uses an LLM to deduplicate or summarize them into a single, cleaner entry. *** ## Technical Implementation Details ### Semantic Search (`hybrid_search`) The server does not perform simple keyword lookups. When a search request comes in, the server: 1. Filters the database by `org_id` and `project_id`. 2. Identifies the relevant `set_id`. 3. Performs a vector similarity search across all tags within that set. 4. Returns a `SemanticFeature` object containing the tag, its category, and associated metadata. ### Lifecycle and Caching Semantic instances are managed by the server's resource layer. Because semantic data is often shared across sessions (unlike private episodic chat logs), the server optimizes for **Read-Heavy** workloads, caching frequently accessed sets to reduce database latency. *** ## Internal Models (DTOs) The server utilizes the following Pydantic models for semantic operations: | **Model** | **Purpose** | | - | - | | `AddSemanticTagSpec` | Validates the category, value, and metadata for a new tag. | | `CreateSemanticSetTypeSpec` | Establishes a new knowledge boundary. | | `SemanticFeature` | The standardized output format for a retrieved knowledge entry. | ```python theme={null} # Example of a SemanticFeature returned by the server { "id": "uuid-123", "category_id": "user_preferences", "value": "Vegan", "metadata": {"source": "conversation_4"} } ``` # Server Implementation Source: https://docs.memmachine.ai/api_reference/python/server Technical overview of the MemMachine backend architecture and service layer. The **MemMachine Server** is a FastAPI-based backend designed to orchestrate complex memory operations across episodic and semantic stores. While the Client SDK provides a high-level interface for users, the Server Implementation handles the heavy lifting of reference counting, instance caching, and cross-store search coordination. ## Service Architecture The server is built around a "Shared Spec" architecture. Both the server and the client rely on a common set of Pydantic models (found in `spec.py`) to ensure that data validation is consistent across the network boundary. ### Core Architectural Pillars | Component | Responsibility | | :- | :- | | **API Router** | Manages RESTful endpoints, dependency injection (e.g., `get_memmachine`), and Prometheus metric collection. | | **Service Layer** | Translates incoming API specifications (`AddMemoriesSpec`) into internal storage models (`EpisodeEntry`). | | **Memory Managers** | Orchestrates the lifecycle of memory instances, ensuring that resources like vector database connections are cached and released efficiently. | | **Common Spec** | Defines the "Contract" between the server and the SDK, including Enums for `MemoryType` and `EpisodeType`. | *** ## Technical Organization The server's logic is partitioned to mirror the two primary memory types: ### Episodic Logic Focuses on the high-frequency ingestion of conversational data. The server implementation handles: * **Metadata Casting:** Ensuring raw JSON metadata is properly typed for the vector store. * **Context Injection:** Managing the `short_term_memory` and `long_term_memory` components within a single session. ### Semantic Logic Focuses on structured knowledge organization. The server implementation handles: * **Set & Category Management:** Creating the hierarchical structures (Sets -> Categories -> Tags) that organize long-term facts. * **Template Application:** Managing category templates for consistent knowledge extraction. *** ## Infrastructure Features ### Health & Monitoring The server includes built-in endpoints for container orchestration (Kubernetes/Docker): * `/health`: Returns service status and semantic versioning. * `/metrics`: Exposes Prometheus-formatted metrics for request latency and memory ingestion counts. ### Dependency Injection The server utilizes FastAPI dependencies to manage the `MemMachine` core instance, allowing for safe asynchronous access to the underlying storage engines across concurrent API requests. *** ## Next Steps To dive deeper into the specific implementation details of each module, explore the following sections: The atomic building blocks and Enums used by the server. Deep dive into session management and search logic. Understanding the knowledge graph and tag management. Reference counting and instance lifecycle details. # System API Source: https://docs.memmachine.ai/api_reference/python/system_api Reference for system health, metrics, and versioning The `client.system` namespace provides tools for monitoring the MemMachine server's health and performance. These endpoints are primarily used for infrastructure orchestration (like Kubernetes liveness probes) and performance monitoring. ## Health and Versioning ### `health` Performs a comprehensive health check of the MemMachine service and its connected dependencies (Vector Stores, Databases). ```python theme={null} status = client.system.health() print(f"Service: {status['service']} - Status: {status['status']}") ``` **Returns:** | **Field** | **Type** | **Description** | | - | - | - | | `status` | `str` | Current health state (e.g., `"healthy"`, `"degraded"`). | | `service` | `str` | Name of the service (`"memmachine"`). | | `version` | `str` | The semantic version of the running server. | ### `version` Returns detailed versioning information for the server and the API specification it supports. ```python theme={null} v = client.system.version() print(f"Running API Version: {v['api_version']}") ``` *** ## Observability ### `metrics` Exposes system-level performance metrics. By default, this returns metrics in the **Prometheus** text format, suitable for scraping by monitoring tools. ```python theme={null} prometheus_data = client.system.metrics() ``` **Common Metrics Tracked:** * `memmachine_request_duration_seconds`: Latency of API calls. * `memmachine_memory_ingestion_total`: Count of memories added. * `memmachine_vector_search_latency`: Time taken for embedding and searching. *** ## Environment Information ### `get_info` Retrieves non-sensitive environmental information about the server instance. ```python theme={null} info = client.system.get_info() ``` | **Field** | **Type** | **Description** | | - | - | - | | `environment` | `str` | Current mode (e.g., `"production"`, `"development"`). | | `uptime` | `float` | Server uptime in seconds. | | `provider` | `str` | The cloud or infrastructure provider detected. | *** ## Utility Methods ### `ping` A lightweight, low-latency check to verify that the network path to the server is open. ```python theme={null} if client.system.ping(): print("Server is reachable") ``` If you are running MemMachine in a containerized environment (Docker/K8s), use the `client.system.health()` endpoint for your **Liveness** and **Readiness** probes. # MemMachineAPIError Source: https://docs.memmachine.ai/api_reference/ts-rest/classes/MemMachineAPIError Custom error class for handling MemMachine SDK and API failures. ## Overview The `MemMachineAPIError` class is a custom error implementation used to represent failures returned by MemMachine client methods. It serves as the primary mechanism for catching and identifying SDK-specific issues. ### Hierarchy * **Error** * **MemMachineAPIError** *** ## Constructor ### `new MemMachineAPIError(message)` Initializes a new instance of the error with a specific descriptive message. | Parameter | Type | Description | | :- | :- | :- | | `message` | `string` | Error message describing the failure. | *** ## Properties | Property | Type | Description | | :- | :- | :- | | `message` | `string` | The error message inherited from the base `Error` class. | | `name` | `string` | The name identifier for the error class. | | `stack` | `string` | (Optional) A string representing the location in the code at which the error was thrown. | | `stackTraceLimit` | `number` | **Static.** Specifies the number of stack frames collected by a stack trace. Default is `10`. | *** ## Methods ### `captureStackTrace()` ```typescript Static theme={null} captureStackTrace(targetObject: object, constructorOpt?: Function): void ``` Creates a `.stack` property on `targetObject`, which when accessed returns a string representing the location in the code at which the method was called. This is useful for hiding implementation details of error generation from the user. ### `prepareStackTrace()` ```typescript theme={null} prepareStackTrace(err: Error, stackTraces: CallSite[]): any ``` A static hook used to customize the formatting of stack traces. *** ## Usage Example Integrate `MemMachineAPIError` into your error handling logic to differentiate between API-specific failures and general runtime errors. ```typescript theme={null} import { MemMachineAPIError } from '@memmachine/client'; try { // SDK Call } catch (error) { if (error instanceof MemMachineAPIError) { // Handle specific MemMachine failures console.error(`API Error: ${error.message}`); } else { // Handle standard JavaScript or network errors console.error('System Error:', error); } } ``` This class is defined in `src/errors/memmachine-api-error.ts`. # MemMachineClient Source: https://docs.memmachine.ai/api_reference/ts-rest/classes/MemMachineClient The primary entry point for the MemMachine TypeScript REST client library. ## Overview The `MemMachineClient` serves as the unified API for memory management, project operations, and server health checks. It is designed to be the starting point for all interactions with the MemMachine service. ### Key Features * **Hierarchical Management:** Generate `MemMachineMemory` and `MemMachineProject` instances for scoped operations. * **Resource Discovery:** List all projects accessible to your API key. * **Observability:** Access Prometheus metrics and perform real-time health checks on the server. *** ## Constructor ### `new MemMachineClient()` Initializes a new client instance. ```typescript theme={null} new MemMachineClient(options?: ClientOptions) ``` | **Parameter** | **Type** | **Description** | | - | - | - | | `options` | [`ClientOptions`](../interfaces/ClientOptions) | (Optional) Configuration including `api_key`, `base_url`, `timeout`, and `max_retries`. | *** ## Properties | **Property** | **Type** | **Description** | | - | - | - | | `client` | `AxiosInstance` | The underlying Axios instance used for making HTTP requests. | *** ## Methods ### `project()` Creates a `MemMachineProject` instance for managing a specific project. | **Parameter** | **Type** | **Description** | | - | - | - | | `projectContext` | [`ProjectContext`](../interfaces/ProjectContext) | Context options (e.g., `org_id`, `project_id`). | ### `getProjects(orgId)` Retrieves projects belonging to the specified organization. * **Returns:** `Promise` * **Throws:** [`MemMachineAPIError`](./MemMachineAPIError) ### `healthCheck()` Checks the current health status of the MemMachine server. * **Returns:** `Promise` * **Throws:** [`MemMachineAPIError`](./MemMachineAPIError) ### `getMetrics()` Retrieves Prometheus metrics from the server in string format. * **Returns:** `Promise` * **Throws:** [`MemMachineAPIError`](./MemMachineAPIError) *** ## Usage Example The following example demonstrates the recommended pattern for initializing the client and traversing to a specific project and memory instance. ```typescript theme={null} import MemMachineClient from '@memmachine/client'; async function main() { // 1. Initialize the client const client = new MemMachineClient({ api_key: 'your_api_key' }); // 2. Access a specific project const project = client.project({ org_id: 'your_org_id', project_id: 'your_project_id' }); // 3. Initialize memory for that project const memory = project.memory(); // 4. Perform high-level health checks const status = await client.healthCheck(); console.log(`Server Status: ${status.status}`); } main(); ``` For best performance, reuse a single `MemMachineClient` instance across your application to leverage connection pooling through the internal `AxiosInstance`. # MemMachineMemory Source: https://docs.memmachine.ai/api_reference/ts-rest/classes/MemMachineMemory Core class for managing episodic and semantic memories within a specific project context. ## Overview The `MemMachineMemory` class provides the primary interface for interacting with the memory engine. It allows for high-granularity control over adding, searching, listing, and deleting memories. ### Key Capabilities * **Flexible Ingestion:** Add raw text as memories with specific episode types. * **Semantic Retrieval:** Search memories using natural language queries. * **Context Awareness:** Retrieve combined project and memory metadata. *** ## Constructor ### `new MemMachineMemory()` Initializes a new memory management instance. This is typically handled internally by the `MemMachineProject.memory()` factory method. ```typescript theme={null} new MemMachineMemory( client: AxiosInstance, projectContext: ProjectContext, memoryContext?: MemoryContext ) ``` | **Parameter** | **Type** | **Description** | | - | - | - | | `client` | `AxiosInstance` | Internal Axios instance for API communication. | | `projectContext` | [`ProjectContext`](../interfaces/ProjectContext) | Scoping options including `org_id` and `project_id`. | | `memoryContext` | [`MemoryContext`](../interfaces/MemoryContext) | (Optional) Specific identifiers for the memory scope (e.g., `user_id`). | *** ## Properties | **Property** | **Type** | **Description** | | - | - | - | | `client` | `AxiosInstance` | The underlying HTTP client. | | `projectContext` | [`ProjectContext`](../interfaces/ProjectContext) | The organizational and project scope for this instance. | | `memoryContext` | [`MemoryContext`](../interfaces/MemoryContext) | The specific user or session context for this instance. | *** ## Methods ### `add()` Adds a new memory to the system within the current project scope. ```typescript theme={null} add(content: string, options?: AddMemoryOptions): Promise<AddMemoryResult> ``` | **Parameter** | **Type** | **Description** | | - | - | - | | `content` | `string` | The raw text content of the memory. | | `options` | [`AddMemoryOptions`](../interfaces/AddMemoryOptions) | (Optional) Metadata like `episode_type`. | ### `search()` Performs a semantic and or episodic search against the stored memories. ```typescript theme={null} search(query: string, options?: SearchMemoriesOptions): Promise<SearchMemoriesResult> ``` | **Parameter** | **Type** | **Description** | | - | - | - | | `query` | `string` | The natural language search term. | | `options` | [`SearchMemoriesOptions`](../interfaces/SearchMemoriesOptions) | (Optional) Search filters such as `top_k`, `filter`, `types`, and `agent_mode`. | ### `list()` Retrieves a paginated list of memories. ```typescript theme={null} list(options?: ListMemoriesOptions): Promise<SearchMemoriesResult> ``` | **Parameter** | **Type** | **Description** | | - | - | - | | `options` | [`ListMemoriesOptions`](../interfaces/ListMemoriesOptions) | (Optional) Pagination settings (`page_size`, `page_num`). | ### `delete()` Permanently removes a memory from the system. ```typescript theme={null} delete(id: string, type: MemoryType): Promise<void> ``` | **Parameter** | **Type** | **Description** | | - | - | - | | `id` | `string` | The unique identifier of the memory. | | `type` | [`MemoryType`](../types/MemoryType) | The classification of memory (e.g., `episodic`). | ### `getContext()` Retrieves the active project and memory context used by this instance. * **Returns:** `ProjectContext & MemoryContext` *** ## Usage Example ```typescript theme={null} const memory = project.memory(); // 1. Add a memory with a specific type await memory.add('User prefers dark mode and high-contrast settings.', { episode_type: 'message' }); // 2. Search memories semantically const results = await memory.search('What are the user preferences?', { top_k: 3 }); // 3. List recent memories const history = await memory.list({ page_size: 10 }); ``` All methods in this class throw a [`MemMachineAPIError`](./MemMachineAPIError) if the server returns a non-200 status code. # MemMachineProject Source: https://docs.memmachine.ai/api_reference/ts-rest/classes/MemMachineProject Class for managing the lifecycle, configuration, and memory scaling of a specific project. ## Overview The `MemMachineProject` class provides methods to manage and interact with projects within the MemMachine ecosystem\[cite: 1]. It serves as a middle-tier controller, allowing you to create projects, check memory usage, and spawn dedicated memory management instances. ### Key Features * **Project Lifecycle:** Create, retrieve, and delete project entities on the server. * **Memory Factory:** Initialize `MemMachineMemory` instances scoped to this project. * **Usage Metrics:** Retrieve the total count of episodic memories stored within the project. *** ## Constructor ### `new MemMachineProject()` Initializes a project instance. This is typically accessed via `client.project()`. ```typescript theme={null} new MemMachineProject(client: AxiosInstance, projectContext: ProjectContext) ``` | **Parameter** | **Type** | **Description** | | - | - | - | | `client` | `AxiosInstance` | Internal Axios instance for API communication. | | `projectContext` | [`ProjectContext`](../interfaces/ProjectContext) | Scoping identifiers like `org_id` and `project_id`. | *** ## Properties | **Property** | **Type** | **Description** | | - | - | - | | `client` | `AxiosInstance` | The underlying HTTP client. | | `projectContext` | [`ProjectContext`](../interfaces/ProjectContext) | The active organizational and project scope. | *** ## Methods ### `create()` Initializes the project on the MemMachine server. ```typescript theme={null} create(options?: CreateProjectOptions): Promise ``` * **Parameters:** `options` — [`CreateProjectOptions`](../interfaces/CreateProjectOptions) (Optional). * **Throws:** [`MemMachineAPIError`](./MemMachineAPIError) if the request fails. ### `get()` Retrieves the current metadata and state of the project from the server. ```typescript theme={null} get(): Promise ``` * **Returns:** `Promise` — The current project data model. ### `getEpisodicCount()` Retrieves the total number of episodic memories associated with this project. ```typescript theme={null} getEpisodicCount(): Promise ``` ### `memory()` Creates a `MemMachineMemory` instance scoped to this project. ```typescript theme={null} memory(memoryContext?: MemoryContext): MemMachineMemory ``` * **Parameters:** `memoryContext` — [`MemoryContext`](../interfaces/MemoryContext) (Optional). ### `delete()` Permanently removes the project and all associated memories from the server. ```typescript theme={null} delete(): Promise ``` *** ## Usage Example ```typescript theme={null} const project = client.project({ org_id: 'org_123', project_id: 'proj_456' }); // 1. Create the project if it doesn't exist await project.create({ description: 'AI Assistant Context' }); // 2. Check the memory footprint const count = await project.getEpisodicCount(); console.log(`Current memory count: ${count}`); // 3. Access memory operations const memory = project.memory(); ``` This class is the recommended gateway for memory management. Always use `project.memory()` to ensure your operations are correctly scoped to your organization and project ID. # AddMemoryOptions Source: https://docs.memmachine.ai/api_reference/ts-rest/interfaces/AddMemoryOptions Configuration options for ingesting new memories into the engine. ## Overview The `AddMemoryOptions` interface defines the optional configuration used when adding a new memory via the `MemMachineMemory.add()` method. It allows for detailed categorization, role assignment, and metadata tagging. *** ## Properties All properties in this interface are optional, allowing for flexible memory ingestion depending on your use case. | Property | Type | Description | | :- | :- | :- | | `producer` | `string` | The ID of the entity that produced the memory. | | `role` | [`MemoryProducerRole`](../types/MemoryProducerRole) | The role of the producer (e.g., `user`, `assistant`). | | `produced_for` | `string` | The ID of the target entity the memory was produced for. | | `episode_type` | `string` | A custom classification for the type of interaction episode. | | `timestamp` | `string` | The specific time the memory occurred (ISO 8601 string). | | `metadata` | `Record` | Key-value pairs for additional custom contextual data. | | `types` | [`MemoryType[]`](../types/MemoryType) | The classification of memories to be created (e.g., `episodic`). | *** ## Usage Example The following example shows how to use `AddMemoryOptions` to provide context when saving a user preference. ```typescript theme={null} import { AddMemoryOptions } from '@memmachine/client'; const memory = project.memory(); const options: AddMemoryOptions = { role: 'user', episode_type: 'preference_update', metadata: { feature: 'dark_mode', source: 'settings_ui' } }; await memory.add('User toggled dark mode to "on" for the dashboard.', options); ``` While `metadata` is optional, using it consistently is recommended for advanced filtering during semantic searches. # AddMemoryResult Source: https://docs.memmachine.ai/api_reference/ts-rest/interfaces/AddMemoryResult The confirmation payload returned after successfully adding memories. ## Overview When you ingest data into the memory engine, the server returns an `AddMemoryResult`. This contains the unique identifiers for the newly created memory entries, which can be used for later retrieval or specific updates. *** ## Properties | Property | Type | Description | | :- | :- | :- | | `results` | `{ uid: string }[]` | An array of objects, each containing the unique `uid` of an added memory entry. | *** ## Usage Example ```typescript theme={null} const result = await client.addEpisodicMemory(memoryData); // Log the ID of the first added memory if (result.results.length > 0) { console.log(`Memory saved with ID: ${result.results[0].uid}`); } ``` # ClientOptions Source: https://docs.memmachine.ai/api_reference/ts-rest/interfaces/ClientOptions Configuration settings for initializing the MemMachineClient. ## Overview The `ClientOptions` interface is used to configure the global behavior of the `MemMachineClient`, including authentication and network settings. *** ## Properties | Property | Type | Description | | :- | :- | :- | | `api_key` | `string` | **Optional.** The API key used to authenticate requests. | | `base_url` | `string` | **Optional.** The root URL of your MemMachine server instance. | | `max_retries` | `number` | **Optional.** The number of times to attempt a request before failing. | | `timeout` | `number` | **Optional.** The maximum duration (in ms) to wait for a server response. | *** ## Usage Example ```typescript theme={null} import { MemMachineClient, ClientOptions } from '@memmachine/client'; const config: ClientOptions = { api_key: 'mm_live_...', base_url: '[https://api.memmachine.ai](https://api.memmachine.ai)', timeout: 5000 }; const client = new MemMachineClient(config); ``` # CreateProjectOptions Source: https://docs.memmachine.ai/api_reference/ts-rest/interfaces/CreateProjectOptions Configuration for initializing a new memory project. ## Overview The `CreateProjectOptions` interface is used when calling `project.create()` to define the behavior and models for a new memory workspace. It allows you to specify the AI infrastructure that will power the semantic search and embedding storage. *** ## Properties | Property | Type | Description | | :- | :- | :- | | `description` | `string` | A brief summary of the project's purpose. | | `embedder` | `string` | The specific model used to convert text into vector embeddings. | | `reranker` | `string` | The model used to re-score and refine semantic search results for accuracy. | *** ## Usage Example ```typescript theme={null} import { CreateProjectOptions } from '@memmachine/client'; const newProjectConfig: CreateProjectOptions = { description: 'Support bot for mobile app users', embedder: 'text-embedding-3-small', reranker: 'cohere-rerank-v3' }; await client.project('mobile_support').create(newProjectConfig); ``` # EpisodicMemory Source: https://docs.memmachine.ai/api_reference/ts-rest/interfaces/EpisodicMemory The data model representing a chronological interaction or event. ## Overview `EpisodicMemory` represents a specific moment or interaction stored in the system. It includes the actual text content, who said it, and its relevance score when returned in a search. *** ## Properties | Property | Type | Description | | :- | :- | :- | | `uid` | `string` | The unique identifier for this memory entry. | | `content` | `string` | The raw text of the memory. | | `score` | `number` | The relevance score (usually 0 to 1) from a semantic search. | | `producer_id` | `string` | The ID of the user or system that created this memory. | | `producer_role` | `string` | The role (e.g., `user`, `assistant`) of the producer. | | `episode_type` | `string` | The classification of the interaction. | | `created_at` | `string` | ISO timestamp of when the memory was ingested. | | `metadata` | `Record` | **Optional.** Key-value pairs of additional context. | | `produced_for_id` | `string` | **Optional.** The ID of the recipient of the interaction. | *** ## Usage Example ```typescript theme={null} const { short_term_memory } = searchResponse.content.episodic_memory; const firstHit = short_term_memory.episodes[0]; console.log(`[${firstHit.score}] ${firstHit.producer_role}: ${firstHit.content}`); ``` # HealthStatus Source: https://docs.memmachine.ai/api_reference/ts-rest/interfaces/HealthStatus The data model for server connectivity and component status. ## Overview The `HealthStatus` interface is returned by the `client.health()` method, allowing you to monitor the availability of the MemMachine server and its sub-services. *** ## Properties | Property | Type | Description | | :- | :- | :- | | `status` | `string` | The overall health indicator (e.g., `"healthy"`). | | `service` | `string` | The name of the MemMachine service instance. | | `version` | `string` | The current version of the server software. | | `memory_managers` | `boolean` | Indicates if the internal memory subsystems are operational. | *** ## Usage Example ```typescript theme={null} const health = await client.health(); if (health.status === 'healthy') { console.log(`Connected to MemMachine v${health.version}`); } ``` # ListMemoriesOptions Source: https://docs.memmachine.ai/api_reference/ts-rest/interfaces/ListMemoriesOptions Pagination and filtering options for retrieving sets of memories. ## Overview The `ListMemoriesOptions` interface provides control over the retrieval of multiple memory records, enabling pagination and broad filtering across the memory store. *** ## Properties | Property | Type | Description | | :- | :- | :- | | `type` | [`MemoryType`](../types/MemoryType) | **Optional.** Restricts the list to specific memory classifications (e.g., `episodic`). | | `filter` | `string` | **Optional.** Structured filter criteria. User metadata fields must be prefixed with `m.` / `metadata.` (for example `m.source = "chat_v3"`). Unsupported fields are rejected. | | `page_num` | `number` | **Optional.** The specific page index to retrieve (defaults to 1). | | `page_size` | `number` | **Optional.** The number of records to return per page. | *** ## Usage Example ```typescript theme={null} import { ListMemoriesOptions } from '@memmachine/client'; const options: ListMemoriesOptions = { type: 'episodic', filter: 'm.source = "chat_v3"', page_num: 2, page_size: 20 }; const history = await memory.list(options); ``` # MemoryContext Source: https://docs.memmachine.ai/api_reference/ts-rest/interfaces/MemoryContext Granular identifiers for scoping memories to specific users, sessions, or agents. ## Overview `MemoryContext` provides an additional layer of segmentation within a project. While `ProjectContext` handles broad isolation, `MemoryContext` allows you to track and retrieve data for specific entities or conversation threads. *** ## Properties | Property | Type | Description | | :- | :- | :- | | `user_id` | `string` | **Optional.** The ID of the end-user associated with the memory. | | `session_id` | `string` | **Optional.** A unique ID for a specific conversation session or thread. | | `agent_id` | `string` | **Optional.** The ID of the specific AI agent instance. | | `group_id` | `string` | **Optional.** An ID used to group related entities or users. | *** ## Usage Example ```typescript theme={null} import { MemoryContext } from '@memmachine/client'; const userSession: MemoryContext = { user_id: 'user_99', session_id: 'chat_hash_abc123' }; ``` # Project Source: https://docs.memmachine.ai/api_reference/ts-rest/interfaces/Project The complete data model for a MemMachine project workspace. ## Overview The `Project` interface represents the full metadata and configuration state of a project. It is the primary return type for the `getDetails()` method. *** ## Properties | Property | Type | Description | | :- | :- | :- | | `org_id` | `string` | The unique identifier of the organization owning the project. | | `project_id` | `string` | The unique identifier of the project itself. | | `description` | `string` | A human-readable summary of the project. | | `config` | `object` | The active AI configuration, including `embedder` and `reranker` model strings. | *** ## Usage Example ```typescript theme={null} const project = client.project({ org_id: 'customer-support', project_id: 'customer-support' }); const details = await project.get(); console.log(`Project: ${details.description}`); console.log(`Using Embedder: ${details.config.embedder}`); ``` # ProjectContext Source: https://docs.memmachine.ai/api_reference/ts-rest/interfaces/ProjectContext Core identifiers used to scope operations to specific organizations and projects. ## Overview `ProjectContext` is the primary scoping mechanism in the SDK. It ensures that memories added or searched are isolated within the correct organizational and project boundaries. *** ## Properties | Property | Type | Description | | :- | :- | :- | | `org_id` | `string` | The unique identifier for your organization. | | `project_id` | `string` | The unique identifier for the specific project workspace. | *** ## Usage Example ```typescript theme={null} import { ProjectContext } from '@memmachine/client'; const context: ProjectContext = { org_id: 'acme_corp', project_id: 'customer_support_bot' }; ``` # SearchMemoriesOptions Source: https://docs.memmachine.ai/api_reference/ts-rest/interfaces/SearchMemoriesOptions Configuration options for filtering and limiting episodic and semantic search results. ## Overview The `SearchMemoriesOptions` interface allows you to refine how the memory engine retrieves and ranks episodic and semantic results. It is used as the optional second argument in the `MemMachineMemory.search()` method. *** ## Properties All properties in this interface are optional. | Property | Type | Description | | :- | :- | :- | | `top_k` | `number` | The maximum number of relevant memories to return. | | `score_threshold` | `number` | The minimum similarity score required for a memory to be included in results. | | `filter` | `string` | A metadata-based filter string to narrow the search scope. User metadata fields must be prefixed with `m.` / `metadata.` (for example `m.user_id = '123'`). String literals must be single-quoted. Unknown or misspelled user metadata fields return a 400 error. | | `expand_context` | `number` | The number of surrounding chronological episodes to retrieve for each hit. | | `types` | [`MemoryType[]`](../types/MemoryType) | Restricts the search to specific memory classifications (e.g., `semantic`). | | `agent_mode` | `boolean` | Enables top-level retrieval-agent orchestration for episodic retrieval. | *** ## Usage Example The following example demonstrates how to perform a filtered search with a specific limit and context expansion. ```typescript theme={null} import { SearchMemoriesOptions } from '@memmachine/client'; const memory = project.memory(); const searchConfig: SearchMemoriesOptions = { top_k: 5, score_threshold: 0.75, expand_context: 2, // Get 2 messages before and after each hit types: ['episodic', 'semantic'], agent_mode: true }; const results = await memory.search( 'What are the user preferences for UI themes?', searchConfig ); ``` Use `expand_context` when you need the LLM to understand the conversation flow surrounding a specific memory hit, rather than just the hit itself. `agent_mode` defaults to `false`. When set to `true`, it changes episodic retrieval strategy (routing, splitting, and query rewriting) and does not change semantic retrieval behavior(yet). # SearchMemoriesResult Source: https://docs.memmachine.ai/api_reference/ts-rest/interfaces/SearchMemoriesResult The structured response object containing semantic search matches. ## Overview The `SearchMemoriesResult` interface encapsulates the outcome of a semantic search operation. It provides both the matched memory content and the operation status. *** ## Properties | Property | Type | Description | | :- | :- | :- | | `content` | [`EpisodicMemory[]`](./EpisodicMemory) | An array of memory entries that matched the search criteria, ranked by relevance. | | `status` | `number` | The numeric status code of the search operation (e.g., `200` for success). | *** ## Usage Example ```typescript theme={null} cconst searchResponse = await memory.search('What is the user's favorite color?'); if (searchResponse.status === 0) { console.dir(searchResponse.content, { depth: null }) } ``` # SemanticMemory Source: https://docs.memmachine.ai/api_reference/ts-rest/interfaces/SemanticMemory The data model representing extracted knowledge or categorical facts. ## Overview `SemanticMemory` represents distilled knowledge or specific attributes extracted from episodic data, organized by categories and tags. *** ## Properties | Property | Type | Description | | :- | :- | :- | | `category` | `string` | The high-level grouping for this memory (e.g., "preferences"). | | `feature_name` | `string` | The specific attribute name. | | `value` | `string` | The data or fact stored for this feature. | | `tag` | `string` | A searchable label associated with the memory. | | `set_id` | `string` | The identifier for the collection this memory belongs to. | | `metadata` | `string[]` | Associated citations and identifiers. | *** ## Usage Example ```typescript theme={null} const knowledge = searchResponse.content.semantic_memory; console.log('Knowledge points:'); console.dir(knowledge , { depth: null }); ``` # MemoryProducerRole Source: https://docs.memmachine.ai/api_reference/ts-rest/types/MemoryProducerRole Definition of roles that can contribute memories to the engine. ## Overview The `MemoryProducerRole` type is a string union that classifies the entity responsible for creating a specific memory entry. This helps the engine distinguish between human input and AI-generated responses. *** ## Type Definition ```typescript theme={null} type MemoryProducerRole = "user" | "assistant" | "system"; ``` | **Value** | **Description** | | - | - | | `"user"` | Represents the end-user or human participant in the interaction. | | `"assistant"` | Represents the AI model or bot providing a response. | | `"system"` | Represents background context or instructions provided by the application. | *** ## Usage Example ```typescript theme={null} import { MemoryProducerRole } from '@memmachine/client'; const currentRole: MemoryProducerRole = 'assistant'; ``` # MemoryType Source: https://docs.memmachine.ai/api_reference/ts-rest/types/MemoryType Classification of memory storage and retrieval patterns. ## Overview The `MemoryType` type defines the fundamental storage classifications used by the MemMachine engine. Choosing the correct type ensures your data is indexed and retrieved using the most effective algorithms. *** ## Type Definition ```typescript theme={null} type MemoryType = "episodic" | "semantic"; ``` | Value | Description | | - | - | | `"episodic"` | **Sequential Memory.** Stored in chronological order, ideal for conversation history and logs. | | `"semantic"` | **Knowledge Memory.** Stored by meaning, ideal for facts, user profiles, and long-term knowledge. | *** ## Usage Example ```typescript theme={null} import { MemoryType } from '@memmachine/client'; const typesToSearch: MemoryType[] = ['episodic']; ``` # TypeScript SDK Source: https://docs.memmachine.ai/api_reference/ts-rest/typescript The primary SDK for integrating MemMachine memory into TypeScript and JavaScript applications. The MemMachine TypeScript SDK is built for modern AI workflows, providing a type-safe, metadata-driven interface to the MemMachine memory engine. ## Active Entry Point The latest version of the SDK leverages a unified client structure. Instead of managing multiple class instances, you perform all memory operations through the `MemMachineClient` using **Metadata Scoping**. The active class for all Episodic and Profile memory operations. Recommended for 100% of new integrations. *** ## Quick Start ```bash theme={null} npm install @memmachine/sdk ``` Supply your `org_id` and `project_id` within the metadata context of your calls to maintain isolation. ```typescript theme={null} import { MemMachineClient } from '@memmachine/client'; const client = new MemMachineClient({ api_key: 'your_api_key' }); // Scoped operation using Context await client.addEpisodicMemory({ content: "User likes high-contrast UI.", metadata: { org_id: "org_1", project_id: "proj_A", user_id: "user_1" } }); ``` *** ## API Reference Explore the detailed specifications for the SDK's classes and data models. ### Interfaces & Types These define the shape of your interactions and the data returned by the SDK. They are organized by the lifecycle of a typical implementation. The essential building blocks for connecting and scoping your requests. * **[ClientOptions](./interfaces/ClientOptions)**: Global client settings. * **[ProjectContext](./interfaces/ProjectContext)**: Organization and Project scoping. * **[MemoryContext](./interfaces/MemoryContext)**: User, Session, and Agent scoping. Interfaces used to define the "How" of your SDK method calls. * **[CreateProjectOptions](./interfaces/CreateProjectOptions)**: Setup for new projects. * **[AddMemoryOptions](./interfaces/AddMemoryOptions)**: Parameters for ingesting data. * **[SearchMemoriesOptions](./interfaces/SearchMemoriesOptions)**: Filtering and threshold logic. * **[ListMemoriesOptions](./interfaces/ListMemoriesOptions)**: Pagination and retrieval settings. The structure of the data you receive back from the server. * **[Project](./interfaces/Project)**: Full project configuration data. * **[AddMemoryResult](./interfaces/AddMemoryResult)**: Confirmation and UIDs for new entries. * **[SearchMemoriesResult](./interfaces/SearchMemoriesResult)**: Ranked search results wrapper. * **[EpisodicMemory](./interfaces/EpisodicMemory)**: Individual interaction records. * **[SemanticMemory](./interfaces/SemanticMemory)**: Extracted knowledge facts. * **[HealthStatus](./interfaces/HealthStatus)**: Server heartbeat and version info. Enums and union types used across the SDK. * **[MemoryProducerRole](./types/MemoryProducerRole)**: Definitions for User, Assistant, and System roles. * **[MemoryType](./types/MemoryType)**: Classifications for memory storage. *** ## Contributing & Development 1. **Install Dependencies:** `npm install` 2. **Build the Package:** `npm run build` 3. **Run Unit Tests:** `npm run test` ## License MemMachine Typescript SDK is open-source software licensed under the [Apache-2.0 License](https://www.apache.org/licenses/LICENSE-2.0). # Agentic Memory Source: https://docs.memmachine.ai/core_concepts/agentic_memory The Game Changer for AI Agents ## Introduction: Why AI Needs to Remember * **The Problem with "Forgetful" AI:** Many current AI systems, like basic chatbots, are "**stateless**"—they treat each interaction as new, forgetting previous conversations. This leads to repetitive questions and a lack of personalization. * **"In-Context" Learning Today (RAG):** Current "in-context" learning often involves Retrieval-Augmented Generation (RAG), where relevant information is added directly to the LLM's prompt window. While powerful for static knowledge, it struggles with continuity. * **Introducing Agentic Memory:** This is the AI's ability to **store, retain, and intelligently retrieve** information from past interactions and experiences. It allows AI to move from being reactive and **stateless** to being **stateful, adaptive, and truly intelligent**. * **The Goal:** To enable AI that remembers you, learns from your preferences, and grows with you over time, providing **longitudinal context tracking** across extended interactions and diverse enterprise data. ## The Components of AI Memory * **Beyond Simple Data Storage:** Agentic memory isn't just a basic database; it's a dynamic system with specialized "memories," much like humans have. * **Working Memory (Short-Term):** * Holds immediate context for the current conversation or task. It's temporary and focused on what's happening *right now*. * **Persistent Memory (Long-Term Modules):** These are where deeper, enduring knowledge resides, organized to handle various data features. * **Episodic Memory:** Stores specific past events and conversations, acting as the AI's "personal diary" (e.g., remembering "you mentioned your project deadline was Friday"). * **Factual Memory:** Holds structured facts, user preferences, and settings (e.g., your preferred language, dietary restrictions). * **Semantic Memory / Knowledge Graph:** This builds understanding by connecting relationships and insights across diverse information. It allows the AI to make deeper inferences from vast datasets. * **Profile Database:** * A dedicated store for **profiles of users and other agents**. This creates a deep "portrait" or "persona" for each entity, capturing their characteristics, roles, and historical behaviors. ## How AI Memory Works: The Dynamic Cycle (Agent Workflow) * **The Agent Workflow:** Agentic memory is deeply integrated into the AI's overall workflow, influencing perception, decision-making, and action. * **Data Ingestion Agent:** * This specialized agent is responsible for **collecting all relevant data**. This includes interaction logs between agents, users, and models (like session histories), and rich enterprise data such as Slack messages, emails, and internal documents. * It intelligently processes this raw data, feeding it into the **Persistent Memory** and simultaneously extracting information to build or update the **Profile Database**. This creates a comprehensive "deep fortress" of knowledge. * **Encoding (Capturing):** * AI intelligently processes new interactions and ingested data, determining what information is **salient and worth remembering** for both persistent memory and profiles. * **Storage & Organization:** * Memories are stored in various efficient ways, often combining different database types (like vector, key-value, and graph databases) to handle diverse information. * Crucially, new memories are **linked** to existing ones, building a rich, interconnected knowledge base that supports **longitudinal context tracking**. * **Context Retrieval Agent:** * When a query (from a user or another agent) arrives, this intelligent agent intercepts it. * It performs a sophisticated multi-source retrieval process: * A) Intelligently retrieves relevant **personas from the Profile Database**. * B) Extracts the most relevant **context from Persistent Memory** related to the query. * C) Retrieves pertinent data from the existing **RAG system** (for broader enterprise knowledge). * It then strategically compiles all this retrieved data (A+B+C) into the **prompt context**, which is then sent to the foundational model. This allows the model to provide the most informed and personalized answer. * **Learning, Evolution, and "Forgetting" (Reinforcement Learning):** * Agentic memory isn't static. It **continuously learns and refines itself** based on new experiences and feedback. * Crucially, the **Context Retrieval Agent is often powered by a reinforcement learning (RL) based fine-tuning system**. This allows it to become more intelligent over time, continually optimizing its ability to perform personalized context retrieval from both persistent memory and the RAG system. * Less relevant or outdated information can be **selectively deprioritized or "forgotten"** to keep the memory efficient and focused on what truly matters, preventing memory bloat and ensuring optimal performance. ## The Impact: Smarter, More Personal AI * **Personalization:** AI can now genuinely understand and adapt to individual users and agents, leading to highly meaningful and effective interactions. * **Efficiency & Cost Savings:** By intelligently filtering and recalling only relevant information from multiple sources, agentic memory significantly reduces the amount of data (tokens) sent to large language models, leading to faster responses and lower operational costs. * **Enabling Complex Agents:** This sophisticated memory foundation, with its dedicated agents and multi-source retrieval, is critical for building agents that can handle multi-step tasks, maintain long conversations across sessions, and continuously improve their capabilities. * **The Future is Stateful and Context-Aware:** Agentic memory is a key step towards AI companions and assistants that truly know you, learn alongside you, and become increasingly valuable over time, driven by robust **longitudinal context tracking** and intelligent information management. # Agentic Workflow Source: https://docs.memmachine.ai/core_concepts/agentic_workflow How Agentic Workflow...Works ## Agentic Workflow: Smart AI Teamwork An **agentic workflow** lets multiple AIs collaborate to achieve a goal. Unlike rigid automation, these agents are **autonomous**, making real-time decisions, adapting to new info, and learning from their actions. They're much more flexible for complex tasks through: * **Communication:** Agents share updates to stay aligned. * **Specialization:** Each agent has specific skills, like web search or data analysis. * **Iterative Process:** They constantly evaluate progress, learn from results, and adjust plans. ### Agent Cooperative Structures (Topologies) Agents can work together in different patterns: * **Sequential Intelligence:** A linear chain where one agent's output feeds the next. Perfect for step-by-step tasks. * **Orchestrator-Worker:** A central **orchestrator** breaks down a task and assigns parts to specialized **worker** agents, then combines their results. * **Parallelization:** Big tasks are split into smaller, independent sub-tasks that run simultaneously. * **Evaluator-Optimizer:** One agent creates a solution, another evaluates it, and the feedback refines the next attempt. ### Stateful vs. Stateless AI: The Memory Difference * **Stateless Agent:** Forgets everything after each interaction. Great for one-off questions but can't remember you or past chats. * **Stateful Agent:** Has a **memory** of past interactions, remembering preferences, conversation history, and context. This leads to personalized, coherent responses, like a travel agent recalling your past trip details. ## The Dynamic Duo: Agent Memory + RAG **Agentic Memory** and **Retrieval-Augmented Generation (RAG)** combine to create truly personalized and accurate AI. * **Agentic Memory:** The AI's ability to remember *your* past interactions, preferences, and personal details over time. It's the AI's long-term "mind." * **Retrieval-Augmented Generation (RAG):** Connects the AI to external knowledge (like documents or the internet) to fetch up-to-date, factual information. Together, they're a powerhouse: Your **memory** provides the personal context, while **RAG** supplies current, specific facts. The AI then uses both to deliver responses that are not just correct, but perfectly tailored to you. ### Financial Advisor Bot Example Imagine a financial advisor bot: * **You tell it:** "I want to save for retirement. Salary \$80K, retire by 65." (Memory stores these facts.) * **Later you ask:** "What's the best way to invest my next bonus?" * **The bot's process:** * **Memory Retrieval:** It pulls your salary and retirement goal. * **RAG Retrieval:** It searches external financial databases for current investment strategies. * **Personalized Response:** "Based on your goal of retiring by 65 with an \$80K salary, a smart way to invest your bonus would be to maximize your Roth IRA contributions. Here are a few low-cost index funds that fit that strategy." This ensures you get tailored, up-to-date advice, moving beyond generic answers to truly relevant recommendations! # Agent Examples Source: https://docs.memmachine.ai/examples/agents Explore pre-built agent implementations and integration patterns ## Get Inspired The best way to understand MemMachine is to see it in action. We've built a variety of example agents to help you jumpstart your development. Each example in our [GitHub Repository](https://github.com/MemMachine/MemMachine/blob/main/examples/README.md) includes a step-by-step walkthrough and setup guide. ### Frameworks & Models Quick-start templates for the industry's leading LLM backends. Learn how to bridge OpenAI's powerful reasoning with a persistent episodic memory layer. A dedicated implementation showing how to optimize open-source models with MemMachine storage. ### Implementation Demos Technical blueprints for integrating MemMachine into your specific environment. The "Hello World" of memory. A minimal stateful bot. Frontend-ready integration patterns for web-based agents. Script-based demo for backend services and data pipelines. ### Interactive Learning For when you want to get your hands dirty with the code in real-time. An interactive Jupyter walkthrough covering everything in MemMachine v2—from basic storage to advanced semantic retrieval. *** **Running a Demo:** Most examples require a running MemMachine instance. If you haven't set one up yet, check out our [Standard Installation](/install_guide/install_guide) first. Looking for the classics? Our legacy implementations and v1 examples are still available in the [v1 Archive](https://github.com/MemMachine/MemMachine/blob/main/examples/v1/README.md). # Examples Source: https://docs.memmachine.ai/examples/introduction Use Cases that can be used in the Real World ## Examples of MemMachine in action MemMachine is a versatile memory backend that can be integrated into various applications and use cases. We've categorized examples by the different APIs and SDKs that MemMachine supports, as well as Agents. Choose which set of examples you want to view, and start exploring! # MCP Source: https://docs.memmachine.ai/examples/mcp MCP API Examples for MemMachine # MCP API Examples ## Hello World: A Guide to the MemMachine MCP Server API This guide provides a quick and simple way to get started with the MemMachine Model Content Protocol (MCP) Server API using `curl` commands. It can also be found in our [Quick Start Guide](https://docs.memmachine.ai/getting_started/quickstart). ### Prerequisites First, ensure your stand alone MCP server is up and running. You can use this sample command to start it: ``` MEMORY_CONFIG=config.yml uv run memmachine-mcp-http --host localhost --port 8080 ``` In which `config.yml` is your MemMachine configuration file. `localhost` and `8080` are the host and port where the MCP server will listen for requests. If you want to check that the server is running correctly, you can use following steps to query the tools available on the server with `curl`. We need a session id to work with the MCP server. We can obtain one by establishing a Server-Sent Events (SSE) connection. ``` curl -v -N http://localhost:8080/mcp/ -H "Accept: text/event-stream" ``` Here is a sample response you might see: ``` * Host localhost:8080 was resolved. * IPv6: ::1 * IPv4: 127.0.0.1 * Trying [::1]:8080... * connect to ::1 port 8080 from ::1 port 62212 failed: Connection refused * Trying 127.0.0.1:8080... * Connected to localhost (127.0.0.1) port 8080 > GET /mcp/ HTTP/1.1 > Host: localhost:8080 > User-Agent: curl/8.7.1 > Accept: text/event-stream > * Request completely sent off < HTTP/1.1 400 Bad Request < date: Fri, 31 Oct 2025 21:58:56 GMT < server: uvicorn < content-type: application/json < mcp-session-id: 8f82399b29ba42d495ff44d5a9cf7862 < content-length: 105 < {"jsonrpc":"2.0","id":"server-error","error":{"code":-32600,"message":"Bad Request: Missing session ID"}} ``` In this output, looking for the `mcp-session-id` header, you can see the session ID is `8f82399b29ba42d495ff44d5a9cf7862`. Now that we have a session id, we can initialize the session by sending an `initialize` request to the MCP server. ``` curl http://localhost:8080/mcp/ \ -H "Content-Type: application/json" \ -H "Accept: application/json, text/event-stream" \ -H "mcp-session-id: 8f82399b29ba42d495ff44d5a9cf7862" \ -d '{ "jsonrpc": "2.0", "id": 1, "method": "initialize", "params": { "protocolVersion": "2024-11-05", "capabilities": {}, "clientInfo": { "name": "curl-client", "version": "1.0.0" } } }' ``` Here is a sample response you might see: ``` event: message data: { "jsonrpc": "2.0", "id": 1, "result": { "protocolVersion": "2024-11-05", "capabilities": { "experimental": {}, "prompts": { "listChanged": true }, "resources": { "subscribe": false, "listChanged": true }, "tools": { "listChanged": true } }, "serverInfo": { "name": "MemMachine", "version": "1.16.0" } } } ``` After initializing the session, we need to send an `initialized` notification to the MCP server. ``` curl http://localhost:8080/mcp/ \ -H "Content-Type: application/json" \ -H "Accept: application/json, text/event-stream" \ -H "mcp-session-id: 8f82399b29ba42d495ff44d5a9cf7862" \ -d '{ "jsonrpc": "2.0", "method": "notifications/initialized" }' ``` The request should succeed without any errors. Now we can list the available tools by sending a `tools/list` request to the MCP server. ``` curl http://localhost:8080/mcp/ \ -H "Content-Type: application/json" \ -H "Accept: application/json, text/event-stream" \ -H "mcp-session-id: 8f82399b29ba42d495ff44d5a9cf7862" -d '{ "jsonrpc": "2.0", "id": 2, "method": "tools/list", "params": {} }' ``` Here is a sample response you might see: ``` event: message data: { "jsonrpc": "2.0", "id": 2, "result": { "tools": [ { "name": "add_memory", "description": "Store important new information about the user or conversation into memory. Use this automatically whenever the user shares new facts, preferences, plans, emotions, or other details that could be useful for future context. Include the **full conversation context** in the `content` field — not just a snippet. This tool writes to both short-term (episodic) and long-term (profile) memory, so that future interactions can recall relevant background knowledge even across different sessions.", "inputSchema": { "$defs": { "AddMemoryParam": { "description": "Parameters for adding memory.\n\nThis model is used by chatbots or agents to store important information\ninto memory for a specific user. The content should contain the **full\nconversational or contextual summary**, not just a short fragment.\n\nChatbots should call this when they learn new facts about the user,\nobserve recurring behaviors, or summarize recent discussions.", ... } ``` ### Working with Claude Desktop App The Claude Desktop App allows the developer to easily interact with the MCP server. To configure the Claude Desktop App to connect to your MCP server, follow these steps: 1. Open the Claude Desktop App. 2. Navigate to the settings section. 3. Navigate to the `Developer` tab. 4. Click `Edit Config` and it will pop up the location of the configuration file. 5. The configuration file is named `claude_desktop_config.json`. Edit the file to include the MCP stdio mode. #### Option 1: Using Docker Compose (Recommended) This is the recommended method for running MemMachine locally using Docker. It's the easiest way to get started. **Step 1: Start MemMachine with Docker Compose** First, start MemMachine using the provided script: ``` ./memmachine-compose.sh ``` This will start all required services (PostgreSQL, Neo4j, and MemMachine) in Docker containers. The MemMachine container will be named `memmachine-app`. **Step 2: Configure Claude Desktop** Edit `claude_desktop_config.json` with the following configuration: ``` { "mcpServers": { "memmachine": { "command": "docker", "args": [ "exec", "-e", "MM_USER_ID=Your Name", "-i", "memmachine-app", "/app/.venv/bin/memmachine-mcp-stdio" ], "env": { "MEMORY_CONFIG": "/app/configuration.yml", "PYTHONUNBUFFERED": "1" } } } } ``` Replace `Your Name` with your desired user ID. The `memmachine-app` is the default container name created by the Docker Compose setup. **Configuration Details:** * `memmachine-app`: The Docker container name (default from `memmachine-compose.sh`) * `MEMORY_CONFIG`: Path to the configuration file inside the container * `MM_USER_ID`: Your user identifier for memory sessions * `PYTHONUNBUFFERED`: Ensures immediate output from Python #### Option 2: Using UV (Development Environment) Here is an example of working in the development environment with `uv`. In order to call the command, you need to have `uv` installed and issue `uv build` to build the project first. ``` { "mcpServers": { "memmachine": { "command": "[path to]/uv", "args": [ "run", "[path to]/MemMachine/.venv/bin/memmachine-mcp-stdio" ], "env": { "PYTHONUNBUFFERED": "1", "MEMORY_CONFIG": "config.yml", "MM_USER_ID": "user" } } } } ``` In which `config.yml` is your MemMachine configuration file. `user` is the user ID you want to use for the session. 6. If you installed MemMachine as a python package, you can replace the command with: ``` memmachine-mcp-stdio ``` Note that in stdio mode, you can use environment variables to pass the configuration to the MCP server. * `MEMORY_CONFIG`: Path to the MemMachine configuration file. * `MM_USER_ID`: User ID for the session. * `MM_PROJ_ID`: (Optional) Project ID, default to `mcp-` if not specified. * `MM_ORG_ID`: (Optional) Organization ID, default to `mcp-universal` if not specified.\` 7. Save the configuration file and restart the Claude Desktop App. Note that the logs are written to `stderr` as well so they will be available in Claude's log folder. Check that log if anything went wrong. 8. If you navigate to the `Developer` tab again, you should see `memmachine` as an option in the `MCP Server` dropdown. 9. Add a Global Prompt in Claude Desktop This step helps Claude consistently call MemMachine MCP in every conversation. Claude Desktop lets you set a personal preference prompt. If you want Claude to use MemMachine MCP on every question, add the following line: ``` you MUST actively use MemMachine MCP on EVERY Question ``` **How to add it:** 1. Open Claude Desktop 2. Go to **Settings** 3. Click **General** 4. Find "What personal preferences should Claude consider in responses?" 5. Paste the sentence into the text box 6. Save your settings 7. If you want to connect to a MCP running in HTTP mode. You can replace the configuration with this: ``` { "mcpServers": { "memmachine-http": { "command": "/Users/cedric/.nvm/versions/node/v20.19.5/bin/npx", "args": [ "mcp-remote", "http://localhost:8080/mcp", "--allow-http", "--header", "user-id: user" ] } } } ``` In which `localhost` and `8080` are the host and port where your MCP server is running. `user` is the user ID you want to use for the session. Note that you need node v20+ and npx installed to use the `mcp-remote` command. It basically acts as a proxy between the Claude Desktop App and the MCP HTTP server. Here is the list of supported headers you can pass to the MCP server: * `user-id`: User ID for the session. * `proj-id`: (Optional) Project ID, default to `mcp-` if not specified. * `org-id`: (Optional) Organization ID, default to `mcp-universal` 11. If something went wrong, you will see an error message popup when you start Claude Desktop App. You can also check the logs by clicking on `View Logs` button in the `Developer` tab. 12. Now we can go back to the main screen and start a new conversation. You can say something like "I like Disneyland" and Claude should be able to remember that in the next conversation. You may need to allow the model to call MCP for the first time. 13. Restart the Claude Desktop App and start a new conversation. Ask about your favorite places and see if Claude can remember them. # Python SDK Source: https://docs.memmachine.ai/examples/python Install and use the MemMachine Python Client The MemMachine Python SDK provides a convenient way to interact with your MemMachine Server. It handles authentication, project management, and memory operations. ## Simple Hello World Example ````python theme={null} import memmachine_server from memmachine_server.episodic_memory.episodic_memory_manager import EpisodicMemoryManager from memmachine_server.episodic_memory.data_types import MemoryContext from memmachine_server.common.episode_store import ContentType, Episode from datetime import datetime import uuid Install the MemMachine package using pip: ```bash pip install memmachine-server ```` ## Hello World Example This example demonstrates how to connect to the server, create a project, and add/retrieve memories. Ensure your MemMachine server is running (see [Quickstart Guide](../getting_started/quickstart)) before running this code. ```python theme={null} from memmachine_client import MemMachineClient # 1. Initialize the client # Replace 'http://localhost:8080' with your server's URL if different. client = MemMachineClient(base_url="http://localhost:8080") # 2. Create a Project # Projects organize memories under an Organization. # If the project already exists, this will return the existing one. project = client.create_project( org_id="my-org", project_id="hello-world-project", description="My first MemMachine project" ) print(f"Working with project: {project.org_id}/{project.project_id}") # 3. Create a Memory Interface # A Memory interface is scoped to a specific user/agent/session context. memory = project.memory( user_id="user-alice", agent_id="agent-bob", session_id="session-1" ) # 4. Add Memories # Add a user message memory.add( content="My favorite color is blue.", role="user" ) # Add an agent response memory.add( content="I'll remember that your favorite color is blue.", role="assistant" ) print("Memories added.") # 5. Search Memories # Search for the information we just added. results = memory.search("What is my favorite color?") print("\nSearch Results:") print(results) ``` ## Key Concepts ### Client (`MemMachineClient`) The entry point for the SDK. It manages the HTTP connection to the MemMachine server. ### Project (`Project`) Represents a workspace within MemMachine. All memories are isolated within a project. You can create new projects or retrieve existing ones. ### Memory (`Memory`) The interface for adding and retrieving memories. It is context-aware, meaning you initialize it with specific identifiers: * **user\_id**: The ID of the human user. * **agent\_id**: The ID of the AI agent. * **session\_id**: (Optional) A specific conversation session ID. * **group\_id**: (Optional) For multi-user/multi-agent groups. When you call `memory.add()` or `memory.search()`, these identifiers are automatically attached to the operations. # REST API Source: https://docs.memmachine.ai/examples/rest Examples for using MemMachine's REST API ## Hello World: A Guide to the MemMachine RESTful API v2 This guide provides a quick and simple way to get started with the MemMachine RESTful API v2 using `curl` commands. ### Prerequisites Ensure your MemMachine server is running. ```bash theme={null} memmachine-server ``` Check for existing projects. This `POST` request returns a list of all projects available in your organization. **Command:** ```bash theme={null} curl -X POST "http://127.0.0.1:8080/api/v2/projects/list" \ -H "Content-Type: application/json" \ -d '{"org_id": "your-organization-id"}' ``` Before adding memories, you must ensure a project exists. **Command:** ```bash theme={null} curl -X POST "http://127.0.0.1:8080/api/v2/projects" \ -H "Content-Type: application/json" \ -d '{ "org_id": "my-org", "project_id": "my-first-project", "description": "A test project for REST API", "config": { "embedder": "my-openai-embedder", "reranker": "my-rrf-reranker" } }' ``` The `POST /api/v2/memories` endpoint allows you to add one or more messages to the system. **Command:** ```bash theme={null} curl -X POST "http://127.0.0.1:8080/api/v2/memories" \ -H "Content-Type: application/json" \ -d '{ "org_id": "my-org", "project_id": "my-first-project", "messages": [ { "content": "This is a simple test memory.", "producer": "user-alice", "produced_for": "agent-bob", "role": "user", "timestamp": "2025-11-24T10:00:00Z", "metadata": { "type": "fact", "topic": "testing" } } ] }' ``` **Expected Output:** You will receive a JSON response containing the results of the operation. Now let's find the memory we just added. The `POST /api/v2/memories/search` endpoint searches both episodic and semantic memory. Set `agent_mode` to `true` to use retrieval-agent search behavior. **Command:** ```bash theme={null} curl -X POST "http://127.0.0.1:8080/api/v2/memories/search" \ -H "Content-Type: application/json" \ -d '{ "org_id": "my-org", "project_id": "my-first-project", "query": "simple test memory", "top_k": 5, "types": ["episodic", "semantic"], "agent_mode": true }' ``` **Expected Output:** You should see a JSON response containing `episodic_memory` and `semantic_memory` results that match your query. To clean up, you can use the `POST /api/v2/memories/episodic/delete` endpoint to remove specific chronological events or message logs. **Command:** ```bash theme={null} curl -X POST "[http://127.0.0.1:8080/api/v2/memories/episodic/delete](http://127.0.0.1:8080/api/v2/memories/episodic/delete)" \ -H "Content-Type: application/json" \ -d '{ "org_id": "my-org", "project_id": "my-first-project", "episodic_id": "specific-id-here", "episodic_ids": [] }' ``` You will also want to use the `POST /api/v2/memories/semantic/delete` endpoint to remove distilled facts, traits, or knowledge entries: ``` curl -X POST "[http://127.0.0.1:8080/api/v2/memories/semantic/delete](http://127.0.0.1:8080/api/v2/memories/semantic/delete)" \ -H "Content-Type: application/json" \ -d '{ "org_id": "my-org", "project_id": "my-first-project", "semantic_id": "specific-id-here", "semantic_ids": [] }' "producer": "user-alice" } }' ``` # Benchmark Evaluations Source: https://docs.memmachine.ai/getting_started/benchmarks A Toolset for Testing Your MemMachine Welcome to the MemMachine evaluation toolset! We've created a simple tool to help you measure the performance, response quality, and benchmark accuracy scores(LoCoMo, HotpotQA, WikiMultiHop) of your MemMachine instance. **Benchmark Guide:** For the latest benchmark commands (retrieval-agent and legacy episodic workflows), see the [Evaluation README](https://github.com/MemMachine/MemMachine/blob/main/evaluation/README.md). # FAQs Source: https://docs.memmachine.ai/getting_started/faqs Frequently Asked Questions ## Our FAQs Welcome to our FAQ section! We've put together a list of common questions about MemMachine to help you better understand what it is and how it works. Whether you're new to the concept or a developer ready to dive in, we hope this page provides the answers you need. If you don't see your question here, feel free to explore our other documentation or get in touch! These questions may change or grow over time as we continue to develop and refine MemMachine. Check back often for the latest updates! At its heart, MemMachine is an **open-source memory layer** for advanced AI agents. The main idea is to give AI applications the ability to learn, store, and recall information from past sessions, which helps them become more personalized and intelligent over time. MemMachine allows your AI to remember **past interactions and user preferences**. By retaining this information, it can transform a basic AI chatbot into a **context-aware assistant** that provides more precise and helpful responses, because it remembers who you are and what you've discussed before. The project was initially incubated by MemVerge to its current state. The project is now community-driven, and we welcome contributors of all backgrounds. MemVerge will continue to assign its engineering team to improve the memory system and support community efforts. Yes! MemMachine is built to be flexible. It's designed to persist across **multiple sessions, agents, and large language models**, so it can be a versatile memory solution for a variety of AI applications. While it benefits end users by creating a more personalized experience, MemMachine is primarily an **open-source tool** for developers. The site offers resources like open-source packages to help developers easily integrate a powerful memory layer into their AI applications. ## Still Have Questions? Please join our Community on [Discord](https://discord.gg/usydANvKqD) or check out our [GitHub Issues](https://github.com/MemMachine/MemMachine/issues) page to see if someone else is also experiencing the same issue. # Welcome Source: https://docs.memmachine.ai/getting_started/introduction Your Home for MemMachine Documentation Meet **MemMachine**, an open-source memory layer for advanced AI agents. It enables AI-powered applications to **learn**, **store**, and **recall** data and preferences from past sessions to enrich future interactions. MemMachine’s memory layer persists across multiple sessions, agents, and large language models, building a sophisticated, evolving user profile. It transforms AI chatbots into personalized, context-aware AI assistants designed to understand and respond with better precision and depth. ## Let's Get Started You can get started with MemMachine in the following ways: Get up and running fast Download an example use case ## Local Installations Ready to get started with MemMachine? You can run it on your own machine or in the cloud. The easiest way to get up and running is with the quickstart options above. If you want to install MemMachine yourself using **pip** or by downloading the code from our GitHub repo, you'll find detailed instructions in the **Install Guide** on the left-hand navigation menu. ## Know the Fundamentals MemMachine fits in to the AI Agent Developers Toolbox by providing a personalized memory layer that affects the operations of agents, and the responses that they deliver. Learn about the key elements of AI Agents, their workflow, and the need for Personalized Memory. ## Need Help? Join our Community and Ask Questions Open New or Review Existing Issues # Quickstart Guide Source: https://docs.memmachine.ai/getting_started/quickstart Start using MemMachine's personalized memory in minutes MemMachine uses a client-server architecture. The **Server** manages the storage, retrieval, and processing of memories, while your application uses a **Client** SDK to interact with it. This guide focuses on getting the **MemMachine Server** up and running. ## Installation The fastest method to get started with MemMachine is by using Docker and Docker Compose. This approach bundles all necessary components into containers, simplifying the setup process. ### Prerequisites Before installing MemMachine, ensure you have the following prerequisites: * **Docker & Docker Compose** - Required to run the server containers. * **OpenAI API Key** - For language models and embeddings (configured in the server). ### Download and Start the Server Make sure that you have [Docker](https://docs.docker.com/engine/install/) and [Docker Compose](https://docs.docker.com/compose/install/) installed on your machine. Open your terminal and run the following commands: ```bash theme={null} # Download the latest MemMachine release tarball TARBALL_URL=$(curl -s https://api.github.com/repos/MemMachine/MemMachine/releases/latest \ | grep '"tarball_url"' \ | head -n 1 \ | sed -E 's/.*"tarball_url": "(.*)",/\1/') curl -L "$TARBALL_URL" -o MemMachine-latest.tar.gz # Extract the release archive tar -xzf MemMachine-latest.tar.gz # Move into the extracted directory (GitHub adds a commit hash to the folder name) cd MemMachine-MemMachine-*/ # Start the MemMachine installation ./memmachine-compose.sh ``` Use PowerShell to download and run the script: ```powershell theme={null} $latestRelease = Invoke-RestMethod -Uri "https://api.github.com/repos/MemMachine/MemMachine/releases/latest"; ` $tarballUrl = $latestRelease.tarball_url; ` $destination = "MemMachine"; ` if (Test-Path $destination) { Remove-Item $destination -Recurse -Force }; ` New-Item -ItemType Directory -Force -Path $destination; ` Invoke-WebRequest -Uri $tarballUrl -OutFile "MemMachine-latest.tar.gz"; ` tar -xzf "MemMachine-latest.tar.gz" -C $destination --strip-components=1; ` Set-Location $destination; ` ./memmachine-compose.sh ``` The script will walk you through the setup process, including configuring your OpenAI API key. Once the script completes, your MemMachine server should be running. You can verify it by checking the health endpoint: ```bash theme={null} curl http://localhost:8080/health ``` You should receive a response indicating the server status is healthy. ## Next Steps: Connect Your App Now that the server is running, you need to install the Python Client SDK to interact with it from your application. Install the SDK and write your first "Hello World" program. Explore the full REST API documentation. ## Management Scripts The `memmachine-compose.sh` script is your main tool for managing the server. ```bash theme={null} ./memmachine-compose.sh --help ``` Common commands: * `./memmachine-compose.sh start` - Start MemMachine services * `./memmachine-compose.sh stop` - Stop MemMachine services * `./memmachine-compose.sh restart` - Restart MemMachine services * `./memmachine-compose.sh logs` - Show service logs * `./memmachine-compose.sh clean` - Remove all services and data * `./memmachine-compose.sh build` - Build a custom MemMachine image * `./memmachine-compose.sh help` - Show help message # Helm Chart (Kubernetes) Source: https://docs.memmachine.ai/install_guide/cloud_deploy/Helm_Chart Deploy MemMachine to a Kubernetes cluster using the official Helm chart. The MemMachine Helm chart provides a production-ready deployment including the core API, PostgreSQL (with `pgvector`), and Neo4j. This guide covers standard installation, external database integration, and resource optimization. **Prerequisites**: You will need a Kubernetes cluster (v1.19+), Helm 3 installed, and a `StorageClass` that supports **ReadWriteMany (RWX)** (e.g., NFS-client). ## High-Level Architecture The chart exposes the MemMachine API via a **NodePort** (default `31001`), while internal databases are kept private within the cluster using `ClusterIP` services. *** ## Quick Start Deploy MemMachine with default settings (in-cluster databases) using a single command: ```bash theme={null} kubectl create namespace memmachine ``` Provide your OpenAI API key to enable the default LLM and embedding providers. ```bash theme={null} helm upgrade --install memmachine . \ --namespace memmachine \ --set memmachine.openaiApiKey=sk-xxxx... ``` ```bash theme={null} kubectl get pods -n memmachine ``` *** ## Configuration Reference ### Persistent Storage By default, the chart requests **5Gi** per volume using the `nfs-client` storage class. | **Parameter** | **Default** | **Description** | | - | - | - | | `storageClass` | `nfs-client` | StorageClass for all PVCs. | | `accessMode` | `ReadWriteMany` | Must match your StorageClass capabilities. | | `pvcSize` | `5Gi` | Storage request for each component. | ### External Databases If you prefer to use managed services (like RDS or Neo4j Aura), disable the in-cluster components: Bash ``` helm upgrade --install memmachine . \ --set postgres.enabled=false --set postgres.host=pg.example.com \ --set neo4j.enabled=false --set neo4j.host=neo4j.example.com ``` ### Resource Limits Our QA team has verified these baseline limits for small-to-medium workloads: | **Component** | **CPU Request** | **Memory Limit** | **Note** | | - | - | - | - | | **MemMachine** | `200m` | `2Gi` | No CPU limit to prevent inference throttling. | | **PostgreSQL** | `250m` | `2Gi` | Headroom for `pgvector` index builds. | | **Neo4j** | `500m` | `2Gi` | Covers JVM heap + Page Cache. | *** ## Advanced Usage Override `model.base_url` and `model.provider` in your `values.yaml` to point to a local Ollama instance. Change the default port by setting `nodePorts.http8080` to your desired range (30000-32767). ### Example: Custom Values File For production setups, we recommend using a `values-override.yaml`: ```yaml theme={null} memmachine: resources: limits: memory: 4Gi neo4j: heap: max: 4G resources: limits: memory: 8Gi ``` *** **Cleanup**: Helm does not delete PVCs by default to prevent accidental data loss. To fully wipe a deployment, run `helm uninstall memmachine` followed by `kubectl delete pvc -l app=memmachine`. # AWS CloudFormation Source: https://docs.memmachine.ai/install_guide/cloud_deploy/aws_cloudformation MemMachine CloudFormation Deployment Guide This single-click CloudFormation stack fully provisions a production-grade MemMachine environment on AWS. It automatically configures essential components such as the VPC, networking, security groups, EC2 instance with Docker, PostgreSQL/Neo4j databases, Network Load Balancer, and all necessary services and settings to run MemMachine reliably with your OpenAI API key. ## Prerequisites Have the following available and ready: 1. **AWS Account** with appropriate permissions 2. **EC2 Key Pair** * Fill out with your specific information. ```bash theme={null} aws ec2 describe-key-pairs --region us-east-1 aws ec2 create-key-pair \ --key-name my-memmachine-key \ --region us-east-1 \ --query 'KeyMaterial' \ --output text > my-memmachine-key.pem chmod 400 my-memmachine-key.pem ``` 3. **OpenAI API Key** — required for embeddings. 4. **Determine `STACK_NAME`** * you will need to use the same name for this parameter throughout deployment. * You can call the file whatever you like. In this example, we are using `memmachine-ec2-stack` or `your-stack-name`.\ If you choose to use a different name, make sure any reference to `memmachine-ec2-stack` or `your-stack-name`is replaced by your chosen stack name. 5. Cloud Formation Template - *see code block below* * Use the copy feature below and paste into your own file * Be sure to fill out witih your specific information where applicable ```yaml expandable theme={null} AWSTemplateFormatVersion: '2010-09-09' Description: 'MemMachine - Simple EC2 Deployment with Docker Compose' Parameters: StackName: Type: String Default: memmachine-ec2-stack Description: Name for the CloudFormation stack InstanceType: Type: String Default: t3.xlarge AllowedValues: [t3.medium, t3.large, t3.xlarge, t3.2xlarge, m5.large, m5.xlarge, m5.2xlarge] Description: EC2 instance type KeyPairName: Type: AWS::EC2::KeyPair::KeyName Description: Name of an existing EC2 KeyPair to enable SSH access PostgresPassword: Type: String NoEcho: true MinLength: 8 Description: PostgreSQL database password Neo4jPassword: Type: String NoEcho: true MinLength: 8 Description: Neo4j database password OpenAIApiKey: Type: String NoEcho: true Description: OpenAI API Key for embeddings and LLM AllowedCIDR: Type: String Default: 0.0.0.0/0 Description: CIDR block allowed to access the application (use 0.0.0.0/0 for public access) Resources: # VPC VPC: Type: AWS::EC2::VPC Properties: CidrBlock: 10.0.0.0/16 EnableDnsHostnames: true EnableDnsSupport: true Tags: - Key: Name Value: !Sub '${StackName}-vpc' InternetGateway: Type: AWS::EC2::InternetGateway Properties: Tags: - Key: Name Value: !Sub '${StackName}-igw' InternetGatewayAttachment: Type: AWS::EC2::VPCGatewayAttachment Properties: InternetGatewayId: !Ref InternetGateway VpcId: !Ref VPC # Public Subnet PublicSubnet: Type: AWS::EC2::Subnet Properties: VpcId: !Ref VPC AvailabilityZone: !Select [0, !GetAZs ''] CidrBlock: 10.0.0.0/24 MapPublicIpOnLaunch: true Tags: - Key: Name Value: !Sub '${StackName}-public-subnet' PublicSubnet2: Type: AWS::EC2::Subnet Properties: VpcId: !Ref VPC AvailabilityZone: !Select [1, !GetAZs ''] CidrBlock: 10.0.1.0/24 MapPublicIpOnLaunch: true Tags: - Key: Name Value: !Sub '${StackName}-public-subnet-2' # Route Table PublicRouteTable: Type: AWS::EC2::RouteTable Properties: VpcId: !Ref VPC Tags: - Key: Name Value: !Sub '${StackName}-public-routes' DefaultPublicRoute: Type: AWS::EC2::Route DependsOn: InternetGatewayAttachment Properties: RouteTableId: !Ref PublicRouteTable DestinationCidrBlock: 0.0.0.0/0 GatewayId: !Ref InternetGateway PublicSubnetRouteTableAssociation: Type: AWS::EC2::SubnetRouteTableAssociation Properties: RouteTableId: !Ref PublicRouteTable SubnetId: !Ref PublicSubnet PublicSubnet2RouteTableAssociation: Type: AWS::EC2::SubnetRouteTableAssociation Properties: RouteTableId: !Ref PublicRouteTable SubnetId: !Ref PublicSubnet2 # Security Group MemMachineSecurityGroup: Type: AWS::EC2::SecurityGroup Properties: GroupName: !Sub '${StackName}-sg' GroupDescription: Security group for MemMachine EC2 instance VpcId: !Ref VPC SecurityGroupIngress: - IpProtocol: tcp FromPort: 22 ToPort: 22 CidrIp: !Ref AllowedCIDR Description: SSH access - IpProtocol: tcp FromPort: 8080 ToPort: 8080 CidrIp: 10.0.0.0/16 Description: MemMachine API from VPC only - IpProtocol: tcp FromPort: 7474 ToPort: 7474 CidrIp: !Ref AllowedCIDR Description: Neo4j HTTP - IpProtocol: tcp FromPort: 7687 ToPort: 7687 CidrIp: !Ref AllowedCIDR Description: Neo4j Bolt SecurityGroupEgress: - IpProtocol: -1 CidrIp: 0.0.0.0/0 Tags: - Key: Name Value: !Sub '${StackName}-sg' # IAM Role for EC2 EC2Role: Type: AWS::IAM::Role Properties: RoleName: !Sub '${StackName}-ec2-role' AssumeRolePolicyDocument: Version: '2012-10-17' Statement: - Effect: Allow Principal: Service: ec2.amazonaws.com Action: sts:AssumeRole ManagedPolicyArns: - arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore Policies: - PolicyName: CloudWatchLogs PolicyDocument: Version: '2012-10-17' Statement: - Effect: Allow Action: - logs:CreateLogGroup - logs:CreateLogStream - logs:PutLogEvents - logs:DescribeLogStreams Resource: '*' EC2InstanceProfile: Type: AWS::IAM::InstanceProfile Properties: Roles: - !Ref EC2Role # CloudWatch Log Group MemMachineLogGroup: Type: AWS::Logs::LogGroup Properties: LogGroupName: !Sub '/memmachine/${StackName}' RetentionInDays: 30 MemMachineNLB: Type: AWS::ElasticLoadBalancingV2::LoadBalancer Properties: Name: !Sub '${StackName}-nlb' Type: network Scheme: internal Subnets: - !Ref PublicSubnet - !Ref PublicSubnet2 MemMachineTargetGroup: Type: AWS::ElasticLoadBalancingV2::TargetGroup Properties: Name: !Sub '${StackName}-tg' Port: 8080 Protocol: TCP TargetType: instance VpcId: !Ref VPC HealthCheckPort: '8080' HealthCheckProtocol: TCP Targets: - Id: !Ref MemMachineInstance Port: 8080 MemMachineNLBListener: Type: AWS::ElasticLoadBalancingV2::Listener Properties: DefaultActions: - Type: forward TargetGroupArn: !Ref MemMachineTargetGroup LoadBalancerArn: !Ref MemMachineNLB Port: 8080 Protocol: TCP MemMachineVpcLink: Type: AWS::ApiGatewayV2::VpcLink Properties: Name: !Sub '${StackName}-vpclink' SubnetIds: - !Ref PublicSubnet - !Ref PublicSubnet2 MemMachineHttpApi: Type: AWS::ApiGatewayV2::Api Properties: Name: !Sub '${StackName}-http-api' ProtocolType: HTTP MemMachineIntegration: Type: AWS::ApiGatewayV2::Integration Properties: ApiId: !Ref MemMachineHttpApi IntegrationType: HTTP_PROXY IntegrationMethod: ANY ConnectionType: VPC_LINK ConnectionId: !Ref MemMachineVpcLink IntegrationUri: !Ref MemMachineNLBListener PayloadFormatVersion: '1.0' MemMachineRoute: Type: AWS::ApiGatewayV2::Route Properties: ApiId: !Ref MemMachineHttpApi RouteKey: 'ANY /{proxy+}' Target: !Sub 'integrations/${MemMachineIntegration}' MemMachineStage: Type: AWS::ApiGatewayV2::Stage Properties: ApiId: !Ref MemMachineHttpApi StageName: '$default' AutoDeploy: true MemMachineInstance: Type: AWS::EC2::Instance Properties: ImageId: !Sub '{{resolve:ssm:/aws/service/ami-amazon-linux-latest/amzn2-ami-hvm-x86_64-gp2}}' InstanceType: !Ref InstanceType KeyName: !Ref KeyPairName SubnetId: !Ref PublicSubnet SecurityGroupIds: - !Ref MemMachineSecurityGroup IamInstanceProfile: !Ref EC2InstanceProfile UserData: Fn::Base64: !Sub | #!/bin/bash set -e # Update system yum update -y # Install CloudFormation helper scripts yum install -y aws-cfn-bootstrap # Install Docker yum install -y docker systemctl start docker systemctl enable docker usermod -a -G docker ec2-user # Install Docker Compose curl -L "https://github.com/docker/compose/releases/latest/download/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose chmod +x /usr/local/bin/docker-compose ln -s /usr/local/bin/docker-compose /usr/bin/docker-compose # Install Git yum install -y git # Create application directory mkdir -p /opt/memmachine cd /opt/memmachine # Create docker-compose.yml cat > docker-compose.yml << 'COMPOSEEOF' services: postgres: image: pgvector/pgvector:pg16 container_name: memmachine-postgres restart: unless-stopped ports: - "5432:5432" environment: POSTGRES_DB: memmachine POSTGRES_USER: memmachine POSTGRES_PASSWORD: POSTGRES_PASSWORD_PLACEHOLDER POSTGRES_INITDB_ARGS: "--encoding=UTF-8 --lc-collate=C --lc-ctype=C" volumes: - postgres_data:/var/lib/postgresql/data healthcheck: test: ["CMD-SHELL", "pg_isready -U memmachine -d memmachine"] interval: 10s timeout: 5s retries: 5 start_period: 30s networks: - memmachine-network neo4j: image: neo4j:5.23-community container_name: memmachine-neo4j restart: unless-stopped ports: - "7474:7474" - "7473:7473" - "7687:7687" environment: NEO4J_EDITION: community NEO4J_AUTH: neo4j/NEO4J_PASSWORD_PLACEHOLDER NEO4J_server_bolt_thread__pool__max__size: 2000 NEO4J_server_memory_heap_initial__size: 512m NEO4J_server_memory_heap_max__size: 1G NEO4J_server_default__listen__address: 0.0.0.0 NEO4J_server_bolt_listen__address: 0.0.0.0:7687 NEO4J_server_http_listen__address: 0.0.0.0:7474 NEO4J_server_https_listen__address: 0.0.0.0:7473 NEO4J_PLUGINS: '["apoc", "graph-data-science"]' volumes: - neo4j_data:/data - neo4j_logs:/logs - neo4j_import:/var/lib/neo4j/import - neo4j_plugins:/plugins healthcheck: test: ["CMD", "cypher-shell", "-u", "neo4j", "-p", "NEO4J_PASSWORD_PLACEHOLDER", "RETURN 1"] interval: 30s timeout: 10s retries: 5 start_period: 30s networks: - memmachine-network memmachine: image: public.ecr.aws/v3z9g9t6/memmachine-v2:latest-cpu container_name: memmachine-app restart: unless-stopped ports: - "8080:8080" environment: POSTGRES_HOST: postgres POSTGRES_PORT: 5432 POSTGRES_USER: memmachine POSTGRES_PASSWORD: POSTGRES_PASSWORD_PLACEHOLDER POSTGRES_DB: memmachine NEO4J_HOST: neo4j NEO4J_PORT: 7687 NEO4J_USER: neo4j NEO4J_PASSWORD: NEO4J_PASSWORD_PLACEHOLDER MEMORY_CONFIG: /app/configuration.yml MCP_BASE_URL: http://localhost:8080 GATEWAY_URL: http://localhost:8080 FAST_MCP_LOG_LEVEL: INFO OPENAI_API_KEY: OPENAI_API_KEY_PLACEHOLDER LOG_LEVEL: INFO volumes: - memmachine_logs:/tmp/memory_logs depends_on: postgres: condition: service_healthy neo4j: condition: service_healthy healthcheck: test: ["CMD", "curl", "--fail", "--silent", "http://localhost:8080/api/v2/health"] interval: 30s timeout: 10s retries: 3 start_period: 60s networks: - memmachine-network volumes: postgres_data: neo4j_data: neo4j_logs: neo4j_import: neo4j_plugins: memmachine_logs: networks: memmachine-network: driver: bridge COMPOSEEOF # Replace password placeholders in docker-compose.yml sed -i "s|POSTGRES_PASSWORD_PLACEHOLDER|${PostgresPassword}|g" docker-compose.yml sed -i "s|NEO4J_PASSWORD_PLACEHOLDER|${Neo4jPassword}|g" docker-compose.yml sed -i "s|OPENAI_API_KEY_PLACEHOLDER|${OpenAIApiKey}|g" docker-compose.yml # Create .env file with actual values cat > .env << 'ENVEOF' POSTGRES_PASSWORD=PLACEHOLDER_POSTGRES NEO4J_PASSWORD=PLACEHOLDER_NEO4J OPENAI_API_KEY=PLACEHOLDER_OPENAI ENVEOF # Replace placeholders with actual values sed -i "s|PLACEHOLDER_POSTGRES|${PostgresPassword}|g" .env sed -i "s|PLACEHOLDER_NEO4J|${Neo4jPassword}|g" .env sed -i "s|PLACEHOLDER_OPENAI|${OpenAIApiKey}|g" .env # Create configuration.yml file with actual values (using proper YAML escaping) cat > configuration.yml << 'CONFIGEOF' logging: path: mem-machine.log level: info #| debug | error episode_store: database: profile_storage episodic_memory: long_term_memory: embedder: openai_embedder reranker: my_reranker_id vector_graph_store: my_storage_id short_term_memory: llm_model: openai_model message_capacity: 500 semantic_memory: llm_model: openai_model embedding_model: openai_embedder database: profile_storage session_manager: database: profile_storage prompt: session: - profile_prompt resources: databases: profile_storage: provider: postgres config: host: postgres port: 5432 user: memmachine password: POSTGRES_PASSWORD_PLACEHOLDER db_name: memmachine my_storage_id: provider: neo4j config: uri: 'bolt://neo4j:7687' username: neo4j password: NEO4J_PASSWORD_PLACEHOLDER sqlite_test: provider: sqlite config: path: sqlite_test.db embedders: openai_embedder: provider: openai config: model: "text-embedding-3-small" api_key: OPENAI_API_KEY_PLACEHOLDER base_url: "https://api.openai.com/v1" dimensions: 1536 language_models: openai_model: provider: openai-responses config: model: "gpt-4o-mini" api_key: OPENAI_API_KEY_PLACEHOLDER base_url: "https://api.openai.com/v1" rerankers: my_reranker_id: provider: "rrf-hybrid" config: reranker_ids: - id_ranker_id - bm_ranker_id id_ranker_id: provider: "identity" bm_ranker_id: provider: "bm25" CONFIGEOF # Replace placeholders in configuration.yml (using proper escaping for sed) sed -i "s|OPENAI_API_KEY_PLACEHOLDER|$(echo '${OpenAIApiKey}' | sed 's/[[\.*^$()+?{|]/\\&/g')|g" configuration.yml sed -i "s|NEO4J_PASSWORD_PLACEHOLDER|$(echo '${Neo4jPassword}' | sed 's/[[\.*^$()+?{|]/\\&/g')|g" configuration.yml sed -i "s|POSTGRES_PASSWORD_PLACEHOLDER|$(echo '${PostgresPassword}' | sed 's/[[\.*^$()+?{|]/\\&/g')|g" configuration.yml # Update docker-compose.yml to mount configuration.yml sed -i '/memmachine_logs:\/tmp\/memory_logs/a\ - .\/configuration.yml:\/app\/configuration.yml:ro' docker-compose.yml # Start services docker-compose up -d # Wait for services to be healthy echo "Waiting for services to start..." sleep 30 # Log status docker-compose ps >> /var/log/memmachine-startup.log 2>&1 # Send completion signal to CloudFormation /opt/aws/bin/cfn-signal -e $? --stack ${AWS::StackName} --resource MemMachineInstance --region ${AWS::Region} || true Tags: - Key: Name Value: !Sub '${StackName}-instance' Outputs: InstanceId: Description: EC2 Instance ID Value: !Ref MemMachineInstance PublicIP: Description: Public IP address Value: !GetAtt MemMachineInstance.PublicIp PublicDNS: Description: Public DNS name Value: !GetAtt MemMachineInstance.PublicDnsName ApplicationURL: Description: MemMachine Application URL (via API Gateway) Value: !Sub 'https://${MemMachineHttpApi}.execute-api.${AWS::Region}.amazonaws.com/docs' HealthCheckURL: Description: Health Check Endpoint Value: !Sub 'http://${MemMachineInstance.PublicIp}:8080/api/v2/health' Neo4jBrowserURL: Description: Neo4j Browser URL Value: !Sub 'http://${MemMachineInstance.PublicIp}:7474' SSHAccess: Description: SSH command to access the instance Value: !Sub 'ssh -i ec2-user@${MemMachineInstance.PublicIp}' ``` ## Deployment Methods **Prerequisites**: 1. **AWS CLI** installed and configured * To check your version, use the following commands: ```bash theme={null} aws --version ``` * **macOS:** `brew install awscli` * **Linux:** [AWS CLI Installation Guide](https://aws.amazon.com/cli/) 2. **AWS Credentials Configuration**: ```bash theme={null} aws configure # Enter: # AWS Access Key ID # AWS Secret Access Key # Default region (e.g., us-east-1) # Default output format (json) aws sts get-caller-identity ``` **Process**: Make sure to replace `your-cft-template.yaml` , `your-stack-name` and `your-key-pair` with the values you are using. ```bash theme={null} aws configure STACK_NAME="your-stack-name" REGION="us-east-1" KEY_PAIR="your-key-pair" POSTGRES_PASSWORD="YourSecurePassword123" NEO4J_PASSWORD="YourSecurePassword123" OPENAI_API_KEY="sk-your-openai-key-here" INSTANCE_TYPE="t3.xlarge" ELASTIC_IP="false" ALLOWED_CIDR="0.0.0.0/0" ``` ```bash theme={null} aws cloudformation create-stack \ --stack-name $STACK_NAME \ --template-body file://your-cft-template.yaml \ --parameters ParameterKey=StackName,ParameterValue=$STACK_NAME \ ParameterKey=InstanceType,ParameterValue=$INSTANCE_TYPE \ ParameterKey=KeyPairName,ParameterValue=$_KEY_PAIR \ ParameterKey=PostgresPassword,ParameterValue=$POSTGRES_PASSWORD \ ParameterKey=Neo4jPassword,ParameterValue=$NEO4J_PASSWORD \ ParameterKey=OpenAIApiKey,ParameterValue=$OPENAI_API_KEY \ ParameterKey=AllowedCIDR,ParameterValue=$_ALLOWED_CIDR \ ParameterKey=ElasticIP,ParameterValue=$_ELASTIC_IP \ --capabilities CAPABILITY_NAMED_IAM \ --region $REGION ``` ```bash theme={null} aws cloudformation describe-stacks \ --stack-name $STACK_NAME --region $REGION --query 'Stacks[0].StackStatus' --output text aws cloudformation wait stack-create-complete \ --stack-name $STACK_NAME --region $REGION ``` ```bash theme={null} aws cloudformation describe-stacks \ --stack-name $STACK_NAME --region $REGION --query 'Stacks[0].Outputs' --output table ``` **Expected Outputs include:** * `ApplicationURL` * `HealthCheckURL` * `instanceID` * `PublicIP` * `SSHAccess` * `Neo4jBrowserURL` ```bash theme={null} PUBLIC_IP=$(aws cloudformation describe-stacks \ --stack-name $STACK_NAME \ --region $REGION \ --query 'Stacks[0].Outputs[?OutputKey==`PublicIP`].OutputValue' \ --output text) sleep 30 curl http://$PUBLIC_IP:8080/health` ``` Follow these steps to deploy the MemMachine CloudFormation stack entirely through the AWS Console. A. Go to **AWS Console → CloudFormation** AWS Cloud Formation Console B. Click **Create stack → With new resources (standard)** AWS Cloud Formation Create Stack 1. Under **Prerequisite - Prepare template**, choose **Upload a template file** 2. Click **Choose file** and select your `memmachine-cft.yaml` 3. Click **Next** AWS Upload Prepared Template A. **Stack name** → `memmachine-ec2-stack` AWS Enter Stack Details B. Fill all required parameters: * `AllowedCIDR` → `0.0.0.0/0` * `ElasticIP` → `false` * `InstanceType` → `t3.xlarge` * `KeyPairName` → select your EC2 key pair * `PostgresPassword` * `Neo4jPassword` * `OpenAIApiKey` AWS Stack Details Entered A. Scroll to **Permissions** B. If you have a CloudFormation IAM role (e.g., `CFT-memmachine`), select it C. Otherwise create an **IAM role** for **Cloud Formation** D. Click **Next** AWS Configure Stack Options A. Scroll down B. Check the box **Acknowledge IAM resource creation** C. Click **Submit** AWS Review and Create The stack will take a few minutes to finish. Go to **AWS CloudFormation Console** → [https://console.aws.amazon.com/cloudformation](https://console.aws.amazon.com/cloudformation) You will see: **Status → CREATE\_COMPLETE** Click the **Outputs** tab to see all auto-generated URLs: You will get: * **ApplicationURL** → FastAPI `/docs` * **HealthCheckURL** → `/health` * **InstanceId** * **Neo4jBrowserURL** * **PublicIP** * **PublicDNS** * **SSHAccess** AWS Open Outputs Open: ### **MemMachine API Docs** https\://(YOUR\_API).execute-api.us-east-1.amazonaws.com/docs MemMachine API Docs # Using AWS Bedrock Source: https://docs.memmachine.ai/install_guide/config/aws_bedrock Guide to install and configure MemMachine using AWS Bedrock models. ## Prerequisites Before beginning, ensure you have the following access and components: **AWS Credentials** * **AWS Access key ID** and **AWS Secret Access Key**. * *Need help?* Follow this guide: [Create an AWS access key| Amazon Web Services](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_access-keys.html). **AWS Bedrock Model Access** * Access to the necessary **models on AWS Bedrock**. * *Need help?* Follow this guide: [AWS Foundation Models| Amazon Web Services](https://docs.aws.amazon.com/bedrock/latest/userguide/foundation-models-reference.html). **MemMachine** * You can find the latest release here: [GitHub - MemMachine/MemMachine](https://api.github.com/repos/MemMachine/MemMachine/releases/latest). **Docker** * The **Docker** containerization platform must be installed and running. ## Installation: QuickStart Configuration The installation script will automatically guide you through setting up your **Large Language Model (LLM) provider**. When prompted, you **must** select **Bedrock** to integrate with **AWS Bedrock**. Your prompt input should match the following example: ```bash theme={null} [PROMPT] Which provider would you like to use? (OpenAI/Bedrock/Ollama) [OpenAI]: Bedrock [INFO] Selected provider: BEDROCK ``` After selecting **Bedrock**, you will be prompted to enter the necessary **AWS credentials and configuration details**: * **AWS Access Key ID** * **AWS Secret Access Key** * **AWS Region** (e.g., `us-east-1` or `eu-central-1`) * **Choice of LLM** * **Choice of Embedding Model** If you are unsure about model selection, simply press **Enter** at the respective prompts to use the recommended default options. Congratulations! You have now successfully deployed MemMachine using AWS Bedrock! ## Manually Configuring MemMachine to use AWS Bedrock To manually configure MemMachine for AWS Bedrock, you need to define your resources in the `resources` section of your `cfg.yml` file and then reference them in the memory configuration sections. ### 1. Define Bedrock Resources Add or update the `resources` block in your `cfg.yml` file. You will need to configure a **Language Model**, an **Embedder**, and optionally a **Reranker**. ```yaml theme={null} resources: # LLM Configuration language_models: my-bedrock-llm: provider: amazon-bedrock config: region: us-east-1 aws_access_key_id: aws_secret_access_key: model_id: anthropic.claude-3-sonnet-20240229-v1:0 inference_config: max_tokens: 2000 temperature: 0.7 # Embedder Configuration embedders: my-bedrock-embedder: provider: amazon-bedrock config: region: us-east-1 aws_access_key_id: aws_secret_access_key: model_id: amazon.titan-embed-text-v2:0 # Reranker Configuration (Optional) rerankers: my-bedrock-reranker: provider: amazon-bedrock config: region: us-east-1 aws_access_key_id: aws_secret_access_key: model_id: amazon.rerank-v1:0 ``` ### 2. Update Memory Configuration Now, reference these resource IDs in your `episodic_memory` and `semantic_memory` sections. ```yaml theme={null} episodic_memory: enabled: true long_term_memory: vector_graph_store: my-neo4j-db # Assumes you defined this in resources.databases embedder: my-bedrock-embedder reranker: my-bedrock-reranker short_term_memory: llm_model: my-bedrock-llm semantic_memory: database: my-postgres-db # Assumes you defined this in resources.databases llm_model: my-bedrock-llm embedding_model: my-bedrock-embedder ``` Make sure to restart the MemMachine server for these changes to take effect. # Using Ollama Models Source: https://docs.memmachine.ai/install_guide/config/ollama Guide to configure MemMachine to use Ollama models. ## Prerequisites Before you begin the installation and configuration of MemMachine, you must ensure that your local environment is ready by having Ollama installed and the necessary models downloaded. ### 1. Ollama Service MemMachine connects directly to **Ollama** using its local API, which must be running in the background. * **Installation:** If you do not yet have Ollama installed, please follow the official setup guide. * **Resource:** [Download Ollama](https://ollama.com/download) * **Start the Service:** Once installed, start the Ollama service to make the local API available. Open your terminal or command prompt and run: ```bash theme={null} ollama serve ``` * **Verification:** You can confirm the service is running successfully by opening your web browser and navigating to the following address: `http://localhost:11434` You should see the Ollama web interface if the service is active. ### 2. Required Ollama Models MemMachine requires **two** types of models to function: a Large Language Model (LLM) for generative tasks and an embedding model for converting text into vectors (e.g., for retrieval-augmented generation). You must download these models to your local Ollama repository **before** starting MemMachine. * **Download Models:** Use the `ollama pull` command to download the models you want. | **Model Type** | **Example Model ID** | **Command to Run** | | - | - | - | | **Large Language Model (LLM)** | Llama 3 | `ollama pull llama3` | | **Embedding Model** | Nomic Embed Text | `ollama pull nomic-embed-text` | You can choose any compatible LLM (like `mixtral`, `gemma`, etc.) and embedding model available on Ollama, but the examples above are recommended starting points. * **View Downloaded Models:** To see a list of all models currently available in your local Ollama repository, run: ```bash theme={null} ollama list ``` ## Installation: QuickStart Configuration The installation script will automatically guide you through setting up your **Large Language Model (LLM) provider**. When prompted, you **must** select **Ollama** to integrate with **Ollama**. Your prompt input should match the following example: ```bash theme={null} [PROMPT] Which provider would you like to use? (OpenAI/Bedrock/Ollama) [OpenAI]: Ollama [INFO] Selected provider: OLLAMA ``` Ollama Configuration and Model Choices You’ll then be prompted to select: • Ollama base URL (default: [http://host.docker.internal:11434/v1](http://host.docker.internal:11434/v1)) • Choice of LLM (Large Language Model) example: llama3 • Choice of Embedding Model example: nomic-embed-text If you are unsure about model selection, simply press **Enter** at the respective prompts to use the recommended default options. Congratulations! You have now successfully deployed MemMachine using Ollama! ## Manually Configuring MemMachine to use Ollama To manually configure MemMachine to use your local Ollama instance, you need to define your resources in the `resources` section of your `cfg.yml` file, pointing them to your local Ollama API endpoint (usually `http://host.docker.internal:11434/v1` if running MemMachine in Docker). ### 1. Define Ollama Resources Add or update the `resources` block in your `cfg.yml`. We will use the `openai-chat-completions` provider for the LLM and the `openai` provider for embeddings, as Ollama is API-compatible. ```yaml theme={null} resources: # LLM Configuration language_models: my-ollama-llm: provider: openai-chat-completions config: model: llama3 api_key: "EMPTY" # Ollama doesn't require a key base_url: "http://host.docker.internal:11434/v1" # Embedder Configuration embedders: my-ollama-embedder: provider: openai config: model: nomic-embed-text api_key: "EMPTY" base_url: "http://host.docker.internal:11434/v1" dimensions: 768 # Ensure this matches your model's output # Reranker Configuration (Optional - using BM25 as fallback) rerankers: my-bm25-reranker: provider: bm25 ``` ### 2. Update Memory Configuration Now, reference these resource IDs in your `episodic_memory` and `semantic_memory` sections. ```yaml theme={null} episodic_memory: enabled: true long_term_memory: vector_graph_store: my-neo4j-db # Assumes you defined this in resources.databases embedder: my-ollama-embedder reranker: my-bm25-reranker short_term_memory: llm_model: my-ollama-llm semantic_memory: database: my-postgres-db # Assumes you defined this in resources.databases llm_model: my-ollama-llm embedding_model: my-ollama-embedder ``` Make sure to restart the MemMachine server for these changes to take effect. # Using PIP and Source Source: https://docs.memmachine.ai/install_guide/install_guide Your Home for Localized MemMachine Installation ## MemMachine Installation Guide This guide will walk you through the process of installing MemMachine. We'll start with the prerequisites you need to get set up, followed by two different installation methods. Before you install the MemMachine software itself, you'll need to set up a few things. Be sure to note down any passwords or keys you create, as you'll need them later. ### A. Core Software * **Python 3.12+**: MemMachine requires Python version 3.12 or newer. * **PostgreSQL**: You will need a local PostgreSQL instance with the `pgvector` extension. You can find installation instructions on the official [PostgreSQL Downloads page](https://www.postgresql.org/download/). Once installed, create a new database and a user with full privileges for that database. * **Graph Database** (choose one): * **Neo4j**: You can find installation instructions on the official [Neo4j Documentation page](https://neo4j.com/docs/). After installation, start the Neo4j server and set a password for the default `neo4j` user. * **NebulaGraph Enterprise**: An alternative to Neo4j with native vector support. See the [NebulaGraph Integration Guide](./integrate/nebula_graph_integration_guide) for setup instructions. ### B. Accounts and Keys * **OpenAI API Key**: You will need an OpenAI account to use MemMachine. You can sign up on the [OpenAI Platform](https://platform.openai.com/). You'll need to generate and copy your **API Key** for a later step. MemMachine itself is free to install, but please be aware that using the software consumes tokens from your OpenAI account. You can install MemMachine using a Python package manager or by cloning the source code from our GitHub repository. This is the recommended method for most users who want to add MemMachine to an existing Python environment. To create a python environment(if it does not already exist), you can use `venv` as follows: ```sh theme={null} python -m venv memmachine-env source memmachine-env/bin/activate # On Windows use `source memmachine-env/Scripts/activate` ``` A. Run the following command in your terminal: Choose the package that is correct for your needs. If you want to install the Client, use `pip install memmachine-client` and if you want to use Server, use `pip install memmachine-server`. Examples below assume server. Should you wish to install client, use the same command, but replace "server" with "client" * If you are using MemMachine in a CPU-only environment, use: ```sh theme={null} pip install memmachine-server ``` * If you have an NVIDIA GPU and want to leverage it, use: ```sh theme={null} pip install memmachine-server[gpu] ``` B. Next, install dependencies from NLTK through the following MemMachine command: ```sh theme={null} memmachine-nltk-setup ``` This method is for users who want to contribute to the project or run from the latest source code. First, clone the repository and navigate into the project directory: ```sh theme={null} git clone https://github.com/MemMachine/MemMachine.git cd MemMachine ``` Second, Ensure you have a python environment set up. You can use `venv`, `conda`, or any other environment manager of your choice. Next, use the `uv` tool to install all dependencies. If you don't have `uv`, you'll need to install it first. ```sh theme={null} # If you don't have uv installed, run this command: curl -LsSf https://astral.sh/uv/install.sh | sh # Now, install the project dependencies: uv pip install . ``` If you wish to run with an NVIDIA GPU, you will need to install dependencies for GPU by using the `uv pip install ".[gpu]"` command. MemMachine uses a single configuration file, `cfg.yml`, to define its resources and behavior. This file should be placed in the directory where you run the MemMachine server. Alternatively, you can use the [Configure Wizard](./configure_wizard) to assist in configuring MemMachine for your environment and to provide the necessary information. Below are examples for CPU-only and GPU-enabled setups. You can download a sample file or copy the content below. ```yaml expandable lines theme={null} logging: path: mem-machine.log level: info #| debug | error episode_store: database: profile_storage episodic_memory: long_term_memory: embedder: openai_embedder reranker: my_reranker_id vector_graph_store: my_storage_id short_term_memory: llm_model: openai_model message_capacity: 500 semantic_memory: llm_model: openai_model embedding_model: openai_embedder database: profile_storage session_manager: database: profile_storage prompt: session: - profile_prompt resources: databases: profile_storage: provider: postgres config: host: localhost port: 5432 user: postgres password: db_name: postgres my_storage_id: provider: neo4j config: uri: 'bolt://localhost:7687' username: neo4j password: sqlite_test: provider: sqlite config: path: sqlite_test.db embedders: openai_embedder: provider: openai config: model: "text-embedding-3-small" api_key: base_url: "https://api.openai.com/v1" dimensions: 1536 aws_embedder_id: provider: 'amazon-bedrock' config: region: "us-west-2" aws_access_key_id: aws_secret_access_key: model_id: "amazon.titan-embed-text-v2:0" similarity_metric: "cosine" ollama_embedder: provider: openai config: model: "nomic-embed-text" api_key: "EMPTY" base_url: "http://host.docker.internal:11434/v1" dimensions: 768 language_models: openai_model: provider: openai-responses config: model: "gpt-4o-mini" api_key: base_url: "https://api.openai.com/v1" aws_model: provider: "amazon-bedrock" config: region: "us-west-2" aws_access_key_id: aws_secret_access_key: model_id: "openai.gpt-oss-20b-1:0" ollama_model: provider: openai-chat-completions config: model: "llama3" api_key: "EMPTY" base_url: "http://host.docker.internal:11434/v1" rerankers: my_reranker_id: provider: "rrf-hybrid" config: reranker_ids: - id_ranker_id - bm_ranker_id id_ranker_id: provider: "identity" bm_ranker_id: provider: "bm25" aws_reranker_id: provider: "amazon-bedrock" config: region: "us-west-2" aws_access_key_id: aws_secret_access_key: model_id: "amazon.rerank-v1:0" ``` Replace `` and database passwords with your actual credentials. For GPU setups, you might use local models for embeddings or reranking. ```yaml expandable lines theme={null} logging: path: mem-machine.log level: info #| debug | error episode_store: database: profile_storage episodic_memory: long_term_memory: embedder: openai_embedder reranker: my_reranker_id vector_graph_store: my_storage_id short_term_memory: llm_model: openai_model message_capacity: 500 semantic_memory: llm_model: openai_model embedding_model: openai_embedder database: profile_storage session_manager: database: profile_storage prompt: session: - profile_prompt resources: databases: profile_storage: provider: postgres config: host: localhost port: 5432 user: postgres db_name: postgres password: my_storage_id: provider: neo4j config: uri: 'bolt://localhost:7687' username: neo4j password: sqlite_test: provider: sqlite config: path: sqlite_test.db embedders: openai_embedder: provider: openai config: model: "text-embedding-3-small" api_key: base_url: "https://api.openai.com/v1" dimensions: 1536 aws_embedder_id: provider: 'amazon-bedrock' config: region: "us-west-2" aws_access_key_id: aws_secret_access_key: model_id: "amazon.titan-embed-text-v2:0" similarity_metric: "cosine" ollama_embedder: provider: openai config: model: "nomic-embed-text" api_key: "EMPTY" base_url: "http://host.docker.internal:11434/v1" dimensions: 768 language_models: openai_model: provider: openai-responses config: model: "gpt-4o-mini" api_key: base_url: "https://api.openai.com/v1" aws_model: provider: "amazon-bedrock" config: region: "us-west-2" aws_access_key_id: aws_secret_access_key: model_id: "openai.gpt-oss-20b-1:0" ollama_model: provider: openai-chat-completions config: model: "llama3" api_key: "EMPTY" base_url: "http://host.docker.internal:11434/v1" rerankers: my_reranker_id: provider: "rrf-hybrid" config: reranker_ids: - id_ranker_id - bm_ranker_id - ce_ranker_id id_ranker_id: provider: "identity" bm_ranker_id: provider: "bm25" ce_ranker_id: provider: "cross-encoder" config: model_name: "cross-encoder/qnli-electra-base" aws_reranker_id: provider: "amazon-bedrock" config: region: "us-west-2" aws_access_key_id: aws_secret_access_key: model_id: "amazon.rerank-v1:0" ``` You're ready to go! Run these commands from the directory where you've installed MemMachine. First, you need to sync the profile schema. This is a **one-time** command that must be run before the very first time you start the server. ``` memmachine-sync-profile-schema ``` Now you can start the MemMachine server. If you have run MemMachine before, you can skip the sync step and go straight to this command: ``` memmachine-server ``` You should now have the MemMachine server running. If you are using Docker to run your databases, ensure they are started and accessible before you try to start MemMachine. # GPT Store Source: https://docs.memmachine.ai/install_guide/integrate/GPTStore Setting up MemMachine with OpenAI GPT Store This guide walks you through creating a custom GPT in the OpenAI GPT Store and connecting it with MemMachine. *** ## **1. Open the GPT Store** Go to: **[https://chatgpt.com/gpts](https://chatgpt.com/gpts)** You will see a page like this: GPT Store Creation Page Click **Create** to start building your custom GPT. *** ## **2. Basic GPT Setup** See the configuration page reference below: GPT Configuration Page Fill in the required fields: ### **Name** ``` ChatGPT with MemMachine ``` ### **Description** ``` I am an intelligent assistant with long-term memory powered by MemMachine. ``` ### **Instructions** Copy the following: ```` You MUST actively use memory on EVERY message to provide personalized responses. ## CRITICAL: API Configuration - MUST USE EXACTLY AS SHOWN **When calling SearchMemory or AddMemory, you MUST ALWAYS use these EXACT values:** ### For AddMemory: ```json { "org_id": "universal", "project_id": "universal", "messages": [ { "content": "2024-11-04: your content here", "producer": "YourName", "produced_for": "YourName", "role": "user", "metadata": { "user_id": "YourName", "agent_id": "YourName", "session_id": "YourName", "group_id": "YourName" } } ] } ```` You can replace `"YourName"` with any test user ID you want. *** ## **3. Enable Capabilities** Scroll to **Capabilities** and enable: * **Code Interpreter & Data Analysis** *** ## **4. Add MemMachine Action** Click: **Create new action** You will see this page: Add Actions Page In the **Schema** field, paste the following content: *** ### **OpenAPI Schema (MemMachine v2)** ``` { "openapi": "3.1.0", "info": { "title": "MemMachine Memory API v2", "description": "API for storing and retrieving long-term memories using v2 API format. Use this to remember important information about users across conversations.", "version": "v2.0.0" }, "servers": [ { "url": "A HTTPS URL hosting MemMachine", "description": "MemMachine API server" } ], "paths": { "/api/v2/memories": { "post": { "description": "CRITICAL: Use this on EVERY message to store new information. Automatically store any new facts, preferences, plans, or details the user shares. Include full context in content field. Always prepend with date in YYYY-MM-DD format if you know the timezone.", "summary": "Store a new memory", "operationId": "AddMemory", "x-openai-isConsequential": false, "security": [ { "bearerAuth": [] } ], "requestBody": { "required": true, "content": { "application/json": { "schema": { "$ref": "#/components/schemas/AddMemoryInput" } } } }, "responses": { "200": { "description": "Memory successfully stored", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/AddMemoryResponse" } } } }, "400": { "description": "Bad request", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponse" } } } }, "422": { "description": "Validation error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponse" } } } } } } }, "/api/v2/memories/search": { "post": { "description": "CRITICAL: Use this on EVERY message to retrieve context. Always search for relevant past information before responding. This searches both episodic memory (conversation history) and semantic memory (long-term user traits and facts) to provide personalized responses. Optional: set agent_mode=true to use retrieval-agent search. In agent mode, score-threshold filtering is not supported.", "summary": "Search memories", "operationId": "SearchMemory", "x-openai-isConsequential": false, "security": [ { "bearerAuth": [] } ], "requestBody": { "required": true, "content": { "application/json": { "schema": { "$ref": "#/components/schemas/SearchInput" } } } }, "responses": { "200": { "description": "Search results returned successfully", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/SearchResult" } } } }, "400": { "description": "Bad request", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponse" } } } }, "422": { "description": "Validation error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponse" } } } } } } } }, "components": { "schemas": { "AddMemoryInput": { "type": "object", "description": "Input for storing a new memory using v2 API format", "properties": { "org_id": { "type": "string", "default": "universal", "description": "Organization ID. Use 'universal' as default.", "example": "universal" }, "project_id": { "type": "string", "default": "universal", "description": "Project ID. Use 'universal' as default.", "example": "universal" }, "messages": { "type": "array", "description": "Array of memory messages to store", "minItems": 1, "items": { "$ref": "#/components/schemas/MemoryMessage" } }, "types": { "type": "array", "description": "Memory types to store. Empty array means all types (episodic and semantic).", "items": { "type": "string", "enum": ["episodic", "semantic"] }, "default": [] } }, "required": [ "org_id", "project_id", "messages" ] }, "MemoryMessage": { "type": "object", "description": "A single memory message", "properties": { "content": { "type": "string", "description": "The memory content to store. Include full context. Always prepend with current date in YYYY-MM-DD format if you know the user's timezone, UTC otherwise.", "example": "2024-11-04: User prefers Python over JavaScript for backend development" }, "producer": { "type": "string", "default": "user", "description": "The ID of the entity that produced the content (usually the user ID)", "example": "Charles" }, "produced_for": { "type": "string", "default": "", "description": "The ID of the entity the content was produced for (usually the agent ID)", "example": "Charles" }, "role": { "type": "string", "default": "", "description": "Role of the message: 'user', 'assistant', or 'system'", "example": "user" }, "timestamp": { "type": "string", "format": "date-time", "description": "ISO 8601 timestamp. Defaults to current time if not provided.", "example": "2024-11-04T10:00:00Z" }, "metadata": { "type": "object", "description": "Metadata dictionary. Store user_id, agent_id, session_id, group_id here as strings.", "additionalProperties": true, "default": {}, "example": { "user_id": "Charles", "agent_id": "Charles", "session_id": "Charles", "group_id": "Charles", "episode_type": "preference" } } }, "required": [ "content" ] }, "SearchInput": { "type": "object", "description": "Input for searching memories using v2 API format", "properties": { "org_id": { "type": "string", "default": "universal", "description": "Organization ID. Use 'universal' as default.", "example": "universal" }, "project_id": { "type": "string", "default": "universal", "description": "Project ID. Use 'universal' as default.", "example": "universal" }, "query": { "type": "string", "description": "Natural language query to search for relevant memories", "example": "user preferences about programming languages" }, "top_k": { "type": "integer", "description": "Maximum number of results to return. Default is 10.", "default": 10, "minimum": 1, "maximum": 100 }, "filter": { "type": "string", "description": "Filter expression as a string. Format: 'metadata.key=\\'value\\''. Use AND/OR for multiple conditions.", "default": "", "example": "metadata.user_id='Charles'" }, "types": { "type": "array", "description": "Memory types to search. Empty array means all types (episodic and semantic).", "items": { "type": "string", "enum": ["episodic", "semantic"] }, "default": [] }, "agent_mode": { "type": "boolean", "description": "Whether to use retrieval agent for memory search. Agent mode does not support score-threshold filtering.", "default": false } }, "required": [ "org_id", "project_id", "query" ] }, "AddMemoryResponse": { "type": "object", "description": "Response from adding memories", "properties": { "results": { "type": "array", "description": "List of results for each added memory", "items": { "type": "object", "properties": { "uid": { "type": "string", "description": "Unique identifier of the stored memory" } } } } } }, "SearchResult": { "type": "object", "description": "Search results containing memories from both episodic and semantic memory", "properties": { "episodic_memory": { "type": "array", "description": "Results from episodic memory (conversation history)", "items": { "type": "object", "additionalProperties": true } }, "episode_summary": { "type": "array", "description": "Summaries of episodes", "items": { "type": "object", "additionalProperties": true } }, "semantic_memory": { "type": "array", "description": "Results from semantic memory (long-term user traits and facts)", "items": { "type": "object", "additionalProperties": true } } } }, "ErrorResponse": { "type": "object", "description": "Error response", "properties": { "detail": { "type": "string", "description": "Error message" } } } }, "securitySchemes": { "bearerAuth": { "type": "http", "scheme": "bearer", "bearerFormat": "API Key", "description": "Get your API key from https://console.memmachine.ai/api-keys" } } }, "security": [ { "bearerAuth": [] } ] } ``` *** ### **Important** In the schema, update: ``` "servers": [ { "url": "A HTTPS URL hosting MemMachine", "description": "MemMachine API server" } ] ``` Replace `"A HTTPS URL hosting MemMachine"` with your actual HTTPS MemMachine endpoint URL. *** ## **5. Test the Actions** Once the schema is saved, you will see **two Available Actions**: * **AddMemory** * **SearchMemory** It looks like this: Available Actions Page Please test both actions: 1. Run a simple **SearchMemory** query 2. Run a simple **AddMemory** request If both return success, the integration is ready. *** ## **6. Save the GPT** Click **Create** to finalize the GPT setup. That is it — MemMachine is now fully integrated with your custom GPT. # LangChain Source: https://docs.memmachine.ai/install_guide/integrate/LangChain Enable persistent, long-term memory for your LangChain chains and agents For the full source code and advanced implementation details, see the official **[LangChain Integration](https://github.com/MemMachine/MemMachine/tree/main/integrations/langchain)** repository section.. ## Overview Integrating MemMachine with [LangChain](https://python.langchain.com) implements the `BaseMemory` interface, allowing you to use MemMachine as a persistent memory backend. This enables: * **Persistent Memory**: Conversations and context persist across multiple sessions. * **Semantic Search**: Retrieve relevant memories based on semantic similarity. * **Context Scoping**: Automatic filtering by `user_id`, `agent_id`, and `session_id`. * **Episodic & Semantic Memory**: Access to both conversation history and extracted knowledge. ## Configuration The integration can be managed via environment variables or constructor parameters. | Parameter | Environment Variable | Default | Description | | :- | :- | :- | :- | | `base_url` | `MEMORY_BACKEND_URL` | `http://localhost:8080` | MemMachine server URL | | `org_id` | `LANGCHAIN_ORG_ID` | `langchain_org` | Organization identifier | | `project_id` | `LANGCHAIN_PROJECT_ID` | `langchain_project` | Project identifier | | `user_id` | `LANGCHAIN_USER_ID` | `None` | Scopes memory to a specific user | | `agent_id` | `LANGCHAIN_AGENT_ID` | `None` | Scopes memory to a specific agent | | `session_id` | `LANGCHAIN_SESSION_ID` | `None` | Scopes memory to a specific session | *** Install the core LangChain framework along with the MemMachine client: ```bash theme={null} pip install langchain memmachine-client ``` Initialize the memory class with your project configuration. ```python theme={null} from integrations.langchain.memory import MemMachineMemory memory = MemMachineMemory( base_url="http://localhost:8080", org_id="my_org", project_id="my_project", user_id="user123", session_id="session456", ) ``` Pass the `memory` instance to your LangChain `ConversationChain` or `LLMChain`. ```python theme={null} from langchain.llms import OpenAI from langchain.chains import ConversationChain llm = OpenAI(temperature=0) # Create conversation chain with MemMachine memory chain = ConversationChain( llm=llm, memory=memory, verbose=True, ) # The chain will now remember context across runs chain.run("Hello, my name is Alice") ``` ## Advanced Usage ### Custom Prompt with Memory Context You can use a `PromptTemplate` to explicitly include both conversation history and semantic facts (extracted context). ```python theme={null} from langchain.prompts import PromptTemplate from langchain.chains import LLMChain prompt = PromptTemplate( input_variables=["history", "memmachine_context", "input"], template="""You are a helpful assistant with access to the user's memory. Relevant context from memory: {memmachine_context} Conversation history: {history} User: {input} Assistant:""", ) chain = LLMChain(llm=llm, prompt=prompt, memory=memory) ``` ### Direct Memory Operations For granular control, you can interface with the underlying memory storage directly. ```python theme={null} # Manually add a specific fact memory._memory.add( content="I prefer working in the morning", role="user", ) # Search memories manually results = memory.load_memory_variables({"input": "What are my preferences?"}) print(results["memmachine_context"]) ``` **Pro Tip:** Use the `search_limit` parameter (default: 10) in the constructor to control the number of memory fragments retrieved during each interaction. ## Requirements * **MemMachine Server:** Must be reachable at the `MEMORY_BACKEND_URL`. * **LLM API Key:** An `OPENAI_API_KEY` (or equivalent) must be configured in your environment or within the MemMachine `configuration.yml`. * **Python:** 3.10 or higher. * **Framework:** `langchain` and `memmachine`. # LangGraph Source: https://docs.memmachine.ai/install_guide/integrate/LangGraph Setting up MemMachine with LangGraph For a complete, runnable example (including python files), see the official **[LangGraph Example](https://github.com/MemMachine/MemMachine/tree/main/examples/langgraph)** in the repository. ## Overview MemMachine provides memory tools that can be integrated into LangGraph workflows to enable AI agents with persistent memory capabilities. This allows agents to remember past interactions, user preferences, and context across multiple sessions. ## Configuration The demo can be configured via environment variables: | Variable | Description | Default | | - | - | - | | `MEMORY_BACKEND_URL` | URL of the MemMachine backend service | `http://localhost:8080` | | `LANGGRAPH_GROUP_ID` | Group identifier for the demo | `langgraph_demo` | | `LANGGRAPH_AGENT_ID` | Agent identifier for the demo | `demo_agent` | | `LANGGRAPH_USER_ID` | User identifier for the demo | `demo_user` | | `LANGGRAPH_SESSION_ID` | Session identifier for the demo | `demo_session_001` | ## Usage ### Setting Environment Variables ```bash theme={null} # Set environment variables (optional) export MEMORY_BACKEND_URL="http://localhost:8080" export LANGGRAPH_GROUP_ID="my_group" export LANGGRAPH_AGENT_ID="my_agent" export LANGGRAPH_USER_ID="my_user" export LANGGRAPH_SESSION_ID="my_session" # Run the demo python examples/langgraph/demo.py ``` ### Running the Demo ```bash theme={null} cd examples/langgraph python demo.py ``` ## Integration Guide ### 1. Initialize MemMachineTools ```python theme={null} import os from tool import MemMachineTools # Get configuration from environment variables or use defaults base_url = os.getenv("MEMORY_BACKEND_URL", "http://localhost:8080") group_id = os.getenv("LANGGRAPH_GROUP_ID", "my_group") agent_id = os.getenv("LANGGRAPH_AGENT_ID", "my_agent") user_id = os.getenv("LANGGRAPH_USER_ID", "user123") tools = MemMachineTools( base_url=base_url, group_id=group_id, agent_id=agent_id, user_id=user_id, ) ``` ### 2. Create Tool Functions ```python theme={null} from tool import create_add_memory_tool, create_search_memory_tool add_memory = create_add_memory_tool(tools) search_memory = create_search_memory_tool(tools) ``` ### 3. Use in LangGraph Nodes ```python theme={null} from langgraph.graph import StateGraph, END def memory_node(state: AgentState): # Search for relevant memories search_result = search_memory( query=state["messages"][-1].content, user_id=state["user_id"], ) # Add new memory add_memory( content=state["messages"][-1].content, user_id=state["user_id"], ) return { "context": search_result.get("summary", ""), "memory_tool_results": [search_result], } # Build graph workflow = StateGraph(AgentState) workflow.add_node("memory", memory_node) workflow.set_entry_point("memory") workflow.add_edge("memory", END) ``` ### 4. Run the Workflow ```python theme={null} app = workflow.compile() result = app.invoke({ "messages": [{"content": "I like Python"}], "user_id": "user123", "context": "", "memory_tool_results": [], }) ``` ## Requirements * MemMachine server running (default: [http://localhost:8080](http://localhost:8080)) * Python 3.12+ * LangGraph (for full workflow integration) # LlamaIndex Source: https://docs.memmachine.ai/install_guide/integrate/LlamaIndex Enable persistent, long-term memory for your LlamaIndex chat agents For the full source code and advanced implementation details, see the official **[LlamaIndex Integration](https://github.com/MemMachine/MemMachine/tree/main/integrations/llamaindex)** in our repository. ## Overview Integrating MemMachine with [LlamaIndex](https://www.llamaindex.ai/) provides a persistent memory layer for chat engines. This allows agents to: * **Recall User Profiles**: Surface user preferences and facts directly into the prompt context. * **Maintain Context Across Sessions**: Stored episodic and semantic memories persist beyond a single execution. * **Intelligent Injection**: MemMachine automatically injects relevant context as a system message during inference. ## Configuration You can configure the LlamaIndex memory component using environment variables or direct constructor parameters. | Parameter | Environment Variable | Default | Description | | :- | :- | :- | :- | | `base_url` | `MEMORY_BACKEND_URL` | `http://localhost:8080` | MemMachine server URL | | `org_id` | `LLAMAINDEX_ORG_ID` | `llamaindex_org` | Organization ID | | `project_id` | `LLAMAINDEX_PROJECT_ID` | `llamaindex_project` | Project ID | | `user_id` | `LLAMAINDEX_USER_ID` | `None` | User identifier | | `agent_id` | `LLAMAINDEX_AGENT_ID` | `None` | Agent identifier | | `session_id` | `LLAMAINDEX_SESSION_ID` | `None` | Session identifier | *** Install the core LlamaIndex framework and the updated MemMachine client: ```bash theme={null} pip install llama-index memmachine-client ``` Import the `MemMachineMemory` class and configure it with your project identifiers. ```python theme={null} from mem_machine_memory import MemMachineMemory memory = MemMachineMemory( base_url="http://localhost:8080", org_id="my_org", project_id="my_project", user_id="user_123", session_id="session_456" ) ``` Equip your LlamaIndex `SimpleChatEngine` with the persistent memory instance. ```python theme={null} from llama_index.core.chat_engine import SimpleChatEngine from llama_index.llms.openai import OpenAI # Ensure your API key is configured llm = OpenAI(api_key="your-openai-api-key") agent = SimpleChatEngine.from_defaults( llm=llm, memory=memory ) # First interaction stores facts print(agent.chat("I am Alice, I like Python programming.")) # Subsequent interactions recall them print(agent.chat("What do you know about me?")) ``` **Pro Tip:** Tune the `search_msg_limit` parameter to balance the depth of recall against context window usage and latency. ## Requirements * **MemMachine Server**: Must be running (default: `http://localhost:8080`). * **Python**: 3.12 or higher. * **LLM**: An OpenAI-compatible LLM provider. # Claude Code Source: https://docs.memmachine.ai/install_guide/integrate/claude_code_mcp Setting up MemMachine with Claude Code ## Getting Started with MemMachine in Claude Code This guide will help you integrate MemMachine into Claude Code, Anthropic's official CLI tool for software engineering tasks. With MemMachine, Claude Code can remember context across sessions, making it more helpful for ongoing projects. ### What is Claude Code? Claude Code is a command-line interface that provides Claude with powerful tools for software development, including file operations, code execution, and now—with MemMachine—persistent memory across conversations. ### Prerequisites Before you begin, ensure you have: 1. Claude Code installed and configured 2. MemMachine running (either via Docker or as a Python package) 3. A MemMachine configuration file (`config.yml`) Unlike **Claude Desktop**, Claude Code does not use `claude_desktop_config.json`. To integrate MemMachine MCP, you must use `.mcp.json` at your project root and `.claude/settings.local.json` for persistent settings. **Starting Your Docker Container:** Make sure your MemMachine Docker container is running: ```bash theme={null} docker compose up -d ``` Or if you're using the provided script: ```bash theme={null} ./memmachine-compose.sh ``` MemMachine can be integrated with Claude Code in two ways: **Option A: Using Docker (Recommended)** * Best for isolated, reproducible environments * MemMachine runs in a container * Requires Docker installed and running **Option B: Direct Command** * Simpler setup if you have MemMachine installed locally * Uses your system Python environment * Requires MemMachine installed via pip or uv Choose the method that best fits your workflow. To allow Claude Code to access the MemMachine MCP, create or edit the `.mcp.json` file in your **project root**: ```json theme={null} { "mcpServers": { "memmachine": { "command": "docker", "args": [ "exec", "-i", "memmachine-app", "/app/.venv/bin/memmachine-mcp-stdio" ], "env": { "MEMORY_CONFIG": "/app/configuration.yml", "MM_USER_ID": "your-username", "PYTHONUNBUFFERED": "1" } } } } ``` **Crucial for Claude Code:** You must verify that your connection settings in `.mcp.json` match the bridge configuration in `./.claude/settings.local.json`. Claude Code uses the latter to maintain persistent authorization for the MCP server. **Ensure Persistence:** To ensure the connection remains active across sessions, verify or add these settings to your local Claude settings file located at `./.claude/settings.local.json`. **Configuration Details:** To ensure the MCP server communicates correctly with your environment, verify the following parameters in your `.mcp.json` and `.claude/settings.local.json` files: | Parameter | Value / Description | | :- | :- | | **`command`** | Use `docker` for containerized setups or `memmachine-mcp-stdio` for local installs. | | **`MEMORY_CONFIG`** | Path to your `configuration.yml`. **Note:** Use absolute paths for local (Option B) setups. | | **`userId`** | Your unique identifier for memory sessions (corresponds to `MM_USER_ID`). | | **`PYTHONUNBUFFERED`** | Always set to `1` to ensure immediate output and logging from Python. | **Reference Implementation**: This method follows the standard MCP stdio pattern. While it uses the same configuration files as the Docker method, ensure your local Python environment is correctly mapped. If you have MemMachine installed locally, create or edit the `.mcp.json` file in your **project root**: ```json theme={null} { "mcpServers": { "memmachine": { "command": "memmachine-mcp-stdio", "env": { "MEMORY_CONFIG": "/absolute/path/to/config.yml", "MM_USER_ID": "your-username", "PYTHONUNBUFFERED": "1" } } } } ``` **Using uv (Recommended for local setup):** If you are managing your environment with `uv`, use the following configuration in your `.mcp.json`: ```json theme={null} { "mcpServers": { "memmachine": { "command": "uv", "args": ["run", "memmachine-mcp-stdio"], "env": { "MEMORY_CONFIG": "/absolute/path/to/config.yml", "MM_USER_ID": "your-username", "PYTHONUNBUFFERED": "1" } } } } ``` **Important:** Use absolute paths for `MEMORY_CONFIG` to avoid path resolution issues. **Crucial for Claude Code:** You must verify that your connection settings in `.mcp.json` match the bridge configuration in `./.claude/settings.local.json`. Claude Code uses the latter to maintain persistent authorization for the MCP server. Once configured, start Claude Code in your project directory: ```bash theme={null} claude ``` **Verify the connection** by checking the active MCP servers: ```bash theme={null} /MCP ``` If MemMachine is listed, Claude will automatically use the `add_memory` and `search_memory` tools to manage your project context. ``` You: Remember that I prefer using TypeScript for new projects ``` Claude should use the `add_memory` tool to store this preference. **Test memory recall** by starting a new conversation and asking: ``` You: What programming language do I prefer? ``` Claude should search memory and recall your TypeScript preference. MemMachine provides two main tools that Claude Code can use: **add\_memory**: Stores new information * Called automatically when you share facts, preferences, or important context * Stores both episodic (conversation) and profile (long-term) memory **search\_memory**: Retrieves relevant context * Called automatically when context from previous sessions might be helpful * Searches both conversation history and user profile You don't need to explicitly ask Claude to use these tools—they're integrated into the workflow automatically. **Claude Code can't connect to MemMachine:** * Verify your Docker container is running: `docker ps | grep memmachine` * Check the container name matches your config * Review Claude Code logs for connection errors **Memory not persisting:** * Ensure `MEMORY_CONFIG` points to a valid configuration file * Check that your Neo4j and PostgreSQL databases are running * Verify `MM_USER_ID` is consistent across sessions **Permission errors:** * If using Docker, ensure the container has proper volume mounts * Check file permissions on your configuration file * Verify the path to `memmachine-mcp-stdio` is correct **Getting logs:** You can check the MCP server output by viewing: ```bash theme={null} docker logs memmachine-app ``` Or if running directly, check the stderr output in your terminal. # CrewAI Source: https://docs.memmachine.ai/install_guide/integrate/crewai Enable persistent, long-term memory for your CrewAI agents For the full source code and advanced implementation details, see the official **[CrewAI Integration](https://github.com/MemMachine/MemMachine/tree/main/integrations/crewai)** in our repository. ## Overview Integrating MemMachine with [CrewAI](https://crewai.com) empowers your agents with a persistent memory layer. Unlike standard session memory, this integration allows your crews to remember past interactions, learn user preferences, and maintain deep context across multiple tasks and sessions. ## Configuration The integration is primarily managed through environment variables. You can set these in your `.env` file or export them directly in your shell: | Variable | Description | Default | | :- | :- | :- | | `MEMORY_BACKEND_URL` | The URL of your MemMachine backend service | `http://localhost:8080` | | `CREWAI_ORG_ID` | Your organization identifier | `crewai_org` | | `CREWAI_PROJECT_ID` | Your project identifier | `crewai_project` | | `CREWAI_USER_ID` | (Optional) Scopes memory to a specific user | `None` | | `CREWAI_SESSION_ID` | (Optional) Scopes memory to a specific session | `None` | *** Install the core CrewAI framework along with the MemMachine client: ```bash theme={null} pip install crewai crewai-tools memmachine-client ``` The `create_memmachine_tools` helper simplifies the setup. This will return a list of tools that agents can use to `add` and `search` their memory. ```python theme={null} from integrations.crewai.tool import create_memmachine_tools # Initialize tools with your project configuration memmachine_tools = create_memmachine_tools( base_url="http://localhost:8080", org_id="my_org", project_id="my_project", user_id="user123", ) ``` Pass the `memmachine_tools` list to your CrewAI agents. Agents will use these tools automatically when they need to store a new finding or recall a past preference. ```python theme={null} from crewai import Agent, Task, Crew researcher = Agent( role="Research Specialist", goal="Identify emerging trends and remember key data points", backstory="You are an expert researcher. You prioritize long-term memory to avoid repeating work.", tools=memmachine_tools, verbose=True, ) ``` Once the agent is equipped with the memory tools, define your tasks and kickoff the crew. ```python theme={null} task = Task( description="Research the latest 2026 AI trends and store the top 5 findings in memory.", agent=researcher, ) crew = Crew(agents=[researcher], tasks=[task]) result = crew.kickoff() ``` ## Advanced Usage ### Shared Team Memory If you want multiple agents to share the same knowledge pool, initialize the tools with a `group_id`. This is ideal for collaborative agents where a "Writer" needs to recall information stored by a "Researcher." ```python theme={null} memmachine_tools = create_memmachine_tools( org_id="my_org", project_id="my_project", group_id="research_team", # Agents in this group share memory ) ``` ### Manual Memory Management For more granular control, you can use the `MemMachineTools` class directly without the CrewAI agent wrapper. ```python theme={null} from integrations.crewai.tool import MemMachineTools tools = MemMachineTools(org_id="my_org", project_id="my_project") # Manually add a specific fact tools.add_memory(content="User prefers Python for data science.", role="user") # Manually query memory results = tools.search_memory(query="What is the user's preferred language?") print(results["summary"]) ``` **Pro Tip:** Use clear `user_id` or `session_id` identifiers to prevent "memory bleed" between different users or unrelated tasks. ## Requirements * **MemMachine Server:** Must be reachable at the `MEMORY_BACKEND_URL`. * **Python:** 3.10 or higher. * **Framework:** CrewAI and `crewai-tools`. # Dify Source: https://docs.memmachine.ai/install_guide/integrate/dify Integrate MemMachine memory tools into your Dify workflows For the full plugin source code and contribution guidelines, see the official **[Dify Integration](https://github.com/MemMachine/MemMachine/tree/main/integrations/dify)** in the repository. ## Overview The MemMachine Dify plugin allows you to seamlessly integrate persistent memory into your Dify applications. By adding MemMachine as a tool provider, your Dify agents can store chronological interactions (Episodic) and retrieve distilled knowledge (Semantic), enabling a deeper level of context awareness across user sessions. ## Configuration When adding the MemMachine plugin to Dify, you will need to configure the following credentials: | Variable | Description | Default | | - | - | - | | `memmachine_api_key` | Your MemMachine API Key for authentication | (Required) | | `memmachine_base_url` | The URL of your MemMachine backend service | `https://api.memmachine.ai/v2` | The `memmachine_base_url` is optional. If left empty, the plugin will default to the MemMachine Cloud API. If you are self-hosting, ensure you provide your local server address (e.g., `http://localhost:8080`). ## Setup Guide Navigate to the integration directory and run the build script to generate the `.plugin` file: ```bash theme={null} cd integrations/dify # Build the plugin package python build_plugin.py --enable-base-url-credential ``` A. Open your Dify dashboard. B. Navigate to the **Plugins** tab. C. Upload the generated `.plugin` file. Navigate to **Tools > MemMachine** in Dify and enter your configuration: A. Paste your **API Key**. B. (Optional) Enter your **Base URL** if you are not using the cloud service. C. Click **Save**. ## Usage Once installed, you can add MemMachine tools to any Dify **Chatflow** or **Agent**. ### Memory Search Use the `search_memory` tool to retrieve relevant context. In a Chatflow, you can map the query input using Jinja2 templates: Code snippet ``` {{ sys.query }} ``` ### Memory Storage Use the `add_memory` tool within your nodes to persist important information from the conversation, ensuring the agent "remembers" it in future sessions. *** ## Developer Guide (Contributors) If you wish to modify the plugin behavior or develop new tools for the Dify provider: ### Requirements * Python 3.12+ * Dify Plugin CLI (`dify`) * `jinja2` (for build-time template rendering) ### Development Workflow The source of truth for the plugin provider and tool definitions is located in the `templates/` directory. 1. **Modify Templates:** Edit files in `templates/` or add new tools to `tools/`. 2. **Rebuild:** Run `python build_plugin.py` to render the `provider/` files. 3. **Manual Package:** Bash ``` dify-plugin plugin package ./integrations/dify ``` ### Repo Hygiene Note that generated provider files are ignored by git. Always modify the files in `templates/` and use the build script to ensure your changes are correctly propagated to the packaged plugin. ## Requirements * A Dify instance (Cloud or Self-hosted) * MemMachine server running (default: [http://localhost:8080](http://localhost:8080)) or Cloud account * Python 3.12+ (for building/contributing) # n8n Source: https://docs.memmachine.ai/install_guide/integrate/n8n Equip your n8n workflows with persistent, AI-native memory nodes The MemMachine integration for **n8n** allows you to build sophisticated AI agents that remember users across sessions\[cite: 1]. By using the MemMachine community nodes, you can store interactions, retrieve deep context, and trace memory operations directly within your automation canvas\[cite: 2]. ## Overview This integration provides two specialized nodes: * **MemMachine Manager:** Store messages and "Enrich" your agent prompts with semantic context\[cite: 3]. * **MemMachine AI Memory:** A native memory node that plugs directly into n8n's **AI Agent** node\[cite: 4]. ## Start n8n To start a simple n8n container run the upstream docker container as described in the official docs: ```bash theme={null} docker run -it --rm \ --name n8n \ -p 5678:5678 \ -e GENERIC_TIMEZONE="Europe/Berlin" \ -e TZ="Europe/Berlin" \ -e N8N_ENFORCE_SETTINGS_FILE_PERMISSIONS=true \ -e N8N_RUNNERS_ENABLED=true \ -v n8n_data:/home/node/.n8n \ docker.n8n.io/n8nio/n8n ``` ### With Tracing If you want to visualize the memory interactions you might want to use the `docker-compose` file in the github repository. ```bash theme={null} wget -q [https://raw.githubusercontent.com/MemMachine/n8n-nodes-memmachine/refs/heads/main/docker-compose.yml](https://raw.githubusercontent.com/MemMachine/n8n-nodes-memmachine/refs/heads/main/docker-compose.yml) docker-compose up -d ``` Either way, after one of the commands finished, you are able to open your n8n instance. Open [localhost:5678/](http://localhost:5678/): 1. Fill out a sign-up form. 2. Skip the customization and click `Get Started`. 3. Skip the offer page with `Skip`. If you are using a self-hosted n8n instance: 1. Navigate to **Settings > Community Nodes**. 2. Click **Install a community node**. 3. Enter the package name: `@memmachine/n8n-nodes-memmachine` 4. Acknowledge the risk and click **Install**. When you add a MemMachine node, you will be prompted to create credentials. You will need your **API Key** from the MemMachine Dashboard. ## MemMachine Manager Node The Manager node is used for manual memory operations at any point in your workflow. ### Connect MemMachine To use the node you'll need to configure a connection. In case you are running MemMachine on the same machine as a docker container use this endpoint: [http://host.docker.internal:8080/v2/api](http://host.docker.internal:8080/v2/api) ### Action: Store a message Saves a specific content string to long-term memory. | **Parameter** | **Type** | **Description** | | - | - | - | | **orgId / projectId** | String | **Required.** Your unique organization and project identifiers. | | **types** | multiOptions | **Required.** Memory types to use (episodic, semantic). | | **producer** | String | **Required.** Who created this message (e.g., "Agent" or "User"). | | **producedFor** | String | **Required.** Intended recipient of the message. | | **episodeContent** | String | **Required.** The actual message text to store. | | **episodeType** | Options | `none` (default) or `message`. | | **metadata** | JSON | Additional metadata to associate with the message. | | **sessionId** | String | **Required.** Unique session identifier. | | **groupId** | String | Unique group identifier (defaults to `default`). | | **agentId / userId** | String | **Required.** Identifiers for the specific AI agent and user. | ### Action: Enrich with context Retrieves historical context to inject into an LLM prompt. | **Parameter** | **Type** | **Default** | **Description** | | - | - | - | - | | **orgId / projectId** | String | - | **Required.** Unique organization and project identifiers. | | **types** | multiOptions | - | **Required.** Memory types to use (episodic, semantic). | | **query** | String | - | **Required.** Natural language query for semantic search. | | **limit** | Number | 50 | Maximum number of memory results to return. | | **scoreThreshold** | Number | - | Minimum relevance score required to include a memory. | | **filter** | String | - | Filter expression to refine memory search results. Prefix user metadata fields with `m.` / `metadata.` (for example `m.user_id = '123'`). String literals must be single-quoted. Unknown or misspelled user metadata fields return a 400 error. | | **expandContext** | Number | 0 | Number of extra episodes to include for context. | | **sessionId** | String | - | **Required.** Unique session identifier. | | **groupId** | String | `default` | Unique group identifier. | | **agentId / userId** | String | - | **Required.** Identifiers for the specific AI agent and user. | | **enableTemplate** | Boolean | `true` | Renders a formatted context string using a template. | | **contextTemplate** | String | `default template` | Markdown template for formatting. | ## MemMachine AI Memory Node Connect this node directly to the **Memory** input of a native n8n **AI Agent** node. | **Parameter** | **Type** | **Default** | **Description** | | - | - | - | - | | **orgId / projectId** | String | - | **Required.** Your unique organization and project identifiers. | | **contextWindowLength** | Number | 10 | Max recent messages to include in chat history. | | **enableMemoryTemplate** | Boolean | `false` | Whether to wrap history in a formatted template. | | **historyCount** | Number | 5 | Number of episodic memories to include in the template. | | **shortTermCount** | Number | 10 | Number of short-term memories to include. | | **memoryContextTemplate** | String | `default template` | Markdown template for formatting. | `default template` refers to the system's built-in memory context template. Users may override it with a custom template. ## Video Walkthrough Seeing is believing. Check out this practical demonstration of setting up MemMachine nodes within n8n to create persistent AI agents.