# API Reference Overview Source: https://docs.mem0.ai/api-reference REST APIs for memory management, search, and entity operations ## Mem0 REST API Mem0 provides a comprehensive REST API for integrating advanced memory capabilities into your applications. Create, search, update, and manage memories across users, agents, and custom entities with simple HTTP requests. > [!NOTE] > > **Quick start:** Get your API key from the [Mem0 Dashboard](https://app.mem0.ai/dashboard/api-keys?utm_source=oss\&utm_medium=api-reference) and make your first memory operation in minutes. *** ## Quick Start Guide Get started with Mem0 API in three simple steps: 1. **[Add Memories](/api-reference/memory/add-memories)** - Store information and context from user conversations 2. **[Search Memories](/api-reference/memory/search-memories)** - Retrieve relevant memories using semantic search 3. **[Get Memories](/api-reference/memory/get-memories)** - Fetch all memories for a specific entity *** ## Core Operations > **[Add Memories](/api-reference/memory/add-memories)** > > Store new memories from conversations and interactions > **[Search Memories](/api-reference/memory/search-memories)** > > Find relevant memories using semantic search with filters > **[Update Memory](/api-reference/memory/update-memory)** > > Modify existing memory content and metadata > **[Delete Memory](/api-reference/memory/delete-memory)** > > Remove specific memories or batch delete operations *** ## API Categories Explore the full API organized by functionality: > **[Memory APIs](/api-reference/memory/add-memories)** > > Core and advanced operations: CRUD, search, batch updates, history, and exports > **[Events APIs](/api-reference/events/get-events)** > > Track and monitor the status of asynchronous memory operations > **[Entities APIs](/api-reference/entities/get-users)** > > Manage users, agents, and their associated memory data > **[Organizations & Projects](/api-reference/organizations-projects)** > > Multi-tenant support, access control, and team collaboration > **[Webhooks](/api-reference/webhook/create-webhook)** > > Real-time notifications for memory events and updates > [!NOTE] > > **Building multi-tenant apps?** Learn about [Organizations & Projects](/api-reference/organizations-projects) for team isolation and access control. *** ## Authentication All API requests require authentication using Token-based authentication. Include your API key in the Authorization header: ```bash theme={null} Authorization: Token ``` Get your API key from the [Mem0 Dashboard](https://app.mem0.ai/dashboard/api-keys?utm_source=oss\&utm_medium=api-reference). > [!WARNING] > > **Keep your API key secure.** Never expose it in client-side code or public repositories. Use environment variables and server-side requests only. *** ## Next Steps > **[Add Your First Memory](/api-reference/memory/add-memories)** > > Start storing memories via the REST API > **[Search with Filters](/api-reference/memory/search-memories)** > > Learn advanced search and filtering techniques > **[Build with cookbooks](/cookbooks/overview)** > > See the API used end to end in real projects. # Preview Dream Scope Source: https://docs.mem0.ai/api-reference/dream/dream-preview post /api/v1/orgs/organizations/{org_id}/projects/{project_id}/dream/preview/ A no-write preview of the scope Dream synthesis would analyze for a project. # Get Dream Activity Source: https://docs.mem0.ai/api-reference/dream/get-dream-activity get /api/v1/orgs/organizations/{org_id}/projects/{project_id}/dream/activity/ Supersede/merge activity feed for a project, newest first (keyset-paginated). # Get Dream Configuration Source: https://docs.mem0.ai/api-reference/dream/get-dream-config get /api/v1/orgs/organizations/{org_id}/projects/{project_id}/dream/config/ Retrieve a project's Dream (memory synthesis) configuration and plan entitlements. # Get a Synthesized Memory's Sources Source: https://docs.mem0.ai/api-reference/dream/get-dream-memory-sources get /api/v1/orgs/organizations/{org_id}/projects/{project_id}/dream/memory/{memory_id}/sources/ The source memories a synthesized (pattern) memory was distilled from. # Get Memories in a Dream Run Source: https://docs.mem0.ai/api-reference/dream/get-dream-run-memories get /api/v1/orgs/organizations/{org_id}/projects/{project_id}/dream/runs/{run_id}/memories/ Keyset page of the synthesized memories within a single synthesis run. # Get Dream Synthesis Runs Source: https://docs.mem0.ai/api-reference/dream/get-dream-runs get /api/v1/orgs/organizations/{org_id}/projects/{project_id}/dream/runs/ Synthesis activity grouped per run, newest first (keyset-paginated). # Get Dream Stats Source: https://docs.mem0.ai/api-reference/dream/get-dream-stats get /api/v1/orgs/organizations/{org_id}/projects/{project_id}/dream/stats/ Lifecycle and synthesis counts for a project, plus reflection freshness. # Update Dream Configuration Source: https://docs.mem0.ai/api-reference/dream/update-dream-config patch /api/v1/orgs/organizations/{org_id}/projects/{project_id}/dream/config/ Enable or disable Synthesis (reflection) for a project, or change the reflection mode. # Delete User Source: https://docs.mem0.ai/api-reference/entities/delete-user delete /v2/entities/{entity_type}/{entity_id}/ Remove a user entity from the Mem0 platform by entity type and ID using the DELETE endpoint. # Get Users Source: https://docs.mem0.ai/api-reference/entities/get-users get /v1/entities/ Retrieve a list of all user entities stored in the Mem0 platform using the GET endpoint. # Get Event Source: https://docs.mem0.ai/api-reference/events/get-event get /v1/event/{event_id}/ Retrieve details of a specific event by ID, including status and payload for async memory operations. Retrieve details about a specific event by passing its `event_id`. This endpoint is particularly helpful for tracking the status, payload, and completion details of asynchronous memory operations. For `POST /v3/memories/add/`, the event confirms that the write pipeline completed. Temporal reasoning enrichment runs asynchronously by default, so the event may be `SUCCEEDED` slightly before temporal ranking signals are available to subsequent `search` calls. # Get Events Source: https://docs.mem0.ai/api-reference/events/get-events get /v1/events/ List recent events for your organization and project, useful for dashboards, alerting, and audit logging. List recent events for your organization and project. ## Use Cases * **Dashboards**: Summarize adds/searches over time by paging through events. * **Alerting**: Poll for `FAILED` events and trigger follow-up workflows. * **Audit**: Store the returned payload/metadata for compliance logs. # Add Memories Source: https://docs.mem0.ai/api-reference/memory/add-memories post /v3/memories/add/ Add facts, messages, or metadata to a user memory store with async processing and event tracking via the V3 additive pipeline. Extract and store memories from a conversation using the V3 additive pipeline. The endpoint uses single-pass ADD-only extraction: one LLM call, no UPDATE/DELETE. Memories accumulate over time; nothing is overwritten. ## Endpoint * **Method**: `POST` * **URL**: `/v3/memories/add/` * **Content-Type**: `application/json` Processing is asynchronous. The response returns an `event_id` you can poll via `GET /v1/event/{event_id}/`. ## Required headers | Header | Required | Description | | - | - | - | | `Authorization: Token ` | Yes | API key scoped to your workspace. | | `Accept: application/json` | Yes | Ensures a JSON response. | ## Request body Provide conversation messages for Mem0 to extract memories from. At least one entity ID (`user_id`, `agent_id`, `app_id`, or `run_id`) is required so the memory is scoped to a session. Entity IDs are accepted at the top level. ```json Basic request theme={null} { "user_id": "alice", "messages": [ { "role": "user", "content": "I moved to Austin last month." } ], "metadata": { "source": "onboarding_form" } } ``` ### Common fields | Field | Type | Required | Description | | - | - | - | - | | `messages` | array | Yes | Conversation turns for Mem0 to extract memories from. Each object should include `role` and `content`. | | `user_id` | string | No\* | Associates the memory with a user. | | `agent_id` | string | No\* | Associates the memory with an agent. | | `run_id` | string | No\* | Associates the memory with a run. | | `app_id` | string | No\* | Associates the memory with an app. | | `metadata` | object | Optional | Custom key/value metadata (e.g., `{"topic": "preferences"}`). | | `infer` | boolean (default `true`) | Optional | Set to `false` to skip inference and store the provided text as-is. | | `expiration_date` | string | Optional | Date in `YYYY-MM-DD` format. The memory is visible through this date and hidden by default after it passes. | > \* At least one entity ID (`user_id`, `agent_id`, `app_id`, or `run_id`) is required. > [!TIP] > > Need more details? See [all request parameters](#body-messages) below for complete field descriptions, types, and constraints. ## Response The request is queued for background processing. The response contains an `event_id` for tracking status. ```json 200 response theme={null} { "event_id": "evt-uuid", "status": "PENDING" } ``` ```json 400 response theme={null} { "error": "400 Bad Request", "details": { "message": "Invalid input data. Please refer to the memory creation documentation at https://docs.mem0.ai/platform/quickstart#4-1-create-memories for correct formatting and required fields." } } ``` > [!NOTE] > > Poll the event status via `GET /v1/event/{event_id}/`. Status will be `SUCCEEDED` or `FAILED` once processing completes. > [!NOTE] > > Memories with `expiration_date` remain stored after they expire. Search and get-all hide them by default; pass `show_expired: true` to include them. > [!NOTE] > > Python uses `expiration_date`; TypeScript uses `expirationDate`. # Batch Delete Memories Source: https://docs.mem0.ai/api-reference/memory/batch-delete delete /v1/batch/ Delete multiple memories in a single batch request using the Mem0 API DELETE endpoint. # Batch Update Memories Source: https://docs.mem0.ai/api-reference/memory/batch-update put /v1/batch/ Update multiple memories in a single batch request using the Mem0 API PUT endpoint. # Create Memory Export Source: https://docs.mem0.ai/api-reference/memory/create-memory-export post /v1/exports/ Submit an export job to create a structured memory export using a customizable Pydantic schema and filters. Submit a job to create a structured export of memories using a customizable Pydantic schema. This process may take some time to complete, especially if you're exporting a large number of memories. You can tailor the export by applying various filters (e.g., `user_id`, `agent_id`, `app_id`, or `run_id`) and by modifying the Pydantic schema to ensure the final data matches your exact needs. # Delete Memories Source: https://docs.mem0.ai/api-reference/memory/delete-memories delete /v1/memories/ Delete all memories matching specified filters from the Mem0 memory store using the DELETE endpoint. # Delete Memory API Endpoint Source: https://docs.mem0.ai/api-reference/memory/delete-memory delete /v1/memories/{memory_id}/ Delete a single memory by its unique memory ID from the Mem0 platform using the DELETE endpoint. # Feedback Source: https://docs.mem0.ai/api-reference/memory/feedback post /v1/feedback/ Submit positive or negative feedback on memory results to help improve memory accuracy and relevance. # Get Memories Source: https://docs.mem0.ai/api-reference/memory/get-memories post /v3/memories/ Retrieve memories with paginated results and advanced filtering using logical operators like AND, OR, NOT, and comparison queries. List memories scoped by filters with paginated results. Entity IDs (`user_id`, `agent_id`, `app_id`, `run_id`) **must** be passed inside the `filters` object: top-level entity IDs are rejected with 400. Expired memories are hidden by default. Pass `show_expired: true` to include memories whose `expiration_date` has passed. Python uses `show_expired`; TypeScript uses `showExpired`. The `filters` object supports complex logical operations (AND, OR, NOT) and comparison operators: * `in`: Matches any of the values specified * `gte`: Greater than or equal to * `lte`: Less than or equal to * `gt`: Greater than * `lt`: Less than * `ne`: Not equal to * `icontains`: Case-insensitive containment check * `*`: Wildcard character that matches everything Pass `page` and `page_size` as query parameters to paginate through results. ```python Code theme={null} memories = client.get_all( filters={ "AND": [ { "user_id": "alex" }, { "created_at": {"gte": "2024-07-01", "lte": "2024-07-31"} } ] }, show_expired=False, page=1, page_size=50 ) ``` ```python Output theme={null} { "count": 2, "next": null, "previous": null, "results": [ { "id": "f4cbdb08-7062-4f3e-8eb2-9f5c80dfe64c", "memory": "Alex is planning a trip to San Francisco from July 1st to July 10th", "expiration_date": null, "created_at": "2024-07-01T12:00:00Z", "updated_at": "2024-07-01T12:00:00Z" }, { "id": "a2b8c3d4-5e6f-7g8h-9i0j-1k2l3m4n5o6p", "memory": "Alex prefers vegetarian restaurants", "expiration_date": null, "created_at": "2024-07-05T15:30:00Z", "updated_at": "2024-07-05T15:30:00Z" } ] } ``` > [!NOTE] > > The response is a paginated envelope with `count`, `next`, `previous`, and `results`. Use `page` and `page_size` query params to step through results. # Get Memory Source: https://docs.mem0.ai/api-reference/memory/get-memory get /v1/memories/{memory_id}/ Retrieve a single memory by its unique memory ID from the Mem0 platform using the GET endpoint. # Get Memory Export Source: https://docs.mem0.ai/api-reference/memory/get-memory-export post /v1/exports/get Retrieve the latest structured memory export after submitting an export job, with optional entity filters. Retrieve the latest structured memory export after submitting an export job. You can filter the export by `user_id`, `agent_id`, `app_id`, `run_id`, `created_at`, or `updated_at` to get the most recent export matching your filters. # Memory History Source: https://docs.mem0.ai/api-reference/memory/history-memory get /v1/memories/{memory_id}/history/ Retrieve the full change history of a specific memory to track how it has evolved over time. # Search Memories Source: https://docs.mem0.ai/api-reference/memory/search-memories post /v3/memories/search/ Search memories with hybrid retrieval (semantic + BM25 + entity matching) and advanced filtering using logical and comparison operators. Relevance-ranked hybrid search across stored memories. V3 uses multi-signal retrieval: semantic, BM25 keyword, and entity matching scored in parallel and fused. The returned `score` is a combined `[0, 1]` value. Entity IDs (`user_id`, `agent_id`, `app_id`, `run_id`) **must** be passed inside the `filters` object: top-level entity IDs are rejected with 400. At least one entity ID is required. Expired memories are hidden by default. Pass `show_expired: true` to include memories whose `expiration_date` has passed. Python uses `show_expired`; TypeScript uses `showExpired`. The `filters` object supports complex logical operations (AND, OR, NOT) and comparison operators: * `in`: Matches any of the values specified * `gte`: Greater than or equal to * `lte`: Less than or equal to * `gt`: Greater than * `lt`: Less than * `ne`: Not equal to * `icontains`: Case-insensitive containment check * `*`: Wildcard character that matches everything ### Search parameter defaults | Parameter | Default | | - | - | | `top_k` | `10` (range 1–1000) | | `threshold` | `0.1` (pass `0.0` to disable) | | `rerank` | `false` (pass `true` to enable) | ```python Platform API Example theme={null} related_memories = client.search( query="What are Alice's hobbies?", show_expired=False, filters={ "OR": [ { "user_id": "alice" }, { "agent_id": {"in": ["travel-agent", "sports-agent"]} } ] }, ) ``` ```json Output theme={null} { "results": [ { "id": "ea925981-272f-40dd-b576-be64e4871429", "memory": "Likes to play cricket and plays cricket on weekends.", "user_id": "alice", "metadata": { "category": "hobbies" }, "score": 0.82, "expiration_date": null, "created_at": "2024-07-26T10:29:36.630547-07:00", "updated_at": null, "categories": ["hobbies"] } ] } ``` ```python Wildcard Example theme={null} # Using wildcard to match all run_ids for a specific user all_memories = client.search( query="What are Alice's hobbies?", filters={ "AND": [ { "user_id": "alice" }, { "run_id": "*" } ] }, ) ``` ```python Categories Filter Examples theme={null} # Example 1: Using 'contains' for partial matching finance_memories = client.search( query="What are my financial goals?", filters={ "AND": [ { "user_id": "alice" }, { "categories": { "contains": "finance" } } ] }, ) # Example 2: Using 'in' for exact matching personal_memories = client.search( query="What personal information do you have?", filters={ "AND": [ { "user_id": "alice" }, { "categories": { "in": ["personal_information"] } } ] }, ) ``` # Update Memory API Endpoint Source: https://docs.mem0.ai/api-reference/memory/update-memory put /v1/memories/{memory_id}/ Update the content, metadata, timestamp, or expiration date of a single memory by its unique ID using the PUT endpoint. Use this endpoint to update mutable memory fields. To make a memory expire, set `expiration_date` to a `YYYY-MM-DD` date. To make it permanent again, send `expiration_date: null`. ```python theme={null} client.update("mem_123", expiration_date="2030-01-31") client.update("mem_123", expiration_date=None) ``` TypeScript uses `expirationDate`. # Add Organization Member API Endpoint Source: https://docs.mem0.ai/api-reference/organization/add-org-member post /api/v1/orgs/organizations/{org_id}/members/ Add a new member to an organization with a specified role such as READER or OWNER access level. The API provides two roles for organization members: * `READER`: Allows viewing of organization resources. * `OWNER`: Grants full administrative access to manage the organization and its resources. # Create Organization Source: https://docs.mem0.ai/api-reference/organization/create-org post /api/v1/orgs/organizations/ Create a new organization on the Mem0 platform to manage projects, members, and memory resources. # Delete Organization Source: https://docs.mem0.ai/api-reference/organization/delete-org delete /api/v1/orgs/organizations/{org_id}/ Permanently delete an organization and its associated resources from the Mem0 platform. # Get Organization Source: https://docs.mem0.ai/api-reference/organization/get-org get /api/v1/orgs/organizations/{org_id}/ Retrieve details of a specific organization by its ID from the Mem0 platform using the GET endpoint. # Get Organization Members API Endpoint Source: https://docs.mem0.ai/api-reference/organization/get-org-members get /api/v1/orgs/organizations/{org_id}/members/ Retrieve a list of all members belonging to a specific organization on the Mem0 platform. # Get Organizations Source: https://docs.mem0.ai/api-reference/organization/get-orgs get /api/v1/orgs/organizations/ Retrieve a list of all organizations associated with your Mem0 account using the GET endpoint. # Remove Organization Member Source: https://docs.mem0.ai/api-reference/organization/remove-org-member delete /api/v1/orgs/organizations/{org_id}/members/ Remove a member from an organization to revoke their access to its projects and resources. # Update Organization Member Source: https://docs.mem0.ai/api-reference/organization/update-org-member put /api/v1/orgs/organizations/{org_id}/members/ Update an existing member's role within an organization to change their permissions and access level. # Organizations & Projects Source: https://docs.mem0.ai/api-reference/organizations-projects Manage multi-tenant applications with organization and project APIs ## Overview Organizations and projects provide multi-tenant support, access control, and team collaboration capabilities for Mem0 Platform. Use these APIs to build applications that support multiple teams, customers, or isolated environments. > [!NOTE] > > Organizations and projects are **optional** features. You can use Mem0 without them for single-user or simple multi-user applications. ## Key Capabilities * **Multi-org/project Support**: Organization and project are resolved automatically from your API key via `/v1/ping/`: no org or project params are accepted by `MemoryClient.__init__`. Use a project-specific API key to target a particular project. * **Member Management**: Control access to data through organization and project membership * **Access Control**: Only members can access memories and data within their organization/project scope * **Team Isolation**: Maintain data separation between different teams and projects for secure collaboration *** ## Using Organizations & Projects ### Initialize with Org/Project Context Example with the mem0 Python package: **Python** ```python theme={null} from mem0 import MemoryClient client = MemoryClient(api_key="your-api-key") ``` **Node.js** ```javascript theme={null} import { MemoryClient } from "mem0ai"; const client = new MemoryClient({ apiKey: "your-api-key" }); ``` *** ## Project Management The Mem0 client provides comprehensive project management through the `client.project` interface: ### Get Project Details Retrieve information about the current project: ```python theme={null} # Get all project details project_info = client.project.get() # Get specific fields only project_info = client.project.get(fields=["name", "description", "custom_categories"]) ``` ### Create a New Project Create a new project within your organization: ```python theme={null} # Create a project with name and description new_project = client.project.create( name="My New Project", description="A project for managing customer support memories" ) ``` ### Update Project Settings Modify project configuration including custom instructions, categories, language preferences, and memory decay: ```python theme={null} # Update project with custom categories client.project.update( custom_categories=[ {"customer_preferences": "Customer likes, dislikes, and preferences"}, {"support_history": "Previous support interactions and resolutions"} ] ) # Update project with custom instructions client.project.update( custom_instructions="..." ) # Separate extraction instructions for agent-scoped memories # (see /platform/features/custom-instructions) client.project.update( agent_custom_instructions="..." ) # Use the input language for memory storage and retrieval client.project.update(multilingual=True) # Enable Memory Decay (boosts recently-accessed memories at search time) client.project.update(decay=True) # Update multiple settings at once client.project.update( custom_instructions="...", custom_categories=[ {"personal_info": "User personal information and preferences"}, {"work_context": "Professional context and work-related information"} ], multilingual=True ) ``` #### Toggle Memory Decay `decay` is a per-project boolean that turns on [Memory Decay](/platform/features/memory-decay): a search-time ranking bias that reinforces recently-accessed memories and gently dampens stale ones. The flag is `false` by default; set it via the same project-update endpoint: ```bash cURL theme={null} curl -X PATCH https://api.mem0.ai/api/v1/orgs/organizations/$ORG_ID/projects/$PROJECT_ID/ \ -H "Authorization: Token $MEM0_API_KEY" \ -H "Content-Type: application/json" \ -d '{"decay": true}' ``` The current state is returned on every project read (and supports `?fields=decay` for a minimal response). Toggling has no effect on stored memories, only on how v3 search ranks them. ### Delete Project > [!WARNING] > > This action will remove all memories, messages, and other related data in the project. **This operation is irreversible.** Remove a project and all its associated data: ```python theme={null} # Delete the current project (irreversible) result = client.project.delete() ``` *** ## Member Management Manage project members and their access levels: ```python theme={null} # Get all project members members = client.project.get_members() # Add a new member as a reader client.project.add_member( email="colleague@company.com", role="READER" # or "OWNER" ) # Update a member's role client.project.update_member( email="colleague@company.com", role="OWNER" ) # Remove a member from the project client.project.remove_member(email="colleague@company.com") ``` ### Member Roles | Role | Permissions | | - | - | | **READER** | Can view and search memories, but cannot modify project settings or manage members | | **OWNER** | Full access including project modification, member management, and all reader permissions | *** ## Async Support All project methods are available in async mode: ```python theme={null} from mem0 import AsyncMemoryClient async def manage_project(): client = AsyncMemoryClient(api_key="your-api-key") # All methods support async/await project_info = await client.project.get() await client.project.update(multilingual=True) members = await client.project.get_members() # To call the async function properly import asyncio asyncio.run(manage_project()) ``` *** ## API Reference For complete API specifications and additional endpoints, see: > **[Organizations APIs](/api-reference/organization/create-org)** > > Create, get, and manage organizations > **[Project APIs](/api-reference/project/create-project)** > > Full project CRUD and member management endpoints # Generate Profiles Source: https://docs.mem0.ai/api-reference/profiles/generate-profiles post /v2/profiles/jobs/ Start one generation: sample a few entities, or build one for a single entity. # Get Profile Source: https://docs.mem0.ai/api-reference/profiles/get-profile get /v2/entities/{entity_type}/{entity_id}/profile/ Retrieve the structured profile for a user, with a status describing whether generation has completed. # Get Generation Job Source: https://docs.mem0.ai/api-reference/profiles/get-profile-job get /v2/profiles/jobs/{job_id}/ Read the progress of a generation, and whether it finished. # Get Profile Settings Source: https://docs.mem0.ai/api-reference/profiles/get-profile-settings get /v2/profiles/settings/ Retrieve the profile schema, custom instructions, and enabled flag for the current project. # Update Profile Settings Source: https://docs.mem0.ai/api-reference/profiles/update-profile-settings post /v2/profiles/settings/ Set the JSON Schema, custom instructions, or enabled flag that control profile generation for the project. # Add Project Member API Endpoint Source: https://docs.mem0.ai/api-reference/project/add-project-member post /api/v1/orgs/organizations/{org_id}/projects/{project_id}/members/ Add a new member to a project with a specified role such as READER or OWNER access level. The API provides two roles for project members: * `READER`: Allows viewing of project resources. * `OWNER`: Grants full administrative access to manage the project and its resources. # Create Project Source: https://docs.mem0.ai/api-reference/project/create-project post /api/v1/orgs/organizations/{org_id}/projects/ Create a new project within an organization on the Mem0 platform to isolate memory resources. # Delete Project Source: https://docs.mem0.ai/api-reference/project/delete-project delete /api/v1/orgs/organizations/{org_id}/projects/{project_id}/ Permanently delete a project and its associated data from the Mem0 platform by project ID. # Get Project Source: https://docs.mem0.ai/api-reference/project/get-project get /api/v1/orgs/organizations/{org_id}/projects/{project_id}/ Retrieve details of a specific project by its organization and project ID using the GET endpoint. # Get Project Members API Endpoint Source: https://docs.mem0.ai/api-reference/project/get-project-members get /api/v1/orgs/organizations/{org_id}/projects/{project_id}/members/ Retrieve a list of all members belonging to a specific project on the Mem0 platform. # Get Projects Source: https://docs.mem0.ai/api-reference/project/get-projects get /api/v1/orgs/organizations/{org_id}/projects/ Retrieve a list of all projects within an organization on the Mem0 platform using the GET endpoint. # Remove Project Member Source: https://docs.mem0.ai/api-reference/project/remove-project-member delete /api/v1/orgs/organizations/{org_id}/projects/{project_id}/members/ Remove a member from a project to revoke their access to its memories, configuration, and resources. # Update Project Source: https://docs.mem0.ai/api-reference/project/update-project patch /api/v1/orgs/organizations/{org_id}/projects/{project_id}/ Update a project's settings, including name, custom instructions, and other configuration options. # Update Project Member Source: https://docs.mem0.ai/api-reference/project/update-project-member put /api/v1/orgs/organizations/{org_id}/projects/{project_id}/members/ Update an existing member's role within a project to change their permissions and access level. # Create Webhook Source: https://docs.mem0.ai/api-reference/webhook/create-webhook post /api/v1/webhooks/projects/{project_id}/ Create a new webhook for a project to receive real-time notifications about memory events. # Delete Webhook Source: https://docs.mem0.ai/api-reference/webhook/delete-webhook delete /api/v1/webhooks/{webhook_id}/ Delete an existing webhook by its ID to stop receiving notifications for memory events. # Get Webhook Source: https://docs.mem0.ai/api-reference/webhook/get-webhook get /api/v1/webhooks/projects/{project_id}/ Retrieve webhook configuration details for a specific project on the Mem0 platform. # Update Webhook Source: https://docs.mem0.ai/api-reference/webhook/update-webhook put /api/v1/webhooks/{webhook_id}/ Update an existing webhook configuration, such as its URL or event subscriptions, by webhook ID. # Highlights Source: https://docs.mem0.ai/changelog/highlights Major product launches, headline features, and milestones for Mem0. **2026-08-24** DeepSeek Harness plugin **DeepSeek Harness: Mem0 as a Native Cordis Plugin** The DeepSeek Harness agent forgets everything between sessions. [`@mem0/deepseek-plugin`](https://www.npmjs.com/package/@mem0/deepseek-plugin) gives it two Mem0-backed tools, so recall and writes persist across runs against the same memory bank you already use from Claude Code, Codex, and every other connected agent. * **Two agent-callable tools:** `search_memory` recalls facts relevant to a query, `add_memory` stores a fact for future sessions. Both accept per-call `userId` / `agentId` / `runId` scope overrides. * **Native Cordis lifecycle:** The plugin declares `inject = ['tools']` so it waits for the harness tool registry, then registers through `ctx.tools.register()`. Unmounting the plugin removes the tools automatically. * **Managed backend, not a memory file:** Server-side extraction, semantic dedup, and conflict resolution, rather than a Markdown file the agent has to maintain itself. * **Config:** `userId` is required, `apiKey` defaults to `$MEM0_API_KEY`, and `host` optionally targets a dedicated Mem0 Platform base URL. See [DeepSeek Harness](/integrations/deepseek-plugin) for setup and [SDK & Tools](/changelog/sdk) for PR links. > [!NOTE] > > Developer preview. Auto-capture and auto-recall, where memory reaches the context with no explicit tool call, are planned but not yet built. **2026-08-24** Strands Agents integration **Strands Agents: Mem0 as a Native MemoryStore** [`mem0-strands`](https://pypi.org/project/mem0-strands/) plugs Mem0 into AWS's [Strands Agents](https://strandsagents.com/) SDK as a native `MemoryStore`, so recall and writes happen inside the agent loop rather than as tool calls the model has to remember to make. * **Automatic recall:** The `MemoryManager` drives the store on every turn, searching Mem0 and injecting the results into the prompt with no tool call required. * **Server-side extraction:** Because the store implements `add_messages`, enabling extraction routes raw conversation turns straight to Mem0's extraction pipeline, skipping the extra client-side model call needed to distill facts first. * **Hosted or self-hosted:** An API key targets the hosted Mem0 Platform; a config dict targets self-hosted Mem0 OSS. * **Entity scoping:** Accepts `user_id`, `agent_id`, `run_id`, and `app_id`, with at least one required and invalid combinations rejected at construction rather than on the first write. See [Strands Agents](/integrations/strands) for setup and [SDK & Tools](/changelog/sdk) for PR links. **2026-08-13** Kimi Code plugin **Kimi Code: Mem0 Joins the Editor Plugin Family** The shared Mem0 editor plugin now covers Kimi Code alongside Claude Code, Cursor, Codex, and Antigravity, running on the same scripts, skills, and memory bank, so context written in one editor is available in the others. * **Hosted MCP server:** Registers `https://mcp.mem0.ai/mcp/`, authenticated with `MEM0_API_KEY` as a bearer token. * **Automatic capture and recall:** SessionStart loads context through the `context-loader` skill, and hooks on prompt submit, file reads, Bash output, stop, and pre-compact capture and inject memory without an explicit tool call. * **Guardrails:** Direct `Write` / `Edit` / `MultiEdit` to memory files is blocked, and metadata defaults are enforced on every Mem0 MCP tool call. * **Kimi hook adapter:** A shim normalizes Kimi Code's hook contract to the shape the shared scripts already expect, resolving the real project directory and translating the differing prompt, tool-output, and MCP tool-name fields. See [SDK & Tools](/changelog/sdk) for version details and PR links. **2026-07-30** n8n and Zapier integrations **Workflow Automation: Mem0 Memory in n8n and Zapier** Mem0 now plugs into two no-code automation platforms, so workflows that used to start from zero on every run can store durable facts and recall them later. * **n8n community node:** [`@mem0/n8n-nodes-mem0`](https://www.npmjs.com/package/@mem0/n8n-nodes-mem0) adds a **Mem0** node with a Memory resource covering Add, Search, Get, Get Many, Update, and Delete. Install it from **Settings → Community Nodes** on a self-hosted instance, then connect your API key once as a Mem0 API credential. See [n8n](/integrations/n8n). * **n8n AI Agent tool:** Attach the same node to an [AI Agent](https://docs.n8n.io/advanced-ai/) node and it becomes a tool the agent calls on its own, so it can decide when to remember and when to recall. * **Zapier app:** Add Memory, Search Memories, Get Memories, and Delete Memory actions let any of Zapier's thousands of apps write and read Mem0 context with no code and no server. See [Zapier](/integrations/zapier). * **One-time connection:** Both integrations authenticate with a single Mem0 API key and default to `https://api.mem0.ai`, with a configurable base URL for self-hosted deployments. > [!NOTE] > > The Zapier app is not yet listed in Zapier's public App Directory. Email [support@mem0.ai](mailto:support@mem0.ai) for an invite link. **2026-07-13** TypeScript provider expansion **TypeScript OSS SDK: 26 New Providers, Reranking, and Zero-Dependency Imports** TypeScript SDK v3.1.0 is the largest provider release for the OSS SDK so far, closing most of the remaining gap with the Python SDK. Python SDK v2.0.12 ships alongside it with fixes and security patches. * **17 new vector stores:** Pinecone, Weaviate, Milvus, Chroma, MongoDB, Elasticsearch, OpenSearch, Databricks, AWS Neptune Analytics, S3 Vectors, Azure MySQL, Google Vertex AI Vector Search, Turbopuffer, Upstash Vector, Valkey, Cassandra, and Baidu Mochow. * **5 new LLM providers:** AWS Bedrock, xAI Grok, Together, vLLM, and Sarvam. * **4 new embedding providers:** Vertex AI, HuggingFace, FastEmbed, and Together. * **Reranking in TypeScript:** Four rerankers (Cohere, ZeroEntropy, cross-encoder, and LLM-based) with per-search rerank via a `rerank` option on `search()`. * **Install only what you use:** Importing `mem0ai/oss` no longer pulls in any provider SDK. Provider packages are resolved lazily on first use, so an app that configures only OpenAI and Qdrant does not need the other provider SDKs installed. See [SDK & Tools](/changelog/sdk) for version details and PR links. **2026-06-27** SDK memory expiration **SDK Memory Expiration: Expiring Memories Across Python and TypeScript** The latest SDK releases add first-class expiration controls to memory writes, updates, and reads, plus new TypeScript provider coverage for production deployments. * **Python client updates:** `MemoryClient.update()` and `AsyncMemoryClient.update()` now accept `expiration_date`, including `None` to clear an existing expiration. * **TypeScript client updates:** `AddMemoryOptions`, `update()`, and `Memory` now support `expirationDate`; `search()` and `getAll()` can include expired memories with `showExpired`. * **New TypeScript LLM providers:** `MiniMaxLLM` and `LiteLLM` are now available for OpenAI-compatible MiniMax and LiteLLM proxy deployments. * **PGVector deployment flexibility:** TypeScript PGVector config now supports `connectionString` and `ssl`, so apps can use a managed Postgres URI instead of separate connection fields. See [SDK & Tools](/changelog/sdk) for version details and PR links. **2026-06-25** Mem0 Plugin v0.2.11 **Mem0 Plugin: Shared Memory for Claude Code, Cursor, Codex, and Antigravity** The shared Mem0 editor plugin is current through v0.2.11: * **Automatic context injection:** File reads, bash errors, session resume prompts, and startup timelines can retrieve relevant memories automatically. * **Project and global scopes:** Project-scoped memories remain the default, while `global_search` supports team-wide recall across users and app scopes. * **Coding categories:** A 17-category coding taxonomy installs in the background and is cached per Mem0 account. * **Reliable capture:** Auto-capture, compaction summaries, session summaries, and metadata defaults keep memories scoped and readable. * **Editor correctness:** Telemetry now reports Claude Code, Cursor, Codex, and Antigravity separately with each editor's real plugin version. **2026-06-25** Antigravity Plugin v0.1.3 **Antigravity Plugin: Mem0 for Google Antigravity** Antigravity support in the shared Mem0 editor plugin family is current through v0.1.3: * **Self-contained plugin:** Includes its own plugin manifest, MCP config, hooks, shared scripts, and skills. * **AGENTS.md convention:** Uses Antigravity's `contextFileName: "AGENTS.md"` convention. * **Lifecycle hooks:** Wires session start, prompt recall, file-read context, memory-tool metadata enforcement, bash-error lookup, post-tool tracking, and stop summaries. * **Shared memory layer:** Reuses the Mem0 Platform MCP tools and the shared 16-skill command bundle. * **Better automatic recall:** v0.1.3 adds reranked injected context and clean `files_touched` metadata in session summaries. * **Telemetry correctness:** v0.1.2 reports Antigravity as `antigravity` with the plugin's own version. **2026-06-22** OpenCode Plugin v0.2.0 **OpenCode Plugin: Native SDK Memory Tools for OpenCode** `@mem0/opencode-plugin` adds memory to OpenCode and is current through v0.2.0: * **Native SDK tools:** Memory tools register through `@opencode-ai/plugin` and call the `mem0ai` SDK directly, so the plugin no longer depends on `mcp.mem0.ai`. * **Memory scopes:** Operations support `project`, `session`, and `global` scope, with `/mem0-scope` to change the default. * **Automatic context:** File-context injection, structured compaction summaries, and a recent-activity timeline surface relevant memories without manual recall. * **Auto-dream consolidation:** Gated consolidation merges duplicates, drops stale or sensitive entries, and rewrites vague memories. * **Skills load in place:** The `config` hook adds bundled skills to `skills.paths` instead of copying them into user config directories. * **Safety controls:** Blocks `MEMORY.md` writes and redacts secrets before storing memories. **2026-06-12** Pi Agent Plugin v0.1.2 **Pi Agent Plugin: Persistent Memory for Pi Agent** `@mem0/pi-agent-plugin` adds semantic memory to Pi Agent and has been updated through v0.1.2: * **Agent memory tool:** Registers `mem0_memory` for scoped search, add, get, delete, and delete-all operations. * **Slash commands:** Adds `/mem0-remember`, `/mem0-search`, `/mem0-forget`, `/mem0-tour`, `/mem0-dream`, `/mem0-pin`, `/mem0-scope`, and `/mem0-status`. * **Auto-capture:** Stores user and assistant memories after agent turns. * **Dream consolidation:** Merges duplicates, resolves contradictions, and prunes stale memories behind session, time, and memory-count gates. * **Project scoping:** Uses git-root detection for stable `app_id` values across monorepos. * **Relevant command results:** v0.1.2 adds visible command feedback and thresholded, reranked search for search, forget, and pin commands. **2026-06-12** OpenClaw v1.0.13 **OpenClaw Plugin: Current Memory Backend for OpenClaw** `@mem0/openclaw-mem0` is current through v1.0.13, with the original production-ready memory backend plus newer setup, security, and runtime work: * **Skills-based memory architecture:** Triage, recall, and dream skills handle extraction, recall, consolidation, and tool guidance. * **Chat and CLI setup:** Supports chat-based platform setup, `openclaw mem0 init`, direct API keys, email OTP, autonomous agent setup, and OSS onboarding. * **Platform and OSS modes:** Works with Mem0 Platform or self-hosted OSS providers including OpenAI, Anthropic, Ollama, Qdrant, and PGVector. * **Agent-friendly CLI:** All 16 CLI commands support `--json` for machine-driven setup and diagnostics. * **Runtime integration:** Exposes OpenClaw memory capability APIs for search manager and backend config status. * **Security and compliance:** Added path containment checks, sensitive config metadata, dependency overrides, telemetry hashing, and metadata-only registration safety. **2026-06-10** Vercel AI SDK Provider v3.0.0 **Vercel AI SDK Provider: Memory-Augmented Generation for AI SDK v6** The Vercel AI SDK provider moved to the v6 provider contract and Mem0 v3 APIs: * **AI SDK v6 support:** Migrated to `LanguageModelV3` / `ProviderV3`, including v3 stream lifecycle events and content arrays. * **Mem0 v3 API support:** Memory writes and searches now use `/v3/memories/add/` and `/v3/memories/search/`. * **Mem0 sources in responses:** `generateText` and `streamText` responses include memories as sources with `providerMetadata.mem0.memories`. * **Safer prompt handling:** Prompts are cloned before memory injection, avoiding caller-side mutation. * **Async storage fix:** `addMemories` is awaited so generated memories are not silently dropped. * **Raw memory utilities:** Exports `searchMemories`, `retrieveMemories`, `getMemories`, and `addMemories` for apps that need direct memory control. * **Deployment controls:** Per-request `mem0ApiKey` and `host` support Mem0 Platform, custom API keys, and self-hosted API endpoints. **2026-05-13** Temporal Reasoning for Mem0 Platform v3 **Temporal Reasoning: Time-Aware Retrieval for Platform v3** Mem0 Platform v3 can now interpret time-aware memories and queries so assistants retrieve the right information for questions about the past, upcoming plans, and current state. * **Search intent parsing:** Queries like `last week`, `upcoming`, `right now`, and `as of March 2025` now resolve against memory timestamps automatically. * **Default v3 behavior:** No per-request toggle is needed for v3 writes or searches. * **Deterministic testing:** Pass `reference_date` to anchor relative phrases in tests, backfills, and demos. * **Stable API shape:** Temporal reasoning changes ranking, not the client response contract. See [Temporal Reasoning](/platform/features/temporal-reasoning) for usage details. **2026-05-08** Memory Decay **Memory Decay: Recently-Used Memories Surface Higher** Per-project search-time ranking bias that boosts recently-touched memories and gently dampens stale ones. Off by default; opt in per project via the `decay` field on the project endpoint, or via `client.project.update(decay=True)` in the SDKs (Python `v2.0.2` / TypeScript `v3.0.3`). * **Soft bias, never a filter.** The scaling factor stays in `0.3×–1.5×`. Decay can reorder candidates but never removes them; anything that surfaced before decay can still surface after. * **Reinforcement loop.** Every memory returned in a search has its access history updated, so frequently-used facts naturally float to the top over time. * **Public score still clamped to `[0, 1]`.** Existing API contract preserved; no client-side changes needed. * **v3 search only**, fully reversible. See [Memory Decay docs](/platform/features/memory-decay). **2026-04-14** Mem0 SDK v2.0.0 / v3.0.0 **New Memory Algorithm: State-of-the-Art Accuracy at \~3-4x Lower Cost** Ground-up rewrite of the memory pipeline with 20+ point benchmark improvements: * **LoCoMo:** 71.4 → **91.6** (+20) for multi-turn conversation recall. * **LongMemEval:** 67.8 → **93.4** (+26) for long-term memory across sessions. * **BEAM (1M tokens):** **64.1** on production-scale memory evaluation. * **Agent memories:** Assistant recall moves from 46% to **100%**. * **Temporal reasoning:** "Where did I live before SF?" improves from 51% to **93%**. * **Lower token use:** Retrieval stays under 7K tokens versus 25K+ for full-context approaches. * **ADD-only extraction:** Memories accumulate; nothing is overwritten or deleted. * **Hybrid retrieval:** Semantic search, BM25 keyword search, and entity boost are scored in parallel. * **Graph memory (built-in)**: entities extracted, embedded, and linked across memories, with no external graph store required Breaking changes: external graph stores removed from OSS (replaced by built-in graph memory), `search()` defaults changed, deprecated params removed. See [migration guide](/migration/oss-v2-to-v3). **2026-04-06** Mem0 Skill Graph **Mem0 Skill Graph: In-Context Documentation for AI Agents** AI coding agents in Claude Code, Cursor, and Codex can now access Mem0 knowledge directly in their workflow without leaving the editor. Three interconnected skills launched: * **mem0 Core Skill:** Python and TypeScript SDK reference, REST API patterns, and integration guides for LangChain, CrewAI, Autogen, and more. * **mem0-cli Skill:** Terminal command reference, configuration walkthroughs, and CI/CD recipes. * **mem0-vercel-ai-sdk Skill:** Vercel AI SDK provider API, memory-augmented generation patterns, and multi-provider setup. **2026-04-06** Mem0 CLI v0.2.2 **Official Mem0 CLI: Now on PyPI and npm** A full-featured command-line interface for Mem0, available in both Python and Node.js: * **Install:** `pip install mem0-cli` or `npm install -g @mem0/cli` * **Full command suite:** `add`, `search`, `list`, `get`, `update`, `delete`, `import`, `config`, `init`, `status`, `entity`, `event`. * **Interactive setup:** `mem0 init` supports email verification and direct API key entry. * **Runtime coverage:** Works with Mem0 Platform and self-hosted OSS modes. * **Automation support:** Use `--json` for CI/CD pipelines and agent workflows. * **Dual implementation:** Same commands and behavior across Python and Node.js. **2026-03-21** New Providers **Apache AGE, Turbopuffer, MiniMax, and pgvector for Node.js** Major expansion of the provider ecosystem: * **Apache AGE:** New graph store support, bringing the total to 4 graph store backends (Neo4j, Memgraph, Kuzu, Apache AGE). **Note:** All external graph store backends (Neo4j, Memgraph, Kuzu, Apache AGE) were subsequently removed in v2.0.0 (2026-04-14). Graph memory is now built-in entity linking with no external graph store required; see the [v2.0.0 entry above](#mem0-sdk-v2-0-0-v3-0-0). * **Turbopuffer:** New vector database provider for Python SDK. * **MiniMax:** New LLM provider with dedicated AWS Bedrock support. * **pgvector for Node.js:** PostgreSQL vector support added to the TypeScript OSS SDK. * **Reasoning models:** `reasoning_effort` parameter for OpenAI o1/o3-style models. **2026-03-14** Mem0 Platform Skill **Mem0 Platform Skill on skills.sh** First skill launch: a dedicated Mem0 skill providing platform API reference, quickstart patterns, and integration examples directly inside agent sessions. Available on [skills.sh](https://skills.sh) for any compatible AI coding agent. # Platform Source: https://docs.mem0.ai/changelog/platform Release notes for the Mem0 hosted platform: backend, dashboard, billing, and infrastructure changes. **2026-05-13** **New Features:** * **Memory:** Added Temporal Reasoning for Platform v3 to improve ranking for time-aware queries such as `last week`, `upcoming`, `right now`, and `as of ...` * **Search:** Added `reference_date` support to anchor relative temporal queries for tests, backfills, and reproducible demos **Improvements:** * **API:** Temporal reasoning preserves the normal client response shape for search and get-all results **2026-05-04** **New Features:** * **Memory Decay:** Per-project search-time ranking bias that boosts recently-used memories and gently dampens stale ones. Opt-in via `decay` on the project endpoint; off by default. The scaling factor stays in `0.3×–1.5×`, the public `score` remains clamped to `[0, 1]`, and the bias never filters a candidate out. See [Memory Decay docs](/platform/features/memory-decay). **2026-04-16** **Improvements:** * **UI:** Removed the legacy external-graph-store visualization tab, page, and its references from dashboard, sidebar, project settings, playground, and billing **2025-07-23** **Bug Fixes:** * **Memory:** Fixed ADD functionality **2025-07-19** **New Features:** * **UI:** Added Settings UI and latency display * **Performance:** Neo4j query optimization **Bug Fixes:** * **OpenMemory:** Fixed OMM raising unnecessary exceptions **2025-07-18** **Improvements:** * **UI:** Updated Event UI * **Performance:** Fixed N+1 query issue in semantic\_search\_v2 by optimizing MemorySerializer field selection **Bug Fixes:** * **Memory:** Fixed duplicate memory index sentry error **2025-07-17** **New Features:** * **UI:** New Settings Page * **Memory:** Duplicate memories entities support **Improvements:** * **Performance:** Optimized semantic search and get\_all APIs by eliminating N+1 queries **2025-07-16** **New Features:** * **Database:** Implemented read replica routing with enhanced logging and app-specific DB routing **Improvements:** * **Performance:** Improved query performance in search v2 and get all v2 endpoints **Bug Fixes:** * **API:** Fixed pagination for get all API **2025-07-12** **Bug Fixes:** * **Graph:** Fixed social graph bugs and connection issues **2025-07-11** **Improvements:** * **Rate Limiting:** New rate limit for V2 Search **Bug Fixes:** * **Slack:** Fixed Slack rate limit error with backend improvements **2025-07-10** **Improvements:** * **Performance:** * Changed connection pooling time to 5 minutes * Separated graph lambdas for better performance **2025-07-09** **Improvements:** * **Graph:** Graph Optimizations V2 and memory improvements **2025-07-08** **New Features:** * **Database:** Added read replica support for improved database performance * **UI:** Implemented UI changes for Users Page * **Feedback:** Enabled feedback functionality **Bug Fixes:** * **Serializer:** Fixed GET ALL Serializer **2025-07-05** **New Features:** * **UI:** User Page Revamp and New Users Page **2025-07-04** **New Features:** * **Users:** New Users Page implementation * **Tools:** Added script to backfill memory categories **Bug Fixes:** * **Filters:** Fixed Filters Get All functionality **2025-07-03** **Improvements:** * **Graph:** Graph Memory optimization * **Memory:** Fixed exact memories and semantically similar memories retrieval **2025-07-02** **Improvements:** * **Categorization:** Refactored categorization logic to utilize Gemini 2.5 Flash and improve message handling **2025-07-01** **Bug Fixes:** * **Memory:** Fixed old\_memory issue in Async memory addition lambda * **Events:** Fixed missing events **2025-06-30** **Improvements:** * **Graph:** Improvements to graph memory and added user to LTM-STM **2025-06-28** **New Features:** * **Graph:** Added support for SQS in graph memory addition * **Testing:** Added Locust load testing script and Grafana Dashboard **2025-06-27** **Improvements:** * **Rate Limiting:** Updated rate limiting for ADD API to 1000/min * **Performance:** Improved Neo4j performance **2025-06-26** **New Features:** * **Memory:** Edit Memory From Drawer functionality * **API:** Added Topic Suggestions API Endpoint **2025-06-25** **New Features:** * **Group Chat:** Group-Chat v2 with Actor-Aware Memories * **Memory:** Editable Metadata in Memories * **UI:** Memory Actions Badges **2025-06-19** **New Features:** * **Rate Limiting:** Implemented comprehensive rate limiting system **Improvements:** * **Performance:** Added performance indexes for memory stats query **Bug Fixes:** * **Search:** Fixed search events not respecting top-k parameter **2025-06-18** **New Features:** * **Memory Management:** Implemented OpenAI Batch API for Memory Cleaning with fallback * **Playground:** Added Claude 4 support on Playground **Improvements:** * **Memory:** Added ability to update memory metadata **2025-06-17** **New Features:** * **UI:** New Memories Page UI design **2025-06-16** **Improvements:** * **Infrastructure:** Migrated to Application Load Balancer (ALB) **2025-06-13** **Improvements:** * **Memory Management:** Enhanced Memory Management with Cosine Similarity Fallback **2025-06-11** **New Features:** * **OMM:** Added OMM Script and UI functionality **Improvements:** * **API:** Added filters validation to semantic\_search\_v2 endpoint **2025-06-09** **New Features:** * **Intercom:** Set Intercom events for ADD and SEARCH operations * **OpenMemory:** Added Posthog integration and feedback functionality * **MCP:** New JavaScript MCP Server with feedback support **Improvements:** * **Structured Data:** Enhanced structured data handling in memory management **2025-06-06** **New Features:** * **OAuth:** Added Mem0 OAuth integration * **OMM:** Added OMM-Mem0 sync for deleted memories **2025-06-05** **New Features:** * **Filters:** Implemented Wildcard Filters and refactored filter logic in V2 Views **2025-06-02** **New Features:** * **OpenMemory Cloud:** Added OpenMemory Cloud support * **Structured Data:** Added 'structured\_attributes' field to Memory model **2025-05-30** **New Features:** * **Projects:** Added version and enable\_graph to project views * **OpenMemory:** Added Postgres support for OpenMemory **2025-05-19** **Bug Fixes:** * **Core:** Fixed unicode error in user\_id, agent\_id, run\_id and app\_id # SDK & Tools Source: https://docs.mem0.ai/changelog/sdk Release notes for the Mem0 Python SDK, TypeScript SDK, Vercel AI SDK, CLI, and editor plugins. **Python** **2026-09-25** v2.2.1 **Bug Fixes:** * **Core:** `add()` (`Memory` and `AsyncMemory`) no longer reports records the vector store rejected as successful `ADD` events. Only records that were actually inserted are written to history, entity-linked, and returned. If none of the extracted memories could be inserted, `add()` now raises `VectorStoreError` instead of returning memories that were never stored ([#7066](https://github.com/mem0ai/mem0/pull/7066)) * **Core:** Restore the context-manager protocol on `Memory` (`with Memory() as m:`) and `AsyncMemory` (`async with AsyncMemory() as m:`), which closes the instance on exit ([#7354](https://github.com/mem0ai/mem0/pull/7354)) * **LLMs:** The AWS Bedrock Anthropic path now returns the first Converse content block that carries text instead of always reading `content[0]`. Claude reasoning models can emit a `reasoningContent` block before the text block, which previously made the call fail with a `KeyError` ([#6369](https://github.com/mem0ai/mem0/pull/6369)) * **Vector Stores:** Turbopuffer filters now apply every operator (`eq`, `ne`, `gt`, `gte`, `lt`, `lte`, `in`, `nin`). Only `gte` and `lte` were read before, so any other operator was silently dropped and the query returned unfiltered results. An unsupported operator now raises `ValueError` ([#6564](https://github.com/mem0ai/mem0/pull/6564)) * **Vector Stores:** Turbopuffer `search()` scores now respect `distance_metric`. With `euclidean_squared`, the unbounded squared distance maps to `1 / (1 + distance)` instead of `1 - distance`, which went negative and inverted ranking for any distance above 1 ([#6559](https://github.com/mem0ai/mem0/pull/6559)) * **Vector Stores:** S3 Vectors `search()` scores are now metric-aware. With `euclidean`, the distance maps to `1 / (1 + distance)` instead of `max(0, 1 - distance)`, which collapsed most scores to 0 ([#6547](https://github.com/mem0ai/mem0/pull/6547)) **2026-09-23** v2.2.0 **New Features:** * **Client:** Add User Profiles to `MemoryClient` and `AsyncMemoryClient`: `get_profile()`, `generate_profile()`, `get_profile_settings()`, `update_profile_settings()`, `sample_profiles()`, and `get_profile_job()`. A profile is a structured, always-current JSON summary of one user, shaped by a JSON Schema you configure per project and filled by an LLM from that user's memories. Generation is asynchronous. Every job POST carries an `Idempotency-Key`; to retry a lost request without starting a second job, pass the same `idempotency_key` on each attempt ([#7340](https://github.com/mem0ai/mem0/pull/7340)) **Bug Fixes:** * **Vector Stores:** Guard against `None` timestamps in the Valkey vector store's `insert()` and `update()` paths. `created_at` and `updated_at` fields that were present in the payload but set to `None` previously passed the `"created_at" not in payload` / `"updated_at" in payload` checks and raised `TypeError` when `datetime.fromisoformat()` received `None`. Both paths now use `.get()` with a truthiness check so `None` values fall through to the default, matching the Redis provider's behavior ([#6993](https://github.com/mem0ai/mem0/pull/6993)) **2026-09-18** v2.1.0 **Improvements:** * **Client:** Requests now carry three surface-identity headers so the platform can tell which product made a call. `X-Mem0-Source` names the surface and `X-Application` the host app it runs inside, both set-once so a wrapper that already declared its identity keeps it. `X-Mem0-Client` is append-only and carries `name/version` per layer, outermost first, so a plugin calling this SDK reports the whole chain rather than only the last speaker. `MEM0_SOURCE`, `MEM0_APPLICATION` and `MEM0_CLIENT_STACK` set them from the environment for wrappers that cannot pass options ([#7326](https://github.com/mem0ai/mem0/pull/7326)) * **Client:** The client stack is bounded by dropping whole entries rather than slicing characters, and this SDK's own entry is the reserved one. Truncating the joined string could sever an identifier mid-name and the platform parsed the fragment as a real client ([#7326](https://github.com/mem0ai/mem0/pull/7326)) **2026-09-02** v2.0.20 **Improvements:** * **OSS notices:** Notice configuration now comes from a static, cacheable repository file with a bundled disabled fallback and deterministic rollout assignment, instead of calling PostHog's feature-flag evaluation API. This keeps notices fail-safe when the remote config is unavailable and removes the PostHog feature-flag request from notice evaluation ([#7185](https://github.com/mem0ai/mem0/pull/7185)) * **Vector Stores:** `RedisDBConfig` now uses Pydantic's native `extra="forbid"` handling for unknown fields instead of a custom model validator, preserving strict validation while returning standard Pydantic errors ([#7089](https://github.com/mem0ai/mem0/pull/7089)) **2026-08-24** v2.0.19 **Bug Fixes:** * **Embeddings:** `HuggingFaceEmbedding` now falls back to the `HUGGINGFACE_API_KEY` env var, then a placeholder key, when `huggingface_base_url` is set and no `api_key` is configured. The OpenAI-compatible client used to talk to TEI endpoints raises at construction when no key resolves at all, so a TEI deployment that doesn't require a real key previously failed to initialize ([#6947](https://github.com/mem0ai/mem0/pull/6947)) * **Core:** `remove_code_blocks()` now accepts list-shaped content (a sequence of `{"text": ...}` blocks, as some agent frameworks pass) by joining each block's text before stripping code fences, instead of raising `AttributeError` from calling `.strip()` on a list ([#6947](https://github.com/mem0ai/mem0/pull/6947)) * **Core:** `create_procedural_memory()` (`Memory` and `AsyncMemory`) now raises a clear `ValueError` when the LLM returns no content for the summary, instead of continuing with empty content that surfaced as a confusing error further down the call ([#6947](https://github.com/mem0ai/mem0/pull/6947)) * **Proxy:** `mem0.proxy` no longer auto-installs `litellm` via a `pip install` subprocess when the import fails; it now raises `ImportError` with instructions to install it yourself. The auto-install could hang or fail silently in restricted environments and ran an unreviewed install on the caller's behalf ([#6947](https://github.com/mem0ai/mem0/pull/6947)) * **Client:** `get_all()` (sync and async) now sends `page` and `page_size` as independent query params instead of requiring both to be set before either was sent. Passing only `page_size` without `page` previously had it silently dropped, so results came back at the server's default page size ([#6900](https://github.com/mem0ai/mem0/pull/6900)) * **LLMs:** Add `provider_override` to `AWSBedrockConfig`, an explicit provider name (for example `"anthropic"`) for when `model` is an application inference profile ARN whose opaque ID has no provider substring for `extract_provider()` to detect. Without it, those ARNs raised `ValueError: Unable to determine provider` ([#6899](https://github.com/mem0ai/mem0/pull/6899)) * **LLMs:** `VllmConfig` now falls back to the `VLLM_BASE_URL` env var when `vllm_base_url` isn't passed explicitly. The default was filled in before the env var was ever checked, so `VLLM_BASE_URL` was silently ignored ([#6897](https://github.com/mem0ai/mem0/pull/6897)) **2026-08-11** v2.0.18 **Bug Fixes:** * **Core:** Percent-escape `%`, `&`, and `=` in `user_id`, `agent_id`, and `run_id` when building the session scope key for the recent-conversation buffer, so the key stays unambiguous for ids containing those characters. Ordinary ids keep their existing key; an id already containing `%`, `&`, or `=` maps to a new key, so its buffer starts empty once and refills on the next `add()`. Stored memories are unaffected ([#6892](https://github.com/mem0ai/mem0/pull/6892)) * **Vector Stores:** Raise `ValueError` when a PGVector `in`/`nin` filter value is not a list. A string value was previously iterated character by character into the generated `= ANY(...)` array (so `{"user_id": {"in": "alice"}}` matched `a`, `l`, `i`, `c`, `e`), and a non-iterable value raised a bare `TypeError` from deep inside filter building ([#6879](https://github.com/mem0ai/mem0/pull/6879)) * **Vector Stores:** Reject `index_accuracy=0` in the Oracle AI Vector Search config. The range check sat behind a truthiness test, so `0` skipped validation entirely and was passed through to `WITH TARGET ACCURACY 0` instead of raising ([#6848](https://github.com/mem0ai/mem0/pull/6848)) * **Vector Stores:** Close the Oracle connection or pool that Mem0 opened when initialization fails. A client version check, a database version check, or a `create_col()` error previously propagated with the connection still open, leaking it for the life of the process. A caller-supplied `client` is left untouched ([#6839](https://github.com/mem0ai/mem0/pull/6839)) **2026-08-05** v2.0.17 **New Features:** * **Client:** Add `agent_custom_instructions` to `project.update()`/`update_project()` (sync and async) and to the `ProjectUpdateOptions` and `AddMemoryOptions` typed models. It sets a second extraction instruction set that applies only to agent-scoped memories: an add passing `agent_id` without `user_id` uses it, one passing both splits by attribution, and while it is unset `custom_instructions` continues to apply to every memory ([#6809](https://github.com/mem0ai/mem0/pull/6809)) **2026-08-04** v2.0.16 **New Features:** * **Client:** Add `reference_date`, `latest_only`, and `keyword_search` to `SearchMemoryOptions`, and `latest_only` to `GetAllMemoryOptions`, keeping the Python client's typed options in sync with the Platform API and the CLIs ([#6696](https://github.com/mem0ai/mem0/pull/6696)) **Bug Fixes:** * **Core:** Stop `add()` metadata from setting a memory's identity scope. `_build_filters_and_metadata()` now strips `user_id`, `agent_id`, `run_id`, and `actor_id` from caller-supplied `metadata` before building the creation template, so metadata can no longer place a memory into a scope that was never passed through the entity params ([#6656](https://github.com/mem0ai/mem0/pull/6656)) * **Vector Stores:** Validate Upstash filter keys and values in `search()`, `keyword_search()`, and `list()`. Filter keys must match a safe identifier pattern, values must be `str`/`int`/`float`/`bool`, and string values containing a double quote or backslash are now rejected instead of being interpolated unescaped into the generated query string ([#5981](https://github.com/mem0ai/mem0/pull/5981)) * **Embeddings:** `FastEmbedEmbedding.embed()` now converts its result with `.tolist()` before returning, so callers get a plain `List[float]` instead of a numpy array ([#6770](https://github.com/mem0ai/mem0/pull/6770)) * **Embeddings:** `HuggingFaceEmbedding` now passes `api_key` to the OpenAI-compatible client when `huggingface_base_url` is set. The configured key was previously dropped, so the client fell back to `OPENAI_API_KEY` from the environment or raised `OpenAIError` at construction when that was unset ([#6770](https://github.com/mem0ai/mem0/pull/6770)) * **Embeddings:** Replace Ollama's interactive `pip install` prompt on import with a plain `ImportError`. Importing `mem0.embeddings.ollama` without the `ollama` package previously blocked on stdin and then called `sys.exit(1)`, killing the host process instead of raising ([#6770](https://github.com/mem0ai/mem0/pull/6770)) * **Core:** `remove_code_blocks()` now returns an empty string for `None` input instead of raising `AttributeError` ([#6770](https://github.com/mem0ai/mem0/pull/6770)) * **Core:** `parse_vision_messages()` now chains the original exception (`raise ... from e`) when an image download fails, so the root cause is preserved in the traceback ([#6770](https://github.com/mem0ai/mem0/pull/6770)) * **Core:** `process_telemetry_filters(None)` now returns `([], {})`, matching the two-value tuple every caller unpacks, instead of `{}` ([#6770](https://github.com/mem0ai/mem0/pull/6770)) * **Core:** `LlmFactory.create()` no longer mutates the caller's config dict in place via `.update(kwargs)`; the merge now builds a new dict ([#6770](https://github.com/mem0ai/mem0/pull/6770)) * **Rerankers:** The Cohere, HuggingFace, SentenceTransformer, and Zero Entropy rerankers' failure-fallback path no longer mutates the caller's document dicts in place when stamping `rerank_score`; it now falls back on copies ([#6770](https://github.com/mem0ai/mem0/pull/6770)) * **Vector Stores:** Remove `logging.basicConfig()` calls from the MongoDB and Vertex AI Vector Search providers, so selecting either provider no longer reconfigures the host application's root logger as a side effect ([#6770](https://github.com/mem0ai/mem0/pull/6770)) **2026-08-01** v2.0.15 **Bug Fixes:** * **Core:** `delete_all()` now paginates through the vector store in batches of 1000 instead of listing once, so accounts with more memories than a single page (most vector stores default to \~100) had the remainder silently left behind ([#6636](https://github.com/mem0ai/mem0/pull/6636)) * **Vector Stores:** Cap Supabase `search()`/`list()` `top_k` at the `vecs` query limit of 1000 instead of erroring, and fix a `col_info()` crash by reading collection attributes directly instead of calling the removed `describe()` method ([#6695](https://github.com/mem0ai/mem0/pull/6695)) * **Vector Stores:** Set `size` on Elasticsearch KNN search queries, so results respect `top_k` instead of being capped at Elasticsearch's default of 10 hits ([#5910](https://github.com/mem0ai/mem0/pull/5910)) **Changes:** * **Rerankers:** `LLMReranker`'s default model is now `gpt-5-mini` (was `gpt-4o-mini`) ([#6703](https://github.com/mem0ai/mem0/pull/6703)) **2026-07-25** v2.0.14 **New Features:** * **Vector Stores:** Add an Oracle AI Vector Search provider (`oracledb`) with connection pooling, `HNSW`/`IVF` indexes, JSON metadata filtering, and six selectable distance metrics ([#5358](https://github.com/mem0ai/mem0/pull/5358)) **Bug Fixes:** * **Vector Stores:** Translate a `"*"` filter value in OpenSearch into an `exists` query for every key, not just identity keys. It was previously ignored or matched literally against the string `"*"`, so a wildcard filter returned nothing ([#6522](https://github.com/mem0ai/mem0/pull/6522)) * **Vector Stores:** Re-raise errors from OpenSearch `search()` instead of returning `[]`, so a transport, auth, or index misconfiguration surfaces instead of looking like zero matches. `keyword_search()` still degrades on failure, since it is a best-effort BM25 signal ([#6519](https://github.com/mem0ai/mem0/pull/6519)) * **Vector Stores:** Guard the `text` field in Milvus `update()` behind the `_has_bm25_schema` check, matching `insert()`, so updating a memory in a collection without the BM25 `text`/`sparse` schema no longer fails ([#5705](https://github.com/mem0ai/mem0/pull/5705)) **2026-07-22** v2.0.13 **Bug Fixes:** * **Vector Stores:** Fix `reset()` silently leaving stale vectors behind on local (on-disk) Qdrant when the old collection directory could not be removed, for example an open file handle on Windows or NFS ([#6412](https://github.com/mem0ai/mem0/pull/6412)) * **Core:** Stop `update()` metadata from overwriting or injecting `user_id`, `agent_id`, `run_id`, or `actor_id`. These identity fields are immutable after creation, so passing them in `metadata` can no longer move a memory into a different tenant's scope ([#6278](https://github.com/mem0ai/mem0/pull/6278)) * **Vector Stores:** Scope Pinecone `delete_col()`/`reset()` to the configured namespace instead of deleting the whole index, so resetting a namespaced Pinecone store no longer wipes out the other namespaces sharing that index ([#6287](https://github.com/mem0ai/mem0/pull/6287)) * **Vector Stores:** Convert Baidu Mochow's raw L2 distance into a similarity score in `search()` (`1 / (1 + distance)`), so closer matches rank higher instead of lower, matching the Milvus provider and the rest of the `VectorStoreBase` contract ([#6435](https://github.com/mem0ai/mem0/pull/6435)) * **LLMs:** Read `OPENAI_BASE_URL` (was `OPENAI_API_BASE`) in `OpenAIStructuredLLM`, matching the official OpenAI SDK's environment variable and the rest of the OpenAI-compatible providers ([#6322](https://github.com/mem0ai/mem0/pull/6322)) **Improvements:** * **LLMs:** Remove a dead, no-op `api_key` attribute check from `LLMBase.__init__` ([#6460](https://github.com/mem0ai/mem0/pull/6460)) **Changes:** * **Client:** Remove the `retrieval_criteria` parameter from `MemoryClient.update_project()`/`AsyncMemoryClient.update_project()` and `Project.update()`/`AsyncProject.update()`. It was accepted and forwarded but never affected retrieval, so removing it is not a behavior change ([#6313](https://github.com/mem0ai/mem0/pull/6313)) **2026-07-13** v2.0.12 **New Features:** * **Memory (OSS):** Accept `text` in `Memory.update()` and `AsyncMemory.update()`. `data` still works but is now deprecated, so prefer `text` in new code ([#6044](https://github.com/mem0ai/mem0/pull/6044)) **Bug Fixes:** * **Core:** Coerce non-string entity IDs (`user_id`, `agent_id`, `run_id`) instead of crashing on `.strip()`, so passing an integer ID no longer raises `AttributeError` ([#6206](https://github.com/mem0ai/mem0/pull/6206)) * **Core:** Stop requiring `langchain-core` for the default async procedural memory path. The optional dependency is now only imported when you pass a custom LangChain LLM, matching the sync behavior ([#6209](https://github.com/mem0ai/mem0/pull/6209)) * **Client:** Encode dynamic URL path segments so IDs containing special characters no longer produce malformed requests ([#5963](https://github.com/mem0ai/mem0/pull/5963)) * **LLMs:** Skip `temperature` and `top_p` for newer Anthropic models that reject sampling parameters. Detection is automatic per model family and version, and the new `enable_sampling_parameters` config flag overrides it ([#6211](https://github.com/mem0ai/mem0/pull/6211)) * **Vector Stores:** Stop writing internal `OutputData` model fields as properties on Weaviate `update()` ([#6149](https://github.com/mem0ai/mem0/pull/6149)) * **Vector Stores:** Improve wildcard search handling in Milvus ([#6187](https://github.com/mem0ai/mem0/pull/6187)) * **Vector Stores:** Keep env-resolved Upstash Vector credentials after config validation. An env-var-only config previously passed validation and then failed to build ([#5811](https://github.com/mem0ai/mem0/pull/5811)) * **Vector Stores:** Restore the previous payload when a Neptune Analytics vector upsert fails inside `update()`, so a partial write can no longer leave the payload and embedding out of sync ([#5824](https://github.com/mem0ai/mem0/pull/5824)) **Changes:** * **LLMs:** The Together default model is now `MiniMaxAI/MiniMax-M3` (was `mistralai/Mixtral-8x7B-Instruct-v0.1`) ([#6049](https://github.com/mem0ai/mem0/pull/6049)) * **LLMs:** The xAI default model is now `grok-4.3` (was `grok-2-latest`) ([#6115](https://github.com/mem0ai/mem0/pull/6115)) * **Embeddings:** The Together default embedding model is now `intfloat/multilingual-e5-large-instruct` at 1024 dimensions (was `togethercomputer/m2-bert-80M-8k-retrieval` at 768). If you use the Together embedder without pinning `model`, existing vectors were written at the old dimension: either re-embed them, or pin `model` and `embedding_dims` to the old values ([#5989](https://github.com/mem0ai/mem0/pull/5989)) * **Rerankers:** The Cohere default rerank model is now `rerank-v3.5` (was `rerank-english-v3.0`) ([#6055](https://github.com/mem0ai/mem0/pull/6055)) **Security:** * **Vector Stores:** Fix SQL and Cypher injection vulnerabilities in the PGVector, Azure MySQL, and Neptune providers ([#4878](https://github.com/mem0ai/mem0/pull/4878)) * **Vector Stores:** Validate Elasticsearch filter keys and values to prevent term query injection ([#5980](https://github.com/mem0ai/mem0/pull/5980)) * **Dependencies:** Require `transformers>=5.3.0` to remediate GHSA-29pf-2h5f-8g72 (CVE-2026-4372) ([#6110](https://github.com/mem0ai/mem0/pull/6110)) **2026-07-01** v2.0.11 **Bug Fixes:** * **Embeddings:** Guard against an `embed_batch` count mismatch in the OpenAI and Azure OpenAI embedders ([#5966](https://github.com/mem0ai/mem0/pull/5966)) * **Memory:** Re-raise LLM extraction failures instead of silently returning `[]` ([#5878](https://github.com/mem0ai/mem0/pull/5878)) * **Vector Stores:** Normalize vectors for the cosine distance strategy in FAISS ([#5960](https://github.com/mem0ai/mem0/pull/5960)) **Security:** * **Vector Stores:** Validate OpenSearch filter values to prevent term query injection ([#5986](https://github.com/mem0ai/mem0/pull/5986)) * **Vector Stores:** Validate value types and escape quotes in Azure AI Search OData filters ([#5983](https://github.com/mem0ai/mem0/pull/5983)) * **Vector Stores:** Validate Databricks catalog/schema/table identifiers to prevent SQL injection ([#5988](https://github.com/mem0ai/mem0/pull/5988)) * **Graph:** Escape Neptune filter values in openCypher queries to prevent injection ([#5982](https://github.com/mem0ai/mem0/pull/5982)) **2026-06-27** v2.0.10 **New Features:** * **Client:** Expose `expiration_date` on `MemoryClient.update()` and `AsyncMemoryClient.update()`: callers can now set or clear a memory's expiration date; `None` is preserved and forwarded to the API ([#5874](https://github.com/mem0ai/mem0/pull/5874)) **Bug Fixes:** * **Memory (OSS):** Apply `remove_code_blocks()` to the LangChain path in async `_create_procedural_memory` so code fences are stripped consistently ([#5711](https://github.com/mem0ai/mem0/pull/5711)) * **Rerankers:** Score HuggingFace cross-encoder results with per-document sigmoid instead of set-relative min-max, preventing a single low-score document from collapsing all relevance scores to zero ([#5715](https://github.com/mem0ai/mem0/pull/5715)) * **Core:** Validate and trim entity IDs (`user_id`, `agent_id`, `run_id`) in `delete_all()` for both sync and async `Memory` ([#5735](https://github.com/mem0ai/mem0/pull/5735)) * **Vector Stores:** Use `.get()` for `hash` and `created_at` in the Redis `insert()` and `update()` paths so entity payloads that omit those fields no longer raise `KeyError` ([#5709](https://github.com/mem0ai/mem0/pull/5709)) * **Memory:** Fix scale-threshold notices not firing for Redis and search-engine backends by resolving `col_info()` signature differences and adding `num_docs` to the count-extraction lookup ([#5687](https://github.com/mem0ai/mem0/pull/5687)) * **Vector Stores:** Escape special characters in Valkey FT.SEARCH tag filter values to prevent wildcard and operator injection through tenant-isolation filters ([#5750](https://github.com/mem0ai/mem0/pull/5750)) **2026-06-24** v2.0.9 **Bug Fixes:** * **Memory (OSS):** Improve entity extraction precision by avoiding sentence-start common noun noise, preserving useful topic phrases, and exact-deduplicating entity links before semantic matching ([#5829](https://github.com/mem0ai/mem0/pull/5829)) **2026-06-24** v2.0.8 **New Features:** * **Embeddings:** Add native `embed_batch` to five embedders for batched embedding requests: LM Studio, Together, HuggingFace, Vertex AI, and Google GenAI ([#5609](https://github.com/mem0ai/mem0/pull/5609)) **Bug Fixes:** * **Core:** Guard against malformed `image_url` entries in `parse_vision_messages` to prevent crashes ([#5631](https://github.com/mem0ai/mem0/pull/5631)) * **Core:** Return `attributed_to` from `get()`, `get_all()`, and `search()` ([#5629](https://github.com/mem0ai/mem0/pull/5629)) * **Core:** Fix `reset()` only dropping the history table and leaving stale messages behind ([#5541](https://github.com/mem0ai/mem0/pull/5541)) * **Core:** Guard against an entity `embed_batch` count mismatch in the v3 add pipeline ([#5604](https://github.com/mem0ai/mem0/pull/5604)) * **Core:** Fix an async `delete_all` race condition that corrupted the entity store's `linked_memory_ids` ([#5553](https://github.com/mem0ai/mem0/pull/5553)) * **LLMs:** Skip the JSON `response_format` for Groq compound models that reject it ([#5513](https://github.com/mem0ai/mem0/pull/5513)) * **LLMs:** Preserve reasoning fields during base-to-provider config conversion ([#5638](https://github.com/mem0ai/mem0/pull/5638)) * **LLMs:** Pass the configured `anthropic_base_url` to the Anthropic client ([#5626](https://github.com/mem0ai/mem0/pull/5626)) * **LLMs:** Stop the Azure provider from mutating and corrupting caller messages during content rewrite ([#5731](https://github.com/mem0ai/mem0/pull/5731)) * **LLMs & Embeddings:** Repair HTTP proxy support for `httpx>=0.28` and preserve `proxies` in `LlmFactory` ([#5447](https://github.com/mem0ai/mem0/pull/5447)) * **Embeddings:** Forward `embedding_dims` to Titan V2 in the AWS Bedrock embedder ([#5671](https://github.com/mem0ai/mem0/pull/5671)) * **Rerankers:** Log reranking failures instead of swallowing them silently ([#5717](https://github.com/mem0ai/mem0/pull/5717)) * **Rerankers:** Clamp out-of-range LLM scores instead of mis-parsing them ([#5635](https://github.com/mem0ai/mem0/pull/5635)) * **Rerankers:** Export all five rerankers from the package root ([#5636](https://github.com/mem0ai/mem0/pull/5636)) * **Vector Stores:** Point the FastEmbed-missing warning at `mem0ai[extras]` ([#5622](https://github.com/mem0ai/mem0/pull/5622)) * **Vector Stores:** Preserve empty Azure AI Search update values ([#5524](https://github.com/mem0ai/mem0/pull/5524)) * **Vector Stores:** Add an `auto_refresh` option for OpenSearch Serverless compatibility ([#3893](https://github.com/mem0ai/mem0/pull/3893)) * **Vector Stores:** Wrap a scalar `vector_id` in a list for Chroma `delete()` ([#5703](https://github.com/mem0ai/mem0/pull/5703)) * **Vector Stores:** Wrap Chroma `update()` ids, embeddings, and metadatas in lists ([#5757](https://github.com/mem0ai/mem0/pull/5757)) * **Vector Stores:** Wrap a scalar `vector_id` in a list for Milvus `delete()` ([#5704](https://github.com/mem0ai/mem0/pull/5704)) * **Vector Stores:** Map all comparison operators in the Pinecone `_create_filter()` ([#5707](https://github.com/mem0ai/mem0/pull/5707)) * **Vector Stores:** Return `None` instead of `{}` from Chroma `_generate_where_clause` for empty filters ([#5713](https://github.com/mem0ai/mem0/pull/5713)) * **Vector Stores:** Return `[[]]` from the OpenSearch `list()` error path to honor the `list()` contract ([#5727](https://github.com/mem0ai/mem0/pull/5727)) * **Vector Stores:** Return `[[]]` from the Pinecone `list()` error path instead of a dict ([#5706](https://github.com/mem0ai/mem0/pull/5706)) * **Vector Stores:** Return `[[]]` for an uninitialized FAISS index to honor the `list()` contract ([#5725](https://github.com/mem0ai/mem0/pull/5725)) * **Vector Stores:** Wrap the MongoDB `list()` return in an outer list to match the interface contract ([#5729](https://github.com/mem0ai/mem0/pull/5729)) * **Vector Stores:** Deep-copy Redis `DEFAULT_FIELDS` so instances keep distinct dims ([#5633](https://github.com/mem0ai/mem0/pull/5633)) * **Vector Stores:** Pass the required `vectors` arg in Vertex AI `list()` and similarity search ([#5627](https://github.com/mem0ai/mem0/pull/5627)) * **Vector Stores:** Return `None` from Redis `get()` for missing IDs ([#5625](https://github.com/mem0ai/mem0/pull/5625)) * **Vector Stores:** Drop a stray `print` in Weaviate `list_cols` ([#5637](https://github.com/mem0ai/mem0/pull/5637)) * **Graph:** Keep distinct entities that share a substring prefix ([#5630](https://github.com/mem0ai/mem0/pull/5630)) * **Client:** Check the HTTP status before parsing the ping response in `_validate_api_key` ([#5639](https://github.com/mem0ai/mem0/pull/5639)) * **Server:** Fetch filtered dashboard memories beyond the default page ([#5753](https://github.com/mem0ai/mem0/pull/5753)) * **Server:** Return 404/400 instead of 502 for not-found and invalid input ([#5634](https://github.com/mem0ai/mem0/pull/5634)) * **Server:** Return 404 instead of 500 for a malformed API key id on revoke ([#5640](https://github.com/mem0ai/mem0/pull/5640)) * **Server:** Use `127.0.0.1` in the dashboard healthcheck to avoid IPv6 localhost resolution ([#5612](https://github.com/mem0ai/mem0/pull/5612)) **Improvements:** * **Vector Stores:** Batch BM25 sparse encoding in Qdrant insert ([#5592](https://github.com/mem0ai/mem0/pull/5592)) **Security:** * **Vector Stores:** Sanitize Milvus and Baidu filter values to prevent expression injection ([#5746](https://github.com/mem0ai/mem0/pull/5746)) * **Vector Stores:** Reject dict filter values in MongoDB to prevent NoSQL operator injection ([#5748](https://github.com/mem0ai/mem0/pull/5748)) **2026-06-17** v2.0.7 **New Features:** * **LLMs:** Add Gemini via Vertex AI as LLM provider ([#4030](https://github.com/mem0ai/mem0/pull/4030)) * **Embeddings:** Add native `embed_batch` to `OllamaEmbedding` for batched embedding requests ([#5415](https://github.com/mem0ai/mem0/pull/5415)) **Bug Fixes:** * **Core:** Fix `api_error_handler` silently dropping return values from async methods ([#5540](https://github.com/mem0ai/mem0/pull/5540)) * **Core:** Fix `AsyncMemory.reset()` not resetting the entity store ([#5535](https://github.com/mem0ai/mem0/pull/5535)) * **Core:** Fix `async delete_all` aborting on first error, leaving partial deletion ([#5529](https://github.com/mem0ai/mem0/pull/5529)) * **Core:** Skip messages without a `content` key in message parsers to prevent `KeyError` crashes ([#5575](https://github.com/mem0ai/mem0/pull/5575)) * **Core:** Preserve custom metadata fields during memory update ([#5480](https://github.com/mem0ai/mem0/pull/5480)) * **LLMs:** Fix Anthropic `tool_choice` format and tool response parsing ([#5537](https://github.com/mem0ai/mem0/pull/5537)) * **LLMs:** Fix Ollama `json` format mutating the caller's messages list in-place ([#5539](https://github.com/mem0ai/mem0/pull/5539)) * **LLMs:** Omit `None` config values from Gemini `GenerateContentConfig` to prevent validation errors ([#5528](https://github.com/mem0ai/mem0/pull/5528)) * **LLMs:** Honor reasoning-model params in `AzureOpenAIStructuredLLM` ([#5548](https://github.com/mem0ai/mem0/pull/5548)) * **LLMs:** Honor reasoning-model params in `OpenAIStructuredLLM` ([#5458](https://github.com/mem0ai/mem0/pull/5458)) * **LLMs:** Send `max_completion_tokens` for the GPT-5 family across all providers ([#5547](https://github.com/mem0ai/mem0/pull/5547)) * **LLMs:** Accept and forward `**kwargs` in Together, LangChain, and Sarvam providers ([#5556](https://github.com/mem0ai/mem0/pull/5556)) * **LLMs:** Fix Bedrock AI21 response parse default using `dict` literal instead of `set` ([#5527](https://github.com/mem0ai/mem0/pull/5527)) * **LLMs:** Fix LiteLLM function-calling check blocking all calls on non-tool models ([#5536](https://github.com/mem0ai/mem0/pull/5536)) * **LLMs:** Fix HuggingFace provider using `self.config` instead of raw `config` parameter ([#5538](https://github.com/mem0ai/mem0/pull/5538)) * **Embeddings:** Honor `aws_session_token` in AWS Bedrock embeddings ([#5566](https://github.com/mem0ai/mem0/pull/5566)) * **Rerankers:** Respect `config.top_k` in Cohere and ZeroEntropy fallback paths ([#5560](https://github.com/mem0ai/mem0/pull/5560)) * **Vector Stores:** Fix FAISS filtered search dropping over-fetched candidates before filtering ([#5453](https://github.com/mem0ai/mem0/pull/5453)) * **Vector Stores:** Fix Weaviate `reset()` crashing with missing `vector_size` argument ([#5531](https://github.com/mem0ai/mem0/pull/5531)) * **Vector Stores:** Pass embedding dims in Weaviate `reset()` to avoid re-init crash ([#5570](https://github.com/mem0ai/mem0/pull/5570)) * **Vector Stores:** Fix MongoDB `reset()` passing wrong argument to `create_col()` ([#5532](https://github.com/mem0ai/mem0/pull/5532)) * **Vector Stores:** Fix Pinecone hybrid search crashing when `filters` is `None` ([#5533](https://github.com/mem0ai/mem0/pull/5533)) * **Vector Stores:** Fix Redis crashing on empty or `None` filters in `search()` and `list()` ([#5446](https://github.com/mem0ai/mem0/pull/5446)) * **Vector Stores:** Return `None` from `get()` for missing IDs in Milvus, Weaviate, and Supabase ([#5562](https://github.com/mem0ai/mem0/pull/5562)) * **Vector Stores:** Return `None` from ChromaDB `get()` for missing IDs ([#5561](https://github.com/mem0ai/mem0/pull/5561)) **2026-06-13** v2.0.6 **New Features:** * **Memory:** Add a contextual OSS-to-Platform notices system that surfaces occasional, situation-aware messages (first run, scale/performance thresholds, slow queries, and when temporal/decay features are relevant) pointing to the corresponding Mem0 Platform capabilities; disable via `MEM0_TELEMETRY=false` ([#5494](https://github.com/mem0ai/mem0/pull/5494)) **Bug Fixes:** * **Memory:** Prevent a crash in `parse_vision_messages` when vision support is disabled ([#5487](https://github.com/mem0ai/mem0/pull/5487)) * **Vector Stores:** Expose the `https` option on the Qdrant vector store configuration so TLS endpoints can be targeted explicitly ([#5380](https://github.com/mem0ai/mem0/pull/5380)) * **Vector Stores:** Use valid S3 Vectors entity index names, fixing index operations that failed on invalid names ([#5416](https://github.com/mem0ai/mem0/pull/5416)) * **Vector Stores:** Fix `search()` crashing with a `TypeError` in the LangChain vector store when a result score is `None` ([#5072](https://github.com/mem0ai/mem0/pull/5072)) * **Vector Stores:** Use `is not None` instead of a truthiness check for vector/payload in the PGVector `update()` path, so valid empty/zero values are no longer skipped ([#5488](https://github.com/mem0ai/mem0/pull/5488)) * **Vector Stores:** Index the Valkey `memory` field as `TEXT` rather than `TAG` so full-text search behaves correctly ([#5443](https://github.com/mem0ai/mem0/pull/5443)) * **Vector Stores:** Implement `$not` filter support in the ChromaDB vector store ([#5485](https://github.com/mem0ai/mem0/pull/5485)) **2026-06-10** v2.0.5 **New Features:** * **Memory:** Warn at init time when hybrid/BM25 search silently degrades to semantic-only because the configured vector store does not implement `keyword_search`. Affected stores: Chroma, FAISS, Cassandra, LangChain, Neptune Analytics, S3 Vectors, Supabase, TurboPuffer, Valkey ([#5444](https://github.com/mem0ai/mem0/pull/5444)) * **Memory:** Add opt-in `explain=True` parameter to `Memory.search()` and `AsyncMemory.search()`. When enabled, each result includes a `score_details` dict with `semantic_score`, `bm25_score`, `entity_boost`, `raw_score`, `max_possible_score`, `final_score`, and `threshold` so callers can understand and tune retrieval ranking ([#5102](https://github.com/mem0ai/mem0/pull/5102)) **Bug Fixes:** * **Vector Stores:** Normalize similarity scores to `[0, 1]` (higher = better) consistently across all backends. 11 adapters previously returned raw distance metrics (lower = better): FAISS, Chroma, Milvus, Redis, Cassandra, PGVector, S3 Vectors, Supabase, Valkey, Azure MySQL, and Vertex AI Vector Search: causing incorrect ranking in multi-store setups ([#5391](https://github.com/mem0ai/mem0/pull/5391)) * **Memory:** Parallelize entity boost searches in `Memory.search()` and `AsyncMemory.search()`. Previously up to 8 entities were embedded and queried sequentially (16 serial round-trips with remote embedders); all entity lookups now run concurrently, eliminating multi-second latency on entity-rich queries ([#5377](https://github.com/mem0ai/mem0/pull/5377)) * **Memory:** Reject empty or whitespace-only queries in `Memory.search()`, `AsyncMemory.search()`, `MemoryClient.search()`, and `AsyncMemoryClient.search()` before any embedding or API call is made. Also strips leading/trailing whitespace from valid queries ([#5258](https://github.com/mem0ai/mem0/pull/5258)) * **LLMs:** Add `is_reasoning_model: Optional[bool]` override to `BaseLlmConfig` (surfaced on `OpenAILlmConfig` and `AzureOpenAILlmConfig`). Fixes silent zero-extraction when using Azure deployments with versioned `gpt-5.x` names that the automatic name-based heuristic cannot recognize ([#5327](https://github.com/mem0ai/mem0/pull/5327)) * **LLMs:** Fix xAI LLM provider: add `XAIConfig` with `xai_base_url`, forward `tools`/`tool_choice` in `generate_response()`, and parse `tool_calls` in the response. Previously the provider raised `AttributeError` at init and silently dropped tool results ([#5190](https://github.com/mem0ai/mem0/pull/5190)) * **Vector Stores:** Fix PGVector `ConnectionPool` hang in Docker Compose environments where the app container starts before Postgres is DNS-resolvable: switched to `open=False` to avoid blocking constructor or silent zombie pool ([#5155](https://github.com/mem0ai/mem0/pull/5155)) * **Vector Stores:** Fix PGVector `sslmode` handling for PostgreSQL URIs: the `sslmode` query parameter is now correctly extracted and forwarded when building the async connection pool ([#5308](https://github.com/mem0ai/mem0/pull/5308)) * **Vector Stores:** Fix S3 Vectors `list()` not applying metadata filters: filtering is now done client-side after fetching, with pagination preserved and `top_k` applied after filtering to prevent pre-truncation of matching rows ([#5018](https://github.com/mem0ai/mem0/pull/5018)) * **Vector Stores:** Fix Upstash Vector `search()` routing all queries to the default namespace: `namespace` is now passed as a top-level keyword argument to `query_many()` instead of inside the per-query dict where it was silently ignored ([#5202](https://github.com/mem0ai/mem0/pull/5202)) * **Core:** Replace mutable default arguments with `None` sentinels in embedder configs and the proxy module, preventing cross-request state contamination ([#5302](https://github.com/mem0ai/mem0/pull/5302)) **2026-05-27** v2.0.4 **New Features:** * **Client:** `delete()` and async `delete()` accept `delete_linked` (default `False`). When `True`, deleting a memory also removes the older memories it superseded (the v3 `linked_memory_ids` chain), transitively: the delete-side counterpart of `latest_only`, so a superseded memory does not resurface after the current one is deleted ([#5270](https://github.com/mem0ai/mem0/pull/5270)) **2026-05-26** v2.0.3 **Bug Fixes:** * **Vector Stores:** PGVector adapter now supports rich filter operators (`eq`, `ne`, `gt`, `gte`, `lt`, `lte`, `in`, `nin`, `contains`, `icontains`, wildcard `*`, `$or`, `$not`) in `search()`, `keyword_search()`, and `list()`. Previously only exact-equality filters worked: operator dicts were silently stringified and returned zero results ([#5263](https://github.com/mem0ai/mem0/pull/5263)) * **Server:** Fixed `/search` endpoint returning 502 when `user_id`, `agent_id`, or `run_id` are sent as top-level request fields. The server now maps these into the `filters` dict before calling `Memory.search()`, matching the v3 API contract. Top-level entity ID fields are marked as deprecated in the OpenAPI schema and emit a warning log: clients should migrate to `filters={"user_id": "..."}` ([#5263](https://github.com/mem0ai/mem0/pull/5263)) **2026-05-08** v2.0.2 **Bug Fixes:** * **Telemetry:** Stitch OSS and platform PostHog identities on `MemoryClient` init so `$identify` events fire and a single user is no longer tracked as two or three disconnected personas ([#5040](https://github.com/mem0ai/mem0/pull/5040)) * **Security:** Harden against SQL injection and prompt injection ([#4997](https://github.com/mem0ai/mem0/pull/4997)) **New Features:** * **SDK:** Expose `decay` on `project.update` ([#5062](https://github.com/mem0ai/mem0/pull/5062)) **Improvements:** * **Plugin:** Hand `mem0` search decisions to the agent ([#4992](https://github.com/mem0ai/mem0/pull/4992)) **2026-04-25** v2.0.1 **Bug Fixes:** * **Client:** Map `user_id`, `agent_id`, `run_id` entity params to filters in `GET /memories` ([#4960](https://github.com/mem0ai/mem0/pull/4960)) * **Memory:** Honor `prompt` param in vector store extraction pipeline ([#4914](https://github.com/mem0ai/mem0/pull/4914)) * **Memory:** Add missing `text_lemmatized` field in `AsyncMemory._create_memory` ([#4886](https://github.com/mem0ai/mem0/pull/4886)) * **Memory:** Merge same-key operator dicts in AND metadata filters ([#4853](https://github.com/mem0ai/mem0/pull/4853)) * **LLMs:** Narrow `_is_reasoning_model` check to not match `gpt-5.x` variants ([#4746](https://github.com/mem0ai/mem0/pull/4746)) * **Vector Stores:** Add `ca_certs` config option for Elasticsearch vector store ([#3993](https://github.com/mem0ai/mem0/pull/3993)) * **Vector Stores:** Add `agent_id` and `run_id` to Elasticsearch/OpenSearch default mappings ([#4906](https://github.com/mem0ai/mem0/pull/4906)) * **Embeddings:** Set FastEmbed `embedding_dims` from model metadata at init ([#4711](https://github.com/mem0ai/mem0/pull/4711)) **Security:** * Bump vulnerable dependencies to patched versions ([#4835](https://github.com/mem0ai/mem0/pull/4835)) **2026-04-14** v2.0.0 **Major Release**: Python SDK with V3 memory pipeline, ADD-only extraction, and cleaned-up API surface. **New Features:** * **Single-Pass Extraction:** Replaced 2-LLM-call pipeline with additive extraction using `ADDITIVE_EXTRACTION_PROMPT`. Memories accumulate via `linked_memory_ids`: no more UPDATE/DELETE events ([#4805](https://github.com/mem0ai/mem0/pull/4805)) * **Hybrid Search:** Combined semantic + BM25 keyword matching + entity boost with additive scoring. Native `keyword_search()` added to 15 vector store adapters (Qdrant, Elasticsearch, OpenSearch, Azure AI Search, Weaviate, Redis, PGVector, Pinecone, Databricks, MongoDB, Milvus, Baidu, Upstash, Azure MySQL, Vertex AI) ([#4805](https://github.com/mem0ai/mem0/pull/4805)) * **Entity Extraction & Linking:** spaCy-based entity extraction with second vector collection (`{collection}_entities`) for cross-memory relationship retrieval. Optional dependency: `pip install mem0ai[nlp]` ([#4805](https://github.com/mem0ai/mem0/pull/4805)) * **Batch Operations:** Batch embedding, batch persist, and batch entity linking (8-phase pipeline) for both sync `Memory` and async `AsyncMemory` at full parity ([#4805](https://github.com/mem0ai/mem0/pull/4805)) * **Message Persistence:** SQLite-based rolling window (10 messages per session scope) for LLM context ([#4805](https://github.com/mem0ai/mem0/pull/4805)) * **Valkey Cluster Mode:** Added `cluster_mode` parameter for Valkey Cluster Mode Enabled (CME) deployments ([#4759](https://github.com/mem0ai/mem0/pull/4759)) * **V3 API Endpoints:** `MemoryClient.add()` now posts to `/v3/memories/add/`; `MemoryClient.get_all()` posts to `/v3/memories/` and returns a paginated envelope `{"count": int, "next": str | None, "previous": str | None, "results": [...]}` ([#4856](https://github.com/mem0ai/mem0/pull/4856)) * **Default model:** `gpt-5-mini` is now the default across `OpenAILLM`, `OpenAIStructuredLLM`, `AzureOpenAILLM`, `AzureOpenAIStructuredLLM`, and `LiteLLM` fallback ([#4829](https://github.com/mem0ai/mem0/pull/4829)) **Breaking Changes:** * **`add()` returns ADD-only events**: No more `"UPDATE"` or `"DELETE"` events. Memories accumulate; nothing is overwritten ([#4805](https://github.com/mem0ai/mem0/pull/4805)) * **`search()` default `threshold` is now `0.1`**: Pass `threshold=0.0` for previous behavior ([#4805](https://github.com/mem0ai/mem0/pull/4805)) * **`search()` `score` is now a combined multi-signal score**: The top-level `score` fuses semantic similarity, BM25 keyword match, entity signals, and temporal boosts into one value. Absolute numbers shift versus the old raw cosine score; retune any hard thresholds against representative queries ([#4805](https://github.com/mem0ai/mem0/pull/4805), [#4836](https://github.com/mem0ai/mem0/pull/4836)) * **`search()` default `rerank` is now `False`**: Pass `rerank=True` for previous behavior ([#4805](https://github.com/mem0ai/mem0/pull/4805)) * **`top_k` default changed 100 → 20** in `Memory.get_all()` and `Memory.search()` (sync + async). Pass `top_k=100` explicitly to restore the old behavior ([#4843](https://github.com/mem0ai/mem0/pull/4843)) * **Entity ID validation:** `user_id` / `agent_id` / `run_id` are trimmed; empty-string and whitespace-only values now raise `ValueError` ([#4843](https://github.com/mem0ai/mem0/pull/4843)) * **Search params validation:** `threshold` must be a number in `[0, 1]`; `top_k` must be a non-negative integer: invalid inputs raise `ValueError` ([#4843](https://github.com/mem0ai/mem0/pull/4843)) * **`messages` in `Memory.add()` rejects invalid types:** Passing `None` or non-`(str | dict | list)` values raises `Mem0ValidationError` (`error_code="VALIDATION_003"`) ([#4843](https://github.com/mem0ai/mem0/pull/4843)) * **`qdrant-client>=1.12.0` required**: Upgrade from `>=1.9.1` ([#4805](https://github.com/mem0ai/mem0/pull/4805)) * **`org_id` and `project_id` removed**: Removed from `MemoryClient` constructor and all method signatures ([#4740](https://github.com/mem0ai/mem0/pull/4740)) * **External Graph Store Removed (OSS):** `mem0/memory/graph_memory.py`, `memgraph_memory.py`, `kuzu_memory.py`, `apache_age_memory.py`, and `mem0/graphs/` (Neo4j / Memgraph / Kuzu / Apache AGE / Neptune drivers) deleted, about 4,000 lines. The external graph store integration is no longer part of the OSS SDK; graph drivers (neo4j, memgraph, kuzu, etc.) can be uninstalled. Graph memory now runs natively as built-in entity linking. Remove `enable_graph` and `graph_store` from your config ([#4805](https://github.com/mem0ai/mem0/pull/4805)) * **`enable_graph` removed from Client SDK:** Graph memory now runs automatically and no longer needs a flag. Remove `enable_graph` from `MemoryClient.add()` / `search()` / `get_all()` / `update_project()` calls ([#4776](https://github.com/mem0ai/mem0/pull/4776)) * **`custom_fact_extraction_prompt` renamed to `custom_instructions`**: Update config and memory module references ([#4740](https://github.com/mem0ai/mem0/pull/4740)) * **Typed option classes**: Added Pydantic v2 typed classes: `AddMemoryOptions`, `SearchMemoryOptions`, `GetAllMemoryOptions`, `DeleteAllMemoryOptions`, `UpdateMemoryOptions`, `ProjectUpdateOptions` ([#4740](https://github.com/mem0ai/mem0/pull/4740)) **Security:** * **FAISS:** Prevent arbitrary code execution via pickle deserialization in `FAISS` vector store ([#4833](https://github.com/mem0ai/mem0/pull/4833)) **Bug Fixes:** * **V3 migration crashes:** Fixed crashes in the v3 migration path; entity linking on OSS is now functional across Qdrant and Milvus backends ([#4836](https://github.com/mem0ai/mem0/pull/4836)) * **Qdrant entity store:** Entity store now shares the existing Qdrant client when using embedded mode (`path=...`), eliminating RocksDB lock contention between the main and entity collections ([#4836](https://github.com/mem0ai/mem0/pull/4836)) * **Reranker:** Fixed incorrect use of SentenceTransformer for cross-encoder reranker models: switched to CrossEncoder API for proper scoring ([#4806](https://github.com/mem0ai/mem0/pull/4806)) * **S3 Vectors:** Handle `vector=None` in `update()` to prevent boto3 validation error when `event=NONE` ([#4594](https://github.com/mem0ai/mem0/pull/4594)) * **LLMs:** Made OpenAI `store` parameter opt-in to prevent leaking to non-OpenAI backends like Google Gemini ([#4757](https://github.com/mem0ai/mem0/pull/4757)) * **LLMs:** Forward `response_format` to Azure OpenAI API to prevent JSON parsing failures ([#4689](https://github.com/mem0ai/mem0/pull/4689)) * **Core:** Guard `temp_uuid_mapping` lookups against LLM-hallucinated IDs with safe `.get()` and warnings ([#4674](https://github.com/mem0ai/mem0/pull/4674)) * **Client:** Prevent `MemoryClient.feedback()` telemetry TypeError by merging feedback data into single payload ([#4795](https://github.com/mem0ai/mem0/pull/4795)) **Improvements:** * **Telemetry:** Sample OSS hot-path events at 10% via PostHog `before_send` hook to reduce event volume ([#4771](https://github.com/mem0ai/mem0/pull/4771)) See the [OSS v2 to v3 migration guide](https://docs.mem0.ai/migration/oss-v2-to-v3) and [Platform migration guide](https://docs.mem0.ai/migration/platform-v2-to-v3) for upgrade instructions. **2026-04-06** v1.0.11 **New Features & Updates:** * **SDK:** Added `multilingual` parameter to project update ([#4314](https://github.com/mem0ai/mem0/pull/4314)) **Bug Fixes:** * **LLMs:** Fixed Groq model configuration ([#4700](https://github.com/mem0ai/mem0/pull/4700)) * **Core:** Prevented thread and memory leaks from PostHog telemetry ([#4535](https://github.com/mem0ai/mem0/pull/4535)) * **Vector Stores:** Used `DatetimeRange` for datetime string values in Qdrant range filters ([#4659](https://github.com/mem0ai/mem0/pull/4659)) * **Configs:** Added missing `ConfigDict` to vector store configs (Elasticsearch, MongoDB, Neptune, OpenSearch, PGVector, Supabase, Valkey) ([#4656](https://github.com/mem0ai/mem0/pull/4656)) **2026-04-01** v1.0.10 **New Features & Updates:** * **LLMs:** Added MiniMax provider support for AWS Bedrock ([#4609](https://github.com/mem0ai/mem0/pull/4609)) **Bug Fixes:** * **Configs:** Migrated CassandraConfig and AzureMySQLConfig to pydantic v2 ConfigDict ([#4646](https://github.com/mem0ai/mem0/pull/4646)) * **LLMs:** Forward `response_format` to OpenAI-compatible API for DeepSeek ([#4635](https://github.com/mem0ai/mem0/pull/4635)) * **LLMs:** Forward `response_format` to OpenAI-compatible API for vLLM ([#4608](https://github.com/mem0ai/mem0/pull/4608)) * **Vector Stores:** Only list authorized collections when listing MongoDB collections ([#3888](https://github.com/mem0ai/mem0/pull/3888)) * **Core:** Reset graph database in `Memory.reset()` ([#4185](https://github.com/mem0ai/mem0/pull/4185)) * **Core:** Make `AsyncMemory.from_config` a regular classmethod ([#4183](https://github.com/mem0ai/mem0/pull/4183)) **2026-03-28** v1.0.9 **New Features & Updates:** * **LLMs:** Added `reasoning_effort` parameter support for reasoning models ([#4461](https://github.com/mem0ai/mem0/pull/4461)) **Bug Fixes:** * **Core:** Preserved original `actor_id` during memory update ([#4570](https://github.com/mem0ai/mem0/pull/4570)) * **Core:** Set `updated_at` on creation and preserve pre-existing `created_at` ([#4499](https://github.com/mem0ai/mem0/pull/4499)) * **Core:** Centralized entity cleanup and skip malformed LLM relation dicts ([#4515](https://github.com/mem0ai/mem0/pull/4515)) * **Core:** Removed `README.md` from wheel shared-data ([#4052](https://github.com/mem0ai/mem0/pull/4052)) * **Vector Stores:** Handled `vector=None` in Milvus and Qdrant update methods ([#4568](https://github.com/mem0ai/mem0/pull/4568)) * **Vector Stores:** Rebuilt FAISS index on vector deletion ([#4178](https://github.com/mem0ai/mem0/pull/4178)) **Improvements:** * **Embeddings:** Updated default Gemini and Vertex AI embedder model to `gemini-embedding-001` ([#4571](https://github.com/mem0ai/mem0/pull/4571)) **2026-03-26** v1.0.8 **New Features & Updates:** * **Vector Stores:** Integrated Turbopuffer as a vector database provider ([#4428](https://github.com/mem0ai/mem0/pull/4428)) * **LLMs:** Added MiniMax LLM provider ([#4431](https://github.com/mem0ai/mem0/pull/4431)) **Bug Fixes:** * **Core:** Fixed merging of multiple filter operators for the same key ([#4559](https://github.com/mem0ai/mem0/pull/4559)) * **Core:** Prevented in-place mutation of metadata in `_create_memory` ([#4529](https://github.com/mem0ai/mem0/pull/4529)) * **Core:** Preserved custom metadata when updating memory ([#4495](https://github.com/mem0ai/mem0/pull/4495)) * **Core:** Handled chatty LLM responses in JSON parsing ([#4525](https://github.com/mem0ai/mem0/pull/4525)) * **Core:** Prevented double embedding in `mem0.add` ([#3996](https://github.com/mem0ai/mem0/pull/3996)) * **Core:** Raised `ValueError` when deleting nonexistent memory ([#4455](https://github.com/mem0ai/mem0/pull/4455)) * **Core:** Cleaned up graph store data on `Memory.delete()` ([#4505](https://github.com/mem0ai/mem0/pull/4505)) * **Vector Stores:** Prevented SQL injection in Databricks vector store ([#4558](https://github.com/mem0ai/mem0/pull/4558)) * **Vector Stores:** Upgraded MongoDB vector store from deprecated `knnVector` to GA `vectorSearch` ([#3995](https://github.com/mem0ai/mem0/pull/3995)) * **Vector Stores:** Prevented embedding corruption in Valkey and Redis when vector is `None` ([#4362](https://github.com/mem0ai/mem0/pull/4362)) * **Vector Stores:** Accepted default `/tmp/chroma` path in `ChromaDbConfig` validator ([#4179](https://github.com/mem0ai/mem0/pull/4179)) * **Vector Stores:** Wrapped vector and payload in lists for `Langchain.update` ([#4446](https://github.com/mem0ai/mem0/pull/4446)) * **Graph:** Soft-delete graph relationships instead of hard `DELETE` ([#4188](https://github.com/mem0ai/mem0/pull/4188)) * **Graph:** Sanitized hyphens in Neo4j Cypher relationship names ([#4154](https://github.com/mem0ai/mem0/pull/4154)) * **Graph:** Used root LLM config as fallback for graph store instead of hardcoded OpenAI default ([#4466](https://github.com/mem0ai/mem0/pull/4466)) * **Qdrant:** Fixed `do not remove local path on init` ([#4475](https://github.com/mem0ai/mem0/pull/4475)) * **Qdrant:** Implemented enhanced metadata filtering operators ([#4127](https://github.com/mem0ai/mem0/pull/4127)) * **Embeddings:** Fixed OpenAI embedding dimensions ([#4481](https://github.com/mem0ai/mem0/pull/4481)) * **LLMs:** Omitted `topP` for Anthropic Converse in Bedrock; used `AWSBedrockConfig` in `LlmFactory` ([#4469](https://github.com/mem0ai/mem0/pull/4469)) * **LLMs:** Avoided sending both `temperature` and `top_p` to Anthropic API ([#4471](https://github.com/mem0ai/mem0/pull/4471)) * **LLMs:** Handled `None` content and empty candidates in `GeminiLLM` parsing ([#4462](https://github.com/mem0ai/mem0/pull/4462)) * **LLMs:** Added missing `_parse_response` to `AzureOpenAIStructuredLLM` ([#4434](https://github.com/mem0ai/mem0/pull/4434)) * **History:** Added timestamps for `DELETE` operations in history ([#4492](https://github.com/mem0ai/mem0/pull/4492)) **Improvements:** * **Vector Stores:** Added vector validation to OpenSearchDB to ensure non-null, non-empty, and correct-dimension vectors ([#4472](https://github.com/mem0ai/mem0/pull/4472)) **2026-03-19** v1.0.7 **Bug Fixes:** * **Core:** Fixed control characters in LLM JSON responses causing parse failures ([#4420](https://github.com/mem0ai/mem0/pull/4420)) * **Core:** Replaced hardcoded US/Pacific timezone references with `timezone.utc` ([#4404](https://github.com/mem0ai/mem0/pull/4404)) * **Core:** Preserved `http_auth` in `_safe_deepcopy_config` for OpenSearch ([#4418](https://github.com/mem0ai/mem0/pull/4418)) * **Core:** Normalized malformed LLM fact output before embedding ([#4224](https://github.com/mem0ai/mem0/pull/4224)) * **Embeddings:** Pass `encoding_format='float'` in OpenAI embeddings for proxy compatibility ([#4058](https://github.com/mem0ai/mem0/pull/4058)) * **LLMs:** Fixed Ollama to pass tools to `client.chat` and parse `tool_calls` from response ([#4176](https://github.com/mem0ai/mem0/pull/4176)) * **Reranker:** Support nested LLM config in `LLMReranker` for non-OpenAI providers ([#4405](https://github.com/mem0ai/mem0/pull/4405)) * **Vector Stores:** Cast `vector_distance` to float in Redis search ([#4377](https://github.com/mem0ai/mem0/pull/4377)) **Improvements:** * **Embeddings:** Improved Ollama embedder with model name normalization and error handling ([#4403](https://github.com/mem0ai/mem0/pull/4403)) **2026-03-16** v1.0.6 **Bug Fixes:** * **Telemetry:** Fixed telemetry vector store initialization still running when `MEM0_TELEMETRY` is disabled (#4351) * **Core:** Removed destructive `vector_store.reset()` call from `delete_all()` that was wiping the entire vector store instead of deleting only the target memories (#4349) * **OSS:** `OllamaLLM` now respects the configured URL instead of always falling back to localhost (#4320) * **Core:** Fixed `KeyError` when LLM omits the `entities` key in tool call response (#4313) * **Prompts:** Ensured JSON instruction is included in prompts when using `json_object` response format (#4271) * **Core:** Fixed incorrect database parameter handling (#3913) **Dependencies:** * Updated LangChain dependencies to v1.0.0 (#4353) * Bumped protobuf dependency to 5.29.6 and extended upper bound to `<7.0.0` (#4326) **2026-03-03** v1.0.5 * **Telemetry Fix** * Fixed an issue where the PostHog client was initialized even after telemetry was disabled. Although events were not captured, the client was unnecessarily initialized. **2026-02-17** v1.0.4 **New Features & Updates:** * **Memory Update:** * Added `timestamp` parameter to `update()`: accepts Unix epoch (int/float) or ISO 8601 string **2026-01-29** v1.0.3 **New Features & Updates:** * **Project Settings:** * Added inclusion prompt, exclusion prompt, memory depth, and usecase setting **2026-01-13** v1.0.2 **New Features & Updates:** * **Vector Stores:** * Added DriverInfo metadata to MongoDB vector store **2025-11-14** v1.0.1 **New Features & Updates:** * **Vector Stores:** * Added Apache Cassandra vector store support * **Embeddings:** * Added FastEmbed embedding support for local embeddings * **Graph Store:** * Added configurable embedding similarity threshold for graph store node matching **Bug Fixes:** * **Core:** * Fixed condition check for memories\_result type in Memory class * Fixed list\_memories endpoint Pydantic validation error * Fixed memory deletion not removing from vector store **2025-10-16** v1.0.0 **New Features & Updates:** * **Vector Stores:** * Added Azure MySQL support * Added Azure AI Search Vector Store support * **LLMs:** * Added Tool Call support for LangchainLLM * Enabled custom model and parameters for Hugging Face with huggingface\_base\_url * Updated default LLM configuration * **Rerankers:** * Added reranker support: Cohere, ZeroEntropy, Hugging Face, Sentence Transformers, and LLMs * **Core:** * Added metadata filtering for OSS * Added Assistant memory retrieval * Enabled async mode as default **Improvements:** * **Prompts:** * Improved prompt for better memory retrieval * **Dependencies:** * Updated dependency compatibility with OpenAI 2.x * **Validation:** * Validated embedding\_dims for Kuzu integration **Bug Fixes:** * **Vector Stores:** * Fixed Databricks Vector Store integration * Fixed Milvus DB bug and added test coverage * Fixed Weaviate search method * **LLMs:** * Fixed bug with thinking LLM in vLLM **2025-09-25** v0.1.118 **New Features & Updates:** * **Vector Stores:** * Added Valkey vector store support * Added support for ChromaDB Cloud * Added Mem0 vector store backend integration for Neptune Analytics * **Graph Store:** * Added Neptune-DB graph store with vector store * **Core:** * Implemented structured exception classes with error codes and suggested actions **Improvements:** * **Dependencies:** * Updated OpenAI dependency and improved Ollama compatibility * **Testing:** * Added Weaviate DB test * Added comprehensive test suite for SQLiteManager * **Documentation:** * Updated category docs * Updated Search V2 / Get All V2 filters documentation * Refactored AWS example title * Fixed Quickstart cURL example **Bug Fixes:** * **Vector Stores:** * Databricks bug fixes * Fixed S3 Vectors memory initialization issue from configuration * **Core:** * Fixed JSON parsing with new memories * Replaced hardcoded LLM provider with provider from configuration * **LLMs:** * Fixed Bedrock Anthropic models to use system field **2025-09-03** v0.1.117 **New Features & Updates:** * **OpenMemory:** * Added memory export / import feature * Added vector store integrations: Weaviate, FAISS, PGVector, Chroma, Redis, Elasticsearch, Milvus * Added `export_openmemory.sh` migration script * **Vector Stores:** * Added Amazon S3 Vectors support * Added Databricks Mosaic AI vector store support * Added support for OpenAI Store * **Graph Memory:** Added support for graph memory using Kuzu * **Azure:** Added Azure Identity for Azure OpenAI and Azure AI Search authentication * **Elasticsearch:** Added headers configuration support **Improvements:** * Added custom connection client to enable connecting to local containers for Weaviate * Updated configuration AWS Bedrock * Fixed dependency issues and tests; updated docstrings * **Documentation:** * Fixed Graph Docs page missing in sidebar * Updated integration documentation * Added version param in Search V2 API documentation * Updated Databricks documentation and refactored docs * Updated favicon logo * Fixed typos and Typescript docs **Bug Fixes:** * Baidu: Added missing provider for Baidu vector DB * MongoDB: Replaced `query_vector` args in search method * Fixed new memory mistaken for current * AsyncMemory.\_add\_to\_vector\_store: handled edge case when no facts found * Fixed missing commas in Kuzu graph INSERT queries * Fixed inconsistent created and updated properties for Graph * Fixed missing `app_id` on client for Neptune Analytics * Correctly pick AWS region from environment variable * Fixed Ollama model existence check **Refactoring:** * **PGVector:** Use internal connection pools and context managers **2025-08-14** v0.1.116 **New Features & Updates:** * **Pinecone:** Added namespace support and improved type safety * **Milvus:** Added db\_name field to MilvusDBConfig * **Vector Stores:** Added multi-id filters support * **Vercel AI SDK:** Migration to AI SDK V5.0 * **Python Support:** Added Python 3.12 support * **Graph Memory:** Added sanitizer methods for nodes and relationships * **LLM Monitoring:** Added monitoring callback support **Improvements:** * **Performance:** * Improved async handling in AsyncMemory class * **Documentation:** * Added async add announcement * Added personalized search docs * Added Neptune examples * Added V5 migration docs * **Configuration:** * Refactored base class config for LLMs * Added sslmode for pgvector * **Dependencies:** * Updated psycopg to version 3 * Updated Docker compose **Bug Fixes:** * **Tests:** * Fixed failing tests * Restricted package versions * **Memgraph:** * Fixed async attribute errors * Fixed n\_embeddings usage * Fixed indexing issues * **Vector Stores:** * Fixed Qdrant cloud indexing * Fixed Neo4j Cypher syntax * Fixed LLM parameters * **Graph Store:** * Fixed LM config prioritization * **Dependencies:** * Fixed JSON import for psycopg **Refactoring:** * **Google AI:** Refactored from Gemini to Google AI * **Base Classes:** Refactored LLM base class configuration **2025-07-24** v0.1.115 **New Features & Updates:** * Enhanced project management via `client.project` and `AsyncMemoryClient.project` interfaces * Full support for project CRUD operations (create, read, update, delete) * Project member management: add, update, remove, and list members * Manage project settings including custom instructions, categories, retrieval criteria, and graph enablement * Both sync and async support for all project management operations **Improvements:** * **Documentation:** * Added detailed API reference and usage examples for new project management methods. * Updated all docs to use `client.project.get()` and `client.project.update()` instead of deprecated methods. * **Deprecation:** * Marked `get_project()` and `update_project()` as deprecated (these methods were already present); added warnings to guide users to the new API. **Bug Fixes:** * **Tests:** * Fixed Gemini embedder and LLM test mocks for correct error handling and argument structure. * **vLLM:** * Fixed duplicate import in vLLM module. **2025-07-05** v0.1.114 **New Features:** * **OpenAI Agents:** Added OpenAI agents SDK support * **Amazon Neptune:** Added Amazon Neptune Analytics graph\_store configuration and integration * **vLLM:** Added vLLM support **Improvements:** * **Documentation:** * Added SOC2 and HIPAA compliance documentation * Enhanced group chat feature documentation for platform * Added Google AI ADK Integration documentation * Fixed documentation images and links * **Setup:** Fixed Mem0 setup, logging, and documentation issues **Bug Fixes:** * **MongoDB:** Fixed MongoDB Vector Store misaligned strings and classes * **vLLM:** Fixed missing OpenAI import in vLLM module and call errors * **Dependencies:** Fixed CI issues related to missing dependencies * **Installation:** Reverted pip install changes **2025-06-30** v0.1.113 **Bug Fixes:** * **Gemini:** Fixed Gemini embedder configuration **2025-06-27** v0.1.112 **New Features:** * **Memory:** Added immutable parameter to add method * **OpenMemory:** Added async\_mode parameter support **Improvements:** * **Documentation:** * Enhanced platform feature documentation * Fixed documentation links * Added async\_mode documentation * **MongoDB:** Fixed MongoDB configuration name **Bug Fixes:** * **Bedrock:** Fixed Bedrock LLM, embeddings, tools, and temporary credentials * **Memory:** Fixed memory categorization by updating dependencies and correcting API usage * **Gemini:** Fixed Gemini Embeddings and LLM issues **2025-06-23** v0.1.111 **New Features:** * **OpenMemory:** * Added OpenMemory augment support * Added OpenMemory Local Support using new library * **vLLM:** Added vLLM support integration **Improvements:** * **Documentation:** * Added MCP Client Integration Guide and updated installation commands * Improved Agent Id documentation for Mem0 OSS Graph Memory * **Core:** Added JSON parsing to solve hallucination errors **Bug Fixes:** * **Gemini:** Fixed Gemini Embeddings migration **2025-06-20** v0.1.110 **New Features:** * **Baidu:** Added Baidu vector database integration **Improvements:** * **Documentation:** * Updated changelog * Fixed example in quickstart page * Updated client.update() method documentation in OpenAPI specification * **OpenSearch:** Updated logger warning **Bug Fixes:** * **CI:** Fixed failing CI pipeline **2025-06-19** v0.1.109 **New Features:** * **AgentOps:** Added AgentOps integration * **LM Studio:** Added response\_format parameter for LM Studio configuration * **Examples:** Added Memory agent powered by voice (Cartesia + Agno) **Improvements:** * **AI SDK:** Added output\_format parameter * **Client:** Enhanced update method to support metadata * **Google:** Added Google Genai library support **Bug Fixes:** * **Build:** Fixed Build CI failure * **Pinecone:** Fixed pinecone for async memory **2025-06-14** v0.1.108 **New Features:** * **MongoDB:** Added MongoDB Vector Store support * **Client:** Added client support for summary functionality **Improvements:** * **Pinecone:** Fixed pinecone version issues * **OpenSearch:** Added logger support * **Testing:** Added python version test environments **2025-06-11** v0.1.107 **Improvements:** * **Documentation:** * Updated Livekit documentation migration * Updated OpenMemory hosted version documentation * **Core:** Updated categorization flow * **Storage:** Fixed migration issues **2025-06-09** v0.1.106 **New Features:** * **Cloudflare:** Added Cloudflare vector store support * **Search:** Added threshold parameter to search functionality * **API:** Added wildcard character support for v2 Memory APIs **Improvements:** * **Documentation:** Updated README docs for OpenMemory environment setup * **Core:** Added support for unique user IDs **Bug Fixes:** * **Core:** Fixed error handling exceptions **2025-06-03** v0.1.104 **Bug Fixes:** * **Vector Stores:** Fixed GET\_ALL functionality for FAISS and OpenSearch **2025-06-02** v0.1.103 **New Features:** * **LLM:** Added support for OpenAI compatible LLM providers with baseUrl configuration **Improvements:** * **Documentation:** * Fixed broken links * Improved Graph Memory features documentation clarity * Updated enable\_graph documentation * **TypeScript SDK:** Updated Google SDK peer dependency version * **Client:** Added async mode parameter **2025-05-26** v0.1.102 **New Features:** * **Examples:** Added Neo4j example * **AI SDK:** Added Google provider support * **OpenMemory:** Added LLM and Embedding Providers support **Improvements:** * **Documentation:** * Updated memory export documentation * Enhanced role-based memory attribution rules documentation * Updated API reference and messages documentation * Added Mastra and Raycast documentation * Added NOT filter documentation for Search and GetAll V2 * Announced Claude 4 support * **Core:** * Removed support for passing string as input in client.add() * Added support for sarvam-m model * **TypeScript SDK:** Fixed types from message interface **Bug Fixes:** * **Memory:** Prevented saving prompt artifacts as memory when no new facts are present * **OpenMemory:** Fixed typos in MCP tool description **2025-05-15** v0.1.101 **New Features:** * **Neo4j:** Added base label configuration support **Improvements:** * **Documentation:** * Updated Healthcare example index * Enhanced collaborative task agent documentation clarity * Added criteria-based filtering documentation * **OpenMemory:** Added cURL command for easy installation * **Build:** Migrated to Hatch build system **2025-05-10** v0.1.100 **New Features:** * **Memory:** Added Group Chat Memory Feature support * **Examples:** Added Healthcare assistant using Mem0 and Google ADK **Bug Fixes:** * **SSE:** Fixed SSE connection issues * **MCP:** Fixed memories not appearing in MCP clients added from Dashboard **2025-05-07** v0.1.99 **New Features:** * **OpenMemory:** Added OpenMemory support * **Neo4j:** Added weights to Neo4j model * **AWS:** Added support for OpenSearch Serverless * **Examples:** Added ElizaOS Example **Improvements:** * **Documentation:** Updated Azure AI documentation * **AI SDK:** Added missing parameters and updated demo application * **OSS:** Fixed AOSS and AWS BedRock LLM **2025-04-30** v0.1.98 **New Features:** * **Neo4j:** Added support for Neo4j database * **AWS:** Added support for AWS Bedrock Embeddings **Improvements:** * **Client:** Updated delete\_users() to use V2 API endpoints * **Documentation:** Updated timestamp and dual-identity memory management docs * **Neo4j:** Improved Neo4j queries and removed warnings * **AI SDK:** Added support for graceful failure when services are down **Bug Fixes:** * Fixed AI SDK filters * Fixed new memories wrong type * Fixed duplicated metadata issue while adding/updating memories **2025-04-23** v0.1.97 **New Features:** * **HuggingFace:** Added support for HF Inference **Bug Fixes:** * Fixed proxy for Mem0 **2025-04-16** v0.1.96 **New Features:** * **Vercel AI SDK:** Added Graph Memory support **Improvements:** * **Documentation:** Fixed timestamp and README links * **Client:** Updated TS client to use proper types for deleteUsers * **Dependencies:** Removed unnecessary dependencies from base package **2025-04-09** v0.1.95 **Improvements:** * **Client:** Fixed Ping Method for using default org\_id and project\_id * **Documentation:** Updated documentation **Bug Fixes:** * Fixed mem0-migrations issue **2025-04-26** v0.1.94 **New Features:** * **Integrations:** Added Memgraph integration * **Memory:** Added timestamp support * **Vector Stores:** Added reset function for VectorDBs **Improvements:** * **Documentation:** * Updated timestamp and expiration\_date documentation * Fixed v2 search documentation * Added "memory" in EC "Custom config" section * Fixed typos in the json config sample **2025-04-21** v0.1.93 **Improvements:** * **Vector Stores:** Initialized embedding\_model\_dims in all vectordbs **Bug Fixes:** * **Documentation:** Fixed agno link **2025-04-18** v0.1.92 **New Features:** * **Memory:** Added Memory Reset functionality * **Client:** Added support for Custom Instructions * **Examples:** Added Fitness Checker powered by memory **Improvements:** * **Core:** Updated capture\_event * **Documentation:** Fixed curl for v2 get\_all **Bug Fixes:** * **Vector Store:** Fixed user\_id functionality * **Client:** Various client improvements **2025-04-16** v0.1.91 **New Features:** * **LLM Integrations:** Added Azure OpenAI Embedding Model * **Examples:** * Added movie recommendation using grok3 * Added Voice Assistant using Elevenlabs **Improvements:** * **Documentation:** * Added keywords AI * Reformatted navbar page URLs * Updated changelog * Updated openai.mdx * **FAISS:** Silenced FAISS info logs **2025-04-11** v0.1.90 **New Features:** * **LLM Integrations:** Added Mistral AI as LLM provider **Improvements:** * **Documentation:** * Updated changelog * Fixed memory exclusion example * Updated xAI documentation * Updated YouTube Chrome extension example documentation **Bug Fixes:** * **Core:** Fixed EmbedderFactory.create() in GraphMemory * **Azure OpenAI:** Added patch to fix Azure OpenAI * **Telemetry:** Fixed telemetry issue **2025-04-11** v0.1.89 **New Features:** * **Langchain Integration:** Added support for Langchain VectorStores * **Examples:** * Added personal assistant example * Added personal study buddy example * Added YouTube assistant Chrome extension example * Added agno example * Updated OpenAI Responses API examples * **Vector Store:** Added capability to store user\_id in vector database * **Async Memory:** Added async support for OSS **Improvements:** * **Documentation:** Updated formatting and examples **2025-04-09** v0.1.87 **New Features:** * **Upstash Vector:** Added support for Upstash Vector store **Improvements:** * **Code Quality:** Removed redundant code lines * **Build:** Updated MAKEFILE * **Documentation:** Updated memory export documentation **2025-04-07** v0.1.86 **Improvements:** * **FAISS:** Added embedding\_dims parameter to FAISS vector store **2025-04-07** v0.1.84 **New Features:** * **Langchain Embedder:** Added Langchain embedder integration **Improvements:** * **Langchain LLM:** Updated Langchain LLM integration to directly pass the Langchain object LLM **2025-04-07** v0.1.83 **Bug Fixes:** * **Langchain LLM:** Fixed issues with Langchain LLM integration **2025-04-07** v0.1.82 **New Features:** * **LLM Integrations:** Added support for Langchain LLMs, Google as new LLM and embedder * **Development:** Added development docker compose **Improvements:** * **Output Format:** Set output\_format='v1.1' and updated documentation **Documentation:** * **Integrations:** Added LMStudio and Together.ai documentation * **API Reference:** Updated output\_format documentation * **Integrations:** Added PipeCat integration documentation * **Integrations:** Added Flowise integration documentation for Mem0 memory setup **Bug Fixes:** * **Tests:** Fixed failing unit tests **2025-04-02** v0.1.79 **New Features:** * **FAISS Support:** Added FAISS vector store support **2025-04-02** v0.1.78 **New Features:** * **Livekit Integration:** Added Mem0 livekit example * **Evaluation:** Added evaluation framework and tools **Documentation:** * **Multimodal:** Updated multimodal documentation * **Examples:** Added examples for email processing * **API Reference:** Updated API reference section * **Elevenlabs:** Added Elevenlabs integration example **Bug Fixes:** * **OpenAI Environment Variables:** Fixed issues with OpenAI environment variables * **Deployment Errors:** Added `package.json` file to fix deployment errors * **Tools:** Fixed tools issues and improved formatting * **Docs:** Updated API reference section for `expiration date` **2025-03-26** v0.1.77 **Bug Fixes:** * **OpenAI Environment Variables:** Fixed issues with OpenAI environment variables * **Deployment Errors:** Added `package.json` file to fix deployment errors * **Tools:** Fixed tools issues and improved formatting * **Docs:** Updated API reference section for `expiration date` **2025-03-19** v0.1.76 **New Features:** * **Supabase Vector Store:** Added support for Supabase Vector Store * **Supabase History DB:** Added Supabase History DB to run Mem0 OSS on Serverless * **Feedback Method:** Added feedback method to client **Bug Fixes:** * **Azure OpenAI:** Fixed issues with Azure OpenAI * **Azure AI Search:** Fixed test cases for Azure AI Search **TypeScript** **2026-09-25** v3.3.1 **Bug Fixes:** * **Config (OSS):** `ConfigManager` no longer injects OpenAI's default `baseURL` and `model` into non-OpenAI LLM providers. The defaults now apply only to `openai` and `openai_structured`, so a DeepSeek, xAI, or other provider config without an explicit `baseURL` or `model` falls back to that provider's own defaults and env vars (`DEEPSEEK_API_BASE`, `XAI_API_BASE`, ...) instead of pointing at OpenAI with an OpenAI model name ([#7350](https://github.com/mem0ai/mem0/pull/7350)) * **Vector Stores:** Turbopuffer filters now apply every operator (`eq`, `ne`, `gt`, `gte`, `lt`, `lte`, `in`, `nin`). Only the range operators were read before, so `eq`, `ne`, `in`, and `nin` were silently dropped. A `"*"` value now matches anything instead of nothing, an array value is treated as `in`, and an unsupported operator throws ([#6578](https://github.com/mem0ai/mem0/pull/6578)) * **Vector Stores:** Turbopuffer `search()` with `euclidean_squared` now maps the unbounded squared distance to `1 / (1 + distance)` instead of `1 - distance`, which went negative and inverted ranking for any distance above 1 ([#6580](https://github.com/mem0ai/mem0/pull/6580)) * **Packaging:** `pg`, `@types/pg`, and `natural` are now optional peer dependencies, and `pg` / `@types/pg` accept caret ranges instead of the exact `8.11.3` / `8.11.0` pins, so installing `mem0ai` no longer pulls in `pg` or conflicts with an app's own `pg` version. The PGVector store now imports `pg` only when it is used, so install it alongside `mem0ai` (`npm install pg`) if you use that store. `@types/jest` moved from peer dependencies to dev dependencies ([#7450](https://github.com/mem0ai/mem0/pull/7450)) **2026-09-23** v3.3.0 **New Features:** * **Client:** Add User Profiles to `MemoryClient`: `getProfile()`, `generateProfile()`, `getProfileSettings()`, `updateProfileSettings()`, `sampleProfiles()`, and `getProfileJob()`. A profile is a structured, always-current JSON summary of one user, shaped by a JSON Schema you configure per project and filled by an LLM from that user's memories. Generation is asynchronous. Every job POST carries an `Idempotency-Key`; to retry a lost request without starting a second job, pass the same `idempotencyKey` on each attempt ([#7340](https://github.com/mem0ai/mem0/pull/7340)) **2026-09-18** v3.2.0 **Improvements:** * **Client:** Requests now carry `X-Mem0-Source`, `X-Application` and `X-Mem0-Client`, matching the Python SDK. The first two are set-once so an outer wrapper keeps its identity; the third is append-only and reports the whole layer chain. Read from `MEM0_SOURCE`, `MEM0_APPLICATION` and `MEM0_CLIENT_STACK` when set ([#7326](https://github.com/mem0ai/mem0/pull/7326)) * **Client:** The SDK version in `X-Mem0-Client` is injected at build time rather than hardcoded, so it cannot go stale at the next release ([#7326](https://github.com/mem0ai/mem0/pull/7326)) **2026-09-02** v3.1.8 **Improvements:** * **OSS notices:** Notice configuration now comes from a static, cacheable repository file with a bundled disabled fallback and deterministic rollout assignment, instead of calling PostHog's feature-flag evaluation API. This keeps notices fail-safe when the remote config is unavailable and removes the PostHog feature-flag request from notice evaluation ([#7185](https://github.com/mem0ai/mem0/pull/7185)) **2026-08-24** v3.1.7 **Bug Fixes:** * **Vector Stores:** Redis and Valkey `search()` / `get()` / `list()` now preserve `agent_id`, `run_id`, and `user_id` as snake\_case in the returned payload. The shared payload formatter camelCased every key including those three identity fields, so entity ids came back as `agentId` / `runId` / `userId`, inconsistent with every other vector store ([#6902](https://github.com/mem0ai/mem0/pull/6902)) * **Memory (OSS):** Embedding-cache lookups now use `Object.prototype.hasOwnProperty.call()` instead of the `in` operator or a falsy `||` check. Memory text matching an inherited `Object.prototype` property name (`constructor`, `toString`, and similar) previously short-circuited the lookup and resolved to that inherited value instead of computing a real embedding, silently corrupting the stored vector ([#6903](https://github.com/mem0ai/mem0/pull/6903)) * **Client:** `getAll()` now sends `page` and `pageSize` as independent query params instead of requiring both to be set before either was sent. Passing only `pageSize` without `page` previously had it silently dropped, so results came back at the server's default page size ([#6900](https://github.com/mem0ai/mem0/pull/6900)) * **LLMs:** Add `providerOverride` to the Bedrock `LLMConfig`, an explicit provider name for when `model` is an application inference profile ARN whose opaque ID has no provider substring for `extractProvider()` to detect. Without it, those ARNs threw before the provider-specific settings could be initialized ([#6899](https://github.com/mem0ai/mem0/pull/6899)) **Security:** * **Dependencies:** Resolved 17 additional high and critical severity dependency vulnerabilities across 5 pnpm workspaces (`mem0-ts`, `vercel-ai-sdk`, `n8n-nodes-mem0`, `zapier-mem0`, `server/dashboard`) via `pnpm.overrides` and a `tar` patch ([#7032](https://github.com/mem0ai/mem0/pull/7032)) **2026-08-11** v3.1.6 **New Features:** * **Vector Stores:** Add an Oracle AI Vector Search vector store (`oracledb`) to the OSS SDK, with pooled connections, `HNSW`/`IVF` indexes, an optional `indexAccuracy` target, JSON payload filtering, and six selectable distance metrics ([#6690](https://github.com/mem0ai/mem0/pull/6690)) **Bug Fixes:** * **Core:** Percent-escape `%`, `&`, and `=` in `userId`, `agentId`, and `runId` when building the session scope key for the recent-conversation buffer, so the key stays unambiguous for ids containing those characters. Ordinary ids keep their existing key; an id already containing `%`, `&`, or `=` maps to a new key, so its buffer starts empty once and refills on the next `add()`. Stored memories are unaffected ([#6892](https://github.com/mem0ai/mem0/pull/6892)) * **Vector Stores:** Close and clear the Oracle pool that Mem0 created when `initialize()` fails, and reset the cached init promise so the next call retries instead of replaying the rejection forever. A caller-supplied `client` is left untouched ([#6839](https://github.com/mem0ai/mem0/pull/6839)) * **Vector Stores:** Validate Oracle `insert()` batches before touching the database: `ids` and `payloads` must match `vectors` in length, so a short array can no longer write rows with `undefined` ids or silently drop payloads ([#6839](https://github.com/mem0ai/mem0/pull/6839)) **Improvements:** * **Vector Stores:** Cut Oracle round trips. `insert()` now sends the whole batch through one `executeMany()` with explicit `bindDefs` instead of one `INSERT` per vector, `list()` reads the total from a `COUNT(*) OVER ()` window in the same statement instead of issuing a second count query, and an unfiltered `search()` adds the `VECTOR_INDEX_TRANSFORM` hint so the vector index is used ([#6835](https://github.com/mem0ai/mem0/pull/6835)) **Security:** * **Dependencies:** Patched 8 high and 18 medium severity dependency vulnerabilities across the pnpm workspace via `pnpm.overrides` (`undici`, `brace-expansion`, `ip-address`) ([#6847](https://github.com/mem0ai/mem0/pull/6847)) **2026-08-05** v3.1.5 **New Features:** * **Client:** Add `agentCustomInstructions` to `PromptUpdatePayload`, `AddMemoryOptions`, and `ProjectResponse`. It sets a second extraction instruction set that applies only to agent-scoped memories: an add passing `agentId` without `userId` uses it, one passing both splits by attribution, and while it is unset `customInstructions` continues to apply to every memory ([#6809](https://github.com/mem0ai/mem0/pull/6809)) **2026-08-04** v3.1.4 **New Features:** * **Client:** Add `referenceDate` and `keywordSearch` to `SearchMemoryOptions`, keeping the TypeScript client's typed search options in sync with the Platform API ([#6696](https://github.com/mem0ai/mem0/pull/6696)) **Bug Fixes:** * **Client:** Take the `/v1/ping/` identity/telemetry call off the request critical path. Every method previously did `if (this.telemetryId === "") await this.ping();`, blocking the first call on each client instance on a network round trip; the ping now resolves in the background through a shared, credentials-keyed promise cache (FIFO-capped at 50 entries), so concurrent clients on the same host/API key share one ping instead of issuing one each, and a failed ping is not cached so the process can retry ([#6788](https://github.com/mem0ai/mem0/pull/6788)) * **Client:** `deleteUsers()` now issues its per-entity DELETE requests through the shared `fetch()`-based helper instead of the axios instance, which defaulted to `keepAlive: false`. Deleting every user, agent, app, and run now reuses pooled connections instead of paying a fresh TCP/TLS handshake per entity ([#6788](https://github.com/mem0ai/mem0/pull/6788)) * **Memory (OSS):** Stop `add()` metadata from setting or overwriting a memory's identity scope. Metadata now runs through the same `stripIdentityKeys()` helper as `update()`, so `user_id`/`agent_id`/`run_id` (snake\_case or camelCase) and `actor_id` passed in metadata can no longer place a memory into a scope the caller didn't request through `userId`/`agentId`/`runId`/`filters` ([#6377](https://github.com/mem0ai/mem0/pull/6377)) * **Vector Stores:** Fix Redis `search()` and `list()` building an invalid, empty RediSearch filter expression when `filters` was an empty object or contained only null/undefined values. The shared `buildRedisFilterExpr()` helper now falls back to `"*"` (match all) instead of joining zero conditions into `""` ([#6014](https://github.com/mem0ai/mem0/pull/6014)) **2026-08-01** v3.1.3 **New Features:** * **Vector Stores:** Add Qdrant server-side BM25 `keywordSearch()` (requires Qdrant >= 1.15.2) plus payload filter indexes, so keyword search runs without a client-side BM25 dependency ([#5851](https://github.com/mem0ai/mem0/pull/5851)) **Bug Fixes:** * **Core:** `deleteAll()` now paginates through the vector store in batches of 1000 instead of listing once, so accounts with more memories than a single page had the remainder silently left behind ([#4872](https://github.com/mem0ai/mem0/pull/4872)) * **Vector Stores:** Supabase `list()` now paginates past PostgREST's 1000-row cap instead of stopping at the first page, `search()` warns when results may have been truncated by that same cap, and the initialization probe reads a row instead of writing a test vector, so Row Level Security policies that only grant read access no longer fail table verification ([#6695](https://github.com/mem0ai/mem0/pull/6695)) * **Embeddings:** Honor `TOGETHER_API_BASE` in the Together embedder, matching the Together LLM provider, so a custom gateway URL is no longer silently ignored for embeddings ([#6572](https://github.com/mem0ai/mem0/pull/6572)) **Changes:** * **Rerankers:** `RerankerFactory`'s default LLM reranker model is now `gpt-5-mini` (was `gpt-4o-mini`) ([#6703](https://github.com/mem0ai/mem0/pull/6703)) **Security:** * **Dependencies:** Patched 32 high and 57 medium severity dependency vulnerabilities across the pnpm workspace via `pnpm.overrides` (`axios`, `brace-expansion`, `js-yaml`, `postcss`, `protobufjs`, `mongoose`, `tar`, `fast-xml-parser`, `thrift`) ([#6639](https://github.com/mem0ai/mem0/pull/6639)) **2026-07-25** v3.1.2 **Bug Fixes:** * **Vector Stores:** Apply every operator in a Cassandra compound field filter (e.g. `{ age: { gte: 10, lte: 20 } }`) instead of stopping after the first, so the remaining bounds are no longer silently ignored ([#6511](https://github.com/mem0ai/mem0/pull/6511)) * **Vector Stores:** Stop the Chroma where-clause translator from dropping filter conditions. Same-field ranges (`gte` + `lte`), multi-field conditions inside `$or`, and negated `contains`/`icontains` under `$not` each collapsed to a single clause or vanished, widening the search instead of narrowing it ([#6521](https://github.com/mem0ai/mem0/pull/6521)) * **Vector Stores:** Skip `"*"` wildcard filter values in Milvus instead of matching them literally, so a filter like `{ user_id: "*" }` no longer returns zero memories ([#6508](https://github.com/mem0ai/mem0/pull/6508)) * **Vector Stores:** Read `textLemmatized` for BM25 keyword search on Milvus, OpenSearch, and MongoDB, matching the field the memory layer actually writes, so hybrid search on those backends no longer loses the keyword signal ([#6497](https://github.com/mem0ai/mem0/pull/6497)) * **LLMs:** Forward `responseFormat` to Gemini's `responseMimeType` in `generateResponse()`, so requesting `json_object` returns JSON instead of free-form text ([#6468](https://github.com/mem0ai/mem0/pull/6468)) * **LLMs:** Find the Anthropic text block by type instead of indexing `content[0]`, so a thinking-enabled model whose `thinking` block comes first no longer throws `Unexpected response type from Anthropic API` ([#6506](https://github.com/mem0ai/mem0/pull/6506)) **2026-07-22** v3.1.1 **New Features:** * **Embeddings:** Add an AWS Bedrock embedding provider ([#6185](https://github.com/mem0ai/mem0/pull/6185)) **Bug Fixes:** * **Packaging:** Finish the lazy-loading work started in v3.1.0. The remaining LLMs (Anthropic, Google, Groq, LangChain, Mistral, Ollama), embedders (Google, LangChain, Ollama, Vertex AI), vector stores (Azure AI Search, Azure MySQL, Baidu, LangChain, Qdrant, Redis, Supabase, Valkey, Vectorize), and the Supabase history store still imported their SDKs at module load, so importing `mem0ai/oss` required every provider package to be installed ([#6389](https://github.com/mem0ai/mem0/pull/6389)) * **Vector Stores:** Convert Baidu Mochow's raw L2 distance into a similarity score in `search()` (`1 / (1 + distance)`), so closer matches rank higher instead of lower. A row the backend returns without a score is now left `undefined` instead of being treated as the closest match ([#6485](https://github.com/mem0ai/mem0/pull/6485)) * **Memory (OSS):** Coerce non-string entity IDs (e.g. a numeric `user_id`) to strings instead of crashing on `.trim()` ([#6263](https://github.com/mem0ai/mem0/pull/6263)) * **Memory (OSS):** Stop `update()` metadata from overwriting or injecting `user_id`, `agent_id`, `run_id`, or `actor_id` (in either snake\_case or camelCase). These identity fields are immutable after creation, so passing them in `metadata` can no longer move a memory into a different tenant's scope ([#6343](https://github.com/mem0ai/mem0/pull/6343)) * **Vector Stores:** Scope Pinecone `deleteCol()`/`reset()` to the configured namespace instead of deleting the whole index, so resetting a namespaced Pinecone store no longer wipes out the other namespaces sharing that index ([#6287](https://github.com/mem0ai/mem0/pull/6287)) **Changes:** * **Client:** Remove the unused `retrievalCriteria` field from `PromptUpdatePayload`. It was accepted and forwarded but never affected retrieval, so removing it is not a behavior change ([#6313](https://github.com/mem0ai/mem0/pull/6313)) **2026-07-13** v3.1.0 The largest provider release for the TypeScript OSS SDK so far: 17 new vector stores, 5 new LLM providers, 4 new embedders, and reranking support. Importing `mem0ai/oss` no longer pulls in any provider SDK, so you only install what you actually configure. **New Features:** * **Rerankers:** Add reranking to the OSS SDK with four providers (Cohere, ZeroEntropy, cross-encoder, and LLM-based), plus per-search rerank via a `rerank` option on `search()` ([#6055](https://github.com/mem0ai/mem0/pull/6055)) * **Memory (OSS):** Accept `text` in `Memory.update()`. `data` still works but is now deprecated, so prefer `text` in new code ([#6044](https://github.com/mem0ai/mem0/pull/6044)) * **Vector Stores:** Add Pinecone ([#5802](https://github.com/mem0ai/mem0/pull/5802)), Weaviate ([#5800](https://github.com/mem0ai/mem0/pull/5800)), Milvus ([#5889](https://github.com/mem0ai/mem0/pull/5889)), Chroma ([#6145](https://github.com/mem0ai/mem0/pull/6145)), MongoDB ([#5793](https://github.com/mem0ai/mem0/pull/5793)), Elasticsearch ([#5866](https://github.com/mem0ai/mem0/pull/5866)), and OpenSearch ([#5810](https://github.com/mem0ai/mem0/pull/5810)) * **Vector Stores:** Add Databricks ([#5824](https://github.com/mem0ai/mem0/pull/5824)), AWS Neptune Analytics ([#5797](https://github.com/mem0ai/mem0/pull/5797)), S3 Vectors ([#5822](https://github.com/mem0ai/mem0/pull/5822)), Azure MySQL ([#5827](https://github.com/mem0ai/mem0/pull/5827)), and Google Vertex AI Vector Search ([#5791](https://github.com/mem0ai/mem0/pull/5791)) * **Vector Stores:** Add Turbopuffer ([#5801](https://github.com/mem0ai/mem0/pull/5801)), Upstash Vector ([#5811](https://github.com/mem0ai/mem0/pull/5811)), Valkey ([#5826](https://github.com/mem0ai/mem0/pull/5826)), Cassandra ([#5823](https://github.com/mem0ai/mem0/pull/5823)), and Baidu Mochow ([#5790](https://github.com/mem0ai/mem0/pull/5790)) * **LLMs:** Add AWS Bedrock ([#5890](https://github.com/mem0ai/mem0/pull/5890)), xAI Grok ([#6115](https://github.com/mem0ai/mem0/pull/6115)), Together ([#6049](https://github.com/mem0ai/mem0/pull/6049)), vLLM ([#5805](https://github.com/mem0ai/mem0/pull/5805)), and Sarvam ([#6130](https://github.com/mem0ai/mem0/pull/6130)) * **Embeddings:** Add Vertex AI ([#5882](https://github.com/mem0ai/mem0/pull/5882)), HuggingFace ([#6027](https://github.com/mem0ai/mem0/pull/6027)), FastEmbed ([#5862](https://github.com/mem0ai/mem0/pull/5862)), and Together ([#5989](https://github.com/mem0ai/mem0/pull/5989)) **Improvements:** * **Packaging:** Lazy-load optional provider SDKs so importing `mem0ai/oss` never requires them. Provider packages are now resolved on first use, so an app that only configures OpenAI and Qdrant does not need the other provider SDKs installed ([#6280](https://github.com/mem0ai/mem0/pull/6280)) **Bug Fixes:** * **Memory (OSS):** Re-raise LLM extraction transport failures instead of returning `[]`, so a network error during extraction surfaces as an error rather than a silently empty result ([#6102](https://github.com/mem0ai/mem0/pull/6102)) * **Vector Stores:** Prevent an unhandled promise rejection in the Supabase and Redis constructors ([#6111](https://github.com/mem0ai/mem0/pull/6111)) * **Client:** Encode dynamic URL path segments so IDs containing special characters no longer produce malformed requests ([#5963](https://github.com/mem0ai/mem0/pull/5963)) **Security:** * **Dependencies:** Patch the `fast-xml-parser` and `tar` transitive CVEs ([#6160](https://github.com/mem0ai/mem0/pull/6160)) **2026-07-01** v3.0.13 **Bug Fixes:** * **Embeddings:** Guard against an `embed_batch` count mismatch in the OpenAI and Azure OpenAI embedders ([#5966](https://github.com/mem0ai/mem0/pull/5966)) * **LLMs:** Handle empty Google chat candidates without crashing ([#5817](https://github.com/mem0ai/mem0/pull/5817)) **2026-06-27** v3.0.12 **New Features:** * **Client:** Add `expirationDate` to `AddMemoryOptions`, `update()`, and the `Memory` interface; add `showExpired` to `SearchMemoryOptions` and `GetAllMemoryOptions` ([#5874](https://github.com/mem0ai/mem0/pull/5874)) * **LLMs:** Add `MiniMaxLLM` provider backed by the OpenAI-compatible MiniMax API (`api.minimax.io/v1`, default model `MiniMax-M2.7`) ([#5858](https://github.com/mem0ai/mem0/pull/5858)) * **LLMs:** Add `LiteLLM` provider for routing requests through a local or hosted LiteLLM proxy ([#5830](https://github.com/mem0ai/mem0/pull/5830)) * **Vector Stores:** Add `connectionString` and `ssl` options to the PGVector config, allowing connection via URI instead of individual host/user/password/port fields ([#5789](https://github.com/mem0ai/mem0/pull/5789)) **Bug Fixes:** * **Memory (OSS):** Validate and trim entity IDs (`userId`, `agentId`, `runId`) in `deleteAll()` via `validateAndTrimEntityId` ([#5735](https://github.com/mem0ai/mem0/pull/5735)) * **Vector Stores:** Use nullish coalescing for `hash` and timestamps in the Redis `insert()` and `update()` paths so entity payloads that omit those fields no longer crash ([#5860](https://github.com/mem0ai/mem0/pull/5860)) **Security:** * **Dependencies:** Bump `undici` to `>=6.27.0` via pnpm override to remediate CVE-2026-12151 ([#5861](https://github.com/mem0ai/mem0/pull/5861)) **2026-06-24** v3.0.11 **Bug Fixes:** * **Memory (OSS):** Align entity extraction with Python by reducing generic entity noise, preserving useful topic phrases, and exact-deduplicating entity links before semantic matching ([#5829](https://github.com/mem0ai/mem0/pull/5829)) **2026-06-24** v3.0.10 **Bug Fixes:** * **Memory (OSS):** Guard against malformed `image_url` entries in `parseVisionMessages` to prevent crashes ([#5631](https://github.com/mem0ai/mem0/pull/5631)) * **Memory (OSS):** Return `attributedTo` from `get()`, `search()`, and `getAll()` ([#5675](https://github.com/mem0ai/mem0/pull/5675)) * **Memory (OSS):** Preserve message roles in the extraction input so assistant facts aren't attributed to the user ([#5643](https://github.com/mem0ai/mem0/pull/5643)) * **Memory (OSS):** Reject empty or blank messages in `Memory.add()` to prevent hallucinated memories ([#5545](https://github.com/mem0ai/mem0/pull/5545)) * **Memory (OSS):** Check `message.role` instead of `content` when detecting system messages ([#3921](https://github.com/mem0ai/mem0/pull/3921)) * **LLMs:** Honor the configured `baseURL` in `AnthropicLLM` ([#5740](https://github.com/mem0ai/mem0/pull/5740)) * **Client:** Preserve `customCategories` names through key conversion ([#5741](https://github.com/mem0ai/mem0/pull/5741)) * **Client:** Prevent hallucinated memories on an empty messages payload ([#5613](https://github.com/mem0ai/mem0/pull/5613)) * **Client:** Preserve user metadata keys across the case-conversion round-trip ([#5515](https://github.com/mem0ai/mem0/pull/5515)) **Security:** * **Dependencies:** Upgrade `form-data` to `>=4.0.6` across pnpm workspaces to remediate CVE-2026-12143 ([#5618](https://github.com/mem0ai/mem0/pull/5618)) **2026-06-17** v3.0.9 **Bug Fixes:** * **LLMs:** Fix Anthropic `tool_choice` format: was incorrectly sent as a bare string `"auto"` (rejected by the API); now correctly sent as `{ type: "auto" }`. Also fixes tool response parsing: `tool_use` blocks are now parsed into `toolCalls` objects instead of throwing. Updated default model to `claude-sonnet-4-6` and default `max_tokens` to `2000` to match the Python provider. Added `temperature`, `topP`, and `maxTokens` to `LLMConfig` so Anthropic params can be configured ([#5537](https://github.com/mem0ai/mem0/pull/5537)) * **Memory (OSS):** Preserve custom metadata fields during `update()`: fields such as `category`, `priority`, and other user-defined keys were previously dropped on update; the existing payload is now spread before applying the new data ([#5480](https://github.com/mem0ai/mem0/pull/5480)) * **Client:** Preserve user-defined schema keys in `createMemoryExport` ([#5594](https://github.com/mem0ai/mem0/pull/5594)) **Security:** * **Dependencies:** Bump `esbuild` to `>=0.28.1` across all npm packages via pnpm overrides to remediate upstream vulnerability ([#5563](https://github.com/mem0ai/mem0/pull/5563)) **2026-06-13** v3.0.8 **New Features:** * **Memory:** Add a contextual OSS-to-Platform notices system that surfaces occasional, situation-aware messages (first run, scale/performance thresholds, slow queries, and when temporal/decay features are relevant) pointing to the corresponding Mem0 Platform capabilities; disable via `MEM0_TELEMETRY=false` ([#5494](https://github.com/mem0ai/mem0/pull/5494)) **Security:** * **Dependencies:** Upgrade `@langchain/community` to `^1.1.18` to remediate CVE-2026-27795 and CVE-2026-26019 ([#5510](https://github.com/mem0ai/mem0/pull/5510)) * **Dependencies:** Resolve all open MEDIUM Dependabot alerts via pnpm overrides ([#5489](https://github.com/mem0ai/mem0/pull/5489)) **2026-06-10** v3.0.7 **New Features:** * **Embeddings:** Add `LMStudioEmbedding` provider for local embeddings via the LM Studio server ([#5377](https://github.com/mem0ai/mem0/pull/5377)) * **Memory:** Add opt-in `explain: true` option to `Memory.search()`. When enabled, each result includes a `scoreBreakdown` object with `semantic`, `keyword`, `entityBoost`, and `temporalBoost` fields so callers can inspect and tune retrieval ranking ([#5102](https://github.com/mem0ai/mem0/pull/5102)) **Bug Fixes:** * **Memory:** Parallelize entity boost searches in `Memory.search()`. All entity embed + store lookups now run concurrently instead of sequentially, eliminating multi-second latency on entity-rich queries with remote embedding providers ([#5377](https://github.com/mem0ai/mem0/pull/5377)) * **Vector Stores:** Normalize similarity scores to `[0, 1]` (higher = better): fixed score inversion in the Redis vector store adapter ([#5391](https://github.com/mem0ai/mem0/pull/5391)) * **Embeddings:** Request `encoding_format: "float"` from the OpenAI embedder in both `embed()` and `embedBatch()`. Fixes incorrect vector dimensions when using OpenAI-compatible proxies that default to base64 encoding ([#5170](https://github.com/mem0ai/mem0/pull/5170)) **2026-06-01** v3.0.6 **Security:** * **Dependencies:** Bumped `axios` to `^1.16.0` to remediate high-severity prototype-pollution CVEs (credential theft, MITM, DoS). Pinned transitive dependencies via pnpm overrides: `jws` → 4.0.1 (CVE-2025-65945), `langsmith` → ^0.6.0 (CVE-2026-45134), `tar-fs` → ^2.1.4 (CVE-2025-48387, CVE-2025-59343), `picomatch` → ^2.3.2 (CVE-2026-33671), `minimatch` → ^3.1.3 / ^5.1.8 / ^9.0.7 (CVE-2026-27903, CVE-2026-27904, CVE-2026-26996), `path-to-regexp` → ^8.4.0 (CVE-2026-4926), `rollup` → ^4.59.0 (CVE-2026-27606), `glob` → ^10.5.0 (CVE-2025-64756), `@modelcontextprotocol/sdk` → ^1.25.4 (CVE-2025-66414, CVE-2026-0621) **2026-05-27** v3.0.5 **New Features:** * **Client:** `delete()` accepts an options object with `deleteLinked` (serialized as `delete_linked`, default `false`). When `true`, deleting a memory also removes the older memories it superseded (the v3 linked chain), transitively: the delete-side counterpart of `latestOnly`, so a superseded memory does not resurface after the current one is deleted ([#5270](https://github.com/mem0ai/mem0/pull/5270)) **2026-05-26** v3.0.4 **Bug Fixes:** * **Vector Stores:** PGVector adapter now supports rich filter operators (`eq`, `ne`, `gt`, `gte`, `lt`, `lte`, `in`, `nin`, `contains`, `icontains`, wildcard `*`, `$or`, `$not`) in `search()`, `keywordSearch()`, and `list()`. Previously only exact-equality filters worked: operator objects were passed as raw values and returned incorrect results ([#5263](https://github.com/mem0ai/mem0/pull/5263)) **2026-05-08** v3.0.3 **Bug Fixes:** * **Telemetry:** Stitch OSS and platform PostHog identities on `MemoryClient` init so `$identify` events fire and a single user is no longer tracked as two or three disconnected personas ([#5040](https://github.com/mem0ai/mem0/pull/5040)) * **Vector Stores:** Fix inverted vector distance in PGVector implementation ([#4944](https://github.com/mem0ai/mem0/pull/4944)) * **Security:** Harden against SQL injection and prompt injection ([#4997](https://github.com/mem0ai/mem0/pull/4997)) **New Features:** * **SDK:** Expose `decay` on `project.update` ([#5062](https://github.com/mem0ai/mem0/pull/5062)) **2026-04-25** v3.0.2 **Bug Fixes:** * **LLMs:** Forward `timeout` config to OpenAI client in JS OSS LLM providers ([#4770](https://github.com/mem0ai/mem0/pull/4770)) **Improvements:** * **Telemetry:** Harden TS telemetry version injection and require changelog entry on version bump ([#4900](https://github.com/mem0ai/mem0/pull/4900)) * **Docs:** Update memory tool list, CLI usage, and config file reading logic ([#4861](https://github.com/mem0ai/mem0/pull/4861)) **2026-04-20** v3.0.1 **Bug Fixes:** * **Telemetry:** SDK version is now injected into telemetry at build time via esbuild's `define`, replacing the two hardcoded version strings in `src/client/telemetry.ts` and `src/oss/src/utils/telemetry.ts`. Previously these were stuck at `2.1.36` and `2.1.34` while the published package was on `3.x`, so every telemetry event was reporting the wrong `client_version`. The placeholder is substituted with a string literal at bundle time: no runtime `require("./package.json")` in the shipped bundle ([#4897](https://github.com/mem0ai/mem0/pull/4897)). **2026-04-14** v3.0.0 **Major Release**: TypeScript SDK with V3 memory pipeline, camelCase parameters, and cleaned-up API surface. **V3 Memory Pipeline (OSS):** * **Single-Pass Extraction:** Additive extraction pipeline aligned with Python SDK: memories accumulate, no UPDATE/DELETE events ([#4805](https://github.com/mem0ai/mem0/pull/4805)) * **Entity Extraction & Linking:** New `entity_extraction.ts` module (720+ lines) with cross-memory relationship retrieval ([#4805](https://github.com/mem0ai/mem0/pull/4805)) * **Message Persistence:** SQLite-based message history via new `SQLiteManager.ts` with rolling window for LLM context ([#4805](https://github.com/mem0ai/mem0/pull/4805)) * **Batch Embeddings:** `embedBatch()` support in OpenAI and Azure embedding providers ([#4805](https://github.com/mem0ai/mem0/pull/4805)) * **Scoring & Lemmatization:** New `scoring.ts` and `lemmatization.ts` utilities for hybrid search ([#4805](https://github.com/mem0ai/mem0/pull/4805)) * **New Prompts:** `prompts/index.ts` (592+ lines) with additive extraction prompt aligned with Python SDK ([#4805](https://github.com/mem0ai/mem0/pull/4805)) * **V3 API Endpoints:** `MemoryClient.add()` now posts to `/v3/memories/add/`; `MemoryClient.getAll()` posts to `/v3/memories/` with paginated envelope `{ count, next, previous, results }` ([#4856](https://github.com/mem0ai/mem0/pull/4856)) * **Default model:** `gpt-5-mini` is now the default in `OpenAI`, `OpenAIStructured`, and `Azure` LLM providers ([#4829](https://github.com/mem0ai/mem0/pull/4829)) **Breaking Changes:** * **External Graph Store Removed (OSS):** `graph_memory.ts` (675 lines), `graphs/tools.ts` (267 lines), `graphs/utils.ts` (116 lines), `graphs/configs.ts` (30 lines) deleted. The external graph store integration is no longer part of the OSS SDK; graph memory now runs natively as built-in entity linking ([#4805](https://github.com/mem0ai/mem0/pull/4805)) * **camelCase Parameters (Client SDK):** All user-facing parameters converted from snake\_case to camelCase. Mapping is transparent at API boundary via `camelToSnakeKeys()` / `snakeToCamelKeys()` ([#4776](https://github.com/mem0ai/mem0/pull/4776)) ```typescript theme={null} // Before client.add(messages, { user_id: "alice", top_k: 5 }); // After client.add(messages, { userId: "alice", topK: 5 }); ``` * **Per-Method Option Types:** Replaced monolithic `MemoryOptions` with typed interfaces: `AddMemoryOptions`, `SearchMemoryOptions`, `GetAllMemoryOptions`, `DeleteAllMemoryOptions` ([#4740](https://github.com/mem0ai/mem0/pull/4740)) * **Removed Deprecated Parameters:** `org_id`, `project_id`, `api_version`, `output_format`, `async_mode`, `enable_graph`, `limit` removed from client method signatures. `ClientOptions` reduced to `{ apiKey, host }` only ([#4740](https://github.com/mem0ai/mem0/pull/4740)) * **`limit` renamed to `topK` (OSS):** Update all search calls ([#4740](https://github.com/mem0ai/mem0/pull/4740)) * **`topK` default changed 100 → 20** in `Memory.getAll()` and `Memory.search()`. Pass `topK: 100` explicitly to restore the old behavior ([#4843](https://github.com/mem0ai/mem0/pull/4843)) * **Entity ID validation:** `userId` / `agentId` / `runId` are trimmed; empty-string and whitespace-only values now throw ([#4843](https://github.com/mem0ai/mem0/pull/4843)) * **Search params validation:** `threshold` must be in `[0, 1]`; `topK` must be a non-negative integer: invalid inputs throw ([#4843](https://github.com/mem0ai/mem0/pull/4843)) * **`messages` in `Memory.add()` is required:** Passing `undefined` or `null` now throws ([#4843](https://github.com/mem0ai/mem0/pull/4843)) * **`customPrompt` renamed to `customInstructions` (OSS):** Update memory and vector store configurations ([#4740](https://github.com/mem0ai/mem0/pull/4740)) * **`enableGraph` removed (OSS):** Config option removed: graph memory no longer available in OSS ([#4776](https://github.com/mem0ai/mem0/pull/4776)) **New Features:** * **LLMs:** Added DeepSeek LLM provider with OpenAI-compatible integration using custom baseURL to `api.deepseek.com` ([#4613](https://github.com/mem0ai/mem0/pull/4613)) * **Entity store isolation:** `MemoryVectorStore` now uses a dedicated `_entities.db` file, preventing entity/memory store collisions ([#4829](https://github.com/mem0ai/mem0/pull/4829), [#4841](https://github.com/mem0ai/mem0/pull/4841)) * **Payload backward compatibility:** Legacy camelCase payload keys normalized to snake\_case on read ([#4841](https://github.com/mem0ai/mem0/pull/4841)) **Bug Fixes:** * **V3 migration:** Fixed crashes in the OSS migration path; entity linking works end-to-end ([#4836](https://github.com/mem0ai/mem0/pull/4836)) * **PGVector init race:** `PGVector.initialize()` now memoises the in-flight init promise ([#4841](https://github.com/mem0ai/mem0/pull/4841)) * **Redis module detection:** Handles both node-redis v4+ and legacy `moduleList` response shapes ([#4841](https://github.com/mem0ai/mem0/pull/4841)) * **Config:** Fixed `ConfigManager.mergeConfig()` to only include `graphStore` when explicitly provided by user, preventing default Neo4j connection attempts ([#4776](https://github.com/mem0ai/mem0/pull/4776)) * **LLMs:** Config manager now falls back to `userConf.url` for `baseURL`: prevents custom LLM providers (Ollama, LMStudio) from silently connecting to OpenAI ([#4761](https://github.com/mem0ai/mem0/pull/4761)) **Improvements:** * **Telemetry:** Sample OSS hot-path events at 10% to reduce PostHog event volume ([#4771](https://github.com/mem0ai/mem0/pull/4771)) See the [OSS v2 to v3 migration guide](https://docs.mem0.ai/migration/oss-v2-to-v3) for upgrade instructions. **2026-04-06** v2.4.6 **New Features & Updates:** * **Client:** Added `multilingual` parameter to project update types ([#4314](https://github.com/mem0ai/mem0/pull/4314)) **2026-04-01** v2.4.5 **Bug Fixes:** * **OSS:** Replace `.single()` with `.maybeSingle()` in SupabaseDB.get() to handle missing rows ([#4599](https://github.com/mem0ai/mem0/pull/4599)) * **Embeddings:** Pass dimensions parameter to OpenAI embeddings API ([#4632](https://github.com/mem0ai/mem0/pull/4632)) * **OSS:** Extract JSON from chatty LLM responses in fact retrieval ([#4533](https://github.com/mem0ai/mem0/pull/4533)) **2026-03-28** v2.4.4 **Bug Fixes:** * **OSS:** Fixed Qdrant Cloud "Illegal host" error by defaulting to port 6333 when URL has no explicit port ([#4565](https://github.com/mem0ai/mem0/pull/4565)) **2026-03-26** v2.4.3 **New Features & Updates:** * **OSS:** Added pgvector support to NodeJS OSS `VectorStoreFactory` ([#3997](https://github.com/mem0ai/mem0/pull/3997)) **Bug Fixes:** * **OSS:** Made pgvector `pg` import compatible with ESM ([#4544](https://github.com/mem0ai/mem0/pull/4544)) * **OSS:** Registered pgvector in `VectorStoreFactory` ([#4502](https://github.com/mem0ai/mem0/pull/4502)) * **OSS:** Used root LLM config as fallback for graph store instead of hardcoded OpenAI default ([#4466](https://github.com/mem0ai/mem0/pull/4466)) * **OSS:** Fixed `toCamelCase` in Redis `get` method for the payload ([#3172](https://github.com/mem0ai/mem0/pull/3172)) * **Client:** Fixed Zod Schema incompatibility with OpenAI Structured Outputs API ([#3462](https://github.com/mem0ai/mem0/pull/3462)) **2026-03-19** v2.4.2 **Bug Fixes:** * **Client:** Fixed webhook `createWebhook` and `updateWebhook` API serialization * **Client:** Added missing `MEMORY_CATEGORIZED` event type to `WebhookEvent` enum * **Types:** Added `WebhookCreatePayload` and `WebhookUpdatePayload` for better type safety **Tests:** * Added end-to-end unit test coverage for the platform client: CRUD, batch, search, webhooks, users, project, and initialization (#4357) * Added real API integration tests for memory CRUD, batch operations, search, user management, project configuration, and webhook lifecycle (#4395) * Deleted obsolete e2e test files replaced by the new structured test suite (#4419) **2026-03-16** v2.4.1 **Bug Fixes:** * **Core:** Fixed code block content extraction: content inside code blocks is now properly extracted instead of being deleted (#4317) **Improvements:** * **Code Quality:** Fixed linting issues across the SDK (#4334) **2026-03-14** v2.4.0 **Bug Fixes:** * **OSS Storage:** Fixed `SQLITE_CANTOPEN` errors when running as a LaunchAgent, systemd service, or in containers where `process.cwd()` is read-only (e.g. `/`). Default `vector_store.db` location changed from `process.cwd()/vector_store.db` to `~/.mem0/vector_store.db`. * **OSS Storage:** Fixed `historyDbPath` config being silently ignored: config merging always overwrote it with defaults. Top-level `historyDbPath` is now correctly propagated into `historyStore.config` with proper precedence. * **OSS Storage:** Added `ensureSQLiteDirectory()`: parent directories for SQLite database files are now auto-created before opening, preventing `SQLITE_CANTOPEN` when using nested paths. **Improvements:** * **Migration:** Added deprecation warning when an existing `vector_store.db` is found at the old `process.cwd()` location, guiding users to move it or set `vectorStore.config.dbPath` explicitly. * **Config:** Limited default SQLite config spreading to only SQLite history providers, preventing config leaking into Supabase or other providers. **2026-03-09** v2.3.0 **Breaking Changes:** * **Dependencies:** Minimum Node.js version for OSS sqlite features is now Node 20+ (due to `better-sqlite3` v12) **Bug Fixes:** * **OSS Storage:** Replaced `sqlite3` with `better-sqlite3` to fix native binding resolution failures under jiti-based loaders (e.g. OpenClaw plugin system). Fixes issues where the `bindings` module walked V8 stack frames with synthetic filenames, failing to locate the native `.node` addon. * **OSS Storage:** Fixed async init race condition in `SQLiteManager`: `init()` is now synchronous * **OSS Vector Store:** Migrated `MemoryVectorStore` from `sqlite3` to `better-sqlite3` with transactional batch inserts **Improvements:** * **Performance:** Cached prepared statements in `SQLiteManager` for faster history operations * **Performance:** Batch `insert()` in `MemoryVectorStore` wrapped in a transaction for atomicity * **Build:** Updated `tsup.config.ts` externals from `sqlite3` to `better-sqlite3` **2026-02-17** v2.2.3 **New Features & Updates:** * **Memory Update:** * Added `timestamp` parameter to `update()`: accepts Unix epoch or ISO 8601 string **2026-01-29** v2.2.2 **New Features & Updates:** * **Project Settings:** * Added inclusion prompt, exclusion prompt, memory depth, and usecase setting **2025-12-30** v2.2.1 **Improvements:** * **Client:** Added support for keyword arguments in `add` and `search` methods, allowing additional properties beyond defined options for experimental features **2025-12-29** v2.2.0 **New Features:** * **Vector Stores:** Added Azure AI Search vector store support **Improvements:** * **Config:** Fixed embedder config schema to support `embeddingDims` and `url` parameters * **Graph Memory:** Replaced hardcoded LLM provider with provider from configuration **Bug Fixes:** * **Embedders:** Fixed hardcoded `embeddingDims` values in embedders (OpenAI, Ollama, Google, Azure) * **Build:** Fixed TypeScript build errors **2025-09-04** v2.1.38 **New Features:** * **Client:** Added `metadata` param to `update` method. **2025-08-04** v2.1.37 **New Features:** * **OSS:** Added `RedisCloud` search module check **2025-07-08** v2.1.36 **New Features:** * **Client:** Added `structured_data_schema` param to `add` method. **2025-07-08** v2.1.35 **New Features:** * **Client:** Added `createMemoryExport` and `getMemoryExport` methods. **2025-07-03** v2.1.34 **New Features:** * **OSS:** Added Gemini support **2025-06-24** v2.1.33 **Improvement:** * **Client:** Added `immutable` param to `add` method. **2025-06-20** v2.1.32 **Improvement:** * **Client:** Made `api_version` V2 as default. **2025-06-17** v2.1.31 **Improvement:** * **Client:** Added param `filter_memories`. **2025-06-06** v2.1.30 **New Features:** * **OSS:** Added Cloudflare support **Improvements:** * **OSS:** Fixed baseURL param in LLM Config. **2025-05-30** v2.1.29 **Improvements:** * **Client:** Added Async Mode Param for `add` method. **2025-05-30** v2.1.28 **Improvements:** * **SDK:** Update Google SDK Peer Dependency Version. **2025-05-27** v2.1.27 **Improvements:** * **OSS:** Added baseURL param in LLM Config. **2025-05-23** v2.1.26 **Improvements:** * **Client:** Removed type `string` from `messages` interface **2025-05-08** v2.1.25 **Improvements:** * **Client:** Improved error handling in client. **2025-05-06** v2.1.24 **New Features:** * **Client:** Added new param `output_format` to match Python SDK. * **Client:** Added new enum `OutputFormat` for `v1.0` and `v1.1` **2025-05-05** v2.1.23 **New Features:** * **Client:** Updated `deleteUsers` to use `v2` API. * **Client:** Deprecated `deleteUser` and added deprecation warning. **2025-05-02** v2.1.22 **New Features:** * **Client:** Updated `deleteUser` to use `entity_id` and `entity_type` **2025-05-01** v2.1.21 **Improvements:** * **OSS SDK:** Bumped version of `@anthropic-ai/sdk` to `0.40.1` **2025-04-28** v2.1.20 **Improvements:** * **Client:** Fixed `organizationId` and `projectId` being assigned to default in `ping` method **2025-04-22** v2.1.19 **Improvements:** * **Client:** Added support for `timestamps` **2025-04-17** v2.1.18 **Improvements:** * **Client:** Added support for custom instructions **2025-04-15** v2.1.17 **New Features:** * **OSS SDK:** Added support for Langchain LLM * **OSS SDK:** Added support for Langchain Embedder * **OSS SDK:** Added support for Langchain Vector Store * **OSS SDK:** Added support for Azure OpenAI Embedder **Improvements:** * **OSS SDK:** Changed `model` in LLM and Embedder to use type any from `string` to use langchain llm models * **OSS SDK:** Added client to vector store config for langchain vector store * **OSS SDK:** - Updated Azure OpenAI to use new OpenAI SDK **2025-04-11** v2.1.16-patch.1 **Bug Fixes:** * **Azure OpenAI:** Fixed issues with Azure OpenAI **2025-04-11** v2.1.16 **New Features:** * **Azure OpenAI:** Added support for Azure OpenAI * **Mistral LLM:** Added Mistral LLM integration in OSS **Improvements:** * **Zod:** Updated Zod to 3.24.1 to avoid conflicts with other packages **2025-04-09** v2.1.15 **Improvements:** * **Client:** Added support for Mem0 to work with Chrome Extensions **2025-04-01** v2.1.14 **New Features:** * **Mastra Example:** Added Mastra example * **Integrations:** Added Flowise integration documentation for Mem0 memory setup **Improvements:** * **Demo:** Updated Demo Mem0AI * **Client:** Enhanced Ping method in Mem0 Client * **AI SDK:** Updated AI SDK implementation **2025-03-29** v2.1.13 **Improvements:** * **Introduced `ping` method to check if API key is valid and populate org/project id** **2025-03-29** AI SDK v1.0.0 **New Features:** * **Vercel AI SDK Update:** Support threshold and rerank **Improvements:** * **Made add calls async to avoid blocking** * **Bump `mem0ai` to use `2.1.12`** **2025-03-26** v2.1.12 **New Features:** * **Mem0 OSS:** Support infer param **Improvements:** * **Updated Supabase TS Docs** * **Made package size smaller** **2025-03-19** v2.1.11 **New Features:** * **Supabase Vector Store Integration** * **Feedback Method** **CLI** **2026-09-18** Python v0.2.13 / Node v0.2.14 **Improvements:** * **Client:** Requests now carry the three surface-identity headers (`X-Mem0-Source`, `X-Application`, `X-Mem0-Client`) introduced in the Python and TypeScript SDKs, so the platform can attribute calls made through the CLI to the correct surface and version ([#7326](https://github.com/mem0ai/mem0/pull/7326)) **2026-08-24** Python v0.2.12 / Node v0.2.13 **New Features:** * **`version`:** New `mem0 version` subcommand, alongside the existing `--version` flag, so scripts and agent harnesses can read the CLI version as a regular subcommand instead of a root-level flag (Python and Node [#6907](https://github.com/mem0ai/mem0/pull/6907)) * **`add`:** New `--agent-custom-instructions` flag, threaded through to `agent_custom_instructions` on the `/v3/memories/add/` payload: a second extraction instruction set that applies only to agent-scoped memories, matching the SDKs' `agentCustomInstructions` / `agent_custom_instructions` support (Python and Node [#6910](https://github.com/mem0ai/mem0/pull/6910)) **Documentation:** * **`search --filter`:** The `--filter` help text and `docs/platform/cli.mdx` now spell out the JSON shape (`{"AND": [...]}` / `{"OR": [...]}`) with a concrete example instead of just calling it "an advanced filter expression," and a matching example command was added to both the CLI help text and the docs page (Python and Node [#6907](https://github.com/mem0ai/mem0/pull/6907)) **2026-08-04** Python v0.2.11 / Node v0.2.12 **New Features:** * **`add`:** New `--custom-instructions`, `--custom-categories`, `--structured-data-schema`, and `--timestamp` flags, matching the Platform `/v3/memories/add/` payload fields (Python and Node [#6696](https://github.com/mem0ai/mem0/pull/6696)) * **`search`:** New `--show-expired`, `--reference-date`, and `--latest-only` flags, forwarded to `/v3/memories/search/` as `show_expired`, `reference_date`, and `latest_only` (Python and Node [#6696](https://github.com/mem0ai/mem0/pull/6696)) * **`list`:** New `--show-expired` and `--latest-only` flags (Python and Node [#6696](https://github.com/mem0ai/mem0/pull/6696)) * **`update`:** New `--expires` and `--timestamp` flags (Python and Node [#6696](https://github.com/mem0ai/mem0/pull/6696)) * **`delete`:** New `--delete-linked` flag to also delete memories linked to the target memory (Python and Node [#6696](https://github.com/mem0ai/mem0/pull/6696)) **Bug Fixes:** * **`help --json`:** Emit JSON automatically under agent mode (`--agent`), not only when `--json` is passed explicitly. Python checks `is_agent_mode()` and now renders through `console.print_json()` instead of a plain `console.print(json.dumps(...))` call; Node also checks the root `--agent` flag in addition to the subcommand's `--json` flag (Python and Node [#6773](https://github.com/mem0ai/mem0/pull/6773)) **Changes:** * **`add`:** `--categories` is no longer forwarded on `add`. The `/v3/memories/add/` payload has no `categories` field (only `custom_categories`), so the CLI was sending a key the endpoint does not accept. Passing the flag now exits 1 with a message pointing to `--custom-categories` (Python and Node [#6696](https://github.com/mem0ai/mem0/pull/6696)) **Security:** * **Dependencies (Node):** Tighten the `postcss` pnpm override from `<8.5.10 → >=8.5.10` to `<8.5.18 → >=8.5.18 <9.0.0`, closing a newer CVE range the previous floor didn't cover, as part of a wider dependency patch sweep across the pnpm workspaces ([#6639](https://github.com/mem0ai/mem0/pull/6639)) **2026-07-13** Python v0.2.10 / Node v0.2.11 **Bug Fixes:** * **Platform backend:** Encode dynamic URL path segments so memory and entity IDs containing special characters no longer produce malformed requests (Python and Node [#5963](https://github.com/mem0ai/mem0/pull/5963)) **2026-07-01** Python v0.2.9 / Node v0.2.10 **Bug Fixes:** * **`entity delete`:** Keep every deleted entity in the result output instead of only the last one (Python [#5936](https://github.com/mem0ai/mem0/pull/5936), Node [#5970](https://github.com/mem0ai/mem0/pull/5970)) * **Output formatters (Python):** Handle null memory fields in the output formatters instead of erroring ([#5957](https://github.com/mem0ai/mem0/pull/5957)) * **Config (Python):** Reject invalid integer config values with a clean error instead of a traceback ([#5956](https://github.com/mem0ai/mem0/pull/5956)) **2026-06-19** Python v0.2.8 / Node v0.2.9 **Security:** * **Telemetry key handling:** CLI telemetry no longer passes the Mem0 API key to a child process through command-line arguments. The context is sent over stdin, so the key is not visible in `ps`, `/proc//cmdline`, or Activity Monitor. Fixes #4862. **Bug Fixes:** * **Python package version:** `__version__` now matches the packaged `mem0-cli` version. **2026-06-01** Node v0.2.8 **Security:** * **Dependencies:** Pinned transitive dependencies via pnpm overrides to remediate high-severity CVEs: `jws` → 4.0.1 (CVE-2025-65945), `langsmith` → ^0.6.0 (CVE-2026-45134), `tar-fs` → ^2.1.4 (CVE-2025-48387, CVE-2025-59343), `picomatch` → ^2.3.2 (CVE-2026-33671), `minimatch` → ^3.1.3 / ^5.1.8 / ^9.0.7 (CVE-2026-27903, CVE-2026-27904, CVE-2026-26996), `path-to-regexp` → ^8.4.0 (CVE-2026-4926), `rollup` → ^4.59.0 (CVE-2026-27606), `glob` → ^10.5.0 (CVE-2025-64756), `@modelcontextprotocol/sdk` → ^1.25.4 (CVE-2025-66414, CVE-2026-0621) **2026-05-20** Python v0.2.7 / Node v0.2.7 **New Features:** * **`mem0 whoami`:** Prints the active agent's `default_user_id` from local config without a network call. * **`mem0 agent-rush `:** Wraps the `/v1/agent-rush/` platform endpoints for the AGENTRUSH game. Project routing is resolved server-side, and platform error codes are shown as actionable hints. * **PII safety prompt:** The first interactive `mem0 agent-rush add` asks users to acknowledge that AGENTRUSH memories are public. The acknowledgement is stored in `~/.mem0/config.json` under `agent_rush.acknowledged_at`. * **Config schema:** Added `agent_rush.acknowledged_at` for the local acknowledgement timestamp. **Changes:** * **Agent Rush telemetry:** Agent Rush commands send `X-Mem0-Mode: agent-rush` so platform telemetry can split game traffic from regular CLI usage. **2026-05-16** Python v0.2.6 / Node v0.2.6 **Bug Fixes:** * **Claim flow error message:** The `email_already_claimed` tip in `mem0 init --email` previously suggested running `mem0 link `: a command that doesn't exist. Replaced with honest copy pointing the user to sign in at app.mem0.ai with their existing credentials ([#5152](https://github.com/mem0ai/mem0/pull/5152)) **2026-05-14** Python v0.2.5 / Node v0.2.5 **New Features:** * **Agent Mode (`mem0 init --agent`):** Zero-friction signup for AI agents: mints a working Mem0 API key in under 5 seconds with no email, no dashboard, no OTP. Returns an unclaimed shadow account the human can later claim with `mem0 init --email ` (memories preserved, same key keeps working) ([#5123](https://github.com/mem0ai/mem0/pull/5123)) * **Self-declared agent identity:** Agents pass `--agent-caller ` (e.g. `claude-code`, `cursor`, `codex`) on `mem0 init --agent` so signups attribute to the right tool in analytics. Proof Editor-style: the agent declares itself rather than the CLI sniffing it from env vars ([#5123](https://github.com/mem0ai/mem0/pull/5123)) * **`mem0 identify `:** New subcommand to self-tag an Agent Mode key after the fact when the agent forgot to pass `--agent-caller` on init. Idempotent: re-running just overwrites ([#5123](https://github.com/mem0ai/mem0/pull/5123)) * **Plugin sync:** `~/.claude/settings.json::env::MEM0_API_KEY` and `~/.zshrc`/`.bashrc` `export MEM0_API_KEY=` lines stay in sync with `~/.mem0/config.json` automatically. Idempotent: only updates EXISTING entries, never creates new ones ([#5123](https://github.com/mem0ai/mem0/pull/5123)) * **Claim flow:** `mem0 init --email ` claims an existing Agent Mode shadow via OTP. Upgrade-in-place: the API key never changes, memories transfer to the human's account ([#5123](https://github.com/mem0ai/mem0/pull/5123)) **Bug Fixes:** * **Decision tree network resilience:** `pingKey` now distinguishes network errors from invalid keys: returns false ONLY on HTTP 401/403, returns true on connection failures / timeouts / 5xx. Prevents a VPN flap from silently rotating the user's API key and rewriting plugin-sync targets ([#5123](https://github.com/mem0ai/mem0/pull/5123)) * **Rate-limit error clarity:** DRF's opaque `"You do not have permission"` 403 from Agent Mode rate limits is now translated to `"Daily Agent Mode signup limit reached for this network (5/day). Try again from a different IP or after midnight UTC."` ([#5123](https://github.com/mem0ai/mem0/pull/5123)) * **JSON envelope `command` field:** `mem0 init --agent --json` error envelopes now populate the `command` field correctly instead of returning an empty string ([#5123](https://github.com/mem0ai/mem0/pull/5123)) * **Bootstrap envelope validation:** Defends against partial/malformed backend responses (e.g. `{api_key: null}`) silently persisting null/undefined into typed string fields ([#5123](https://github.com/mem0ai/mem0/pull/5123)) **2026-04-22** Python v0.2.4 / Node v0.2.4 **New Features:** * **V3 API Routes:** Migrated `add`, `search`, and `list` commands from v1/v2 to v3 API endpoints: `POST /v3/memories/add/`, `POST /v3/memories/search/`, `POST /v3/memories/`. Aligns both CLIs with the Python and TypeScript SDKs which already use v3 ([#4916](https://github.com/mem0ai/mem0/pull/4916)) **Breaking Changes:** * **`--graph` / `--no-graph` removed:** The `enable_graph` config option, `--graph` and `--no-graph` CLI flags, and `MEM0_ENABLE_GRAPH` environment variable have been removed from both CLIs. Graph memory is now a project-level setting on the Platform ([#4916](https://github.com/mem0ai/mem0/pull/4916)) **2026-04-11** Python v0.2.3 / Node v0.2.3 **Bug Fixes:** * **Telemetry:** Replaced shared `"anonymous-cli"` fallback with a persistent per-machine random hash (`cli-anon-`), so anonymous CLI users are counted individually in PostHog instead of collapsing into one identity ([#4789](https://github.com/mem0ai/mem0/pull/4789)) * **Telemetry:** Added PostHog `$identify` event on first authenticated run to stitch pre-signup anonymous history onto the authenticated user profile ([#4789](https://github.com/mem0ai/mem0/pull/4789)) **Improvements:** * **API:** All API calls now include `source=CLI` in request bodies (POST/PUT) and query params (GET/DELETE) for server-side attribution ([#4789](https://github.com/mem0ai/mem0/pull/4789)) **2026-04-06** Python v0.2.2 / Node v0.2.2 **New Features:** * **Telemetry:** Added PostHog telemetry and source tracking to both Python and Node CLIs ([#4699](https://github.com/mem0ai/mem0/pull/4699)) * **Validation:** API key validated upfront via `/v1/ping/` on startup: fail-fast with a helpful error instead of cryptic 401s ([#4701](https://github.com/mem0ai/mem0/pull/4701)) **Bug Fixes:** * **CD:** Fixed OIDC trusted publishing with `npx npm@latest` ([#4724](https://github.com/mem0ai/mem0/pull/4724)) * **CD:** Removed npm self-upgrade from CD workflows ([#4723](https://github.com/mem0ai/mem0/pull/4723)) **2026-04-03** Python v0.2.1 / Node v0.2.1 **New Features:** * **Docs:** Comprehensive README with installation, usage examples, and purple branding ([#4680](https://github.com/mem0ai/mem0/pull/4680)) **Bug Fixes:** * **npm:** Added `repository` field to Node packages for npm provenance ([#4671](https://github.com/mem0ai/mem0/pull/4671)) * **CD:** Added CD workflows for Node SDK packages with OIDC trusted publishing ([#4670](https://github.com/mem0ai/mem0/pull/4670)) **2026-04-02** Python v0.2.0 / Node v0.1.1 **New Features:** * **`event` commands:** `mem0 event list` shows recent background processing events in a table; `mem0 event status ` shows full detail including nested memory results ([#4649](https://github.com/mem0ai/mem0/pull/4649)) * **`--json` / `--agent` flag:** Root-level flag switches all command output to a structured JSON envelope for programmatic/agent consumption. Envelope format: `{"status", "command", "duration_ms", "scope", "count", "data"}` ([#4649](https://github.com/mem0ai/mem0/pull/4649)) * **Agent output sanitization:** Raw API responses projected to only relevant fields per command (e.g., `add` → `{id, memory, event}`, `search` → `{id, memory, score, created_at, categories}`) ([#4649](https://github.com/mem0ai/mem0/pull/4649)) * **Email login:** Added email verification code login to `mem0 init` ([#4623](https://github.com/mem0ai/mem0/pull/4623)) * **Brand update:** Updated color palette from purple to golden ([#4664](https://github.com/mem0ai/mem0/pull/4664)) * **CI/CD:** Added CI pipelines and CD workflows for both CLIs ([#4640](https://github.com/mem0ai/mem0/pull/4640), [#4653](https://github.com/mem0ai/mem0/pull/4653)) **Bug Fixes:** * **Node:** Fixed critical `MODULE_NOT_FOUND` crash on `status`, `import`, and all commands when installed globally: replaced runtime `createRequire` with build-time version injection ([#4636](https://github.com/mem0ai/mem0/pull/4636)) * **Node:** API errors now show full response detail instead of bare "Bad Request" ([#4636](https://github.com/mem0ai/mem0/pull/4636)) * **Python:** Fixed double error printing on all commands ([#4636](https://github.com/mem0ai/mem0/pull/4636)) * **`status` command:** Replaced heavyweight `/v1/entities/` check with dedicated `GET /v1/ping/` endpoint ([#4649](https://github.com/mem0ai/mem0/pull/4649)) * **`add` command:** Deduplicated PENDING results from API; changed misleading count message ([#4649](https://github.com/mem0ai/mem0/pull/4649)) * **`init` command:** Partial flags now work in non-TTY; warns before overwriting existing config; added `--force` flag ([#4649](https://github.com/mem0ai/mem0/pull/4649)) * **`delete` command:** Fixed entity delete via v2 API for all entity types ([#4649](https://github.com/mem0ai/mem0/pull/4649)) **Improvements:** * Tables now show full UUIDs (was truncated to 8 chars, making `mem0 get ` fail) ([#4636](https://github.com/mem0ai/mem0/pull/4636)) * Search table includes Score column ([#4636](https://github.com/mem0ai/mem0/pull/4636)) * `config get api_key` short-form aliases added ([#4636](https://github.com/mem0ai/mem0/pull/4636)) * Client-side validation for `--expires`, `--page-size`, `--page`, `--top-k`, `--threshold`, and empty content ([#4636](https://github.com/mem0ai/mem0/pull/4636)) * `printInfo` / `printScope` moved to stderr to avoid contaminating JSON piping ([#4636](https://github.com/mem0ai/mem0/pull/4636)) **2026-03-26** Python v0.1.0 / Node v0.1.0 **Initial Release: Official Mem0 CLI** A full-featured command-line interface for Mem0, available in both Python and Node.js: * **Install:** `pip install mem0-cli` (Python) or `npm install -g @mem0/cli` (Node.js) * **Full command suite:** `add`, `search`, `list`, `get`, `update`, `delete`, `import`, `config`, `init`, `status`, `entity` * **Interactive setup:** `mem0 init` with API key entry and user ID configuration * **Works everywhere:** Platform (Mem0 Cloud) and self-hosted OSS modes * **Scriptable:** `-o json` flag for CI/CD pipelines and automation * **Dual SDK:** Same commands, same experience across Python and Node.js * **Shared spec:** Both implementations driven by a single `cli-spec.json` ensuring identical behavior ([#4575](https://github.com/mem0ai/mem0/pull/4575)) **Plugins** **Mem0 Plugin** **2026-09-08** Shared agent plugin runtime **Changed:** * Consolidated the coding-agent integrations into `integrations/agent-plugin-core/`: one Python runtime, one TypeScript utility library, and six canonical Python-plugin skill templates. Native adapters retain each host's event contracts and capabilities. * Python plugins ship generated, self-contained `core/` and `skills/` directories. Builds validate portable schemas and skills, parse native JSON, and reject generated-file drift, missing files, stale generated files, and symlinks. TypeScript packages bundle the shared source into their distributable JavaScript and verify their entry points. * Replaced the old `integrations/mem0-plugin/` layout with native host directories and one portable `integrations/mem0-agent-plugin/` package. Updated marketplace paths, installation guides, and integration-skill links. OpenCode now lives in `integrations/opencode-plugin/`. * Native Python plugins expose one local, read-only `search_memories` MCP tool and six skills: search, remember, forget, status, pause, and resume. The shared search tool accepts optional `run_id` with every scope (`repo`, `dir`, and `mine`) to recall memories from a specific coding-agent session. Omitting it searches across sessions. This local tool is separate from the hosted Mem0 MCP server's tool set. **Fixes:** * Hooks, controls, MCP servers, and detached workers use the same host-specific data directory. Detached workers retain the host identity and telemetry source; `--plugin-data-dir` reaches the shared resolver. * Session-end workers flush the conversation already captured by hooks. Repeated and concurrent response hooks no longer duplicate an answer, while identical answers after separate prompts are preserved. * Shared prompts and responses are redacted without the previous 6,000-character cutoff. Python extraction splits oversized messages without dropping text to enforce each request's input budget. Flush event selection and claims share one write transaction, delayed handoffs are replaced atomically, and permanent HTTP polling errors fail promptly. * Extraction instructions refer to the current coding agent. Python redaction covers JSON-shaped credentials; both telemetry runtimes recursively remove sensitive keys, including keys inside nested lists. * New Git repository writes use a hash of the remote identity in `agent_id`. Search and explicit shared-memory deletion include both current and legacy repository IDs within the repository's `app_id`. Existing memories are not rewritten. Legacy IDs retain their original ambiguity for matching owner/repository names on different Git hosts. **Packaging:** * Claude Code, Cursor, Codex, Kimi, Antigravity, and the portable Python bundle are versioned at `0.3.1`. OpenCode and DeepSeek Harness are `0.3.0`; Pi Agent is `0.3.0`; OpenClaw is `1.1.0`. Each host's changes and upgrade considerations are listed in its tab. * Python and TypeScript CI run their respective runtime suites. Package checks build the installable artifacts, check generated-file consistency, and reject TypeScript output that still imports monorepo source. [#7203](https://github.com/mem0ai/mem0/pull/7203) **2026-08-24** mem0-plugin v0.2.15 **Fixes:** * **Search:** A failed search request now prints `[mem0] search request failed: ` to stderr before returning no results. `search_memories()` swallowed every exception and returned `[]`, so an expired API key, a network failure, or a 500 from the backend was indistinguishable from a genuine "nothing stored yet" and the agent carried on with no context and no warning. Shared by Claude Code, Cursor, Codex, Antigravity, and Kimi ([#6898](https://github.com/mem0ai/mem0/pull/6898)) * **Cursor:** `mcpServers` in `.cursor-plugin/plugin.json` now points at `./.cursor-mcp.json` instead of `.cursor-mcp.json`. The un-prefixed path resolved inconsistently depending on Cursor's working directory when it loaded the plugin ([#6948](https://github.com/mem0ai/mem0/pull/6948)) * **Codex:** `install_codex_hooks.py` now prints all six registered events (`PreToolUse, SessionStart, UserPromptSubmit, PostToolUse, Stop, PreCompact`) after installing, instead of a stale four-event list left over from an earlier version of the installer. The README's hook table is corrected to match, documenting the three `PreToolUse` handlers and two `PostToolUse` handlers that were previously undocumented ([#6948](https://github.com/mem0ai/mem0/pull/6948)) **Documentation:** * New [Claude.ai](/integrations/claude-ai) integration page ([#6948](https://github.com/mem0ai/mem0/pull/6948)) > [!NOTE] > > The Claude Code, Cursor, and Codex per-editor manifests (`.claude-plugin/plugin.json`, `.cursor-plugin/plugin.json`, `.codex-plugin/plugin.json`) had drifted to `0.2.13` while the `.claude-plugin/marketplace.json` and `.cursor-plugin/marketplace.json` listings had already moved to `0.2.14`, so installs were pinned one release behind what the marketplace advertised. This release realigns every manifest and marketplace listing to `0.2.15`. **2026-08-04** mem0-plugin v0.2.14 **Fixes:** * **Settings loading no longer crashes on a malformed `settings.json`:** If `~/.mem0/settings.json` parsed as valid JSON but wasn't an object (a list or a bare string, for example), `load_settings()` called `.items()` on it and raised. `resolve_config()` guards only against `ImportError`, so the failure escaped into every hook that resolves identity, not just setup. Settings loading now keeps the defaults instead. Setup also stopped claiming it "Created" the settings file when one already existed; it only prints that when it actually wrote one. Shared across Claude Code, Cursor, Codex, and Antigravity. **New Features:** * **Unknown settings key warning:** Setup now flags keys in `settings.json` that the plugin doesn't recognize, so a typo'd setting no longer fails silently. **Removed:** * Dropped the `mem0_doc_search` "openmemory" section now that OpenMemory has been removed from the docs site, so the skill no longer links to pages that don't exist. **2026-07-14** mem0-plugin v0.2.13 **Fixes:** * **Assistant messages no longer stored as your own:** The session-summary hook (fires at the end of every assistant turn) and the post-compaction hook were sending the assistant's own message to Mem0 tagged `role: "user"`. Because Mem0 extracts *facts about the user* from each message and uses `role` to decide who spoke, the assistant's first-person prose was being saved as the human's stated preferences: "I recommend we drop Redis" became `User prefers dropping Redis entirely`. Both hooks now send `role: "assistant"`, so the same session is stored as `Assistant recommended...`. Affects Claude Code, Cursor, Codex, and Antigravity, which share these hooks. Existing memories written by the previous versions are not rewritten. If your memories contain preferences you never expressed, delete them; the plugin will not recreate them. **2026-06-30** mem0-plugin v0.2.12 **New Features:** * **Query-driven prefetch:** The `UserPromptSubmit` hook now searches Mem0 with the current prompt and injects the top matches, so relevant memories are guaranteed in context instead of relying on the agent to search for them. Opt out with `MEM0_PREFETCH=false`. **Improvements:** * **Multi-hop guidance:** The decision rubric now tells the agent to run follow-up searches for multi-part or comparative questions instead of stopping after one. Tool descriptions for every memory tool were sharpened with clearer "what + when to use" guidance. **2026-06-25** mem0-plugin v0.2.11 **Fixes:** * **Session summary metadata:** `files_touched` now stores a real list instead of a double-encoded JSON string, so returned memories render readable file paths across Claude Code, Cursor, Codex, and Antigravity. **Improvements:** * **Reranked auto-injected context:** File-context, bash-error lookup, and session-resume prefetch now rerank by default. Disable with `MEM0_RERANK=0`, `false`, `no`, or `off`. **2026-06-25** mem0-plugin v0.2.10 **Fixes:** * **Editor telemetry attribution:** Antigravity is no longer counted as Claude Code, Codex no longer falls back to the generic `plugin` bucket, and Cursor wrappers now pin their platform before delegating to shared hook scripts. * **Per-editor plugin version:** Telemetry reads the manifest for the detected platform instead of always reading the Claude plugin manifest. **New Features:** * **`MEM0_PLATFORM` override:** Explicit platform markers now win over env-var auto-detection for reliable telemetry labels. **2026-06-25** mem0-plugin v0.2.9 **New Features:** * **File-context injection:** Before supported editors read a file, Mem0 searches for memories that reference that path and injects a compact prior-work timeline. * **Stop hook session summaries:** Session-end hooks store structured summaries with request, decisions, learnings, next steps, and files touched. * **SessionStart activity timeline:** Sessions with existing memories show recent decisions, bug fixes, and session summaries on startup. **Changes:** * Added shared `file_context.py`, `capture_session_summary.py`, and `session_timeline.py` helpers for the hook pipeline. **2026-06-25** mem0-plugin v0.2.8 **New Features:** * **Global search mode:** `global_search` lets reads search all users and projects in the platform project while writes stay scoped to the current `user_id` and `app_id`. * **Automatic coding categories:** The coding taxonomy is installed in the background on session start and gated by an API-key and taxonomy fingerprint. * **Global scope controls:** `/mem0:switch-project --global` and `/mem0:switch-project --no-global` persist global-search behavior in `~/.mem0/settings.json`. * **Scope-aware startup:** Session banners show `scope=global` when global search is active, and startup memory counts use the same global filter. * **Category setup state:** `~/.mem0/categories_setup.json` caches setup per Mem0 account and taxonomy fingerprint, so categories are applied once and re-applied only when the taxonomy changes. * **Tests:** Added coverage for category fingerprints, state-file gating, state save/load, and idempotent category application. **Changes:** * Session start spawns `auto_setup_categories.py` in the background alongside project-file auto-import. * Onboarding no longer asks users to install coding categories manually; it verifies status and applies categories only if the background run has not finished. * New-project startup copy now tells users that coding categories install automatically. **2026-06-25** mem0-plugin v0.2.7 **Fixes:** * **First-install auth:** Removed `authorizationUrl` from `.mcp.json` so Claude Code uses the `MEM0_API_KEY` header instead of falling into a broken OAuth reconnect flow. * **Onboarding auth copy:** `/mem0:onboard` no longer tells users to complete browser OAuth. * **Invalid configure command:** Removed `claude plugin configure mem0` references and clarified that Claude Code stores the plugin API key through the enable UI prompt. **2026-06-25** mem0-plugin v0.2.6 **Fixes:** * **Memory count and stats:** Removed the `run_id: "*"` filter from read paths so memories written without `run_id` are visible again. * **Write scoping:** `add_memory` moved session tracking from top-level `run_id` to `metadata.session_id`, keeping new memories in the default query partition. * **Session stats:** Memory add/search tracking moved into `enforce_metadata_defaults.sh`, because plugin MCP tools do not trigger PostToolUse hooks. * **Auto-capture reliability:** Added direct API auto-capture every third message plus a proportional prompt nudge when few memories have been stored. * **Desktop API keys:** `_identity.sh` and `_identity.py` can read `MEM0_API_KEY` from common shell profiles when Claude Code Desktop does not inherit shell env vars. * **Import cleanup:** Stale auto-import chunks now delete through the v1 delete endpoint, matching Mem0 v3 add behavior. **Removed:** * Removed Stop and SessionEnd hook capture paths, redundant post-commit/task/subagent scripts, dead settings, and the deleted file-read test. **Changes:** * Stats and tour now query with `user_id` + `app_id` filters only. * Session banners now tell agents to store learnings incrementally instead of waiting until session end. * Session-start resets per-user message counters so nudges begin cleanly. **2026-06-25** mem0-plugin v0.2.5 **Fixes:** * **Hook schema:** PostToolUse scripts now read `tool_response`, Stop hook output is schema-compliant, and SessionStart uses visible raw stdout. * **Tool coverage:** Memory write blocking includes `MultiEdit`, and metadata enforcement covers add, search, get, update, and delete-all variants. * **Identity injection:** `add_memory`, `search_memories`, `get_memories`, and `delete_all_memories` receive safe default `user_id` and `app_id` values when the agent omits them. * **Skill API calls:** Export, stats, pin, health, memory-reviewer, dream, tour, onboard, context-loader, and weekly stats examples now use the correct filter and `top_k` shapes. * **Compact summary capture:** `capture_compact_summary.py` is spawned correctly after compaction and guarded against unset identity variables. **New Features:** * **Stop hook analyzer:** Added `stop_hook_check.py` to detect meaningful work before prompting memory capture. * **Skill checklists:** Added progress checklists to `/mem0:dream` and `/mem0:onboard`. **Changes:** * `enforce_metadata_defaults.sh` was rewritten around handler-based dispatch and never overrides explicitly provided identity. **2026-06-25** mem0-plugin v0.2.4 **Fixes:** * **PostToolUse matcher:** Supports both `mcp__mem0__` and `mcp__plugin_mem0_mem0__` names so session stats record memory operations again. * **File-read noise:** File-read recall now prefers `metadata.files` plus score threshold before falling back to basename search. * **Pinning:** `/mem0:pin` no longer uses removed `immutable=True`; it relies on pinned metadata/text conventions. * **Project listing:** `/mem0:list-projects` merges null-scoped and app-scoped memories so legacy records are counted. * **ID lookup:** `/mem0:peek` routes memory-id references to `get_memory` instead of semantic search. **New Features:** * **Session ID capture:** SessionStart persists the Claude session ID for session-scoped memory operations. * **Search controls:** `_search.py` gained `min_score`, metadata filters, rerank, and threshold support. * **Reranked tour and peek:** `/mem0:tour` and `/mem0:peek` use reranking for better precision. **Removed:** * Removed the nonexistent `PostToolUseFailure` hook and the superseded `/mem0:protocol` skill. **2026-06-25** mem0-plugin v0.2.3 **New Features:** * **Read hook:** Added `PreToolUse(Read)` file recall with skip rules for non-code files, lockfiles, and `node_modules`. * **Shared search module:** Added `_search.py` for v3 search calls and consistent context formatting. * **Settings file:** Added `~/.mem0/settings.json` with search, retention, confidence, debug, and capture settings. * **Memory skills:** Added `/mem0:forget`, `/mem0:peek`, `/mem0:memory-reviewer`, and `/mem0:context-loader`. * **Compact output style:** Added compact `[type] content [mem0:id]` memory display. * **Claude userConfig:** Added sensitive `api_key` plugin config support. **Changes:** * Skills were renamed to shorter command names, bash-error hooks now run real searches, resume prompts prefetch context, and remember-intent phrases route to `/mem0:remember`. * API key resolution now checks `CLAUDE_PLUGIN_OPTION_API_KEY`, and hook timeouts increased for prompt and bash-output searches. **Removed:** * Removed `/mem0:dream --forget`, `/mem0:dream --schedule`, `/mem0:health --fix`, and CLI config fallback. **2026-06-25** mem0-plugin v0.2.2 **Fixes:** * **Compaction writes:** Prevented duplicate pre-compaction captures and shortened session-state content before letting Mem0 infer structured memories. * **Error detection:** Reduced false positives from routine test and linter output. * **Git commit noise:** Removed automatic background commit-context writes and gated post-commit prompts behind settings. * **Project identity:** Added git-remote hash fallback when folders are renamed. * **Dependency install race:** Added a lock and failure sentinel for `ensure_deps.sh`. * **Telemetry:** Switched `distinct_id` from MD5 to SHA-256, protected system props, and loaded plugin version from the manifest. **New Features:** * **Chunking and import:** Added shared chunking helpers and Markdown chunk imports. * **Metadata defaults:** Added `enforce_metadata_defaults.sh` for default confidence, source, and type on `add_memory`. * **Project utilities:** Added list-projects, all-project tour, weekly stats, dream forget mode, and competing-tools import. **Removed:** * Removed `on_pre_commit.py` and merged digest, forget, import-tools, and peek flows into existing skills. **2026-06-25** mem0-plugin v0.2.1 **New Features:** * **Skill suite:** Added 11 skills for dream, export, import, tool import, forget, health, peek, pin, remember, stats, and digest. * **Hook suite:** Added bash-error recall, git/commit context hooks, compaction recovery, session-end capture, subagent reminders, tool-failure recovery, and pre-commit capture. * **Telemetry:** Added sampled PostHog telemetry with no memory content or API keys and `MEM0_TELEMETRY=false` opt-out. * **Coding categories:** Added 10 more coding categories and dependency-managed SDK install through `ensure_deps.sh`. * **Project onboarding:** Added auto-onboarding, `mem0.md` config loading, inactive API-key banner, import/export parsers, and competing-tool import. **Changes:** * Memory scoping moved from `metadata.project_id` to top-level `app_id`, and write paths moved to `/v3/memories/add/`. * Session stats gained category counters and recent memory IDs. * Tour, onboard, prompt hooks, and MCP guidance were updated for project-aware workflows. **Fixes:** * Shared scripts now resolve plugin API-key env vars consistently and pass hook CWD into project/branch resolution. **2026-06-25** mem0-plugin v0.2.0 **New Features:** * **Project-scoped memories:** Deterministic project IDs from git remotes isolate memories per repo. * **Branch-aware tagging:** Session-state and compact-summary memories include branch metadata. * **Project file import:** SessionStart imports `CLAUDE.md`, `AGENTS.md`, `.cursorrules`, `.windsurfrules`, and `mem0.md` as project-profile memories. * **Active identity banner:** Startup shows user, project, branch, and memory count. * **Session report:** Stop hook reports memory writes, retrieves, and touched categories. * **Onboarding, tour, and switch-project skills:** Added first-run setup, proof-of-value browsing, and manual project override. * **Session stats tracker:** Added local add/search tracking for reports. **2026-04-02** mem0-plugin v0.1.3 **Fixes:** * **User ID regression:** `user_id` resolution no longer derives from `MEM0_API_KEY`, restoring `MEM0_USER_ID` to `$USER` to `default` order so older memories remain reachable. **Upgrade Notes:** * The `~/.mem0/identity.json` cache is no longer used. * Users who stored memories under the short-lived API-key hash can recover them by temporarily setting `MEM0_USER_ID` to the old hash. **2026-04-02** mem0-plugin v0.1.2 **New Features:** * **Identity resolver:** Added deterministic user-id resolver, later reverted in v0.1.3. * **Compact summaries:** Added SessionStart compact handler for `compact_summary` memories. * **Coding taxonomy setup:** Added one-shot coding category setup for architecture, anti-patterns, task learnings, tooling, bug fixes, conventions, and preferences. * **Debug logging:** Added opt-in hook logs with `MEM0_DEBUG=1`. * **Shared MCP skill:** Replaced the Claude-Code-specific Codex skill with `mem0-mcp`. **Fixes:** * Session IDs are stored in memory metadata, startup exits quietly without an API key, memory-write blocking avoids `docs/memory/*.md`, duplicate compact writes were removed, and hook captures now expire after 90 days. **2026-04-02** mem0-plugin v0.1.1 **Fixes:** * Cursor plugin became fully functional. * Codex plugin support and integration docs were added. * Codex lifecycle hooks became available through the opt-in installer. * Invalid Claude plugin config keys were removed. **2026-04-02** mem0-plugin v0.1.0 **Mem0 Plugin for Claude Code, Cursor, and Codex** Initial release of the Mem0 plugin for Claude Code and Cursor, followed by Codex support: * **9 MCP memory tools:** `add_memory`, `search_memories`, `get_memories`, `get_memory`, `update_memory`, `delete_memory`, `delete_all_memories`, `delete_entities`, `list_entities`: all via `mcp.mem0.ai`. * **Lifecycle hooks:** Automatic memory capture at session start, context compaction, task completion, and session end. * **Cloud MCP server:** Managed endpoint replaces local MCP and Smithery setup. * **Streamable HTTP transport:** New MCP transport protocol for real-time streaming. * **Codex-specific skill:** Dedicated skill in `mem0-plugin/skills/mem0-codex` for Codex workflows. **Claude Code** **2026-09-23** Claude Code plugin v0.3.3 **Improvements:** * **Search:** The `search_memories` tool description no longer tells the agent to call it before answering anything that could depend on prior context. It now asks for a search before repeating investigation or when earlier decisions, fixes, commands, or results may help, which reduces unnecessary searches ([#7420](https://github.com/mem0ai/mem0/pull/7420)) * **Sidekick:** Sidekick searches memories when earlier sessions could help, instead of before every answer ([#7420](https://github.com/mem0ai/mem0/pull/7420)) * **Extraction:** Repository memory instructions are shorter. They no longer ask for a dedicated memory for each command that failed and was then fixed, and no longer carry separate rules against saving personal preferences or memories that only name the repository, branch, or directory ([#7420](https://github.com/mem0ai/mem0/pull/7420)) * **Search skill:** `/search` no longer describes categories as best-effort labels or asks for a retry without the category ([#7420](https://github.com/mem0ai/mem0/pull/7420)) * **Packaging:** `PLUGIN_VERSION` bumped to `0.3.3`, so the `mem0-plugin/` wire header and `plugin_version` telemetry field identify builds with these prompts ([#7420](https://github.com/mem0ai/mem0/pull/7420)) **2026-09-18** Claude Code plugin v0.3.2 **Improvements:** * **Telemetry:** `PLUGIN_VERSION` bumped to `0.3.2`. The `mem0-plugin/` wire header and `plugin_version` telemetry field now reflect the fixes from #7322 through #7358 ([#7373](https://github.com/mem0ai/mem0/pull/7373)) * **Telemetry:** Events are no longer delivered twice, no longer lose parked events on flush, and now attribute each event to the plugin that produced it ([#7323](https://github.com/mem0ai/mem0/pull/7323), [#7324](https://github.com/mem0ai/mem0/pull/7324), [#7358](https://github.com/mem0ai/mem0/pull/7358)) **Changes:** * **Sidekick:** Sidekick is now available only in Claude Code, with Sonnet, worktree isolation, and parent memories. **2026-09-08** Claude Code plugin v0.3.1 **Changed:** * Extracted hook orchestration and memory behavior into the shared Python core; Claude transcript parsing remains in its native adapter. The installed package contains the generated runtime rather than importing files outside its plugin directory. * Preserves the public `mem0` name, hook declarations, MCP launch configuration, user configuration, and `mem0:sidekick` worktree behavior. The manifest and marketplace version advance from `0.3.0` to `0.3.1` so installations can identify the update. **Fixes:** * Session-end extraction no longer appends a final answer already captured from the transcript while an earlier extraction was running. * Existing repository memories remain searchable after the shared-ID change; explicit shared-memory deletion also covers the legacy ID. Background workers and control skills consistently use Claude's data directory. * Receives the shared JSON-secret redaction and nested telemetry filtering fixes. The local search tool exposes query, result count, category, scope, and optional `run_id` for session-specific recall across all scopes. [#7203](https://github.com/mem0ai/mem0/pull/7203) **Cursor** **2026-09-23** Cursor plugin v0.3.3 **Improvements:** * **Search:** The `search_memories` tool description no longer tells the agent to call it before answering anything that could depend on prior context. It now asks for a search before repeating investigation or when earlier decisions, fixes, commands, or results may help, which reduces unnecessary searches ([#7420](https://github.com/mem0ai/mem0/pull/7420)) * **Extraction:** Repository memory instructions are shorter. They no longer ask for a dedicated memory for each command that failed and was then fixed, and no longer carry separate rules against saving personal preferences or memories that only name the repository, branch, or directory ([#7420](https://github.com/mem0ai/mem0/pull/7420)) * **Search skill:** `/search` no longer describes categories as best-effort labels or asks for a retry without the category ([#7420](https://github.com/mem0ai/mem0/pull/7420)) * **Packaging:** `PLUGIN_VERSION` bumped to `0.3.3`, so the `mem0-plugin/` wire header and `plugin_version` telemetry field identify builds with these prompts ([#7420](https://github.com/mem0ai/mem0/pull/7420)) **2026-09-18** Cursor plugin v0.3.2 **Improvements:** * **Telemetry:** `PLUGIN_VERSION` bumped to `0.3.2`. The `mem0-plugin/` wire header and `plugin_version` telemetry field now reflect the fixes from #7322 through #7358 ([#7373](https://github.com/mem0ai/mem0/pull/7373)) * **Telemetry:** Events are no longer delivered twice, no longer lose parked events on flush, and now attribute each event to the plugin that produced it ([#7323](https://github.com/mem0ai/mem0/pull/7323), [#7324](https://github.com/mem0ai/mem0/pull/7324), [#7358](https://github.com/mem0ai/mem0/pull/7358)) **Changes:** * **Sidekick:** Removes Sidekick and its start/stop hooks. Memory capture, search, and six skills remain available. **2026-09-08** Cursor plugin v0.3.1 **Changed:** * Moves from the legacy shared editor-plugin directory to a native `integrations/cursor-plugin/` package with generated Python core and skills, Cursor variables, local MCP configuration, and a native Sidekick. * Translates Cursor conversation/workspace fields, response and summary fields, tool outcomes, and subagent lifecycle events into the shared runtime. The Sidekick searches memory itself because Cursor's subagent-start response cannot inject parent context. **Fixes:** * Adapter errors are logged and exit successfully so a memory failure does not terminate the host hook. Sidekick telemetry reports zero parent-injected context because this host uses self-search. * Repeated response events and Stop/session-end capture do not duplicate the same answer. * Receives shared data-directory handling, background-worker identity, redaction, and legacy-memory retrieval fixes. [#7203](https://github.com/mem0ai/mem0/pull/7203) **Codex** **2026-09-23** Codex plugin v0.3.3 **Improvements:** * **Search:** The `search_memories` tool description no longer tells the agent to call it before answering anything that could depend on prior context. It now asks for a search before repeating investigation or when earlier decisions, fixes, commands, or results may help, which reduces unnecessary searches ([#7420](https://github.com/mem0ai/mem0/pull/7420)) * **Extraction:** Repository memory instructions are shorter. They no longer ask for a dedicated memory for each command that failed and was then fixed, and no longer carry separate rules against saving personal preferences or memories that only name the repository, branch, or directory ([#7420](https://github.com/mem0ai/mem0/pull/7420)) * **Search skill:** `/search` no longer describes categories as best-effort labels or asks for a retry without the category ([#7420](https://github.com/mem0ai/mem0/pull/7420)) * **Packaging:** `PLUGIN_VERSION` bumped to `0.3.3`, so the `mem0-plugin/` wire header and `plugin_version` telemetry field identify builds with these prompts ([#7420](https://github.com/mem0ai/mem0/pull/7420)) **2026-09-18** Codex plugin v0.3.2 **Improvements:** * **Telemetry:** `PLUGIN_VERSION` bumped to `0.3.2`. The `mem0-plugin/` wire header and `plugin_version` telemetry field now reflect the fixes from #7322 through #7358 ([#7373](https://github.com/mem0ai/mem0/pull/7373)) * **Telemetry:** Events are no longer delivered twice, no longer lose parked events on flush, and now attribute each event to the plugin that produced it ([#7323](https://github.com/mem0ai/mem0/pull/7323), [#7324](https://github.com/mem0ai/mem0/pull/7324), [#7358](https://github.com/mem0ai/mem0/pull/7358)) **Changes:** * **Sidekick:** Renames shared tracking to use subagent terminology. Native subagent memory support remains available. **2026-09-08** Codex plugin v0.3.1 **Changed:** * Moves from the legacy shared editor-plugin directory to a native `integrations/codex-plugin/` package, with generated Python core and six skills, a local search MCP server, and native lifecycle hooks. * Resolves MCP repository searches from Codex workspace metadata when supplied. Control skills, hooks, and workers use the same plugin data directory. * Native subagent start/stop hooks supply parent-retrieved memory context and record completions for every native subagent. Named custom agents remain project/user configuration; the plugin does not distribute a named Codex Sidekick. **Fixes:** * Receives shared credential redaction, legacy-memory retrieval, background-worker identity, and duplicate-response fixes. Codex tool outcomes use available structured failure indicators; missing outcome information is recorded as unknown. [#7203](https://github.com/mem0ai/mem0/pull/7203) **OpenCode** **2026-09-23** OpenCode plugin v0.4.1 **Improvements:** * **Search:** The `search_memories` tool description no longer asks the agent to search proactively or to run several searches for multi-part questions. It now asks for a search before repeating investigation or when earlier decisions, fixes, commands, or results may help, the same wording as the other coding-agent plugins ([#7420](https://github.com/mem0ai/mem0/pull/7420)) * **Session context:** Removed two system-context lines that told the agent to run 2 parallel searches before responding and 2-4 parallel searches for non-trivial tasks ([#7420](https://github.com/mem0ai/mem0/pull/7420)) * **Skills:** `/mem0-search` and `/mem0-context-loader` make one `search_memories` call instead of 2 and 2-4 parallel calls. `/mem0-context-loader` now uses the search skill description from the other coding-agent plugins instead of asking to load at every new task or context switch ([#7420](https://github.com/mem0ai/mem0/pull/7420)) **2026-09-18** OpenCode plugin v0.4.0 **Changes:** * **Telemetry:** The PostHog `source` tag changed from the literal `"plugin"` to `OPENCODE_PLUGIN`, and `project_hash` is now salted. Saved PostHog insights filtering on `source = "plugin"` will stop matching new events; historical data is unaffected ([#7322](https://github.com/mem0ai/mem0/pull/7322)) * **Config:** A new `keyFingerprint` key appears in the install-count deduplication logic; installs are now counted once per key rather than on every activation ([#7325](https://github.com/mem0ai/mem0/pull/7325)) **2026-09-08** OpenCode plugin v0.3.0 **Changed:** * Moved the source from `integrations/mem0-plugin/.opencode-plugin/` to `integrations/opencode-plugin/`, retaining the `@mem0/opencode-plugin` package name and native OpenCode hooks. * Reuses shared conversation preparation, redaction, scoping, and telemetry. Builds a self-contained Bun/ESM `dist/index.js` and publishes its TypeScript entry declaration. * Global memory tool scope requires the user to enable it in plugin settings first; empty and wildcard identities are rejected. * Retains the seven commands for context loading, search, remember, forget, scope, status, and tour; bundled skills continue loading through OpenCode's native configuration. **Removed:** * Removed auto-Dream consolidation, its gates and state handling, and the Dream and pin skills/commands. Existing configurations and workflows that use these features must be updated. **Builds:** * Updated build and publish paths for the relocated source directory; the existing release tag prefix and publishing workflow filename are unchanged. [#7203](https://github.com/mem0ai/mem0/pull/7203) **2026-07-22** OpenCode plugin v0.2.2 **Fixes:** * **Shell-profile API key recovery:** When `MEM0_API_KEY` isn't set in the process environment, the plugin now falls back to reading it from `.zshrc`, `.bashrc`, `.zprofile`, `.bash_profile`, or `.profile`, fixing startup failures on clients (e.g. Desktop) that launch without shell-exported environment variables. **2026-06-30** OpenCode plugin v0.2.1 **Improvements:** * **Sharper tool descriptions:** Every memory tool (`get_memories`, `get_memory`, `update_memory`, `delete_memory`, `delete_all_memories`, `delete_entities`, `list_entities`, `get_event_status`) now states what it does and when to use it. `search_memories` nudges proactive, multi-hop retrieval and the destructive tools carry explicit irreversible-action warnings. **2026-06-22** OpenCode plugin v0.2.0 **Breaking Changes:** * **Native SDK tools:** Memory tools are registered through `@opencode-ai/plugin` and backed by the `mem0ai` SDK directly. The plugin no longer registers or depends on `mcp.mem0.ai`. * **Skills load in place:** The `config` hook adds `opencode-skills/` to `skills.paths`; skills are no longer copied into user config directories. * **Focused skill set:** Trimmed to 9 skills: `context-loader`, `dream`, `forget`, `status`, `search`, `scope`, `pin`, `remember`, and `tour`. **New Features:** * **Memory scopes:** Memory operations support `project`, `session`, and `global` scope, with `/mem0-scope` for changing the default. * **Auto-dream:** Gated memory consolidation can merge duplicates, drop stale/sensitive entries, and rewrite vague memories. * **Expanded telemetry:** OpenCode emits the shared `plugin.*` schema, including prompt, bash-error, pre-compact, session-stop, dream-triggered, and dream-completed events. **Fixes:** * **Project ID detection:** Git remote parsing now handles HTTPS, SSH, and custom SSH host aliases before falling back to the repo root. * **Auto-dream visibility:** `/mem0-status` shows which dream gate is blocking consolidation. * **Delete-all safety:** User-wide deletes require explicit `scope="global"`, regardless of the default scope. **2026-06-22** OpenCode plugin v0.1.3 **New Features:** * **File-context injection:** Before a file read, the plugin searches for memories referencing that path and injects prior work as system context. * **Structured compaction summaries:** Session compaction stores `session_summary` memories with `infer=True`. * **Recent activity timeline:** Initial memory loading shows typed memories with age labels instead of bare text. * **PostHog telemetry:** Anonymous plugin telemetry uses the shared `plugin.*` schema and never sends memory content, prompts, or API keys. **2026-06-22** OpenCode plugin v0.1.2 **New Features:** * **Automatic coding categories:** Sets up 17 coding categories at startup, idempotently and in the background. * **Global search mode:** Adds `global_search` support across initial load, per-message recall, resume detection, error lookup, and compaction context. * **Global search env:** Exports `MEM0_GLOBAL_SEARCH` to child shells via the `shell.env` hook. **Changes:** * Search filters now follow the `global_search` setting instead of always using project-scoped filters. * Resume and error-pattern searches broadened by removing narrow metadata type filters. **2026-06-22** OpenCode plugin v0.1.1 **Changes:** * Renamed the package to `@mem0/opencode-plugin` ([#5272](https://github.com/mem0ai/mem0/pull/5272)). * Added the plugin array to the bundled `opencode.json` ([#5271](https://github.com/mem0ai/mem0/pull/5271)). * Fixed `tsconfig`, added `publishConfig` and the bun lockfile ([#5273](https://github.com/mem0ai/mem0/pull/5273)). * Validated the CI/CD publish flow ([#5288](https://github.com/mem0ai/mem0/pull/5288)). **2026-04-02** OpenCode plugin v0.1.0 **Initial Release:** * **Native OpenCode plugin:** Added `@mem0/opencode-plugin` with TypeScript hooks for chat messages, tool execution, system-message transforms, session compaction, and shell env injection. * **Memory tooling:** Added add, search, update, delete, delete-all, entity tools, session-start memory loading, per-prompt semantic search, error-pattern lookup, auto-capture, and compaction capture. * **Skills and commands:** Bundled 16 OpenCode-native Mem0 skills and slash commands. * **Safety:** Blocks `MEMORY.md` writes and redacts secrets before memory storage. **Antigravity** **2026-09-23** Antigravity plugin v0.3.3 **Improvements:** * **Search:** The `search_memories` tool description no longer tells the agent to call it before answering anything that could depend on prior context. It now asks for a search before repeating investigation or when earlier decisions, fixes, commands, or results may help, which reduces unnecessary searches ([#7420](https://github.com/mem0ai/mem0/pull/7420)) * **Extraction:** Repository memory instructions are shorter. They no longer ask for a dedicated memory for each command that failed and was then fixed, and no longer carry separate rules against saving personal preferences or memories that only name the repository, branch, or directory ([#7420](https://github.com/mem0ai/mem0/pull/7420)) * **Search skill:** `/search` no longer describes categories as best-effort labels or asks for a retry without the category ([#7420](https://github.com/mem0ai/mem0/pull/7420)) * **Packaging:** `PLUGIN_VERSION` bumped to `0.3.3`, so the `mem0-plugin/` wire header and `plugin_version` telemetry field identify builds with these prompts ([#7420](https://github.com/mem0ai/mem0/pull/7420)) **2026-09-18** Antigravity plugin v0.3.2 **Improvements:** * **Telemetry:** `PLUGIN_VERSION` bumped to `0.3.2`. The `mem0-plugin/` wire header and `plugin_version` telemetry field now reflect the fixes from #7322 through #7358 ([#7373](https://github.com/mem0ai/mem0/pull/7373)) * **Telemetry:** Events are no longer delivered twice, no longer lose parked events on flush, and now attribute each event to the plugin that produced it ([#7323](https://github.com/mem0ai/mem0/pull/7323), [#7324](https://github.com/mem0ai/mem0/pull/7324), [#7358](https://github.com/mem0ai/mem0/pull/7358)) **Changes:** * **Sidekick:** Removes Sidekick. Memory capture, search, and six skills remain available. **2026-09-08** Antigravity plugin v0.3.1 **Changed:** * Ships a native package with generated Python core and six skills, a local search MCP server, a Sidekick declaration, and an adapter for `PreInvocation`, `PostToolUse`, and `Stop`. * Normalizes conversation IDs, transcript paths, workspace paths, tool calls, and errors. The adapter captures all completed user/assistant transcript messages incrementally, including later-turn intent, without replaying earlier messages. * Sidekick searches Mem0 itself; this plugin does not provide Claude Code's worktree isolation. **Fixes and host limitations:** * Accepts `MEM0_CWD` as an explicit workspace fallback when the host omits `workspacePaths`. Skips capture when neither is available, rather than writing under an unrelated directory. * Documents global MCP registration with `agy mcp add` when the host does not register the plugin-scoped server. Recall on the initial invocation depends on the host providing a prompt or readable transcript. * Receives the shared data-directory, redaction, legacy-memory retrieval, and duplicate-response fixes. [#7203](https://github.com/mem0ai/mem0/pull/7203) **2026-08-24** Antigravity plugin v0.1.7 **Fixes:** * **Hooks:** The `mem0-ensure-deps` and `mem0-session-start` hook commands in `hooks.json` no longer redirect stderr to `/dev/null`. Both commands still end in `|| true` so a failure can't block startup, but a broken dependency install or session bootstrap now shows up in the Antigravity hook log instead of failing invisibly ([#6948](https://github.com/mem0ai/mem0/pull/6948)) **2026-08-04** Antigravity plugin v0.1.6 **Fixes:** * **Settings loading no longer crashes on a malformed `settings.json`:** If `~/.mem0/settings.json` parsed as valid JSON but wasn't an object, every hook that resolves identity previously raised, not just setup. It now keeps the defaults instead, and setup only reports it "Created" the settings file when it actually wrote one. **Improvements:** * **Unknown settings key warning:** Setup now flags keys in `settings.json` it doesn't recognize instead of ignoring them silently. **Removed:** * Dropped the doc-search skill's "openmemory" section now that OpenMemory has been removed from the docs site. **2026-07-14** Antigravity plugin v0.1.5 **Fixes:** * **Assistant messages no longer stored as your own:** The session-summary hook (fires at the end of every assistant turn) and the post-compaction hook were sending the assistant's own message to Mem0 tagged `role: "user"`. Because Mem0 extracts *facts about the user* from each message and uses `role` to decide who spoke, the assistant's first-person prose was being saved as the human's stated preferences: "I recommend we drop Redis" became `User prefers dropping Redis entirely`. Both hooks now send `role: "assistant"`, so the same session is stored as `Assistant recommended...`. Existing memories written by the previous versions are not rewritten. If your memories contain preferences you never expressed, delete them; the plugin will not recreate them. **2026-06-30** Antigravity plugin v0.1.4 **New Features:** * **Query-driven prefetch:** The user-prompt hook now searches Mem0 with the current prompt and injects the top matches, so relevant memories are guaranteed in context instead of relying on the agent to search for them. Opt out with `MEM0_PREFETCH=false`. **Improvements:** * **Multi-hop guidance:** The decision rubric now tells the agent to run follow-up searches for multi-part or comparative questions instead of stopping after one. **2026-06-25** Antigravity plugin v0.1.3 **Fixes:** * **Readable session metadata:** Stop-hook session summaries now store `files_touched` as a real list instead of a double-encoded JSON string, so returned memories show clean file paths. **Improvements:** * **Reranked injected context:** File-context, bash-error lookup, and session-resume recall now rerank by default for higher-quality automatic context. Disable with `MEM0_RERANK=0`, `false`, `no`, or `off`. **2026-06-25** Antigravity plugin v0.1.2 **Fixes:** * **Telemetry attribution:** Antigravity is now reported as `antigravity` instead of being counted as Claude Code. * **Per-editor version reporting:** Telemetry reads Antigravity's own `plugin.json`, so events report the Antigravity plugin version instead of the Claude plugin version. **New Features:** * **Platform override support:** Shared scripts honor `MEM0_PLATFORM` when an editor needs to pin its telemetry platform explicitly. **2026-04-02** Antigravity plugin v0.1.0 **Initial Release:** * **Self-contained plugin:** Added Antigravity plugin packaging with `plugin.json`, `mcp_config.json`, `hooks.json`, lifecycle hooks, shared scripts, and shared Mem0 skills. * **AGENTS.md support:** Uses Antigravity's `contextFileName: "AGENTS.md"` convention. * **Shared memory layer:** Reuses the Mem0 Platform MCP server, shared hook scripts, and 16 slash-command skills. * **Lifecycle hooks:** Wires session start, user prompt, file read, memory-tool metadata enforcement, bash output, post-tool tracking, and stop summaries. * **Install options:** Supports `degit` installs into `~/.gemini/config/plugins/mem0` and local Antigravity plugin installs. * **Codex parity:** Added missing Codex Write/Edit/MultiEdit blocking and pre-compaction hooks during the shared-plugin restructure. **Kimi** **2026-09-23** Kimi Code plugin v0.3.3 **Improvements:** * **Search:** The `search_memories` tool description no longer tells the agent to call it before answering anything that could depend on prior context. It now asks for a search before repeating investigation or when earlier decisions, fixes, commands, or results may help, which reduces unnecessary searches ([#7420](https://github.com/mem0ai/mem0/pull/7420)) * **Extraction:** Repository memory instructions are shorter. They no longer ask for a dedicated memory for each command that failed and was then fixed, and no longer carry separate rules against saving personal preferences or memories that only name the repository, branch, or directory ([#7420](https://github.com/mem0ai/mem0/pull/7420)) * **Search skill:** `/search` no longer describes categories as best-effort labels or asks for a retry without the category ([#7420](https://github.com/mem0ai/mem0/pull/7420)) * **Packaging:** `PLUGIN_VERSION` bumped to `0.3.3`, so the `mem0-plugin/` wire header and `plugin_version` telemetry field identify builds with these prompts ([#7420](https://github.com/mem0ai/mem0/pull/7420)) **2026-09-18** Kimi Code plugin v0.3.2 **Improvements:** * **Telemetry:** `PLUGIN_VERSION` bumped to `0.3.2`. The `mem0-plugin/` wire header and `plugin_version` telemetry field now reflect the fixes from #7322 through #7358 ([#7373](https://github.com/mem0ai/mem0/pull/7373)) * **Telemetry:** Events are no longer delivered twice, no longer lose parked events on flush, and now attribute each event to the plugin that produced it ([#7323](https://github.com/mem0ai/mem0/pull/7323), [#7324](https://github.com/mem0ai/mem0/pull/7324), [#7358](https://github.com/mem0ai/mem0/pull/7358)) **Changes:** * **Sidekick:** Removes Sidekick and its start/stop hooks. Memory capture, recall, and six skills remain available. **2026-09-08** Kimi Code plugin v0.3.1 **Changed:** * Ships a self-contained native package with six skills, nine lifecycle hooks, a local search MCP server, and a native Sidekick declaration. Added a dedicated installation and troubleshooting guide. * Translates Kimi's session, prompt, tool, compaction, shutdown, and subagent events into the shared Python runtime. Sidekicks receive parent memory context through Kimi's native lifecycle. **Fixes:** * Recovers completed assistant output from Kimi's indexed v2 wire transcript when Stop events omit the response text. Repeated Sidekick invocations receive distinct run identifiers. Stops without a host ID are left uncorrelated when multiple matching runs are active, preserving their responses without assigning them to the wrong run. * Keeps controls, hooks, MCP, and detached workers on the same Kimi data directory and preserves host identity in background workers. * Receives the shared redaction, legacy-memory retrieval, and duplicate-response fixes. **Host compatibility:** * Documents `CHOKIDAR_USEPOLLING=1` for the observed macOS watcher issue. Filesystem isolation remains Kimi's responsibility. [#7203](https://github.com/mem0ai/mem0/pull/7203) **2026-08-24** kimi-plugin v0.1.0 **Initial release** of the Mem0 plugin for Kimi Code, sharing its scripts, skills, and marketplace listing with the Claude Code / Cursor / Codex / Antigravity plugin family ([#6919](https://github.com/mem0ai/mem0/pull/6919)) **New Features:** * **MCP server:** Registers the hosted Mem0 MCP server at `https://mcp.mem0.ai/mcp/`, authenticated via the `MEM0_API_KEY` env var as a bearer token. * **Lifecycle hooks:** Wires SessionStart (loads context through the `context-loader` skill), UserPromptSubmit, three PreToolUse hooks (blocks direct `Write`/`Edit`/`MultiEdit` to memory files, enforces metadata defaults on Mem0 MCP tool calls, and injects context on file reads), two PostToolUse hooks (post-tool tracking and Bash-output scanning), Stop, and PreCompact. * **Hook adapter:** `kimi_hook_shim.sh` normalizes Kimi Code's hook contract to what the shared hook scripts expect: it resolves the real project directory from the payload's `cwd` (Kimi forces the plugin root as the working directory), converts the array-shaped `prompt` field and the `tool_output` / `tool_input.path` field names to the Claude-style shapes the scripts already handle, and translates the plugin-scoped MCP tool name prefix. * **Shared policy skill:** Bundles the `/mem0:policy` skill for managing the `## Instructions` and `## Agent Instructions` sections of `mem0.md`. **OpenClaw** **2026-09-23** openclaw-mem0 v1.2.1 **Improvements:** * **Search:** The `memory_search` tool description no longer asks the agent to search proactively or to run several searches for multi-part questions. It now asks for a search before repeating investigation or when earlier decisions, fixes, commands, or results may help. Recall strategies (`smart`, `always`, `manual`) are unchanged ([#7420](https://github.com/mem0ai/mem0/pull/7420)) **2026-09-18** openclaw-mem0 v1.2.0 **Changes:** * **Config:** Added `keyFingerprint` to the config schema for install-count deduplication; installs are now counted once per key rather than on every activation ([#7325](https://github.com/mem0ai/mem0/pull/7325)) * **Telemetry:** Events are no longer delivered twice, and the `plugin_version` field now reflects the plugin that produced the event ([#7323](https://github.com/mem0ai/mem0/pull/7323), [#7324](https://github.com/mem0ai/mem0/pull/7324), [#7358](https://github.com/mem0ai/mem0/pull/7358)) **2026-09-08** openclaw-mem0 v1.1.0 **Changed:** * Reuses shared conversation preparation, redaction, and telemetry while retaining OpenClaw's native memory backend, tools, CLI, and Platform/OSS modes. * Continues to publish a self-contained ESM package under `@mem0/openclaw-mem0`; the plugin manifest and package version now agree. **Removed:** * Removed Dream consolidation: automatic scheduling and locking, `openclaw mem0 dream`, Dream configuration, the memory-dream skill, and Dream-state public artifacts. Triage, recall, and memory/entity artifacts remain available. Update configurations or integrations that use the removed Dream surface. **Fixes:** * `openclaw mem0 status` handles an unconfigured installation without crashing and directs users to setup. * Removed OpenClaw's separate 2,000-character extraction cutoff. Selected user and assistant messages retain their full redacted text; recent-message selection, earlier summary selection, and noise filtering still apply. * Telemetry removes sensitive properties recursively and uses the shared failure-safe delivery implementation. [#7203](https://github.com/mem0ai/mem0/pull/7203) **2026-08-24** openclaw-mem0 v1.0.16 **Security:** * **Dependencies:** Tightened the `undici` pnpm override from `<6.27.0 → >=6.27.0 <8.0.0` to `<7.29.0 → >=7.29.0 <8.0.0`, closing a newer CVE range the previous floor didn't cover, as part of a wider dependency patch sweep across the pnpm workspaces ([#6847](https://github.com/mem0ai/mem0/pull/6847)) **2026-08-01** openclaw-mem0 v1.0.15 **Improvements:** * **Onboarding suggestions:** The example commands shown by `openclaw mem0 config show` now suggest `gpt-5-mini` instead of `gpt-4o` ([#6704](https://github.com/mem0ai/mem0/pull/6704)) **Security:** * **Dependencies:** Patched high and medium severity dependency vulnerabilities via `pnpm.overrides` (`protobufjs`, `axios`, `postcss`, `mongoose`) ([#6639](https://github.com/mem0ai/mem0/pull/6639)) **2026-06-30** openclaw-mem0 v1.0.14 **Improvements:** * **Sharper tool descriptions:** Every memory tool (`memory_search`, `memory_get`, `memory_list`, `memory_add`, `memory_update`, `memory_delete`) now states what it does and when to use it. `memory_search` nudges proactive, multi-hop retrieval; `memory_add` nudges proactive saves; and the delete tools carry explicit irreversible-action warnings. **2026-06-12** openclaw-mem0 v1.0.13 **Fixes:** * **Custom categories payload:** `customCategories` is converted into the list shape expected by the Mem0 SDK before add calls ([#5345](https://github.com/mem0ai/mem0/pull/5345)). * **Metadata registration:** `register()` exits early in `cli-metadata` mode, avoiding backend initialization and hook installation during OpenClaw metadata scans ([#5383](https://github.com/mem0ai/mem0/pull/5383)). **Security:** * Bumped `mem0ai` to `3.0.7` and added a `uuid` override to resolve known dependency advisories ([#5460](https://github.com/mem0ai/mem0/pull/5460), [#5489](https://github.com/mem0ai/mem0/pull/5489)). **Improvements:** * **Repo consolidation:** OpenClaw moved to `integrations/openclaw/`; npm provenance now points to the correct subdirectory ([#5491](https://github.com/mem0ai/mem0/pull/5491)). **2026-06-02** openclaw-mem0 v1.0.12 **Docs:** * **Agent Mode onboarding:** README documents `mem0 init --agent --json` for autonomous setup without email, OTP, or browser. **Security:** * Added overrides for `langsmith`, `picomatch`, `vite`, and `@qdrant/js-client-rest`. **Dependencies:** * Bumped `mem0ai` to `3.0.3` and refreshed Vitest coverage tooling. **2026-04-29** openclaw-mem0 v1.0.11 **New Features:** * **Skills-mode auto-setup:** Onboarding enables triage, recall, dream consolidation, and full tool profile automatically. * **Memory runtime capability:** Exposes `runtime.getMemorySearchManager()` and `resolveMemoryBackendConfig()`. * **Dimension-aware collections:** OSS wizard creates a new collection when embedder dimensions change. * **Tool docs in skills:** Memory triage and dream skills now include full tool reference sections. **Improvements:** * Auto-capture and auto-recall default to enabled. * Skills prefer `memory_update` over delete+add for atomic edits. * Default search threshold lowered to `0.1` for broader recall. * Config writes preserve OpenClaw gateway `plugins` state. **2026-04-23** openclaw-mem0 v1.0.10 **Security:** * Telemetry identity now uses SHA-256 hashes instead of MD5, and user email is hashed before telemetry submission. **Fixes:** * Version-pinned installs are rewritten to updatable specs. * `searchThreshold` is standardized across docs, README, and manifest. * `PLUGIN_VERSION` is injected at build time from `package.json`. **Manifest Compliance:** * Removed non-spec manifest fields and moved endpoint declarations to spec-compliant `providerEndpoints`. **2026-04-22** openclaw-mem0 v1.0.9 **Security & Compliance:** * **Manifest security metadata:** Added required env var declarations, sensitive config schema fields, data locations, privacy notes, and external endpoint declarations for platform and OSS modes. * **Static-analysis cleanup:** Tests now use `vi.stubEnv` / `vi.unstubAllEnvs` instead of direct environment access in places flagged by plugin scanning. **Tests:** * Expanded coverage to 421 tests across 15 files. **2026-04-21** openclaw-mem0 v1.0.8 **New Features:** * **OSS onboarding wizard:** Guided setup for LLM provider, embedding provider, vector store, and user ID. * **Agent-friendly CLI:** `--json` added to all 16 CLI commands. * **Non-interactive OSS setup:** Added `--mode open-source` with `--oss-llm`, `--oss-embedder`, and `--oss-vector`. * **JSON helpers:** Added structured `jsonOut`, `jsonErr`, and `redactSecrets` helpers. **2026-04-20** openclaw-mem0 v1.0.7 **New Features:** * **Chat-based setup:** Users can configure the Mem0 platform connection inside OpenClaw chat instead of editing config files manually. **Improvements:** * **V3 SDK compatibility:** Bumped the `mem0ai` dependency to `3.0.1` for Mem0 v3 API support. * **Config cleanup:** Removed deprecated `orgId`, `projectId`, and `enableGraph` setup paths from docs and CLI prompts. * **Noise filtering:** Expanded memory-add filtering and improved JSON extraction when model output includes leading text. **2026-04-11** openclaw-mem0 v1.0.6 **Fixes:** * **Telemetry identity:** Anonymous users now get a persistent per-machine hash instead of the shared `anonymous-openclaw` fallback. * **Telemetry stitching:** First authenticated runs emit `$identify` so anonymous history can attach to the authenticated profile. * **CLI event flushing:** Short-lived CLI invocations flush queued telemetry before exit. * **Email resolution:** API-key-only users resolve email lazily through `/v1/ping/`. **Improvements:** * **OpenClaw source tag:** Provider calls now send `source: "OPENCLAW"` across add, search, list, recall, CLI, and OSS backend paths. **2026-04-07** openclaw-mem0 v1.0.5 **Fixes:** * **Init menu selection:** `openclaw mem0 init` number choices now select the intended option. * **OSS pgvector recovery:** Warmup errors now reset initialization so failed pgvector clients do not cascade into repeated `client.connect()` failures. **Removed:** * Removed `orgId`, `projectId`, and `enableGraph` from config, CLI, providers, backend, and tools because API keys are project-scoped and graph memory moved to platform-level configuration. **2026-04-04** openclaw-mem0 v1.0.4 **OpenClaw Plugin: Production-Ready** * **Interactive init flow:** `openclaw mem0 init` supports email verification and direct API key setup. * **Unified tools:** `memory_add` and `memory_delete` replace legacy memory tools and match Mem0 naming. * **CLI commands:** Added `init`, `status`, `config`, `import`, `event list`, and `event status`. * **Modular architecture:** Extracted tools, CLI, filesystem safety, and backend modules. * **Security and tests:** Added path traversal protection, pinned dependencies, and 329 tests across 10 files. **2026-04-03** openclaw-mem0 v1.0.3 **Fixes:** * **Path traversal protection:** Added `safePath()` containment checks for skill and domain-overlay reads. * **Noise filter correction:** Restored the `Post-Compaction` pattern after an incorrect rename. **Security:** * Pinned `mem0ai` to exact `2.3.0`. **2026-04-02** openclaw-mem0 v1.0.2 **Fixes:** * **Env resolution:** Removed plugin-side env-var expansion from config because OpenClaw already resolves env references before plugin registration. **2026-04-02** openclaw-mem0 v1.0.1 **New Features:** * **CD workflow:** Added trusted-publishing release workflow. * **Plugin metadata:** Added compatibility and build metadata to `package.json`. * **License:** Added Apache-2.0 license file. **Fixes:** * **Dream gate:** Fixed cheap-first ordering, session isolation, and completion verification. * **Graceful startup:** Plugin starts cleanly when no API key is configured. **2026-04-01** openclaw-mem0 v1.0.0 **New Features:** * **Skills-based memory architecture:** Added the skill loader, memory triage skill, memory dream skill, batched extraction, and skill-aware recall. * **Dream gate:** Added idle-period memory consolidation. * **Enhanced recall:** Added `recall.ts` with improved retrieval and injection logic. * **Plugin manifest:** Added `openclaw.plugin.json` and setup helper scripts. **2026-03-26** openclaw-mem0 v0.4.1 **New Features:** * **Extraction quality:** Improved noise filtering, deduplication, and extraction instructions. **Fixes:** * Improved credential, API key, and secret detection during extraction. * Prevented standalone timestamps from being stored as memories. **2026-03-16** openclaw-mem0 v0.4.0 **New Features:** * **Trigger filtering:** Skips recall and capture for cron, heartbeat, automation, and schedule triggers. * **Subagent isolation:** Routes ephemeral subagent sessions back to the parent namespace. * **Dynamic recall thresholding:** Drops candidates below 50% of the top score. * **OSS resilience:** Adds SQLite init retry and `oss.disableHistory`. **Fixes:** * Lifecycle hooks now use `ctx.sessionKey` directly, removing a concurrent-session race. **2026-03-12** openclaw-mem0 v0.3.1 **New Features:** * **Message filtering pipeline:** Multi-stage noise removal before extraction. * **Broad recall:** Short or new-session prompts trigger secondary broad search. * **Temporal anchoring:** Extraction instructions include the current date. **Changes:** * Extraction now reads the last 20 messages and the monolithic plugin file was split into focused modules. **2026-03-10** openclaw-mem0 v0.3.0 **Fixes:** * Updated `mem0ai` for the SQLite to `better-sqlite3` migration. **2026-03-09** openclaw-mem0 v0.2.0 **New Features:** * **Multi-agent isolation:** Added per-agent memory isolation via `agentId`. * **Docs:** Added guidance for understanding `userId`. **Fixes:** * Migrated platform search to the Mem0 v2 API. **2026-02-19** openclaw-mem0 v0.1.2 **New Features:** * Added a source field for OpenClaw memory entries. **Fixes:** * Fixed auto-recall injection and auto-capture message drops. **2026-02-02** openclaw-mem0 v0.1.0 **Initial Release:** * **Memory backend:** Added Mem0 Cloud and self-hosted OSS modes for OpenClaw. * **Auto-recall:** Injects relevant memories before each turn. * **Auto-capture:** Stores facts after each turn. * **Config:** Added `topK`, `threshold`, and `apiVersion` options. **Pi Agent** **2026-09-23** Pi Agent plugin v0.3.2 **Improvements:** * **Search:** The memory policy, `mem0_memory` tool description, and prompt guidelines no longer ask the agent to search before answering anything that may depend on earlier context or to run several searches per question. They now ask for a search before repeating investigation or when earlier decisions, fixes, commands, or results may help ([#7420](https://github.com/mem0ai/mem0/pull/7420)) * **Skills:** `context-loader` makes one search instead of 2-4 parallel searches, and uses the search skill description from the other coding-agent plugins ([#7420](https://github.com/mem0ai/mem0/pull/7420)) * **Automatic recall:** Injected memories are introduced as "Mem0 found these relevant memories from earlier work in this repository:", the same heading as the Python plugins. The old heading called them a shallow first pass and told the agent to search again ([#7420](https://github.com/mem0ai/mem0/pull/7420)) **2026-09-18** Pi Agent plugin v0.3.1 **Improvements:** * **Telemetry:** Events are no longer delivered twice, no longer lose parked events, and now attribute each event to the plugin that produced it. The `plugin_version` wire field reflects the fixed release ([#7323](https://github.com/mem0ai/mem0/pull/7323), [#7324](https://github.com/mem0ai/mem0/pull/7324), [#7358](https://github.com/mem0ai/mem0/pull/7358)) **2026-09-08** Pi Agent plugin v0.3.0 **Changed:** * Reuses shared conversation preparation, memory formatting, project/session/global scope utilities, and telemetry while preserving Pi's native extension API and `@mem0/pi-agent-plugin` package name. * Pi loads the built `dist/entry.js` extension instead of executing source TypeScript from an installed package. Builds also publish the library entry point and declarations. **Removed:** * Removed Dream consolidation and pin commands, skills, configuration, types, and exports. The remaining commands are remember, search, forget, tour, scope, and status. Update integrations that import removed APIs or invoke removed commands. **Fixes:** * Global memory tool scope requires the user to select `/mem0-scope global` or configure a global default first. Empty and wildcard identities are rejected. * Memory update and delete accept the `mem0:` and `[mem0:]` citations displayed in tool results, as well as raw IDs. * Shared capture preparation filters conversation roles and redacts content; telemetry removes sensitive keys inside nested structures. [#7203](https://github.com/mem0ai/mem0/pull/7203) **2026-08-24** Pi Agent plugin v0.1.5 **Security:** * **Dependencies:** Tightened the `undici` pnpm override from `<6.27.0 → >=6.27.0 <8.0.0` / `>=8.0.0 <8.5.0 → >=8.5.0` to `<7.29.0 → >=7.29.0 <8.0.0` / `>=8.0.0 <8.9.0 → >=8.9.0 <9.0.0`, closing a newer CVE range the previous floors didn't cover, as part of a wider dependency patch sweep across the pnpm workspaces ([#6847](https://github.com/mem0ai/mem0/pull/6847)) **2026-08-01** Pi Agent plugin v0.1.4 **Security:** * **Dependencies:** Patched high and medium severity dependency vulnerabilities via `pnpm.overrides` (`axios`, `brace-expansion`, `postcss`, `mongoose`, `protobufjs`) ([#6639](https://github.com/mem0ai/mem0/pull/6639)) **2026-06-30** Pi Agent plugin v0.1.3 **New Features:** * **Guaranteed retrieval:** Memories relevant to each prompt are now prefetched and injected as a `` block before the agent runs, so context no longer depends on the agent remembering to search. Context injection is on by default; set `contextInjection: false` to disable. **Improvements:** * **Multi-hop retrieval:** The memory policy and the `mem0_memory` tool description now push proactive, multi-hop search -- several queries with different phrasings instead of stopping after one. * **Clearer tool schema:** The `mem0_memory` action and parameter descriptions (`action`, `query`, `content`, `memory_id`, `scope`) now explain each action and scope. **2026-06-12** Pi Agent plugin v0.1.2 **Fixes:** * **Visible command feedback:** `/mem0-remember`, `/mem0-forget`, `/mem0-pin`, and `/mem0-scope` now render persistent message blocks instead of easy-to-miss status notifications. * **Relevance-filtered search:** Search, forget, and pin commands now pass `threshold`, `top_k`, and `rerank` to avoid weak unrelated matches. **Improvements:** * **Richer command output:** Commands show scope, query, match counts, and affected memories. * **Cleaner dream flow:** `/mem0-dream` keeps the consolidation protocol hidden behind a concise status line. * **Configurable relevance floor:** `searchThreshold` defaults to `0.3` in `mem0-config.json` and is shown in `/mem0-status`. **2026-06-10** Pi Agent plugin v0.1.1 **Chores:** * Version bump to validate the new `pi-agent-plugin-checks.yml` and `pi-agent-plugin-cd.yml` release pipeline. **2026-06-09** Pi Agent plugin v0.1.0 **Initial Release:** * **Extension entry point:** Registers the `mem0_memory` tool, 8 slash commands, and auto-capture hooks. * **Agent tool:** Supports search, add, get-all, delete, and delete-all with scoped filters. * **Slash commands:** Adds `/mem0-remember`, `/mem0-forget`, `/mem0-search`, `/mem0-tour`, `/mem0-dream`, `/mem0-pin`, `/mem0-scope`, and `/mem0-status`. * **Auto-capture:** Extracts and stores memories from user and assistant messages on `agent_end`. * **Dream consolidation:** Merges duplicates, resolves contradictions, and prunes stale entries behind session, time, and memory-count gates. * **System prompt injection:** Appends `MEMORY_POLICY` before every agent turn. * **Project scoping:** Uses `git rev-parse --show-toplevel` for stable `app_id` values across monorepos. * **Scopes and categories:** Supports project, session, and global scopes plus 10 default memory categories. * **Agent skills:** Bundles `context-loader`, `remember`, `search`, `forget`, `dream`, `tour`, `pin`, and `status` skills. * **Safety:** Confirmation dialogs protect destructive commands, pins preserve memory IDs, full memory UUIDs stay visible, outputs are truncated, all tool actions respect `AbortSignal`, and shutdown releases dream locks. * **Telemetry:** Batched PostHog telemetry uses PII-safe error payloads. **Strands** **2026-08-25** mem0-strands v0.1.1 **New Features:** * **Usage telemetry:** Anonymous usage events (`strands.store.init`, `strands.store.search`, `strands.store.add`, `strands.store.add_messages`) ride the Mem0 SDK's existing PostHog client, unsampled, with no new dependency. Events carry only counts, durations, booleans, and coarse failure kinds: never queries, memory text, message content, entity ids, metadata, or API keys. Opt out with `MEM0_TELEMETRY=false` ([#7110](https://github.com/mem0ai/mem0/pull/7110)) **2026-08-24** mem0-strands v0.1.0 **Initial release** of [`mem0-strands`](https://pypi.org/project/mem0-strands/), a native `MemoryStore` that plugs Mem0 into the [Strands Agents](https://strandsagents.com/) `MemoryManager` ([#7021](https://github.com/mem0ai/mem0/pull/7021)) **New Features:** * **Automatic recall and injection:** `Mem0MemoryStore.search()` runs every turn through the `MemoryManager`, so relevant memories are searched and prepended to the prompt with no explicit tool call required. * **Server-side extraction:** `add_messages()` renders raw conversation turns to text and hands them to Mem0's own extraction pipeline (`infer=True`), so enabling extraction skips an extra client-side model call to distill facts first. * **Verbatim writes:** `add()` stores a single fact exactly as given (`infer=False`), the sink used by the `add_memory` tool or a client-side extractor. * **Entity scoping:** Accepts `user_id`, `agent_id`, `run_id`, and `app_id`; at least one is required, and mixing the platform-only `app_id` with a self-hosted `config` raises at construction instead of failing on the first write. * **Hosted or self-hosted:** Defaults to the hosted Mem0 Platform via `api_key` (or `$MEM0_API_KEY`), or pass a `config` dict for a self-hosted Mem0 OSS backend. * **Non-blocking construction:** The underlying Mem0 client is built lazily on first use inside `asyncio.to_thread`, so API-key validation and OSS embedder/vector-store setup never block the event loop. > [!NOTE] > > `Mem0MemoryStore` is the automatic-recall store for the `MemoryManager`. For a model-called tool instead, use the [`mem0_memory`](https://github.com/strands-agents/tools) tool from `strands-agents-tools`; both share the same Mem0 backend and namespace. See [Strands Agents](/integrations/strands) for setup. **DeepSeek Harness** **2026-09-23** deepseek-plugin v0.3.2 **Improvements:** * **Search:** The `search_memory` tool description no longer asks the agent to search proactively before answering anything that may depend on earlier context. It now asks for a search before repeating investigation or when earlier decisions, fixes, commands, or results may help ([#7420](https://github.com/mem0ai/mem0/pull/7420)) * **Automatic recall:** Injected memories are introduced as "Mem0 found these relevant memories from earlier work:". The old heading called them a shallow first pass and told the agent to search again with `mem0_memory`, a tool DeepSeek does not have ([#7420](https://github.com/mem0ai/mem0/pull/7420)) **2026-09-18** deepseek-plugin v0.3.1 **Improvements:** * **Telemetry:** Rebuild with the fixed shared telemetry core from `agent-plugin-core`. Events are no longer delivered twice, no longer lose parked events on flush, and now attribute each event to the plugin that produced it ([#7323](https://github.com/mem0ai/mem0/pull/7323), [#7324](https://github.com/mem0ai/mem0/pull/7324), [#7358](https://github.com/mem0ai/mem0/pull/7358)) **2026-09-08** deepseek-plugin v0.3.0 **Added:** * Automatic recall during `system-prompt/assemble`, using the latest human prompt and avoiding repeated context injection within a session. * Automatic capture from the durable `session/event` stream after a completed turn. Interrupted or incomplete turns are not sent through this automatic capture path. `autoRecall` and `autoCapture` default to `true` and can be disabled. **Changed:** * Reuses shared lifecycle, redaction, identity, and telemetry utilities while retaining the explicit `search_memory` and `add_memory` tools and their per-call agent/session scope. Cross-user `userId` overrides now require operator opt-in with `allowUserOverride: true`. * Publishes a self-contained ESM artifact under `@mem0/deepseek-plugin`; native Harness services and the Mem0 SDK remain external dependencies. Plugin cleanup remains tied to the native Cordis lifecycle. **Host compatibility:** * Supports the declared Harness runtime dependencies and documents the macOS watcher workaround. The plugin does not bundle a named Sidekick or provide child filesystem isolation. [#7203](https://github.com/mem0ai/mem0/pull/7203) **2026-08-25** deepseek-plugin v0.1.1 **New Features:** * **Usage telemetry:** Anonymous usage events (`deepseek.plugin.mounted`, `deepseek.tool.search_memory`, `deepseek.tool.add_memory`) are batched to PostHog over native fetch and flushed in the background. Events carry only tool names, durations, counts, and coarse failure kinds: never queries, memory text, filters, or API keys. Opt out with `MEM0_TELEMETRY=false` ([#7110](https://github.com/mem0ai/mem0/pull/7110)) **2026-08-24** deepseek-plugin v0.1.0 **Initial release** of [`deepseek-plugin`](https://www.npmjs.com/package/@mem0/deepseek-plugin), a native DeepSeek Harness (Cordis) plugin that registers Mem0 as two agent-callable tools ([#7027](https://github.com/mem0ai/mem0/pull/7027)) **New Features:** * **`search_memory`:** Recalls facts relevant to a query, with an optional `limit` (default 10) and per-call `userId` / `agentId` / `runId` scope overrides. * **`add_memory`:** Stores a fact for future sessions, tagged `source: "DEEPSEEK_HARNESS"` for backend attribution; extraction runs asynchronously server-side, so a stored fact may take a moment to become searchable. * **Cordis lifecycle:** `apply(ctx, config)` declares `inject = ['tools']`, so the plugin waits for the harness tool registry to exist, and both tools are registered via `ctx.tools.register()` so they auto-unregister when the plugin unmounts. * **Config:** `userId` is required; `apiKey` defaults to `$MEM0_API_KEY`; `host` optionally points at a dedicated Mem0 Platform base URL (not a switch to self-hosted Mem0 OSS). > [!NOTE] > > Developer preview: auto-capture and auto-recall (memory injected into context automatically, without an explicit tool call) are planned but not yet built. The backend's `KNOWN_EVENT_SOURCES` allowlist also needs `"DEEPSEEK_HARNESS"` added before usage surfaces by name in telemetry rather than bucketing into "OTHERS". See [DeepSeek Harness](/integrations/deepseek-plugin) for setup. **Vercel AI SDK** **2026-09-18** Vercel AI SDK v3.0.3 **Improvements:** * **Client:** Inherits the three surface-identity headers (`X-Mem0-Source`, `X-Application`, `X-Mem0-Client`) from the TypeScript SDK bump, so platform calls made through the Vercel AI SDK provider are now correctly attributed ([#7326](https://github.com/mem0ai/mem0/pull/7326)) **2026-08-24** Vercel AI SDK v3.0.2 **Security:** * **Dependencies:** Tightened the `js-yaml` pnpm overrides from `<3.15.0 → >=3.15.0 <4.0.0` / `>=4.0.0 <4.3.0 → >=4.3.0 <5.0.0` to `<3.15.1 → >=3.15.1 <4.0.0` / `>=4.0.0 <4.3.1 → >=4.3.1 <5.0.0`, closing a newer CVE range the previous floors didn't cover, as part of a wider dependency patch sweep across the pnpm workspaces ([#7032](https://github.com/mem0ai/mem0/pull/7032)) **2026-08-01** Vercel AI SDK v3.0.1 **Security:** * **Dependencies:** Patched high and medium severity dependency vulnerabilities via `pnpm.overrides` (`brace-expansion`, `js-yaml`) ([#6639](https://github.com/mem0ai/mem0/pull/6639)) **2026-06-10** Vercel AI SDK v3.0.0 **Major Release**: Migrated to Vercel AI SDK v6 (`LanguageModelV3` / `ProviderV3`) and Mem0 v3 API. **Breaking Changes:** * **AI SDK v6:** Upgraded from AI SDK v5 (`LanguageModelV2`) to v6 (`LanguageModelV3`). Users must upgrade `ai` to `^6.0.199` and all `@ai-sdk/*` provider packages to `^3.x` ([#4741](https://github.com/mem0ai/mem0/pull/4741)) * **Mem0 v3 API:** Memory endpoints migrated from `/v1/memories/` and `/v2/memories/search/` to `/v3/memories/add/` and `/v3/memories/search/`. Entity IDs (`user_id`, `agent_id`, `run_id`) now go inside the `filters` object for search requests ([#4741](https://github.com/mem0ai/mem0/pull/4741)) * **Graph memory removed:** All `enable_graph`, graph prompts, and relation-extraction code removed. Graph memory is now a project-level setting on the Platform ([#4741](https://github.com/mem0ai/mem0/pull/4741)) * **Deprecated params removed:** `org_id`, `project_id`, `org_name`, `project_name`, `output_format`, `filter_memories`, `async_mode`, `enable_graph`, `version`, `api_version` removed from `Mem0ConfigSettings` ([#4741](https://github.com/mem0ai/mem0/pull/4741)) **New Features:** * **V3 provider contract:** `specificationVersion: 'v3'`, `supportedUrls` property, V3 content array in `doGenerate`, V3 stream lifecycle events in `doStream` ([#4741](https://github.com/mem0ai/mem0/pull/4741)) * **Mem0 source in responses:** Memories are attached as a `source` in `generateText`/`streamText` responses with `providerMetadata.mem0.memories` for programmatic access ([#4741](https://github.com/mem0ai/mem0/pull/4741)) * **Raw search helper:** `searchMemories()` is exported alongside `addMemories()`, `retrieveMemories()`, and `getMemories()` for callers that need raw semantic search results. * **Self-hosted API support:** `mem0ApiKey` and `host` can be passed per request, letting apps override the environment API key and point at a custom Mem0 API base URL. * **Provider coverage:** Built-in provider selection covers OpenAI, Anthropic, Google/Gemini, Groq, and Cohere through the AI SDK provider packages. * **Multimodal memory input:** File, image, Markdown, and PDF prompt parts are converted into the Mem0-compatible message shape when adding or searching memories. **Bug Fixes:** * **Async memory storage:** `addMemories` is now properly `await`ed: memories no longer silently fail to store ([#4741](https://github.com/mem0ai/mem0/pull/4741)) * **Prompt mutation:** Prompt array is now cloned before injecting memory context, preventing side effects on the caller's array ([#4741](https://github.com/mem0ai/mem0/pull/4741)) * **Null guard on content:** `doGenerate` guards against null `content` from upstream providers ([#4741](https://github.com/mem0ai/mem0/pull/4741)) * **Stream response:** `doStream` now returns the full `LanguageModelV3StreamResult` object preserving all V3 fields ([#4741](https://github.com/mem0ai/mem0/pull/4741)) * **Response normalization:** `getMemories` and `retrieveMemories` now handle both array and `{results: [...]}` envelope responses from the v3 API ([#4741](https://github.com/mem0ai/mem0/pull/4741)) **2026-06-01** Vercel AI SDK v2.0.6 **Security:** * **Dependencies:** Pinned transitive dependencies via pnpm overrides to remediate high-severity CVEs: `glob` → ^10.5.0 (CVE-2025-64756), `minimatch` → ^3.1.3 / ^5.1.8 / ^9.0.7 (CVE-2026-27903, CVE-2026-27904, CVE-2026-26996), `picomatch` → ^2.3.2 (CVE-2026-33671), `rollup` → ^4.59.0 (CVE-2026-27606) **2025-12-26** Vercel AI SDK v2.0.5 **Bug Fix:** * Removed unnecessary dependencies to make the package lighter. **2025-09-25** Vercel AI SDK v2.0.3 – v2.0.4 **New Features:** * Added file support for multimodal capabilities with memory context (v2.0.3) **Bug Fix:** * Fixed version parameter to use V2 for addition (v2.0.4) **2025-09-03** Vercel AI SDK v2.0.2 **Bug Fix:** * Fixed streaming response in the AI SDK. **2025-08-05** Vercel AI SDK v2.0.0 – v2.0.1 **New Features:** * Migration to AI SDK V5 (v2.0.0) * Added `host` param to the config (v2.0.1) **2025-06-15** Vercel AI SDK v1.0.6 **New Features:** * Added `filter_memories` param. **2025-05-23** Vercel AI SDK v1.0.5 **New Features:** * Added support for Google provider. **2025-05-10** Vercel AI SDK v1.0.3 – v1.0.4 **New Features:** * Added support for `output_format` param (v1.0.4) **Improvements:** * Added graceful failure handling when services are down (v1.0.3) **2025-05-01** Vercel AI SDK v1.0.1 **New Features:** * Added support for graph memories. **n8n** **2026-08-24** n8n-nodes-mem0 v0.1.4 **Security:** * **Dependencies:** Add `js-yaml` pnpm overrides (`<3.15.1 → >=3.15.1 <4.0.0`, `>=4.0.0 <4.3.1 → >=4.3.1 <5.0.0`) to close a HIGH/CRITICAL severity advisory, as part of a wider dependency patch sweep across the pnpm workspaces ([#7032](https://github.com/mem0ai/mem0/pull/7032)) **2026-08-05** n8n-nodes-mem0 v0.1.3 **Changes:** * **License changed to MIT:** The published `@mem0/n8n-nodes-mem0` package is now MIT (was Apache-2.0). n8n's Creator Portal requires verified community nodes to be MIT, and the failing license check was the blocker for verification. The rest of the mem0 repo stays Apache-2.0 ([#6804](https://github.com/mem0ai/mem0/pull/6804)) * **Themed icons:** The node and credential icons now declare `{ light, dark }` variants instead of a single icon, clearing the remaining `icon-prefer-themed-variants` warnings from the Creator Portal scan. No functional changes ([#6804](https://github.com/mem0ai/mem0/pull/6804)) **2026-08-04** n8n-nodes-mem0 v0.1.2 **Changes:** * **Package contact:** `author.email` in the published package is now `integrations@mem0.ai` (was `founders@mem0.ai`), so npm and n8n Creator Portal correspondence reaches the integrations team directly. No functional changes ([#6791](https://github.com/mem0ai/mem0/pull/6791)) **2026-07-30** n8n-nodes-mem0 v0.1.1 **Changes:** * **Published with npm provenance:** Republished through the `n8n-nodes-mem0-cd.yml` GitHub Actions workflow so the package carries a signed provenance attestation. `0.1.0` was published manually and has none, which blocks submission for n8n Creator Portal verification. No functional changes ([#6685](https://github.com/mem0ai/mem0/pull/6685)) **2026-07-29** n8n-nodes-mem0 v0.1.0 **Initial release** of [`@mem0/n8n-nodes-mem0`](https://www.npmjs.com/package/@mem0/n8n-nodes-mem0), a community node that adds long-term memory to n8n workflows and AI Agents ([#6517](https://github.com/mem0ai/mem0/pull/6517)) **New Features:** * **Memory operations:** A single **Mem0** node covers Add, Search, Get, Get Many, Update, and Delete on the Memory resource. * **AI Agent tool:** The node sets `usableAsTool`, so it can be attached to an n8n AI Agent node and invoked by the agent itself rather than wired into a fixed workflow path. * **Scoping:** Add, Search, and Get Many accept User ID, Agent ID, App ID, and Run ID, so memories stay partitioned per user, agent, or session. * **Add options:** Metadata JSON, custom categories, custom instructions, includes/excludes, an `infer` toggle, and a **Wait for Completion** switch that polls until the write lands instead of returning immediately. * **Pagination:** Get Many supports Return All, or explicit Page and Page Size. * **Credential:** A **Mem0 API** credential holds the API key plus a configurable base URL, defaulting to `https://api.mem0.ai` for self-hosted deployments. > [!NOTE] > > Community nodes install from npm, which is a self-hosted n8n feature. See [n8n](/integrations/n8n) for setup. **Zapier** **2026-08-24** Zapier app v0.1.2 **Changes:** * **Connection label:** The saved connection now shows the account's email (`{{user_email}}`, read from the `/v1/ping/` test response) in the Zap editor instead of a static "Mem0" label, so a user with more than one Mem0 connection can tell them apart ([#6985](https://github.com/mem0ai/mem0/pull/6985)) * **Action and search copy:** Reworded labels and descriptions to address Zapier's publishing review: **Get Memories** is now **Find Memories by User**, **Search Memories** is now **Find Memories**, and every description now reads as a third-person statement of what the step does ([#6985](https://github.com/mem0ai/mem0/pull/6985)) * **Attribution:** Add Memory now tags writes with `source: "ZAPIER"` in the request body, so usage is attributed to this integration server-side ([#6985](https://github.com/mem0ai/mem0/pull/6985)) **Removed:** * **Client-side telemetry:** Deleted the embedded PostHog telemetry client (`telemetry.ts`) and its call sites in Add Memory, Get Memories, and Search Memories. Usage attribution now happens server-side via the `source: "ZAPIER"` tag above instead of a separate fire-and-forget analytics call from inside the published app ([#6985](https://github.com/mem0ai/mem0/pull/6985)) **Security:** * **Dependencies:** Tightened the `undici` pnpm override to `<7.29.0 → >=7.29.0 <8.0.0` / `>=8.0.0 <8.9.0 → >=8.9.0 <9.0.0` and added a `brace-expansion` override ([#6847](https://github.com/mem0ai/mem0/pull/6847)), then added a `js-yaml` override (`<3.15.1 → >=3.15.1 <4.0.0`, `>=4.0.0 <4.3.1 → >=4.3.1 <5.0.0`) closing a further HIGH/CRITICAL severity advisory ([#7032](https://github.com/mem0ai/mem0/pull/7032)) **2026-08-04** Zapier app v0.1.1 **Bug Fixes:** * **Add Memory:** **User ID** is now a required field. Mem0 rejects a write that carries no entity ID, so a Zap left blank failed at the API instead of in the editor. If you scoped memories only by Agent ID or Run ID, set a User ID as well ([#6790](https://github.com/mem0ai/mem0/pull/6790)) * **Deployment:** Add a root `index.js` that re-exports the compiled app from `dist/`, and point `main` at it. Zapier's Lambda wrapper loads `/index.js` and ignores the `package.json` `main` field, so the deployed app could not resolve its entry point ([#6789](https://github.com/mem0ai/mem0/pull/6789)) **2026-07-29** Zapier app v0.1.0 **Initial release** of the Mem0 Zapier app, built on the Zapier Platform CLI ([#6518](https://github.com/mem0ai/mem0/pull/6518)) **New Features:** * **Actions:** Add Memory and Delete Memory. * **Searches:** Search Memories and Get Memories, usable as lookup steps in any Zap. * **Authentication:** An API key connection validated against Mem0 the moment it is saved, sent as `Authorization: Token `, with a configurable base URL for self-hosted deployments. **Bug Fixes:** * **Add Memory:** Raise the poll budget past the real API latency tail, so a slower write is no longer reported as a failure ([#6680](https://github.com/mem0ai/mem0/pull/6680)) > [!NOTE] > > The app deploys to Zapier's platform rather than npm and is not yet listed in the public App Directory. See [Zapier](/integrations/zapier) for invite access. # Embedder Configuration Reference Source: https://docs.mem0.ai/components/embedders/config Reference for embedder configuration options in Mem0, including provider selection and model settings. Config in mem0 is a dictionary that specifies the settings for your embedding models. It allows you to customize the behavior and connection details of your chosen embedder. ## How to define configurations? The config is defined as an object (or dictionary) with two main keys: * `embedder`: Specifies the embedder provider and its configuration * `provider`: The name of the embedder (e.g., "openai", "ollama") * `config`: A nested object or dictionary containing provider-specific settings ## How to use configurations? Here's a general example of how to use the config with mem0: ```python Python theme={null} import os from mem0 import Memory os.environ["OPENAI_API_KEY"] = "sk-xx" config = { "embedder": { "provider": "your_chosen_provider", "config": { # Provider-specific settings go here } } } m = Memory.from_config(config) m.add("Your text here", user_id="user", metadata={"category": "example"}) ``` ```typescript TypeScript theme={null} import { Memory } from 'mem0ai/oss'; const config = { embedder: { provider: 'openai', config: { apiKey: process.env.OPENAI_API_KEY || '', model: 'text-embedding-3-small', // Provider-specific settings go here }, }, }; const memory = new Memory(config); await memory.add("Your text here", { userId: "user", metadata: { category: "example" } }); ``` ## Why is Config Needed? Config is essential for: 1. Specifying which embedding model to use. 2. Providing necessary connection details (e.g., model, api\_key, embedding\_dims). 3. Ensuring proper initialization and connection to your chosen embedder. ## Master List of All Params in Config Here's a comprehensive list of all parameters that can be used across different embedders: **Python** | Parameter | Description | Provider | | - | - | - | | `model` | Embedding model to use | All | | `api_key` | API key of the provider | All | | `embedding_dims` | Dimensions of the embedding model | All | | `http_client_proxies` | Allow proxy server settings | All | | `ollama_base_url` | Base URL for the Ollama embedding model | Ollama | | `model_kwargs` | Key-Value arguments for the Huggingface embedding model | Huggingface | | `azure_kwargs` | Key-Value arguments for the AzureOpenAI embedding model | Azure OpenAI | | `openai_base_url` | Base URL for OpenAI API | OpenAI | | `vertex_credentials_json` | Path to the Google Cloud credentials JSON file for VertexAI | VertexAI | | `memory_add_embedding_type` | The type of embedding to use for the add memory action | VertexAI | | `memory_update_embedding_type` | The type of embedding to use for the update memory action | VertexAI | | `memory_search_embedding_type` | The type of embedding to use for the search memory action | VertexAI | | `lmstudio_base_url` | Base URL for LM Studio API | LM Studio | **TypeScript** | Parameter | Description | Provider | | - | - | - | | `model` | Embedding model to use | All | | `apiKey` | API key of the provider | All | | `embeddingDims` | Dimensions of the embedding model | All | ## Supported Embedding Models For detailed information on configuring specific embedders, please visit the [Embedding Models](./overview) section. There you'll find information for each supported embedder with provider-specific usage examples and configuration details. # AWS Bedrock as Embedding Provider Source: https://docs.mem0.ai/components/embedders/models/aws-bedrock Configure AWS Bedrock as an embedding provider in Mem0 with IAM credentials and boto3 authentication. To use AWS Bedrock embedding models, you need the appropriate AWS credentials and permissions. Python uses `boto3`, and TypeScript uses `@aws-sdk/client-bedrock-runtime`. Both SDKs support the Amazon Titan and Cohere embedding model families. ### Setup * Model access is automatic: Bedrock enables serverless foundation models on first invocation in AWS commercial regions, and the [Model access page has been retired](https://docs.aws.amazon.com/bedrock/latest/userguide/model-access.html). Cohere models are served from AWS Marketplace, so an account's first invocation must come from a principal with the `aws-marketplace:Subscribe` permission; after that, any user in the account can invoke them. Browse the models available to you in the [Bedrock model catalog](https://console.aws.amazon.com/bedrock/). * Install the AWS client for your language: ```bash Python theme={null} pip install boto3 ``` ```bash TypeScript theme={null} npm install @aws-sdk/client-bedrock-runtime ``` In TypeScript this package is an optional peer dependency, so it is only required when you actually use the Bedrock embedder. * Set up environment variables for authentication: ```bash theme={null} export AWS_REGION=us-east-1 export AWS_ACCESS_KEY_ID=your-access-key export AWS_SECRET_ACCESS_KEY=your-secret-key ``` Both SDKs fall back to the standard AWS credential chain (environment variables, shared config, SSO, or an instance role) when you do not pass credentials in the config, so you rarely need to hardcode keys. See the [boto3 credentials guide](https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html) for the Python resolution order. ### Usage ```python Python theme={null} import os from mem0 import Memory # For LLM if needed os.environ["OPENAI_API_KEY"] = "your-openai-api-key" # AWS credentials os.environ["AWS_REGION"] = "us-west-2" os.environ["AWS_ACCESS_KEY_ID"] = "your-access-key" os.environ["AWS_SECRET_ACCESS_KEY"] = "your-secret-key" config = { "embedder": { "provider": "aws_bedrock", "config": { "model": "amazon.titan-embed-text-v2:0" } } } m = Memory.from_config(config) messages = [ {"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"}, {"role": "assistant", "content": "How about thriller movies? They can be quite engaging."}, {"role": "user", "content": "I'm not a big fan of thriller movies but I love sci-fi movies."}, {"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."} ] m.add(messages, user_id="alice") ``` ```typescript TypeScript theme={null} import { Memory } from "mem0ai/oss"; // Credentials are read from the AWS default chain (AWS_REGION, // AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, SSO, or an instance role). const memory = new Memory({ embedder: { provider: "aws_bedrock", config: { model: "amazon.titan-embed-text-v2:0", awsRegion: "us-west-2", }, }, }); const messages = [ { role: "user", content: "I'm planning to watch a movie tonight. Any recommendations?" }, { role: "assistant", content: "How about thriller movies? They can be quite engaging." }, { role: "user", content: "I'm not a big fan of thriller movies but I love sci-fi movies." }, { role: "assistant", content: "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future." }, ]; await memory.add(messages, { userId: "alice" }); ``` ### Choosing a model | Model | Notes | | - | - | | `amazon.titan-embed-text-v1` | Default. Fixed 1536-dimension output. | | `amazon.titan-embed-text-v2:0` | Supports a configurable output size of 256, 512, or 1024. | | `cohere.embed-english-v3` | English text. Embeds up to 96 texts per request. | | `cohere.embed-multilingual-v3` | Multilingual text. Embeds up to 96 texts per request. | | `cohere.embed-v4:0` | Text. Embeds up to 96 texts per request. Supports a configurable output size of 256, 512, 1024, or 1536. TypeScript only. | Custom output sizes are model specific. In Python, only Titan Text Embeddings V2 accepts one. In TypeScript, Titan Text Embeddings V2 and Cohere Embed v4 both do, and `embeddingDims` is ignored on Titan V1 and on Cohere v3, which have no such parameter. When you do set it, make sure your vector store dimension matches, otherwise inserts will fail. Bedrock caps a Cohere embedding call at 96 texts. The TypeScript SDK splits larger batches into multiple requests for you, so a 200 text batch becomes 3 calls. ### Config Here are the parameters available for configuring AWS Bedrock embedder: **Python** | Parameter | Description | Default Value | | - | - | - | | `model` | The name of the embedding model to use | `amazon.titan-embed-text-v1` | | `aws_region` | AWS region for the Bedrock client | `us-west-2` | | `aws_access_key_id` | AWS access key ID for authentication | `None` | | `aws_secret_access_key` | AWS secret access key for authentication | `None` | | `aws_session_token` | AWS session token for temporary credentials | `None` | **TypeScript** | Parameter | Description | Default Value | | - | - | - | | `model` | The name of the embedding model to use | `amazon.titan-embed-text-v1` | | `awsRegion` | AWS region for the Bedrock client. Falls back to the `AWS_REGION` environment variable | `us-west-2` | | `embeddingDims` | Output vector size. Titan Text Embeddings V2 (256, 512, or 1024) and Cohere Embed v4 (256, 512, 1024, or 1536) only | `undefined` | | `awsAccessKeyId` | AWS access key ID for authentication | `undefined` | | `awsSecretAccessKey` | AWS secret access key for authentication | `undefined` | | `awsSessionToken` | AWS session token for temporary credentials | `undefined` | Omit the three credential fields to use the AWS default credential chain. If you do pass them, `awsAccessKeyId` and `awsSecretAccessKey` are both required. # Azure OpenAI as Embedding Provider Source: https://docs.mem0.ai/components/embedders/models/azure-openai Configure Azure OpenAI as an embedding provider in Mem0 with API key, deployment, and endpoint settings. To use Azure OpenAI embedding models, set the `EMBEDDING_AZURE_OPENAI_API_KEY`, `EMBEDDING_AZURE_DEPLOYMENT`, `EMBEDDING_AZURE_ENDPOINT` and `EMBEDDING_AZURE_API_VERSION` environment variables. You can obtain the Azure OpenAI API key from the Azure Portal. ### Usage ```python Python theme={null} import os from mem0 import Memory os.environ["EMBEDDING_AZURE_OPENAI_API_KEY"] = "your-api-key" os.environ["EMBEDDING_AZURE_DEPLOYMENT"] = "your-deployment-name" os.environ["EMBEDDING_AZURE_ENDPOINT"] = "your-api-base-url" os.environ["EMBEDDING_AZURE_API_VERSION"] = "version-to-use" os.environ["OPENAI_API_KEY"] = "your_api_key" # For LLM config = { "embedder": { "provider": "azure_openai", "config": { "model": "text-embedding-3-large", "azure_kwargs": { "api_version": "", "azure_deployment": "", "azure_endpoint": "", "api_key": "", "default_headers": { "CustomHeader": "your-custom-header", } } } } } m = Memory.from_config(config) messages = [ {"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"}, {"role": "assistant", "content": "How about thriller movies? They can be quite engaging."}, {"role": "user", "content": "I’m not a big fan of thriller movies but I love sci-fi movies."}, {"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."} ] m.add(messages, user_id="john") ``` ```typescript TypeScript theme={null} import { Memory } from 'mem0ai/oss'; const config = { embedder: { provider: "azure_openai", config: { model: "text-embedding-3-large", modelProperties: { endpoint: "your-api-base-url", deployment: "your-deployment-name", apiVersion: "version-to-use", } } } } const memory = new Memory(config); const messages = [ {"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"}, {"role": "assistant", "content": "How about thriller movies? They can be quite engaging."}, {"role": "user", "content": "I’m not a big fan of thriller movies but I love sci-fi movies."}, {"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."} ] await memory.add(messages, { userId: "john" }); ``` As an alternative to using an API key, the Azure Identity credential chain can be used to authenticate with [Azure OpenAI role-based security](https://learn.microsoft.com/en-us/azure/ai-foundry/openai/how-to/role-based-access-control). > [!NOTE] > > If an API key is provided, it will be used for authentication over an Azure Identity Below is a sample configuration for using Mem0 with Azure OpenAI and Azure Identity: ```python theme={null} import os from mem0 import Memory # You can set the values directly in the config dictionary or use environment variables os.environ["LLM_AZURE_DEPLOYMENT"] = "your-deployment-name" os.environ["LLM_AZURE_ENDPOINT"] = "your-api-base-url" os.environ["LLM_AZURE_API_VERSION"] = "version-to-use" config = { "llm": { "provider": "azure_openai_structured", "config": { "model": "your-deployment-name", "temperature": 0.1, "max_tokens": 2000, "azure_kwargs": { "azure_deployment": "", "api_version": "", "azure_endpoint": "", "default_headers": { "CustomHeader": "your-custom-header", } } } } } ``` Refer to [Azure Identity troubleshooting tips](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/identity/azure-identity/TROUBLESHOOTING.md#troubleshoot-environmentcredential-authentication-issues) for setting up an Azure Identity credential. ### Config Here are the parameters available for configuring Azure OpenAI embedder: **Python** | Parameter | Description | Default Value | | - | - | - | | `model` | The name of the embedding model to use | `text-embedding-3-small` | | `embedding_dims` | Dimensions of the embedding model | `1536` | | `azure_kwargs` | The Azure OpenAI configs | `config_keys` | **TypeScript** | Parameter | Description | Default Value | | - | - | - | | `model` | The name of the embedding model to use | `text-embedding-3-small` | | `embeddingDims` | Dimensions of the embedding model | `1536` | | `apiKey` | Azure OpenAI API key | `None` | | `modelProperties` | Object containing endpoint and other settings | `{ endpoint: "",...rest }` | # FastEmbed Source: https://docs.mem0.ai/components/embedders/models/fastembed Configure FastEmbed as an embedding provider in Mem0 to generate embeddings locally using ONNX-based models without a GPU. You can use FastEmbed to run embedding models locally in Mem0. FastEmbed is an ONNX-based embedding library that runs efficiently on CPU without requiring a GPU or an external API key. ### Installation FastEmbed is an optional dependency, so install it alongside Mem0. ```bash Python theme={null} pip install fastembed ``` ```bash TypeScript theme={null} npm install fastembed ``` ### Usage ```python Python theme={null} import os from mem0 import Memory os.environ["OPENAI_API_KEY"] = "your_api_key" # For LLM config = { "embedder": { "provider": "fastembed", "config": { "model": "thenlper/gte-large" } } } m = Memory.from_config(config) messages = [ {"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"}, {"role": "assistant", "content": "How about thriller movies? They can be quite engaging."}, {"role": "user", "content": "I'm not a big fan of thriller movies but I love sci-fi movies."}, {"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."} ] m.add(messages, user_id="john") ``` ```typescript TypeScript theme={null} import { Memory } from "mem0ai/oss"; // FastEmbed needs no API key. Leave the embedder config empty to use the // default model (fast-bge-small-en-v1.5), or set `model` to one of the // supported models listed below. const memory = new Memory({ embedder: { provider: "fastembed", config: { model: "fast-bge-small-en-v1.5", }, }, llm: { provider: "openai", config: { apiKey: process.env.OPENAI_API_KEY }, // For fact extraction }, }); const messages = [ { role: "user", content: "I'm planning to watch a movie tonight. Any recommendations?" }, { role: "assistant", content: "How about thriller movies? They can be quite engaging." }, { role: "user", content: "I'm not a big fan of thriller movies but I love sci-fi movies." }, { role: "assistant", content: "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future." }, ]; await memory.add(messages, { userId: "john" }); ``` > [!NOTE] > > **The Python and TypeScript SDKs default to different models.** Python defaults to `thenlper/gte-large` (1024 dimensions), while TypeScript defaults to `fast-bge-small-en-v1.5` (384 dimensions). The TypeScript package (`fastembed` on npm) ships a fixed set of ONNX models and does not include `thenlper/gte-large`. Because the two defaults produce vectors of different dimensions, do not point both SDKs at the same vector store collection unless you configure them to use the same model. The TypeScript SDK supports these FastEmbed models. Pass the exact string as `model`: * `fast-bge-small-en-v1.5` (default) * `fast-bge-small-en` * `fast-bge-base-en` * `fast-bge-base-en-v1.5` * `fast-bge-small-zh-v1.5` * `fast-all-MiniLM-L6-v2` * `fast-multilingual-e5-large` ### Config Here are the parameters available for configuring the FastEmbed embedder: **Python** | Parameter | Description | Default Value | | - | - | - | | `model` | The name of the FastEmbed model to use | `thenlper/gte-large` | | `embedding_dims` | Dimensions of the embedding model (auto-derived from the model if not set) | `None` | **TypeScript** | Parameter | Description | Default Value | | - | - | - | | `model` | The FastEmbed model to use (see the supported list above) | `fast-bge-small-en-v1.5` | The embedding dimension is detected automatically at startup, so you do not need to set it manually. # Google AI as Embedding Provider Source: https://docs.mem0.ai/components/embedders/models/google-ai Configure Google AI as an embedding provider in Mem0 using Gemini models and the GOOGLE_API_KEY variable. To use Google AI embedding models, set the `GOOGLE_API_KEY` environment variables. You can obtain the Gemini API key from [here](https://aistudio.google.com/app/apikey). ### Usage ```python Python theme={null} import os from mem0 import Memory os.environ["GOOGLE_API_KEY"] = "key" os.environ["OPENAI_API_KEY"] = "your_api_key" # For LLM config = { "embedder": { "provider": "gemini", "config": { "model": "models/gemini-embedding-001", } } } m = Memory.from_config(config) messages = [ {"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"}, {"role": "assistant", "content": "How about thriller movies? They can be quite engaging."}, {"role": "user", "content": "I'm not a big fan of thriller movies but I love sci-fi movies."}, {"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."} ] m.add(messages, user_id="john") ``` ```typescript TypeScript theme={null} import { Memory } from 'mem0ai/oss'; const config = { embedder: { provider: "google", config: { apiKey: process.env["GOOGLE_API_KEY"], model: "gemini-embedding-001", embeddingDims: 1536, }, }, }; const memory = new Memory(config); const messages = [ {"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"}, {"role": "assistant", "content": "How about thriller movies? They can be quite engaging."}, {"role": "user", "content": "I'm not a big fan of thriller movies but I love sci-fi movies."}, {"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."} ] await memory.add(messages, { userId: "john" }); ``` ### Config Here are the parameters available for configuring Gemini embedder: **Python** | Parameter | Description | Default Value | | - | - | - | | `model` | The name of the embedding model to use | `models/gemini-embedding-001` | | `embedding_dims` | Dimensions of the embedding model | `768` | | `api_key` | The Google API key | `None` | | `output_dimensionality` | Output dimensionality for the embedding model (Gemini-specific; used when `embedding_dims` is not set) | `None` | **TypeScript** | Parameter | Description | Default Value | | - | - | - | | `model` | The name of the embedding model to use | `gemini-embedding-001` | | `embeddingDims` | Dimensions of the embedding model. When not set, uses the model's native output dimensionality (3072 for `gemini-embedding-001`; MRL truncation to 768, 1536, or 3072 is supported) | `None` | | `apiKey` | Google API key | `None` | # Hugging Face Source: https://docs.mem0.ai/components/embedders/models/huggingface Configure Hugging Face as an embedding provider in Mem0 for local embedding generation with open-source models. You can use embedding models from Huggingface to run Mem0 locally. > [!NOTE] > > The TypeScript SDK supports Hugging Face only through a hosted [Text Embeddings Inference (TEI)](#using-text-embeddings-inference-tei) endpoint, or any OpenAI-compatible Hugging Face endpoint. The local `sentence-transformers` mode shown first is Python-only. ### Usage ```python theme={null} import os from mem0 import Memory os.environ["OPENAI_API_KEY"] = "your_api_key" # For LLM config = { "embedder": { "provider": "huggingface", "config": { "model": "multi-qa-MiniLM-L6-cos-v1" } } } m = Memory.from_config(config) messages = [ {"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"}, {"role": "assistant", "content": "How about thriller movies? They can be quite engaging."}, {"role": "user", "content": "I'm not a big fan of thriller movies but I love sci-fi movies."}, {"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."} ] m.add(messages, user_id="john") ``` ### Using Text Embeddings Inference (TEI) You can also use Hugging Face's Text Embeddings Inference service for faster and more efficient embeddings. This is the mode the TypeScript SDK uses. ```python Python theme={null} import os from mem0 import Memory os.environ["OPENAI_API_KEY"] = "your_api_key" # For LLM # Using HuggingFace Text Embeddings Inference API config = { "embedder": { "provider": "huggingface", "config": { "huggingface_base_url": "http://localhost:3000/v1" } } } m = Memory.from_config(config) m.add("This text will be embedded using the TEI service.", user_id="john") ``` ```typescript TypeScript theme={null} import { Memory } from 'mem0ai/oss'; // Point at a running TEI server, or any OpenAI-compatible HF endpoint const config = { embedder: { provider: 'huggingface', config: { huggingfaceBaseUrl: 'http://localhost:3000/v1', }, }, }; const memory = new Memory(config); await memory.add("This text will be embedded using the TEI service.", { userId: "john" }); ``` To run the TEI service, you can use Docker: ```bash theme={null} docker run -d -p 3000:80 -v huggingfacetei:/data --platform linux/amd64 \ ghcr.io/huggingface/text-embeddings-inference:cpu-1.6 \ --model-id BAAI/bge-small-en-v1.5 ``` ### Config Here are the parameters available for configuring the Hugging Face embedder: **Python** | Parameter | Description | Default Value | | - | - | - | | `model` | The name of the model to use | `multi-qa-MiniLM-L6-cos-v1` | | `embedding_dims` | Dimensions of the embedding model | `selected_model_dimensions` | | `model_kwargs` | Additional arguments for the model | `None` | | `huggingface_base_url` | URL to connect to Text Embeddings Inference (TEI) API | `None` | | `api_key` | API key for the endpoint; falls back to the `HUGGINGFACE_API_KEY` env var. Only used on the `huggingface_base_url` path | `"hf"` | **TypeScript** | Parameter | Description | Default Value | | - | - | - | | `huggingfaceBaseUrl` | TEI or OpenAI-compatible endpoint URL. Required; falls back to `baseURL`, `url`, then the `HUGGINGFACE_BASE_URL` env var | `None` | | `model` | Model name sent to the endpoint (TEI ignores it) | `tei` | | `apiKey` | API key for the endpoint; falls back to the `HUGGINGFACE_API_KEY` env var | `"hf"` | # LangChain as Embedding Provider Source: https://docs.mem0.ai/components/embedders/models/langchain Use LangChain as an embedding provider in Mem0 to access a wide range of models through a unified interface. Mem0 supports LangChain as a provider to access a wide range of embedding models. LangChain is a framework for developing applications powered by language models, making it easy to integrate various embedding providers through a consistent interface. For a complete list of available embedding models supported by LangChain, refer to the [LangChain Text Embedding documentation](https://python.langchain.com/docs/integrations/text_embedding/). ## Usage ```python Python theme={null} import os from mem0 import Memory from langchain_openai import OpenAIEmbeddings # Set necessary environment variables for your chosen LangChain provider os.environ["OPENAI_API_KEY"] = "your-api-key" # Initialize a LangChain embeddings model directly openai_embeddings = OpenAIEmbeddings( model="text-embedding-3-small", dimensions=1536 ) # Pass the initialized model to the config config = { "embedder": { "provider": "langchain", "config": { "model": openai_embeddings } } } m = Memory.from_config(config) messages = [ {"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"}, {"role": "assistant", "content": "How about thriller movies? They can be quite engaging."}, {"role": "user", "content": "I'm not a big fan of thriller movies but I love sci-fi movies."}, {"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."} ] m.add(messages, user_id="alice", metadata={"category": "movies"}) ``` ```typescript TypeScript theme={null} import { Memory } from 'mem0ai/oss'; import { OpenAIEmbeddings } from "@langchain/openai"; // Initialize a LangChain embeddings model directly const openaiEmbeddings = new OpenAIEmbeddings({ modelName: "text-embedding-3-small", dimensions: 1536, apiKey: process.env.OPENAI_API_KEY, }); const config = { embedder: { provider: 'langchain', config: { model: openaiEmbeddings, }, }, }; const memory = new Memory(config); const messages = [ {"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"}, {"role": "assistant", "content": "How about thriller movies? They can be quite engaging."}, {"role": "user", "content": "I'm not a big fan of thriller movies but I love sci-fi movies."}, {"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."} ] await memory.add(messages, { userId: "alice", metadata: { category: "movies" } }); ``` ## Supported LangChain Embedding Providers LangChain supports a wide range of embedding providers, including: * OpenAI (`OpenAIEmbeddings`) * Cohere (`CohereEmbeddings`) * Google (`VertexAIEmbeddings`) * Hugging Face (`HuggingFaceEmbeddings`) * Sentence Transformers (`HuggingFaceEmbeddings`) * Azure OpenAI (`AzureOpenAIEmbeddings`) * Ollama (`OllamaEmbeddings`) * Together (`TogetherEmbeddings`) * And many more You can use any of these model instances directly in your configuration. For a complete and up-to-date list of available embedding providers, refer to the [LangChain Text Embedding documentation](https://python.langchain.com/docs/integrations/text_embedding/). ## Provider-Specific Configuration When using LangChain as an embedder provider, you'll need to: 1. Set the appropriate environment variables for your chosen embedding provider 2. Import and initialize the specific model class you want to use 3. Pass the initialized model instance to the config ### Examples with Different Providers #### HuggingFace Embeddings ```python Python theme={null} from langchain_huggingface import HuggingFaceEmbeddings # Initialize a HuggingFace embeddings model hf_embeddings = HuggingFaceEmbeddings( model_name="BAAI/bge-small-en-v1.5", encode_kwargs={"normalize_embeddings": True} ) config = { "embedder": { "provider": "langchain", "config": { "model": hf_embeddings } } } ``` ```typescript TypeScript theme={null} import { Memory } from 'mem0ai/oss'; import { HuggingFaceEmbeddings } from "@langchain/community/embeddings/hf"; // Initialize a HuggingFace embeddings model const hfEmbeddings = new HuggingFaceEmbeddings({ modelName: "BAAI/bge-small-en-v1.5", encode: { normalize_embeddings: true, }, }); const config = { embedder: { provider: 'langchain', config: { model: hfEmbeddings, }, }, }; ``` #### Ollama Embeddings ```python Python theme={null} from langchain_ollama import OllamaEmbeddings # Initialize an Ollama embeddings model ollama_embeddings = OllamaEmbeddings( model="nomic-embed-text" ) config = { "embedder": { "provider": "langchain", "config": { "model": ollama_embeddings } } } ``` ```typescript TypeScript theme={null} import { Memory } from 'mem0ai/oss'; import { OllamaEmbeddings } from "@langchain/community/embeddings/ollama"; // Initialize an Ollama embeddings model const ollamaEmbeddings = new OllamaEmbeddings({ model: "nomic-embed-text", baseUrl: "http://localhost:11434", // Ollama server URL }); const config = { embedder: { provider: 'langchain', config: { model: ollamaEmbeddings, }, }, }; ``` > [!NOTE] > > Make sure to install the necessary LangChain packages and any provider-specific dependencies. ## Config All available parameters for the `langchain` embedder config are present in [Master List of All Params in Config](../config). # LM Studio as Embedding Provider Source: https://docs.mem0.ai/components/embedders/models/lmstudio Configure LM Studio as an embedding provider in Mem0 for local embedding generation with models like nomic-embed-text. You can use embedding models from LM Studio to run Mem0 locally. ### Usage ```python theme={null} import os from mem0 import Memory os.environ["OPENAI_API_KEY"] = "your_api_key" # For LLM config = { "embedder": { "provider": "lmstudio", "config": { "model": "nomic-ai/nomic-embed-text-v1.5-GGUF" } } } m = Memory.from_config(config) messages = [ {"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"}, {"role": "assistant", "content": "How about thriller movies? They can be quite engaging."}, {"role": "user", "content": "I’m not a big fan of thriller movies but I love sci-fi movies."}, {"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."} ] m.add(messages, user_id="john") ``` ### Config Here are the parameters available for configuring LM Studio embedder: | Parameter | Description | Default Value | | - | - | - | | `model` | The name of the LM Studio model to use | `nomic-ai/nomic-embed-text-v1.5-GGUF` | | `embedding_dims` | Dimensions of the embedding model | `1536` | | `lmstudio_base_url` | Base URL for LM Studio connection | `http://localhost:1234/v1` | # Ollama as Embedding Provider Source: https://docs.mem0.ai/components/embedders/models/ollama Configure Ollama as an embedding provider in Mem0 to generate embeddings locally using open-source models. You can use embedding models from Ollama to run Mem0 locally. ### Usage ```python Python theme={null} import os from mem0 import Memory os.environ["OPENAI_API_KEY"] = "your_api_key" # For LLM config = { "embedder": { "provider": "ollama", "config": { "model": "mxbai-embed-large" } } } m = Memory.from_config(config) messages = [ {"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"}, {"role": "assistant", "content": "How about thriller movies? They can be quite engaging."}, {"role": "user", "content": "I'm not a big fan of thriller movies but I love sci-fi movies."}, {"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."} ] m.add(messages, user_id="john") ``` ```typescript TypeScript theme={null} import { Memory } from 'mem0ai/oss'; const config = { embedder: { provider: 'ollama', config: { model: 'nomic-embed-text:latest', // or any other Ollama embedding model url: 'http://localhost:11434', // Ollama server URL }, }, }; const memory = new Memory(config); const messages = [ {"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"}, {"role": "assistant", "content": "How about thriller movies? They can be quite engaging."}, {"role": "user", "content": "I'm not a big fan of thriller movies but I love sci-fi movies."}, {"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."} ] await memory.add(messages, { userId: "john" }); ``` ### Config Here are the parameters available for configuring Ollama embedder: **Python** | Parameter | Description | Default Value | | - | - | - | | `model` | The name of the Ollama model to use | `nomic-embed-text` | | `embedding_dims` | Dimensions of the embedding model | `512` | | `ollama_base_url` | Base URL for ollama connection | `None` | **TypeScript** | Parameter | Description | Default Value | | - | - | - | | `model` | The name of the Ollama model to use | `nomic-embed-text:latest` | | `url` | Base URL for Ollama server | `http://localhost:11434` | | `embeddingDims` | Dimensions of the embedding model | 768 | # OpenAI as Embedding Provider Source: https://docs.mem0.ai/components/embedders/models/openai Configure OpenAI as an embedding provider in Mem0 using models like text-embedding-3-large for vector generation. To use OpenAI embedding models, set the `OPENAI_API_KEY` environment variable. You can obtain the OpenAI API key from the [OpenAI Platform](https://platform.openai.com/account/api-keys). ### Usage ```python Python theme={null} import os from mem0 import Memory os.environ["OPENAI_API_KEY"] = "your_api_key" config = { "embedder": { "provider": "openai", "config": { "model": "text-embedding-3-large" } } } m = Memory.from_config(config) messages = [ {"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"}, {"role": "assistant", "content": "How about thriller movies? They can be quite engaging."}, {"role": "user", "content": "I’m not a big fan of thriller movies but I love sci-fi movies."}, {"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."} ] m.add(messages, user_id="john") ``` ```typescript TypeScript theme={null} import { Memory } from 'mem0ai/oss'; const config = { embedder: { provider: 'openai', config: { apiKey: 'your-openai-api-key', model: 'text-embedding-3-large', }, }, }; const memory = new Memory(config); await memory.add("I'm visiting Paris", { userId: "john" }); ``` ### Config Here are the parameters available for configuring OpenAI embedder: **Python** | Parameter | Description | Default Value | | - | - | - | | `model` | The name of the embedding model to use | `text-embedding-3-small` | | `embedding_dims` | Dimensions of the embedding model | `1536` | | `api_key` | The OpenAI API key | `None` | **TypeScript** | Parameter | Description | Default Value | | - | - | - | | `model` | The name of the embedding model to use | `text-embedding-3-small` | | `embeddingDims` | Dimensions of the embedding model | `1536` | | `apiKey` | The OpenAI API key | `None` | # Together AI as Embedding Provider Source: https://docs.mem0.ai/components/embedders/models/together Configure Together AI as an embedding provider in Mem0 with support for 1024-dimensional embedding models. To use Together embedding models, set the `TOGETHER_API_KEY` environment variable. You can obtain the Together API key from the [Together Platform](https://api.together.ai/settings/projects/~current/api-keys). ### Usage > [!NOTE] > > The `embedding_model_dims` parameter for `vector_store` should be set to `1024` for Together embedder. > [!WARNING] > > **Breaking default change.** The default Together embedding model is now `intfloat/multilingual-e5-large-instruct` (**1024-dim**), replacing the previous default `togethercomputer/m2-bert-80M-8k-retrieval` (**768-dim**). If you created a self-hosted vector store with the old default, its collection is 768-dim and will reject the new 1024-dim vectors — **recreate/reindex the collection at 1024 dimensions** after upgrading. To defer the change, pin the previous values explicitly (`model="togethercomputer/m2-bert-80M-8k-retrieval"`, `embedding_dims=768`) — note Together no longer lists this model among its recommended embeddings, so reindexing at 1024 is the durable path. ```python Python theme={null} import os from mem0 import Memory os.environ["TOGETHER_API_KEY"] = "your_api_key" os.environ["OPENAI_API_KEY"] = "your_api_key" # For LLM config = { "embedder": { "provider": "together", "config": { "model": "intfloat/multilingual-e5-large-instruct" } } } m = Memory.from_config(config) messages = [ {"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"}, {"role": "assistant", "content": "How about thriller movies? They can be quite engaging."}, {"role": "user", "content": "I'm not a big fan of thriller movies but I love sci-fi movies."}, {"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."} ] m.add(messages, user_id="john") ``` ```typescript TypeScript theme={null} import { Memory } from 'mem0ai/oss'; const config = { embedder: { provider: 'together', config: { apiKey: process.env.TOGETHER_API_KEY || '', model: 'intfloat/multilingual-e5-large-instruct', embeddingDims: 1024, }, }, }; const memory = new Memory(config); await memory.add("I'm visiting Paris", { userId: "john" }); ``` ### Config Here are the parameters available for configuring Together embedder: **Python** | Parameter | Description | Default Value | | - | - | - | | `model` | The name of the embedding model to use | `intfloat/multilingual-e5-large-instruct` | | `embedding_dims` | Dimensions of the embedding model | `1024` | | `api_key` | The Together API key | `None` | **TypeScript** | Parameter | Description | Default Value | | - | - | - | | `model` | The name of the embedding model to use | `intfloat/multilingual-e5-large-instruct` | | `embeddingDims` | Dimensions of the embedding model for vector store configuration | `1024` | | `apiKey` | The Together API key | `TOGETHER_API_KEY` | | `baseURL` | Base URL for an OpenAI-compatible Together endpoint | `https://api.together.ai/v1` | # Vertex AI Source: https://docs.mem0.ai/components/embedders/models/vertexai Configure Google Cloud Vertex AI as an embedding provider in Mem0 with support for task-specific embedding types. ### Vertex AI Google Cloud's Vertex AI serves text embedding models such as `gemini-embedding-001`. Mem0 uses them through the provider's own SDK, which you install alongside Mem0. ### Installation The Vertex AI client is an optional dependency, so install it yourself. ```bash Python theme={null} pip install vertexai ``` ```bash TypeScript theme={null} npm install @google-cloud/aiplatform ``` ### Authentication Both SDKs authenticate with [Application Default Credentials](https://cloud.google.com/docs/authentication/application-default-credentials). Pick whichever fits your environment: * **Local development:** run `gcloud auth application-default login`. * **Service account:** create a key in the [Google Cloud Console](https://console.cloud.google.com/) and point `GOOGLE_APPLICATION_CREDENTIALS` at the JSON file, or pass its path through the embedder config. * **Google Cloud runtimes** (Cloud Run, GKE, Compute Engine): the attached service account is picked up automatically. The TypeScript SDK reads the project ID from `googleProjectId`, then the `GCP_PROJECT_ID`, `GOOGLE_CLOUD_PROJECT`, and `GCLOUD_PROJECT` environment variables, and finally from your credentials. Set it explicitly when your credentials cover more than one project. ### Usage ```python Python theme={null} import os from mem0 import Memory # Set the path to your Google Cloud credentials JSON file os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "/path/to/your/credentials.json" os.environ["OPENAI_API_KEY"] = "your_api_key" # For LLM config = { "embedder": { "provider": "vertexai", "config": { "model": "gemini-embedding-001", "memory_add_embedding_type": "RETRIEVAL_DOCUMENT", "memory_update_embedding_type": "RETRIEVAL_DOCUMENT", "memory_search_embedding_type": "RETRIEVAL_QUERY" } } } m = Memory.from_config(config) messages = [ {"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"}, {"role": "assistant", "content": "How about thriller movies? They can be quite engaging."}, {"role": "user", "content": "I'm not a big fan of thriller movies but I love sci-fi movies."}, {"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."} ] m.add(messages, user_id="john") ``` ```typescript TypeScript theme={null} import { Memory } from "mem0ai/oss"; const config = { embedder: { provider: "vertexai", config: { model: "gemini-embedding-001", // Optional. Falls back to GCP_PROJECT_ID / GOOGLE_CLOUD_PROJECT / // GCLOUD_PROJECT, then to the project on your credentials. googleProjectId: process.env.GCP_PROJECT_ID, location: "us-central1", // Optional. Path to a service account key file, or pass the JSON inline // via googleServiceAccountJson. vertexCredentialsJson: "/path/to/your/credentials.json", embeddingDims: 256, memoryAddEmbeddingType: "RETRIEVAL_DOCUMENT", memoryUpdateEmbeddingType: "RETRIEVAL_DOCUMENT", memorySearchEmbeddingType: "RETRIEVAL_QUERY", }, }, }; const memory = new Memory(config); await memory.add("I love sci-fi movies but not thrillers", { userId: "john" }); ``` ### Embedding types Vertex AI embeds the same text differently depending on the task you declare. The embedding types can be one of the following: * SEMANTIC\_SIMILARITY * CLASSIFICATION * CLUSTERING * RETRIEVAL\_DOCUMENT, RETRIEVAL\_QUERY, QUESTION\_ANSWERING, FACT\_VERIFICATION * CODE\_RETRIEVAL\_QUERY Check out the [Vertex AI documentation](https://cloud.google.com/vertex-ai/generative-ai/docs/embeddings/task-types#supported_task_types) for more information. > [!NOTE] > > These embedding types map to the add, update, and search memory actions in both the Python and TypeScript SDKs. Stored memories use the add or update type, and searches use the search type. ### Choosing a model > [!WARNING] > > `gemini-embedding-001` accepts **one input text per request**. When Mem0 embeds several texts at once, such as the memories extracted from a single conversation turn, it issues one request per text. The older `text-embedding-005` and `text-multilingual-embedding-002` models accept up to 250 texts per request, so they are faster and cheaper for large batches. See [Get text embeddings](https://cloud.google.com/vertex-ai/generative-ai/docs/embeddings/get-text-embeddings). ### Config Here are the parameters available for configuring the Vertex AI embedder: **Python** | Parameter | Description | Default Value | | - | - | - | | `model` | The name of the Vertex AI embedding model to use | `gemini-embedding-001` | | `vertex_credentials_json` | Path to the Google Cloud credentials JSON file | `None` | | `embedding_dims` | Dimensions of the embedding model | `256` | | `memory_add_embedding_type` | The embedding type to use for the add memory action | `RETRIEVAL_DOCUMENT` | | `memory_update_embedding_type` | The embedding type to use for the update memory action | `RETRIEVAL_DOCUMENT` | | `memory_search_embedding_type` | The embedding type to use for the search memory action | `RETRIEVAL_QUERY` | **TypeScript** | Parameter | Description | Default Value | | - | - | - | | `model` | The name of the Vertex AI embedding model to use | `gemini-embedding-001` | | `googleProjectId` | Google Cloud project ID (falls back to `GCP_PROJECT_ID` env var, then to your credentials) | Resolved from credentials | | `location` | Google Cloud region (falls back to `GCP_LOCATION` env var) | `us-central1` | | `vertexCredentialsJson` | Path to the Google Cloud credentials JSON file | `None` | | `googleServiceAccountJson` | Service account credentials as a JSON string or object | `None` | | `embeddingDims` | Dimensions of the embedding model | `256` | | `memoryAddEmbeddingType` | The embedding type to use for the add memory action | `RETRIEVAL_DOCUMENT` | | `memoryUpdateEmbeddingType` | The embedding type to use for the update memory action | `RETRIEVAL_DOCUMENT` | | `memorySearchEmbeddingType` | The embedding type to use for the search memory action | `RETRIEVAL_QUERY` | # Embedding Providers Overview Source: https://docs.mem0.ai/components/embedders/overview Overview of all supported embedding model providers in Mem0, including OpenAI, Azure, Ollama, and more. Mem0 offers support for various embedding models, allowing users to choose the one that best suits their needs. ## Supported Embedders See the list of supported embedders below. > [!NOTE] > > All embedders listed below are supported in the Python implementation. The TypeScript implementation supports: **OpenAI**, **Azure OpenAI**, **AWS Bedrock**, **FastEmbed**, **Google AI**, **Hugging Face**, **Langchain**, **LM Studio**, **Ollama**, **Together**, and **Vertex AI**. > **[OpenAI](/components/embedders/models/openai)** > **[Azure OpenAI](/components/embedders/models/azure-openai)** > **[Ollama](/components/embedders/models/ollama)** > **[Hugging Face](/components/embedders/models/huggingface)** > **[Google AI](/components/embedders/models/google-ai)** > **[Vertex AI](/components/embedders/models/vertexai)** > **[Together](/components/embedders/models/together)** > **[LM Studio](/components/embedders/models/lmstudio)** > **[Langchain](/components/embedders/models/langchain)** > **[AWS Bedrock](/components/embedders/models/aws-bedrock)** > **[FastEmbed](/components/embedders/models/fastembed)** ## Usage To utilize an embedding model, you must provide a configuration to customize its usage. If no configuration is supplied, a default configuration will be applied, and `OpenAI` will be used as the embedding model. For a comprehensive list of available parameters for embedding model configuration, please refer to [Config](./config). # LLM Configuration Reference Source: https://docs.mem0.ai/components/llms/config Reference for LLM configuration options in Mem0 for Python and TypeScript, including value precedence rules. ## How to define configurations? **Python** The `config` is defined as a Python dictionary with two main keys: * `llm`: Specifies the llm provider and its configuration * `provider`: The name of the llm (e.g., "openai", "groq") * `config`: A nested dictionary containing provider-specific settings **TypeScript** The `config` is defined as a TypeScript object with these keys: * `llm`: Specifies the LLM provider and its configuration (required) * `provider`: The name of the LLM (e.g., "openai", "groq") * `config`: A nested object containing provider-specific settings * `embedder`: Specifies the embedder provider and its configuration (optional) * `vectorStore`: Specifies the vector store provider and its configuration (optional) * `historyDbPath`: Path to the history database file (optional) ### Config Values Precedence Config values are applied in the following order of precedence (from highest to lowest): 1. Values explicitly set in the `config` object/dictionary 2. Environment variables (e.g., `OPENAI_API_KEY`, `OPENAI_BASE_URL`) 3. Default values defined in the LLM implementation This means that values specified in the `config` will override corresponding environment variables, which in turn override default values. ## How to Use Config Here's a general example of how to use the config with Mem0: ```python Python theme={null} import os from mem0 import Memory os.environ["OPENAI_API_KEY"] = "sk-xx" # for embedder config = { "llm": { "provider": "your_chosen_provider", "config": { # Provider-specific settings go here } } } m = Memory.from_config(config) m.add("Your text here", user_id="user", metadata={"category": "example"}) ``` ```typescript TypeScript theme={null} import { Memory } from 'mem0ai/oss'; // Minimal configuration with just the LLM settings const config = { llm: { provider: 'your_chosen_provider', config: { // Provider-specific settings go here } } }; const memory = new Memory(config); await memory.add("Your text here", { userId: "user123", metadata: { category: "example" } }); ``` ## Why is Config Needed? Config is essential for: 1. Specifying which LLM to use. 2. Providing necessary connection details (e.g., model, api\_key, temperature). 3. Ensuring proper initialization and connection to your chosen LLM. ## Master List of All Params in Config Here's a comprehensive list of all parameters that can be used across different LLMs: **Python** | Parameter | Description | Provider | | - | - | - | | `model` | Embedding model to use | All | | `temperature` | Temperature of the model | All | | `api_key` | API key to use | All | | `max_tokens` | Tokens to generate | All | | `top_p` | Probability threshold for nucleus sampling | All | | `top_k` | Number of highest probability tokens to keep | All | | `http_client_proxies` | Allow proxy server settings | All | | `models` | List of models | Openrouter | | `route` | Routing strategy | Openrouter | | `openrouter_base_url` | Base URL for Openrouter API | Openrouter | | `site_url` | Site URL | Openrouter | | `app_name` | Application name | Openrouter | | `ollama_base_url` | Base URL for Ollama API | Ollama | | `openai_base_url` | Base URL for OpenAI API | OpenAI | | `azure_kwargs` | Azure LLM args for initialization | AzureOpenAI | | `deepseek_base_url` | Base URL for DeepSeek API | DeepSeek | | `xai_base_url` | Base URL for XAI API | XAI | | `sarvam_base_url` | Base URL for Sarvam API | Sarvam | | `reasoning_effort` | Reasoning level (low, medium, high) | All | | `frequency_penalty` | Penalize frequent tokens (-2.0 to 2.0) | Sarvam | | `presence_penalty` | Penalize existing tokens (-2.0 to 2.0) | Sarvam | | `seed` | Seed for deterministic sampling | Sarvam | | `stop` | Stop sequences (max 4) | Sarvam | | `lmstudio_base_url` | Base URL for LM Studio API | LM Studio | | `response_callback` | LLM response callback function | OpenAI | **TypeScript** | Parameter | Description | Provider | | - | - | - | | `model` | Embedding model to use | All | | `temperature` | Temperature of the model | All | | `apiKey` | API key to use | All | | `maxTokens` | Tokens to generate | All | | `topP` | Probability threshold for nucleus sampling | All | | `topK` | Number of highest probability tokens to keep | All | | `openaiBaseUrl` | Base URL for OpenAI API | OpenAI | ## Supported LLMs For detailed information on configuring specific LLMs, please visit the [LLMs](./overview) section. There you'll find information for each supported LLM with provider-specific usage examples and configuration details. # Anthropic Source: https://docs.mem0.ai/components/llms/models/anthropic Configure Anthropic Claude models as the LLM provider in Mem0 with API key setup and usage examples. To use Anthropic's models, please set the `ANTHROPIC_API_KEY` which you find on their [Account Settings Page](https://console.anthropic.com/account/keys). ## Usage ```python Python theme={null} import os from mem0 import Memory os.environ["OPENAI_API_KEY"] = "your-api-key" # used for embedding model os.environ["ANTHROPIC_API_KEY"] = "your-api-key" config = { "llm": { "provider": "anthropic", "config": { "model": "claude-sonnet-4-6", "temperature": 0.1, "max_tokens": 2000, } } } m = Memory.from_config(config) messages = [ {"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"}, {"role": "assistant", "content": "How about thriller movies? They can be quite engaging."}, {"role": "user", "content": "I’m not a big fan of thriller movies but I love sci-fi movies."}, {"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."} ] m.add(messages, user_id="alice", metadata={"category": "movies"}) ``` ```typescript TypeScript theme={null} import { Memory } from 'mem0ai/oss'; const config = { llm: { provider: 'anthropic', config: { apiKey: process.env.ANTHROPIC_API_KEY || '', model: 'claude-sonnet-4-6', temperature: 0.1, maxTokens: 2000, }, }, }; const memory = new Memory(config); const messages = [ {"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"}, {"role": "assistant", "content": "How about thriller movies? They can be quite engaging."}, {"role": "user", "content": "I’m not a big fan of thriller movies but I love sci-fi movies."}, {"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."} ] await memory.add(messages, { userId: "alice", metadata: { category: "movies" } }); ``` ## Config All available parameters for the `anthropic` config are present in [Master List of All Params in Config](../config). # AWS Bedrock as LLM Provider Source: https://docs.mem0.ai/components/llms/models/aws-bedrock Configure AWS Bedrock as an LLM provider in Mem0 with IAM authentication and Claude model support. ### Setup * Before using the AWS Bedrock LLM, make sure you have the appropriate model access from [Bedrock Console](https://us-east-1.console.aws.amazon.com/bedrock/home?region=us-east-1#/modelaccess). * Model availability is per-region. `anthropic.claude-sonnet-4-20250514-v1:0` supports on-demand inference in `us-east-1` and `ap-southeast-4`; from any other region, use the cross-region inference profile ID `us.anthropic.claude-sonnet-4-20250514-v1:0` instead. * Install the AWS SDK for your language: `pip install boto3` (Python) or `npm install @aws-sdk/client-bedrock-runtime` (TypeScript). * Both SDKs fall back to the standard AWS credential chain (environment variables, `~/.aws/credentials`, or an attached IAM role), so exporting `AWS_REGION`, `AWS_ACCESS_KEY_ID`, and `AWS_SECRET_ACCESS_KEY` is the quickest way to get started. In TypeScript you can also pass credentials inline with `awsRegion`, `awsAccessKeyId`, `awsSecretAccessKey`, and `awsSessionToken`, as shown below. ### Usage ```python Python theme={null} import os from mem0 import Memory os.environ['AWS_REGION'] = 'us-east-1' os.environ["AWS_ACCESS_KEY_ID"] = "xx" os.environ["AWS_SECRET_ACCESS_KEY"] = "xx" config = { "llm": { "provider": "aws_bedrock", "config": { "model": "anthropic.claude-sonnet-4-20250514-v1:0", "temperature": 0.2, "max_tokens": 2000, } } } m = Memory.from_config(config) messages = [ {"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"}, {"role": "assistant", "content": "How about thriller movies? They can be quite engaging."}, {"role": "user", "content": "I’m not a big fan of thriller movies but I love sci-fi movies."}, {"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."} ] m.add(messages, user_id="alice", metadata={"category": "movies"}) ``` ```typescript TypeScript theme={null} import { Memory } from 'mem0ai/oss'; const config = { llm: { provider: 'aws_bedrock', config: { model: 'anthropic.claude-sonnet-4-20250514-v1:0', temperature: 0.2, maxTokens: 2000, // Optional. Omit these to use the default AWS credential chain. awsRegion: process.env.AWS_REGION, awsAccessKeyId: process.env.AWS_ACCESS_KEY_ID, awsSecretAccessKey: process.env.AWS_SECRET_ACCESS_KEY, }, }, }; const memory = new Memory(config); const messages = [ {"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"}, {"role": "assistant", "content": "How about thriller movies? They can be quite engaging."}, {"role": "user", "content": "I’m not a big fan of thriller movies but I love sci-fi movies."}, {"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."} ]; await memory.add(messages, { userId: 'alice', metadata: { category: 'movies' } }); ``` > [!NOTE] > > `@aws-sdk/client-bedrock-runtime` is an optional peer dependency of `mem0ai`, so npm will not install it for you. The TypeScript provider loads it lazily and throws a clear error on the first request if the package is missing. > [!NOTE] > > The TypeScript provider calls the Bedrock [Converse API](https://docs.aws.amazon.com/bedrock/latest/userguide/conversation-inference.html), a single uniform interface across the current Bedrock model families. Streaming and `InvokeModel`-only models are not supported yet. ### Application inference profiles Bedrock resolves the model family from the model identifier. An application inference profile ARN ends in an opaque ID, so there is nothing to resolve from. Set `provider_override` (Python) / `providerOverride` (TypeScript) when your model is one: ```python Python theme={null} config = { "llm": { "provider": "aws_bedrock", "config": { "model": "arn:aws:bedrock:us-east-1:123456789012:application-inference-profile/abc123xyz", "provider_override": "anthropic", } } } ``` ```typescript TypeScript theme={null} const config = { llm: { provider: 'aws_bedrock', config: { model: 'arn:aws:bedrock:us-east-1:123456789012:application-inference-profile/abc123xyz', providerOverride: 'anthropic', }, }, }; ``` Without it, initialization raises `Unknown provider in model` (Python: `ValueError`; TypeScript: `Error`). Plain model IDs and cross-region inference profiles such as `us.anthropic.claude-sonnet-4-20250514-v1:0` still resolve automatically and need no override. ### Config All available parameters for the `aws_bedrock` config are present in [Master List of All Params in Config](../config). # Azure OpenAI as LLM Provider Source: https://docs.mem0.ai/components/llms/models/azure-openai Configure Azure OpenAI as an LLM provider in Mem0 with Azure Identity authentication and deployment settings. > [!NOTE] > > Mem0 Now Supports Azure OpenAI Models in TypeScript SDK To use Azure OpenAI models, you have to set the `LLM_AZURE_OPENAI_API_KEY`, `LLM_AZURE_ENDPOINT`, `LLM_AZURE_DEPLOYMENT` and `LLM_AZURE_API_VERSION` environment variables. You can obtain the Azure API key from the [Azure Portal](https://azure.microsoft.com/). Optionally, you can use Azure Identity to authenticate with Azure OpenAI, which allows you to use managed identities or service principals for production and Azure CLI login for development instead of an API key. If an Azure Identity is to be used, ***do not*** set the `LLM_AZURE_OPENAI_API_KEY` environment variable or the api\_key in the config dictionary. > **Note**: The following are currently unsupported with reasoning models `Parallel tool calling`,`temperature`, `top_p`, `presence_penalty`, `frequency_penalty`, `logprobs`, `top_logprobs`, `logit_bias`, `max_tokens` ## Usage ```python Python theme={null} import os from mem0 import Memory os.environ["OPENAI_API_KEY"] = "your-api-key" # used for embedding model os.environ["LLM_AZURE_OPENAI_API_KEY"] = "your-api-key" os.environ["LLM_AZURE_DEPLOYMENT"] = "your-deployment-name" os.environ["LLM_AZURE_ENDPOINT"] = "your-api-base-url" os.environ["LLM_AZURE_API_VERSION"] = "version-to-use" config = { "llm": { "provider": "azure_openai", "config": { "model": "your-deployment-name", "temperature": 0.1, "max_tokens": 2000, "azure_kwargs": { "azure_deployment": "", "api_version": "", "azure_endpoint": "", "api_key": "", "default_headers": { "CustomHeader": "your-custom-header", } } } } } m = Memory.from_config(config) messages = [ {"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"}, {"role": "assistant", "content": "How about thriller movies? They can be quite engaging."}, {"role": "user", "content": "I’m not a big fan of thriller movies but I love sci-fi movies."}, {"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."} ] m.add(messages, user_id="alice", metadata={"category": "movies"}) ``` ```typescript TypeScript theme={null} import { Memory } from 'mem0ai/oss'; const config = { llm: { provider: 'azure_openai', config: { apiKey: process.env.AZURE_OPENAI_API_KEY || '', modelProperties: { endpoint: 'https://your-api-base-url', deployment: 'your-deployment-name', modelName: 'your-model-name', apiVersion: 'version-to-use', // Any other parameters you want to pass to the Azure OpenAI API }, }, }, }; const memory = new Memory(config); const messages = [ {"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"}, {"role": "assistant", "content": "How about thriller movies? They can be quite engaging."}, {"role": "user", "content": "I’m not a big fan of thriller movies but I love sci-fi movies."}, {"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."} ] await memory.add(messages, { userId: "alice", metadata: { category: "movies" } }); ``` We also support the new [OpenAI structured-outputs](https://platform.openai.com/docs/guides/structured-outputs/introduction) model. Typescript SDK does not support the `azure_openai_structured` model yet. ```python theme={null} import os from mem0 import Memory os.environ["LLM_AZURE_OPENAI_API_KEY"] = "your-api-key" os.environ["LLM_AZURE_DEPLOYMENT"] = "your-deployment-name" os.environ["LLM_AZURE_ENDPOINT"] = "your-api-base-url" os.environ["LLM_AZURE_API_VERSION"] = "version-to-use" config = { "llm": { "provider": "azure_openai_structured", "config": { "model": "your-deployment-name", "temperature": 0.1, "max_tokens": 2000, "azure_kwargs": { "azure_deployment": "", "api_version": "", "azure_endpoint": "", "api_key": "", "default_headers": { "CustomHeader": "your-custom-header", } } } } } ``` As an alternative to using an API key, the Azure Identity credential chain can be used to authenticate with [Azure OpenAI role-based security](https://learn.microsoft.com/en-us/azure/ai-foundry/openai/how-to/role-based-access-control). > [!NOTE] > > If an API key is provided, it will be used for authentication over an Azure Identity Below is a sample configuration for using Mem0 with Azure OpenAI and Azure Identity: ```python theme={null} import os from mem0 import Memory # You can set the values directly in the config dictionary or use environment variables os.environ["LLM_AZURE_DEPLOYMENT"] = "your-deployment-name" os.environ["LLM_AZURE_ENDPOINT"] = "your-api-base-url" os.environ["LLM_AZURE_API_VERSION"] = "version-to-use" config = { "llm": { "provider": "azure_openai_structured", "config": { "model": "your-deployment-name", "temperature": 0.1, "max_tokens": 2000, "azure_kwargs": { "azure_deployment": "", "api_version": "", "azure_endpoint": "", "default_headers": { "CustomHeader": "your-custom-header", } } } } } ``` Refer to [Azure Identity troubleshooting tips](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/identity/azure-identity/TROUBLESHOOTING.md#troubleshoot-environmentcredential-authentication-issues) for setting up an Azure Identity credential. ## Config All available parameters for the `azure_openai` config are present in [Master List of All Params in Config](../config). # DeepSeek Source: https://docs.mem0.ai/components/llms/models/deepseek Configure DeepSeek as an LLM provider in Mem0 with API key setup and optional custom endpoint configuration. To use DeepSeek LLM models, you have to set the `DEEPSEEK_API_KEY` environment variable. You can also optionally set `DEEPSEEK_API_BASE` if you need to use a different API endpoint (defaults to `https://api.deepseek.com`). ## Usage ```python Python theme={null} import os from mem0 import Memory os.environ["DEEPSEEK_API_KEY"] = "your-api-key" os.environ["OPENAI_API_KEY"] = "your-api-key" # for embedder model config = { "llm": { "provider": "deepseek", "config": { "model": "deepseek-chat", # default model "temperature": 0.2, "max_tokens": 2000, "top_p": 1.0 } } } m = Memory.from_config(config) messages = [ {"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"}, {"role": "assistant", "content": "How about thriller movies? They can be quite engaging."}, {"role": "user", "content": "I’m not a big fan of thriller movies but I love sci-fi movies."}, {"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."} ] m.add(messages, user_id="alice", metadata={"category": "movies"}) ``` ```typescript TypeScript theme={null} import { Memory } from 'mem0ai/oss'; const config = { llm: { provider: 'deepseek', config: { apiKey: process.env.DEEPSEEK_API_KEY || '', model: 'deepseek-chat', temperature: 0.2, maxTokens: 2000, top_p: 1.0, }, }, }; const memory = new Memory(config); const messages = [ {"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"}, {"role": "assistant", "content": "How about thriller movies? They can be quite engaging."}, {"role": "user", "content": "I’m not a big fan of thriller movies but I love sci-fi movies."}, {"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."} ]; await memory.add(messages, { userId: 'alice', metadata: { category: 'movies' } }); ``` You can also configure the API base URL in the config: ```python theme={null} config = { "llm": { "provider": "deepseek", "config": { "model": "deepseek-chat", "deepseek_base_url": "https://your-custom-endpoint.com", "api_key": "your-api-key" # alternatively to using environment variable } } } ``` ## Config All available parameters for the `deepseek` config are present in [Master List of All Params in Config](../config). # Google AI as LLM Provider Source: https://docs.mem0.ai/components/llms/models/google-ai Configure Google Gemini as an LLM provider in Mem0 using the google.genai SDK and GOOGLE_API_KEY variable. To use the Gemini model, set the `GOOGLE_API_KEY` environment variable. You can obtain the Google/Gemini API key from [Google AI Studio](https://aistudio.google.com/app/apikey). > **Note:** As of the latest release, Mem0 uses the new `google.genai` SDK instead of the deprecated `google.generativeai`. All message formatting and model interaction now use the updated `types` module from `google.genai`. > **Note:** Some Gemini models are being deprecated and will retire soon. It is recommended to migrate to the latest stable models like `"gemini-2.0-flash-001"` or `"gemini-2.0-flash-lite-001"` to ensure ongoing support and improvements. ## Usage ```python Python theme={null} import os from mem0 import Memory os.environ["OPENAI_API_KEY"] = "your-openai-api-key" # Used for embedding model os.environ["GOOGLE_API_KEY"] = "your-gemini-api-key" config = { "llm": { "provider": "gemini", "config": { "model": "gemini-2.0-flash-001", "api_key": "your-gemini-api-key", "temperature": 0.2, "max_tokens": 2000, "top_p": 1.0 } } } m = Memory.from_config(config) messages = [ {"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"}, {"role": "assistant", "content": "How about thriller movies? They can be quite engaging."}, {"role": "user", "content": "I’m not a big fan of thrillers, but I love sci-fi movies."}, {"role": "assistant", "content": "Got it! I'll avoid thrillers and suggest sci-fi movies instead."} ] m.add(messages, user_id="alice", metadata={"category": "movies"}) ``` ```typescript TypeScript theme={null} import { Memory } from "mem0ai/oss"; const config = { llm: { // You can also use "google" as provider ( for backward compatibility ) provider: "gemini", config: { model: "gemini-2.0-flash-001", apiKey: process.env.GOOGLE_API_KEY || '', temperature: 0.1 } } } const memory = new Memory(config); const messages = [ { role: "user", content: "I'm planning to watch a movie tonight. Any recommendations?" }, { role: "assistant", content: "How about thriller movies? They can be quite engaging." }, { role: "user", content: "I’m not a big fan of thrillers, but I love sci-fi movies." }, { role: "assistant", content: "Got it! I'll avoid thrillers and suggest sci-fi movies instead." } ] await memory.add(messages, { userId: "alice", metadata: { category: "movies" } }); ``` ## Config All available parameters for the `Gemini` config are present in [Master List of All Params in Config](../config). # Groq Source: https://docs.mem0.ai/components/llms/models/groq Configure Groq as an LLM provider in Mem0 for high-speed inference using LPU-powered language models. [Groq](https://groq.com/) is the creator of the world's first Language Processing Unit (LPU), providing exceptional speed performance for AI workloads running on their LPU Inference Engine. In order to use LLMs from Groq, go to their [platform](https://console.groq.com/keys) and get the API key. Set the API key as `GROQ_API_KEY` environment variable to use the model as given below in the example. ## Usage ```python Python theme={null} import os from mem0 import Memory os.environ["OPENAI_API_KEY"] = "your-api-key" # used for embedding model os.environ["GROQ_API_KEY"] = "your-api-key" config = { "llm": { "provider": "groq", "config": { "model": "llama-3.3-70b-versatile", "temperature": 0.1, "max_tokens": 2000, } } } m = Memory.from_config(config) messages = [ {"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"}, {"role": "assistant", "content": "How about thriller movies? They can be quite engaging."}, {"role": "user", "content": "I’m not a big fan of thriller movies but I love sci-fi movies."}, {"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."} ] m.add(messages, user_id="alice", metadata={"category": "movies"}) ``` ```typescript TypeScript theme={null} import { Memory } from 'mem0ai/oss'; const config = { llm: { provider: 'groq', config: { apiKey: process.env.GROQ_API_KEY || '', model: 'llama3-70b-8192', temperature: 0.1, maxTokens: 1000, }, }, }; const memory = new Memory(config); const messages = [ {"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"}, {"role": "assistant", "content": "How about thriller movies? They can be quite engaging."}, {"role": "user", "content": "I’m not a big fan of thriller movies but I love sci-fi movies."}, {"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."} ] await memory.add(messages, { userId: "alice", metadata: { category: "movies" } }); ``` ## Config All available parameters for the `groq` config are present in [Master List of All Params in Config](../config). # LangChain as LLM Provider Source: https://docs.mem0.ai/components/llms/models/langchain Use LangChain as an LLM provider in Mem0 to integrate with various chat models through a unified interface. Mem0 supports LangChain as a provider to access a wide range of LLM models. LangChain is a framework for developing applications powered by language models, making it easy to integrate various LLM providers through a consistent interface. For a complete list of available chat models supported by LangChain, refer to the [LangChain Chat Models documentation](https://python.langchain.com/docs/integrations/chat). ## Usage ```python Python theme={null} import os from mem0 import Memory from langchain_openai import ChatOpenAI # Set necessary environment variables for your chosen LangChain provider os.environ["OPENAI_API_KEY"] = "your-api-key" # Initialize a LangChain model directly openai_model = ChatOpenAI( model="gpt-5-mini", temperature=0.2, max_tokens=2000 ) # Pass the initialized model to the config config = { "llm": { "provider": "langchain", "config": { "model": openai_model } } } m = Memory.from_config(config) messages = [ {"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"}, {"role": "assistant", "content": "How about thriller movies? They can be quite engaging."}, {"role": "user", "content": "I'm not a big fan of thriller movies but I love sci-fi movies."}, {"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."} ] m.add(messages, user_id="alice", metadata={"category": "movies"}) ``` ```typescript TypeScript theme={null} import { Memory } from 'mem0ai/oss'; import { ChatOpenAI } from "@langchain/openai"; // Initialize a LangChain model directly const openaiModel = new ChatOpenAI({ modelName: "gpt-4", temperature: 0.2, maxTokens: 2000, apiKey: process.env.OPENAI_API_KEY, }); const config = { llm: { provider: 'langchain', config: { model: openaiModel, }, }, }; const memory = new Memory(config); const messages = [ {"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"}, {"role": "assistant", "content": "How about thriller movies? They can be quite engaging."}, {"role": "user", "content": "I'm not a big fan of thriller movies but I love sci-fi movies."}, {"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."} ] await memory.add(messages, { userId: "alice", metadata: { category: "movies" } }); ``` ## Supported LangChain Providers LangChain supports a wide range of LLM providers, including: * OpenAI (`ChatOpenAI`) * Anthropic (`ChatAnthropic`) * Google (`ChatGoogleGenerativeAI`, `ChatGooglePalm`) * Mistral (`ChatMistralAI`) * Ollama (`ChatOllama`) * Azure OpenAI (`AzureChatOpenAI`) * HuggingFace (`HuggingFaceChatEndpoint`) * And many more You can use any of these model instances directly in your configuration. For a complete and up-to-date list of available providers, refer to the [LangChain Chat Models documentation](https://python.langchain.com/docs/integrations/chat). ## Provider-Specific Configuration When using LangChain as a provider, you'll need to: 1. Set the appropriate environment variables for your chosen LLM provider 2. Import and initialize the specific model class you want to use 3. Pass the initialized model instance to the config > [!NOTE] > > Make sure to install the necessary LangChain packages and any provider-specific dependencies. ## Config All available parameters for the `langchain` config are present in [Master List of All Params in Config](../config). # LiteLLM Source: https://docs.mem0.ai/components/llms/models/litellm Use LiteLLM as an LLM provider in Mem0 to access over 100 language models through a unified interface. [Litellm](https://litellm.vercel.app/docs/) is compatible with over 100 large language models (LLMs), all using a standardized input/output format. You can explore the [available models](https://litellm.vercel.app/docs/providers) to use with Litellm. Ensure you set the `API_KEY` for the model you choose to use. In the TypeScript SDK, run LiteLLM as a [proxy server](https://docs.litellm.ai/docs/simple_proxy) (an OpenAI-compatible endpoint) and point Mem0 at it via `LITELLM_API_BASE` (defaults to `http://localhost:4000`). ## Usage ```python Python theme={null} import os from mem0 import Memory os.environ["OPENAI_API_KEY"] = "your-api-key" config = { "llm": { "provider": "litellm", "config": { "model": "gpt-5-mini", "temperature": 0.2, "max_tokens": 2000, } } } m = Memory.from_config(config) messages = [ {"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"}, {"role": "assistant", "content": "How about thriller movies? They can be quite engaging."}, {"role": "user", "content": "I’m not a big fan of thriller movies but I love sci-fi movies."}, {"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."} ] m.add(messages, user_id="alice", metadata={"category": "movies"}) ``` ```typescript TypeScript theme={null} import { Memory } from 'mem0ai/oss'; // Point Mem0 at your LiteLLM proxy. apiKey defaults to "sk-anything" // (the proxy handles real auth); baseURL defaults to http://localhost:4000. const config = { llm: { provider: 'litellm', config: { apiKey: process.env.LITELLM_API_KEY || 'sk-anything', baseURL: process.env.LITELLM_API_BASE || 'http://localhost:4000', model: 'gpt-5-mini', }, }, }; const memory = new Memory(config); const messages = [ {"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"}, {"role": "assistant", "content": "How about thriller movies? They can be quite engaging."}, {"role": "user", "content": "I’m not a big fan of thriller movies but I love sci-fi movies."}, {"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."} ]; await memory.add(messages, { userId: 'alice', metadata: { category: 'movies' } }); ``` ## Config All available parameters for the `litellm` config are present in [Master List of All Params in Config](../config). # LM Studio as LLM Provider Source: https://docs.mem0.ai/components/llms/models/lmstudio Configure LM Studio as an LLM provider in Mem0 for running local language models via an OpenAI-compatible API. To use LM Studio with Mem0, you'll need to have LM Studio running locally with its server enabled. LM Studio provides a way to run local LLMs with an OpenAI-compatible API. ## Usage ```python Python theme={null} import os from mem0 import Memory os.environ["OPENAI_API_KEY"] = "your-api-key" # used for embedding model config = { "llm": { "provider": "lmstudio", "config": { "model": "lmstudio-community/Meta-Llama-3.1-70B-Instruct-GGUF/Meta-Llama-3.1-70B-Instruct-IQ2_M.gguf", "temperature": 0.2, "max_tokens": 2000, "lmstudio_base_url": "http://localhost:1234/v1", # default LM Studio API URL "lmstudio_response_format": {"type": "json_schema", "json_schema": {"type": "object", "schema": {}}}, } } } m = Memory.from_config(config) messages = [ {"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"}, {"role": "assistant", "content": "How about thriller movies? They can be quite engaging."}, {"role": "user", "content": "I'm not a big fan of thriller movies but I love sci-fi movies."}, {"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."} ] m.add(messages, user_id="alice", metadata={"category": "movies"}) ``` ### Running Completely Locally You can also use LM Studio for both LLM and embedding to run Mem0 entirely locally: ```python theme={null} from mem0 import Memory # No external API keys needed! config = { "llm": { "provider": "lmstudio" }, "embedder": { "provider": "lmstudio" } } m = Memory.from_config(config) messages = [ {"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"}, {"role": "assistant", "content": "How about thriller movies? They can be quite engaging."}, {"role": "user", "content": "I'm not a big fan of thriller movies but I love sci-fi movies."}, {"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."} ] m.add(messages, user_id="alice123", metadata={"category": "movies"}) ``` > [!NOTE] > > When using LM Studio for both LLM and embedding, make sure you have: > > 1. An LLM model loaded for generating responses > 2. An embedding model loaded for vector embeddings > 3. The server enabled with the correct endpoints accessible > [!NOTE] > > To use LM Studio, you need to: > > 1. Download and install [LM Studio](https://lmstudio.ai/) > 2. Start a local server from the "Server" tab > 3. Set the appropriate `lmstudio_base_url` in your configuration (default is usually `http://localhost:1234/v1`) ## Config All available parameters for the `lmstudio` config are present in [Master List of All Params in Config](../config). # MiniMax Source: https://docs.mem0.ai/components/llms/models/minimax Configure MiniMax as an LLM provider in Mem0 with API key setup and optional custom endpoint configuration. To use MiniMax LLM models, you have to set the `MINIMAX_API_KEY` environment variable. You can also optionally set `MINIMAX_API_BASE` if you need to use a different API endpoint (defaults to `https://api.minimax.io/v1`). ## Usage ```python Python theme={null} import os from mem0 import Memory os.environ["MINIMAX_API_KEY"] = "your-api-key" os.environ["OPENAI_API_KEY"] = "your-api-key" # for embedder model config = { "llm": { "provider": "minimax", "config": { "model": "MiniMax-M2.7", # default model "temperature": 0.2, "max_tokens": 2000, "top_p": 1.0 } } } m = Memory.from_config(config) messages = [ {"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"}, {"role": "assistant", "content": "How about thriller movies? They can be quite engaging."}, {"role": "user", "content": "I'm not a big fan of thriller movies but I love sci-fi movies."}, {"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."} ] m.add(messages, user_id="alice", metadata={"category": "movies"}) ``` ```typescript TypeScript theme={null} import { Memory } from 'mem0ai/oss'; const config = { llm: { provider: 'minimax', config: { apiKey: process.env.MINIMAX_API_KEY || '', model: 'MiniMax-M2.7', temperature: 0.2, maxTokens: 2000, topP: 1.0, }, }, }; const memory = new Memory(config); const messages = [ { role: "user", content: "I'm planning to watch a movie tonight. Any recommendations?" }, { role: "assistant", content: "How about thriller movies? They can be quite engaging." }, { role: "user", content: "I'm not a big fan of thriller movies but I love sci-fi movies." }, { role: "assistant", content: "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future." }, ]; await memory.add(messages, { userId: 'alice', metadata: { category: 'movies' } }); ``` You can also configure the API base URL in the config: ```python Python theme={null} config = { "llm": { "provider": "minimax", "config": { "model": "MiniMax-M2.7", "minimax_base_url": "https://your-custom-endpoint.com", "api_key": "your-api-key" # alternatively to using environment variable } } } ``` ```typescript TypeScript theme={null} const config = { llm: { provider: 'minimax', config: { model: 'MiniMax-M2.7', baseURL: 'https://your-custom-endpoint.com', apiKey: 'your-api-key', // alternatively to using the environment variable }, }, }; ``` ## Config All available parameters for the `minimax` config are present in [Master List of All Params in Config](../config). # Mistral AI Source: https://docs.mem0.ai/components/llms/models/mistral-ai Configure Mistral AI as an LLM provider in Mem0 using the litellm integration and Mixtral model family. To use mistral's models, please obtain the Mistral AI api key from their [console](https://console.mistral.ai/). Set the `MISTRAL_API_KEY` environment variable to use the model as given below in the example. ## Usage ```python Python theme={null} import os from mem0 import Memory os.environ["OPENAI_API_KEY"] = "your-api-key" # used for embedding model os.environ["MISTRAL_API_KEY"] = "your-api-key" config = { "llm": { "provider": "litellm", "config": { "model": "open-mixtral-8x7b", "temperature": 0.1, "max_tokens": 2000, } } } m = Memory.from_config(config) messages = [ {"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"}, {"role": "assistant", "content": "How about thriller movies? They can be quite engaging."}, {"role": "user", "content": "I’m not a big fan of thriller movies but I love sci-fi movies."}, {"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."} ] m.add(messages, user_id="alice", metadata={"category": "movies"}) ``` ```typescript TypeScript theme={null} import { Memory } from 'mem0ai/oss'; const config = { llm: { provider: 'mistral', config: { apiKey: process.env.MISTRAL_API_KEY || '', model: 'mistral-tiny-latest', // Or 'mistral-small-latest', 'mistral-medium-latest', etc. temperature: 0.1, maxTokens: 2000, }, }, }; const memory = new Memory(config); const messages = [ {"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"}, {"role": "assistant", "content": "How about thriller movies? They can be quite engaging."}, {"role": "user", "content": "I'm not a big fan of thriller movies but I love sci-fi movies."}, {"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."} ] await memory.add(messages, { userId: "alice", metadata: { category: "movies" } }); ``` ## Config All available parameters for the `litellm` config are present in [Master List of All Params in Config](../config). # Ollama as LLM Provider Source: https://docs.mem0.ai/components/llms/models/ollama Configure Ollama as an LLM provider in Mem0 for running local language models with tool-calling support. You can use LLMs from Ollama to run Mem0 locally. These [models](https://ollama.com/search?c=tools) support tool calling. ## Usage ```python Python theme={null} import os from mem0 import Memory os.environ["OPENAI_API_KEY"] = "your-api-key" # for embedder config = { "llm": { "provider": "ollama", "config": { "model": "mixtral:8x7b", "temperature": 0.1, "max_tokens": 2000, } } } m = Memory.from_config(config) messages = [ {"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"}, {"role": "assistant", "content": "How about thriller movies? They can be quite engaging."}, {"role": "user", "content": "I'm not a big fan of thriller movies but I love sci-fi movies."}, {"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."} ] m.add(messages, user_id="alice", metadata={"category": "movies"}) ``` ```typescript TypeScript theme={null} import { Memory } from 'mem0ai/oss'; const config = { llm: { provider: 'ollama', config: { model: 'llama3.1:8b', // or any other Ollama model url: 'http://localhost:11434', // Ollama server URL temperature: 0.1, }, }, }; const memory = new Memory(config); const messages = [ {"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"}, {"role": "assistant", "content": "How about thriller movies? They can be quite engaging."}, {"role": "user", "content": "I'm not a big fan of thriller movies but I love sci-fi movies."}, {"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."} ] await memory.add(messages, { userId: "alice", metadata: { category: "movies" } }); ``` ## Config All available parameters for the `ollama` config are present in [Master List of All Params in Config](../config). # OpenAI as LLM Provider Source: https://docs.mem0.ai/components/llms/models/openai Configure OpenAI as an LLM provider in Mem0 with support for GPT models and Openrouter compatibility. To use OpenAI LLM models, you have to set the `OPENAI_API_KEY` environment variable. You can obtain the OpenAI API key from the [OpenAI Platform](https://platform.openai.com/account/api-keys). > **Note**: The following are currently unsupported with reasoning models `Parallel tool calling`,`temperature`, `top_p`, `presence_penalty`, `frequency_penalty`, `logprobs`, `top_logprobs`, `logit_bias`, `max_tokens` ## Usage ```python Python theme={null} import os from mem0 import Memory os.environ["OPENAI_API_KEY"] = "your-api-key" config = { "llm": { "provider": "openai", "config": { "model": "gpt-5-mini", "temperature": 0.2, "max_tokens": 2000, } } } # Use Openrouter by passing it's api key # os.environ["OPENROUTER_API_KEY"] = "your-api-key" # config = { # "llm": { # "provider": "openai", # "config": { # "model": "meta-llama/llama-3.1-70b-instruct", # } # } # } m = Memory.from_config(config) messages = [ {"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"}, {"role": "assistant", "content": "How about thriller movies? They can be quite engaging."}, {"role": "user", "content": "I’m not a big fan of thriller movies but I love sci-fi movies."}, {"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."} ] m.add(messages, user_id="alice", metadata={"category": "movies"}) ``` ```typescript TypeScript theme={null} import { Memory } from 'mem0ai/oss'; const config = { llm: { provider: 'openai', config: { apiKey: process.env.OPENAI_API_KEY || '', model: 'gpt-4-turbo-preview', temperature: 0.2, maxTokens: 1500, }, }, }; const memory = new Memory(config); const messages = [ {"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"}, {"role": "assistant", "content": "How about thriller movies? They can be quite engaging."}, {"role": "user", "content": "I’m not a big fan of thriller movies but I love sci-fi movies."}, {"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."} ] await memory.add(messages, { userId: "alice", metadata: { category: "movies" } }); ``` We also support the new [OpenAI structured-outputs](https://platform.openai.com/docs/guides/structured-outputs/introduction) model. ```python theme={null} import os from mem0 import Memory os.environ["OPENAI_API_KEY"] = "your-api-key" config = { "llm": { "provider": "openai_structured", "config": { "model": "gpt-5-mini", "temperature": 0.0, } } } m = Memory.from_config(config) ``` ## Config All available parameters for the `openai` config are present in [Master List of All Params in Config](../config). # Sarvam AI Source: https://docs.mem0.ai/components/llms/models/sarvam Configure Sarvam AI as an LLM provider in Mem0, specializing in Indian language support with the Sarvam-M model. **Sarvam AI** is an Indian AI company developing language models with a focus on Indian languages and cultural context. Their latest model **Sarvam-M** is designed to understand and generate content in multiple Indian languages while maintaining high performance in English. To use Sarvam AI's models, please set the `SARVAM_API_KEY` which you can get from their [platform](https://dashboard.sarvam.ai/). ## Usage ```python Python theme={null} import os from mem0 import Memory os.environ["OPENAI_API_KEY"] = "your-api-key" # used for embedding model os.environ["SARVAM_API_KEY"] = "your-api-key" config = { "llm": { "provider": "sarvam", "config": { "model": "sarvam-m", "temperature": 0.7, } } } m = Memory.from_config(config) messages = [ {"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"}, {"role": "assistant", "content": "How about thriller movies? They can be quite engaging."}, {"role": "user", "content": "I'm not a big fan of thriller movies but I love sci-fi movies."}, {"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."} ] m.add(messages, user_id="alex") ``` ```typescript TypeScript theme={null} import { Memory } from 'mem0ai/oss'; const config = { llm: { provider: 'sarvam', config: { apiKey: process.env.SARVAM_API_KEY || '', model: 'sarvam-m', temperature: 0.7, }, }, }; const memory = new Memory(config); const messages = [ {"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"}, {"role": "assistant", "content": "How about thriller movies? They can be quite engaging."}, {"role": "user", "content": "I'm not a big fan of thriller movies but I love sci-fi movies."}, {"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."} ]; await memory.add(messages, { userId: 'alex' }); ``` ## Advanced Usage with Sarvam-Specific Features ```python theme={null} import os from mem0 import Memory config = { "llm": { "provider": "sarvam", "config": { "model": { "name": "sarvam-m", "reasoning_effort": "high", # Enable advanced reasoning "frequency_penalty": 0.1, # Reduce repetition "seed": 42 # For deterministic outputs }, "temperature": 0.3, "max_tokens": 2000, "api_key": "your-sarvam-api-key" } } } m = Memory.from_config(config) # Example with Hindi conversation messages = [ {"role": "user", "content": "मैं SBI में joint account खोलना चाहता हूँ।"}, {"role": "assistant", "content": "SBI में joint account खोलने के लिए आपको कुछ documents की जरूरत होगी। क्या आप जानना चाहते हैं कि कौन से documents चाहिए?"} ] m.add(messages, user_id="rajesh", metadata={"language": "hindi", "topic": "banking"}) ``` ## Config All available parameters for the `sarvam` config are present in [Master List of All Params in Config](../config). # Together AI as LLM Provider Source: https://docs.mem0.ai/components/llms/models/together Configure Together AI as an LLM provider in Mem0 with API key setup and optional custom endpoint configuration. To use Together LLM models, you have to set the `TOGETHER_API_KEY` environment variable. You can obtain the Together API key from their [Account settings page](https://api.together.ai/settings/projects/~current/api-keys). In the TypeScript SDK, you can optionally set `TOGETHER_API_BASE` or pass `baseURL` in the config (defaults to `https://api.together.ai/v1`). ## Usage ```python Python theme={null} import os from mem0 import Memory os.environ["OPENAI_API_KEY"] = "your-api-key" # used for embedding model os.environ["TOGETHER_API_KEY"] = "your-api-key" config = { "llm": { "provider": "together", "config": { "model": "MiniMaxAI/MiniMax-M3", "temperature": 0.2, "max_tokens": 2000, } } } m = Memory.from_config(config) messages = [ {"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"}, {"role": "assistant", "content": "How about thriller movies? They can be quite engaging."}, {"role": "user", "content": "I'm not a big fan of thriller movies but I love sci-fi movies."}, {"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."} ] m.add(messages, user_id="alice", metadata={"category": "movies"}) ``` ```typescript TypeScript theme={null} import { Memory } from 'mem0ai/oss'; const config = { llm: { provider: 'together', config: { apiKey: process.env.TOGETHER_API_KEY || '', model: 'MiniMaxAI/MiniMax-M3', temperature: 0.2, maxTokens: 2000, }, }, }; const memory = new Memory(config); const messages = [ { role: "user", content: "I'm planning to watch a movie tonight. Any recommendations?" }, { role: "assistant", content: "How about thriller movies? They can be quite engaging." }, { role: "user", content: "I'm not a big fan of thriller movies but I love sci-fi movies." }, { role: "assistant", content: "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future." }, ]; await memory.add(messages, { userId: 'alice', metadata: { category: 'movies' } }); ``` You can also configure the API base URL in the config: ```python Python theme={null} config = { "llm": { "provider": "together", "config": { "model": "MiniMaxAI/MiniMax-M3", "api_key": "your-api-key" } } } ``` ```typescript TypeScript theme={null} const config = { llm: { provider: "together", config: { model: "MiniMaxAI/MiniMax-M3", baseURL: "https://api.together.ai/v1", apiKey: "your-api-key", }, }, }; ``` ## Config All available parameters for the `together` config are present in [Master List of All Params in Config](../config). # vLLM Source: https://docs.mem0.ai/components/llms/models/vllm Configure vLLM as an LLM provider in Mem0 for high-performance local inference with GPU-optimized serving. [vLLM](https://docs.vllm.ai/) is a high-performance inference engine for large language models that provides significant performance improvements for local inference. It's designed to maximize throughput and memory efficiency for serving LLMs. ## Prerequisites 1. **Install vLLM**: ```bash theme={null} pip install vllm ``` 2. **Start vLLM server**: ```bash theme={null} # For testing with a small model vllm serve microsoft/DialoGPT-medium --port 8000 # For production with a larger model (requires GPU) vllm serve Qwen/Qwen2.5-32B-Instruct --port 8000 ``` ## Usage ```python Python theme={null} import os from mem0 import Memory os.environ["OPENAI_API_KEY"] = "your-api-key" # used for embedding model config = { "llm": { "provider": "vllm", "config": { "model": "Qwen/Qwen2.5-32B-Instruct", "vllm_base_url": "http://localhost:8000/v1", "temperature": 0.1, "max_tokens": 2000, } } } m = Memory.from_config(config) messages = [ {"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"}, {"role": "assistant", "content": "How about thriller movies? They can be quite engaging."}, {"role": "user", "content": "I'm not a big fan of thrillers, but I love sci-fi movies."}, {"role": "assistant", "content": "Got it! I'll avoid thrillers and suggest sci-fi movies instead."} ] m.add(messages, user_id="alice", metadata={"category": "movies"}) ``` ```typescript TypeScript theme={null} import { Memory } from "mem0ai/oss"; const config = { llm: { provider: "vllm", config: { model: "Qwen/Qwen2.5-32B-Instruct", baseURL: "http://localhost:8000/v1", apiKey: process.env.VLLM_API_KEY || "vllm-api-key", temperature: 0.1, maxTokens: 2000, }, }, }; const memory = new Memory(config); const messages = [ { role: "user", content: "I'm planning to watch a movie tonight. Any recommendations?", }, { role: "assistant", content: "How about thriller movies? They can be quite engaging.", }, { role: "user", content: "I'm not a big fan of thrillers, but I love sci-fi movies.", }, { role: "assistant", content: "Got it! I'll avoid thrillers and suggest sci-fi movies instead.", }, ]; await memory.add(messages, { userId: "alice", metadata: { category: "movies" } }); ``` ## Configuration Parameters | Parameter | Description | Default | Environment Variable | | - | - | - | - | | `model` | Model name running on vLLM server | `"Qwen/Qwen2.5-32B-Instruct"` | - | | `vllm_base_url` | vLLM server URL | `"http://localhost:8000/v1"` | `VLLM_BASE_URL` | | `api_key` | API key (dummy for local) | `"vllm-api-key"` | `VLLM_API_KEY` | | `temperature` | Sampling temperature | `0.1` | - | | `max_tokens` | Maximum tokens to generate | `2000` | - | ## Environment Variables You can set these environment variables instead of specifying them in config: ```bash theme={null} export VLLM_BASE_URL="http://localhost:8000/v1" export VLLM_API_KEY="your-vllm-api-key" export OPENAI_API_KEY="your-openai-api-key" # for embeddings ``` ## Benefits * **High Performance**: 2-24x faster inference than standard implementations * **Memory Efficient**: Optimized memory usage with PagedAttention * **Local Deployment**: Keep your data private and reduce API costs * **Easy Integration**: Drop-in replacement for other LLM providers * **Flexible**: Works with any model supported by vLLM ## Troubleshooting 1. **Server not responding**: Make sure vLLM server is running ```bash theme={null} curl http://localhost:8000/health ``` 2. **404 errors**: Ensure correct base URL format ```python theme={null} "vllm_base_url": "http://localhost:8000/v1" # Note the /v1 ``` 3. **Model not found**: Check model name matches server 4. **Out of memory**: Try smaller models or reduce `max_model_len` ```bash theme={null} vllm serve Qwen/Qwen2.5-32B-Instruct --max-model-len 4096 ``` ## Config All available parameters for the `vllm` config are present in [Master List of All Params in Config](../config). # xAI Grok as LLM Provider Source: https://docs.mem0.ai/components/llms/models/xAI Configure xAI Grok models as an LLM provider in Mem0 with API key setup and usage examples. [xAI](https://x.ai/) is a new AI company founded by Elon Musk that develops large language models, including Grok. Grok is trained on real-time data from X (formerly Twitter) and aims to provide accurate, up-to-date responses with a touch of wit and humor. In order to use LLMs from xAI, go to their [platform](https://console.x.ai) and get the API key. Set the API key as `XAI_API_KEY` environment variable to use the model as given below in the example. You can also optionally set `XAI_API_BASE` to use a different API endpoint (defaults to `https://api.x.ai/v1`). ## Usage ```python Python theme={null} import os from mem0 import Memory os.environ["OPENAI_API_KEY"] = "your-api-key" # used for embedding model os.environ["XAI_API_KEY"] = "your-api-key" config = { "llm": { "provider": "xai", "config": { "model": "grok-4.3", "temperature": 0.1, "max_tokens": 2000, } } } m = Memory.from_config(config) messages = [ {"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"}, {"role": "assistant", "content": "How about thriller movies? They can be quite engaging."}, {"role": "user", "content": "I’m not a big fan of thriller movies but I love sci-fi movies."}, {"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."} ] m.add(messages, user_id="alice", metadata={"category": "movies"}) ``` ```typescript TypeScript theme={null} import { Memory } from 'mem0ai/oss'; const config = { llm: { provider: 'xai', config: { apiKey: process.env.XAI_API_KEY || '', model: 'grok-4.3', temperature: 0.1, maxTokens: 2000, }, }, }; const memory = new Memory(config); const messages = [ {"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"}, {"role": "assistant", "content": "How about thriller movies? They can be quite engaging."}, {"role": "user", "content": "I’m not a big fan of thriller movies but I love sci-fi movies."}, {"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."} ]; await memory.add(messages, { userId: 'alice', metadata: { category: 'movies' } }); ``` ## Config All available parameters for the `xai` config are present in [Master List of All Params in Config](../config). # LLM Providers Overview Source: https://docs.mem0.ai/components/llms/overview Overview of all supported LLM providers in Mem0, including OpenAI, Anthropic, Groq, Ollama, and more. Mem0 includes built-in support for various popular large language models. Memory can utilize the LLM provided by the user, ensuring efficient use for specific needs. ## Usage To use an LLM, you must provide a configuration to customize its usage. If no configuration is supplied, a default configuration will be applied, and `OpenAI` will be used as the LLM. For a comprehensive list of available parameters for llm configuration, please refer to [Config](./config). ## Supported LLMs See the list of supported LLMs below. > [!NOTE] > > All LLMs are supported in Python. The following LLMs are also supported in TypeScript: **OpenAI**, **Anthropic**, **AWS Bedrock**, **Groq**, **Azure OpenAI**, **DeepSeek**, **Google AI**, **Langchain**, **LM Studio**, **Mistral AI**, and **Ollama**. > **[OpenAI](/components/llms/models/openai)** > **[Ollama](/components/llms/models/ollama)** > **[Azure OpenAI](/components/llms/models/azure-openai)** > **[Anthropic](/components/llms/models/anthropic)** > **[Together](/components/llms/models/together)** > **[Groq](/components/llms/models/groq)** > **[Litellm](/components/llms/models/litellm)** > **[Mistral AI](/components/llms/models/mistral-ai)** > **[Google AI](/components/llms/models/google-ai)** > **[AWS bedrock](/components/llms/models/aws-bedrock)** > **[DeepSeek](/components/llms/models/deepseek)** > **[MiniMax](/components/llms/models/minimax)** > **[xAI](/components/llms/models/xAI)** > **[Sarvam AI](/components/llms/models/sarvam)** > **[LM Studio](/components/llms/models/lmstudio)** > **[Langchain](/components/llms/models/langchain)** ## Structured vs Unstructured Outputs Mem0 supports two types of OpenAI LLM formats, each with its own strengths and use cases: ### Structured Outputs Structured outputs are LLMs that align with OpenAI's structured outputs model: * **Optimized for:** Returning structured responses (e.g., JSON objects) * **Benefits:** Precise, easily parseable data * **Ideal for:** Data extraction, form filling, API responses * **Learn more:** [OpenAI Structured Outputs Guide](https://platform.openai.com/docs/guides/structured-outputs/introduction) ### Unstructured Outputs Unstructured outputs correspond to OpenAI's standard, free-form text model: * **Flexibility:** Returns open-ended, natural language responses * **Customization:** Use the `response_format` parameter to guide output * **Trade-off:** Less efficient than structured outputs for specific data needs * **Best for:** Creative writing, explanations, general conversation Choose the format that best suits your application's requirements for optimal performance and usability. # Config Source: https://docs.mem0.ai/components/rerankers/config Reference for shared and provider-specific reranker configuration options in Mem0, including top_k and API key settings. ## Common Configuration Parameters All rerankers share these common configuration parameters: | Parameter | Description | Type | Default | | - | - | - | - | | `provider` | Reranker provider name | `str` | Required | | `top_k` | Maximum number of results to return after reranking | `int` | `None` | | `api_key` | API key for the reranker service | `str` | `None` | ## Provider-Specific Configuration ### Zero Entropy | Parameter | Description | Type | Default | | - | - | - | - | | `model` | Model to use: `zerank-1` or `zerank-1-small` | `str` | `"zerank-1"` | | `api_key` | Zero Entropy API key | `str` | `None` | ### Cohere | Parameter | Description | Type | Default | | - | - | - | - | | `model` | Cohere rerank model | `str` | `"rerank-v3.5"` | | `api_key` | Cohere API key | `str` | `None` | | `return_documents` | Whether to return document texts in response | `bool` | `False` | | `max_chunks_per_doc` | Maximum chunks per document | `int` | `None` | ### Sentence Transformer | Parameter | Description | Type | Default | | - | - | - | - | | `model` | HuggingFace cross-encoder model name | `str` | `"cross-encoder/ms-marco-MiniLM-L-6-v2"` | | `device` | Device to run model on (`cpu`, `cuda`, etc.) | `str` | `None` | | `batch_size` | Batch size for processing | `int` | `32` | | `show_progress_bar` | Show progress during processing | `bool` | `False` | ### Hugging Face | Parameter | Description | Type | Default | | - | - | - | - | | `model` | HuggingFace reranker model name | `str` | `"BAAI/bge-reranker-large"` | | `api_key` | HuggingFace API token | `str` | `None` | | `device` | Device to run model on (`cpu`, `cuda`, etc.) | `str` | `None` | ### LLM-based | Parameter | Description | Type | Default | | - | - | - | - | | `model` | LLM model to use for scoring | `str` | `"gpt-5-mini"` | | `provider` | LLM provider (`openai`, `anthropic`, etc.) | `str` | `"openai"` | | `api_key` | API key for LLM provider | `str` | `None` | | `temperature` | Temperature for LLM generation | `float` | `0.0` | | `max_tokens` | Maximum tokens for LLM response | `int` | `100` | | `scoring_prompt` | Custom prompt template for scoring | `str` | Default scoring prompt | ### LLM Reranker | Parameter | Description | Type | Default | | - | - | - | - | | `llm.provider` | LLM provider for reranking | `str` | Required | | `llm.config` | LLM configuration object | `dict` | Required | | `top_n` | Number of results to return | `int` | `None` | ## Environment Variables You can set API keys using environment variables: * `ZERO_ENTROPY_API_KEY` - Zero Entropy API key * `COHERE_API_KEY` - Cohere API key * `HUGGINGFACE_API_KEY` - HuggingFace API token * `OPENAI_API_KEY` - OpenAI API key (for LLM-based reranker) * `ANTHROPIC_API_KEY` - Anthropic API key (for LLM-based reranker) ## Basic Configuration Example ```python Python theme={null} config = { "vector_store": { "provider": "chroma", "config": { "collection_name": "my_memories", "path": "./chroma_db" } }, "llm": { "provider": "openai", "config": { "model": "gpt-5-mini" } }, "reranker": { "provider": "zero_entropy", "config": { "model": "zerank-1", "top_k": 5 } } } ``` ## TypeScript SDK The self-hosted [TypeScript SDK](/open-source/features/reranker-search#typescript-sdk) (`mem0ai/oss`) supports the same five providers. Config keys are camelCase (`apiKey`, `topK`, `maxLength`) and each provider's SDK is a peer dependency you install per reranker. | Provider | Install | Default model | Key config fields | | - | - | - | - | | `cohere` | `pnpm add cohere-ai` | `rerank-v3.5` | `apiKey`, `model`, `topK` | | `zero_entropy` | `pnpm add zeroentropy` | `zerank-1` | `apiKey`, `model`, `topK` | | `sentence_transformer` | `pnpm add @huggingface/transformers` | `Xenova/ms-marco-MiniLM-L-6-v2` | `model`, `device`, `maxLength`, `normalize`, `topK` | | `huggingface` | `pnpm add @huggingface/transformers` | `Xenova/bge-reranker-base` | `model`, `device`, `maxLength`, `normalize`, `topK` | | `llm_reranker` | None (uses your LLM provider's own SDK) | `openai` / `gpt-5-mini` | `provider`, `model`, `apiKey`, `llm` (nested override), `topK` | ```typescript theme={null} import { Memory } from "mem0ai/oss"; const memory = new Memory({ reranker: { provider: "zero_entropy", config: { apiKey: process.env.ZERO_ENTROPY_API_KEY, topK: 5 }, }, }); ``` > [!NOTE] > > The local cross-encoder providers (`sentence_transformer`, `huggingface`) run on [Transformers.js](https://huggingface.co/docs/transformers.js) and default to ONNX (`Xenova/*`) model mirrors, so Python default model strings must be swapped for their ONNX equivalents. `batchSize` and `showProgressBar` are accepted for parity with Python but are no-ops in the TypeScript runtime. See the [reranker feature guide](/open-source/features/reranker-search#typescript-sdk) for full examples. # Custom Prompts Source: https://docs.mem0.ai/components/rerankers/custom-prompts Customize the LLM reranker prompt template in Mem0 to control how search results are ranked and scored. When using LLM rerankers, you can customize the prompts used for ranking to better suit your specific use case and domain. ## Default Prompt The default LLM reranker prompt scores each memory individually on a 0.0-1.0 scale: ``` You are a relevance scoring assistant. Given a query and a document, you need to score how relevant the document is to the query. Score the relevance on a scale from 0.0 to 1.0, where: - 1.0 = Perfectly relevant and directly answers the query - 0.8-0.9 = Highly relevant with good information - 0.6-0.7 = Moderately relevant with some useful information - 0.4-0.5 = Slightly relevant with limited useful information - 0.0-0.3 = Not relevant or no useful information Query: "{query}" Document: "{document}" Provide only a single numerical score between 0.0 and 1.0. Do not include any explanation or additional text. ``` ## Custom Prompt Configuration You can provide a custom prompt template using the `scoring_prompt` parameter: ```python theme={null} from mem0 import Memory custom_prompt = """ You are an expert at evaluating memories for a personal AI assistant. Given a user query and a memory entry, score how relevant the memory is. Consider direct relevance, temporal relevance, and actionability. Query: "{query}" Memory: "{document}" Provide only a single numerical score between 0.0 and 1.0. """ config = { "reranker": { "provider": "llm_reranker", "config": { "provider": "openai", "model": "gpt-5-mini", "api_key": "your-openai-key", "scoring_prompt": custom_prompt, "top_k": 5 } } } memory = Memory.from_config(config) ``` ## Prompt Variables Your custom prompt can use the following variables: | Variable | Description | | - | - | | `{query}` | The search query | | `{document}` | The memory entry being scored | > [!NOTE] > > Both `{query}` and `{document}` are required in your custom prompt. The LLM reranker scores each memory individually against the query, so the prompt is called once per candidate memory. ## Domain-Specific Examples ### Customer Support ```python theme={null} customer_support_prompt = """ You are ranking customer support conversation memories. Prioritize memories that: - Relate to the current customer issue - Show previous resolution patterns - Indicate customer preferences or constraints Query: "{query}" Memory: "{document}" Score relevance from 0.0 to 1.0. """ ``` ### Educational Content ```python theme={null} educational_prompt = """ Score this learning memory for relevance to a student query. Consider: - Prerequisite knowledge requirements - Learning progression and difficulty - Relevance to current learning objectives Student Query: "{query}" Memory: "{document}" Score educational relevance from 0.0 to 1.0. """ ``` ### Personal Assistant ```python theme={null} personal_assistant_prompt = """ Score this personal memory for relevance to the user's query. Consider: - Recent vs. historical importance - Personal preferences and habits - Contextual relationships Query: "{query}" Memory: "{document}" Provide relevance score from 0.0 to 1.0. """ ``` ## Advanced Prompt Techniques ### Multi-Criteria Scoring ```python theme={null} multi_criteria_prompt = """ Evaluate this memory using multiple criteria: 1. RELEVANCE (40%): How directly related to the query 2. RECENCY (20%): How recent the memory appears to be 3. IMPORTANCE (25%): Personal or business significance 4. ACTIONABILITY (15%): How useful for next steps Query: "{query}" Memory: "{document}" Compute a weighted score from 0.0 to 1.0 based on these criteria. Provide only the final numerical score. """ ``` ### Chain-of-Thought Scoring ```python theme={null} reasoning_prompt = """ Evaluate this memory's relevance step by step: 1. What is the main intent of the query? 2. What key information does the memory contain? 3. How directly does the memory address the query? Based on this analysis, provide a single relevance score from 0.0 to 1.0. Query: "{query}" Memory: "{document}" Score: """ ``` ## Best Practices 1. **Be Specific**: Clearly define what makes a memory relevant for your use case 2. **Use 0.0-1.0 Scale**: The score extractor expects values between 0.0 and 1.0 3. **Request Only the Score**: Ask for just the numerical score to improve extraction reliability 4. **Test Iteratively**: Refine your prompt based on actual ranking performance 5. **Consider Token Limits**: Keep prompts concise while being comprehensive ## Prompt Testing You can test different prompts by comparing ranking results: ```python theme={null} # Test multiple prompt variations prompts = [ default_prompt, custom_prompt_v1, custom_prompt_v2 ] for i, prompt in enumerate(prompts): config["reranker"]["config"]["scoring_prompt"] = prompt memory = Memory.from_config(config) results = memory.search("test query", filters={"user_id": "test_user"}) print(f"Prompt {i+1} results: {results}") ``` ## Common Issues * **Too Long**: Keep prompts under token limits for your chosen LLM * **Too Vague**: Be specific about scoring criteria * **Wrong Scale**: Use 0.0-1.0 scale to match the default score extractor * **Extra Output**: Ask for only the numeric score: extra text can confuse score extraction # Cohere Source: https://docs.mem0.ai/components/rerankers/models/cohere Configure Cohere as a reranker in Mem0 with support for English and multilingual reranking models. Cohere provides enterprise-grade reranking models with excellent multilingual support and production-ready performance. ## Models Cohere offers several reranking models: * **`rerank-v3.5`** (default): Latest reranker, multilingual, best performance * **`rerank-english-v3.0`**: Previous generation, English only * **`rerank-multilingual-v3.0`**: Previous generation, multilingual ## Installation ```bash theme={null} pip install cohere ``` ## Configuration ```python Python theme={null} from mem0 import Memory config = { "vector_store": { "provider": "chroma", "config": { "collection_name": "my_memories", "path": "./chroma_db" } }, "llm": { "provider": "openai", "config": { "model": "gpt-5-mini" } }, "reranker": { "provider": "cohere", "config": { "model": "rerank-v3.5", "api_key": "your-cohere-api-key", # or set COHERE_API_KEY "top_k": 5, "return_documents": False, "max_chunks_per_doc": None } } } memory = Memory.from_config(config) ``` ## TypeScript (self-hosted) The [TypeScript OSS SDK](/open-source/features/reranker-search#typescript-sdk) (`mem0ai/oss`) ships the Cohere reranker. Config keys are camelCase, it defaults to the `rerank-v3.5` model, and you opt in per search with `rerank: true`. ```bash theme={null} pnpm add cohere-ai ``` ```typescript theme={null} import { Memory } from "mem0ai/oss"; const memory = new Memory({ reranker: { provider: "cohere", config: { apiKey: process.env.COHERE_API_KEY, // or set COHERE_API_KEY // model: "rerank-v3.5", // default topK: 5, }, }, }); const results = await memory.search("What is the user's profession?", { filters: { userId: "bob" }, rerank: true, }); ``` ## Environment Variables Set your API key as an environment variable: ```bash theme={null} export COHERE_API_KEY="your-api-key" ``` ## Usage Example ```python Python theme={null} import os from mem0 import Memory # Set API key os.environ["COHERE_API_KEY"] = "your-api-key" # Initialize memory with Cohere reranker config = { "vector_store": {"provider": "chroma"}, "llm": {"provider": "openai", "config": {"model": "gpt-5-mini"}}, "rerank": { "provider": "cohere", "config": { "model": "rerank-v3.5", "top_k": 3 } } } memory = Memory.from_config(config) # Add memories messages = [ {"role": "user", "content": "I work as a data scientist at Microsoft"}, {"role": "user", "content": "I specialize in machine learning and NLP"}, {"role": "user", "content": "I enjoy playing tennis on weekends"} ] memory.add(messages, user_id="bob") # Search with reranking results = memory.search("What is the user's profession?", filters={"user_id": "bob"}) for result in results['results']: print(f"Memory: {result['memory']}") print(f"Vector Score: {result['score']:.3f}") print(f"Rerank Score: {result['rerank_score']:.3f}") print() ``` ## Multilingual Support For multilingual applications, use the multilingual model: ```python Python theme={null} config = { "rerank": { "provider": "cohere", "config": { "model": "rerank-multilingual-v3.0", "top_k": 5 } } } ``` ## Configuration Parameters | Parameter | Description | Type | Default | | - | - | - | - | | `model` | Cohere rerank model to use | `str` | `"rerank-v3.5"` | | `api_key` | Cohere API key | `str` | `None` | | `top_k` | Maximum documents to return | `int` | `None` | | `return_documents` | Whether to return document texts | `bool` | `False` | | `max_chunks_per_doc` | Maximum chunks per document | `int` | `None` | ## Features * **High Quality**: Enterprise-grade relevance scoring * **Multilingual**: Support for 100+ languages * **Scalable**: Production-ready with high throughput * **Reliable**: SLA-backed service with 99.9% uptime ## Best Practices 1. **Model Selection**: `rerank-v3.5` handles English and multilingual workloads; pin an older `v3.0` model only if you need to reproduce prior results 2. **Batch Processing**: Process multiple queries efficiently 3. **Error Handling**: Implement retry logic for production systems 4. **Monitoring**: Track reranking performance and costs # Hugging Face Reranker Source: https://docs.mem0.ai/components/rerankers/models/huggingface Access thousands of reranking models from Hugging Face Hub ## Overview The Hugging Face reranker provider gives you access to thousands of reranking models available on the Hugging Face Hub. This includes popular models like BAAI's BGE rerankers and other state-of-the-art cross-encoder models. ## Configuration ### Basic Setup ```python theme={null} from mem0 import Memory config = { "reranker": { "provider": "huggingface", "config": { "model": "BAAI/bge-reranker-base", "device": "cpu" } } } m = Memory.from_config(config) ``` ### Configuration Parameters | Parameter | Type | Default | Description | | - | - | - | - | | `model` | str | Required | Hugging Face model identifier | | `device` | str | "cpu" | Device to run model on ("cpu", "cuda", "mps") | | `batch_size` | int | 32 | Batch size for processing | | `max_length` | int | 512 | Maximum input sequence length | | `trust_remote_code` | bool | False | Allow remote code execution | ### Advanced Configuration ```python theme={null} config = { "reranker": { "provider": "huggingface", "config": { "model": "BAAI/bge-reranker-large", "device": "cuda", "batch_size": 16, "max_length": 512, "trust_remote_code": False, "model_kwargs": { "torch_dtype": "float16" } } } } ``` ## TypeScript (self-hosted) The [TypeScript OSS SDK](/open-source/features/reranker-search#typescript-sdk) (`mem0ai/oss`) runs this reranker locally with [Transformers.js](https://huggingface.co/docs/transformers.js), the same cross-encoder path as `sentence_transformer`, just a different default model. It executes ONNX weights, so the default is the ONNX mirror `Xenova/bge-reranker-base`. Point `model` at any ONNX-exported reranker on the Hub (a raw `BAAI/bge-reranker-*` PyTorch checkpoint will not load in this runtime). ```bash theme={null} pnpm add @huggingface/transformers ``` ```typescript theme={null} import { Memory } from "mem0ai/oss"; const memory = new Memory({ reranker: { provider: "huggingface", config: { // model: "Xenova/bge-reranker-base", // default (ONNX) device: "cpu", // "cpu" | "wasm" | "webgpu" maxLength: 512, // max tokens per query-document pair normalize: true, // sigmoid-normalize logits to [0, 1] (default) topK: 5, }, }, }); const results = await memory.search("What are the user's interests?", { filters: { userId: "alice" }, rerank: true, }); ``` > [!NOTE] > > `batchSize` and `showProgressBar` are accepted for parity with the Python SDK but are no-ops in the TypeScript runtime. `trust_remote_code` and `model_kwargs` are Python-only. ## Popular Models ### BGE Rerankers (Recommended) ```python theme={null} # Base model - good balance of speed and quality config = { "reranker": { "provider": "huggingface", "config": { "model": "BAAI/bge-reranker-base", "device": "cuda" } } } # Large model - better quality, slower config = { "reranker": { "provider": "huggingface", "config": { "model": "BAAI/bge-reranker-large", "device": "cuda" } } } # v2 models - latest improvements config = { "reranker": { "provider": "huggingface", "config": { "model": "BAAI/bge-reranker-v2-m3", "device": "cuda" } } } ``` ### Multilingual Models ```python theme={null} # Multilingual BGE reranker config = { "reranker": { "provider": "huggingface", "config": { "model": "BAAI/bge-reranker-v2-multilingual", "device": "cuda" } } } ``` ### Domain-Specific Models ```python theme={null} # For code search config = { "reranker": { "provider": "huggingface", "config": { "model": "microsoft/codebert-base", "device": "cuda" } } } # For biomedical content config = { "reranker": { "provider": "huggingface", "config": { "model": "dmis-lab/biobert-base-cased-v1.1", "device": "cuda" } } } ``` ## Usage Examples ### Basic Usage ```python theme={null} from mem0 import Memory m = Memory.from_config(config) # Add some memories m.add("I love hiking in the mountains", user_id="alice") m.add("Pizza is my favorite food", user_id="alice") m.add("I enjoy reading science fiction books", user_id="alice") # Search with reranking results = m.search( "What outdoor activities do I enjoy?", user_id="alice", rerank=True ) for result in results["results"]: print(f"Memory: {result['memory']}") print(f"Score: {result['score']:.3f}") ``` ### Batch Processing ```python theme={null} # Process multiple queries efficiently queries = [ "What are my hobbies?", "What food do I like?", "What books interest me?" ] results = [] for query in queries: result = m.search(query, filters={"user_id": "alice"}, rerank=True) results.append(result) ``` ## Performance Optimization ### GPU Acceleration ```python theme={null} # Use GPU for better performance config = { "reranker": { "provider": "huggingface", "config": { "model": "BAAI/bge-reranker-base", "device": "cuda", "batch_size": 64, # Increase batch size for GPU } } } ``` ### Memory Optimization ```python theme={null} # For limited memory environments config = { "reranker": { "provider": "huggingface", "config": { "model": "BAAI/bge-reranker-base", "device": "cpu", "batch_size": 8, # Smaller batch size "max_length": 256, # Shorter sequences "model_kwargs": { "torch_dtype": "float16" # Half precision } } } } ``` ## Model Comparison | Model | Size | Quality | Speed | Memory | Best For | | - | - | - | - | - | - | | bge-reranker-base | 278M | Good | Fast | Low | General use | | bge-reranker-large | 560M | Better | Medium | Medium | High quality needs | | bge-reranker-v2-m3 | 568M | Best | Medium | Medium | Latest improvements | | bge-reranker-v2-multilingual | 568M | Good | Medium | Medium | Multiple languages | ## Error Handling ```python theme={null} try: results = m.search( "test query", user_id="alice", rerank=True ) except Exception as e: print(f"Reranking failed: {e}") # Fall back to vector search only results = m.search( "test query", user_id="alice", rerank=False ) ``` ## Custom Models ### Using Private Models ```python theme={null} # Use a private model from Hugging Face config = { "reranker": { "provider": "huggingface", "config": { "model": "your-org/custom-reranker", "device": "cuda", "use_auth_token": "your-hf-token" } } } ``` ### Local Model Path ```python theme={null} # Use a locally downloaded model config = { "reranker": { "provider": "huggingface", "config": { "model": "/path/to/local/model", "device": "cuda" } } } ``` ## Best Practices 1. **Choose the Right Model**: Balance quality vs speed based on your needs 2. **Use GPU**: Significantly faster than CPU for larger models 3. **Optimize Batch Size**: Tune based on your hardware capabilities 4. **Monitor Memory**: Watch GPU/CPU memory usage with large models 5. **Cache Models**: Download once and reuse to avoid repeated downloads ## Troubleshooting ### Common Issues **Out of Memory Error** ```python theme={null} # Reduce batch size and sequence length config = { "reranker": { "provider": "huggingface", "config": { "model": "BAAI/bge-reranker-base", "batch_size": 4, "max_length": 256 } } } ``` **Model Download Issues** ```python theme={null} # Set cache directory import os os.environ["TRANSFORMERS_CACHE"] = "/path/to/cache" # Or use offline mode config = { "reranker": { "provider": "huggingface", "config": { "model": "BAAI/bge-reranker-base", "local_files_only": True } } } ``` **CUDA Not Available** ```python theme={null} import torch config = { "reranker": { "provider": "huggingface", "config": { "model": "BAAI/bge-reranker-base", "device": "cuda" if torch.cuda.is_available() else "cpu" } } } ``` ## Next Steps > **[Reranker Overview](/components/rerankers/overview)** > > Learn about reranking concepts > **[Configuration Guide](/components/rerankers/config)** > > Detailed configuration options # LLM Reranker Source: https://docs.mem0.ai/components/rerankers/models/llm-reranker Use any language model as a reranker with custom prompts ## Overview The LLM reranker allows you to use any supported language model as a reranker. This approach uses prompts to instruct the LLM to score and rank memories based on their relevance to the query. While slower than specialized rerankers, it offers maximum flexibility and can be fine-tuned with custom prompts. ## Configuration ### Basic Setup ```python theme={null} from mem0 import Memory config = { "reranker": { "provider": "llm_reranker", "config": { "provider": "openai", "model": "gpt-5-mini", "api_key": "your-openai-api-key" } } } m = Memory.from_config(config) ``` ### Configuration Parameters | Parameter | Type | Default | Description | | - | - | - | - | | `provider` | str | `"openai"` | LLM provider (openai, anthropic, etc.) | | `model` | str | `"gpt-5-mini"` | LLM model to use for reranking | | `api_key` | str | None | API key for the LLM provider | | `top_k` | int | None | Number of top documents to return after reranking | | `temperature` | float | 0.0 | LLM temperature for consistency | | `max_tokens` | int | 100 | Maximum tokens for LLM response | | `scoring_prompt` | str | None | Custom prompt template for scoring documents | | `llm` | dict | None | Optional nested LLM config for provider-specific fields (e.g., `ollama_base_url`, `azure_endpoint`). Overrides top-level `provider`/`model`/`api_key` when provided. | ### Advanced Configuration ```python theme={null} config = { "reranker": { "provider": "llm_reranker", "config": { "provider": "anthropic", "model": "claude-sonnet-4-20250514", "api_key": "your-anthropic-api-key", "top_k": 15, "temperature": 0.0, "scoring_prompt": """ Rate the relevance of each memory to the query on a scale of 0.0-1.0. Consider semantic similarity, context, and practical utility. Only provide the numeric score. Query: "{query}" Document: "{document}" Score: """ } } } ``` ## TypeScript (self-hosted) The [TypeScript OSS SDK](/open-source/features/reranker-search#typescript-sdk) (`mem0ai/oss`) ships the LLM reranker under the provider name `llm_reranker`. It does **not** reuse the Memory's main `llm` instance; it builds its own LLM from the reranker's own config, defaulting to `openai` / `gpt-5-mini`. Set `provider`/`model`/`apiKey` directly on `config`, or nest a fully separate `config.llm: { provider, config }` (its `provider`/`config` take priority over the top-level fields, which only backfill values missing from the nested config). ```typescript theme={null} import { Memory } from "mem0ai/oss"; const memory = new Memory({ reranker: { provider: "llm_reranker", config: { apiKey: process.env.OPENAI_API_KEY }, }, }); const results = await memory.search("What movies do I like?", { filters: { userId: "alice" }, rerank: true, }); ``` To rerank with a different LLM provider than the Memory's main `llm`, nest it under `config.llm`: ```typescript theme={null} const memory = new Memory({ llm: { provider: "openai", config: { apiKey: process.env.OPENAI_API_KEY } }, reranker: { provider: "llm_reranker", config: { llm: { provider: "anthropic", config: { apiKey: process.env.ANTHROPIC_API_KEY }, }, }, }, }); ``` ## Supported LLM Providers ### OpenAI ```python theme={null} config = { "reranker": { "provider": "llm_reranker", "config": { "provider": "openai", "model": "gpt-5-mini", "api_key": "your-openai-api-key", "temperature": 0.0 } } } ``` ### Anthropic ```python theme={null} config = { "reranker": { "provider": "llm_reranker", "config": { "provider": "anthropic", "model": "claude-sonnet-4-20250514", "api_key": "your-anthropic-api-key" } } } ``` ### Ollama (Local) ```python theme={null} config = { "reranker": { "provider": "llm_reranker", "config": { "provider": "ollama", "model": "llama3.2", "llm": { "provider": "ollama", "config": { "model": "llama3.2", "ollama_base_url": "http://localhost:11434" } } } } } ``` > [!NOTE] > > For providers like Ollama that need extra fields (e.g., `ollama_base_url`), use the optional nested `llm` key to pass provider-specific configuration. The nested `llm` config overrides top-level `provider`/`model`/`api_key` when provided. ### Azure OpenAI ```python theme={null} config = { "reranker": { "provider": "llm_reranker", "config": { "provider": "azure_openai", "model": "gpt-5-mini", "api_key": "your-azure-api-key", "llm": { "provider": "azure_openai", "config": { "model": "gpt-5-mini", "api_key": "your-azure-api-key", "azure_endpoint": "https://your-resource.openai.azure.com/", "azure_deployment": "gpt-5-mini-deployment" } } } } } ``` ## Custom Prompts ### Default Prompt Behavior The default prompt asks the LLM to score relevance on a 0.0-1.0 scale: ``` You are a relevance scoring assistant. Given a query and a document, you need to score how relevant the document is to the query. Score the relevance on a scale from 0.0 to 1.0, where: - 1.0 = Perfectly relevant and directly answers the query - 0.8-0.9 = Highly relevant with good information - 0.6-0.7 = Moderately relevant with some useful information - 0.4-0.5 = Slightly relevant with limited useful information - 0.0-0.3 = Not relevant or no useful information Query: "{query}" Document: "{document}" Provide only a single numerical score between 0.0 and 1.0. Do not include any explanation or additional text. ``` ### Custom Prompt Examples #### Domain-Specific Scoring ```python theme={null} custom_prompt = """ You are a medical information specialist. Rate how relevant each memory is for answering the medical query. Consider clinical accuracy, specificity, and practical applicability. Rate from 0.0 to 1.0 where: - 0.0-0.3: Irrelevant or potentially harmful - 0.4-0.6: Somewhat relevant but incomplete - 0.7-0.8: Relevant and helpful - 0.9-1.0: Highly relevant and clinically useful Query: "{query}" Document: "{document}" Score: """ config = { "reranker": { "provider": "llm_reranker", "config": { "provider": "openai", "model": "gpt-5-mini", "api_key": "your-api-key", "scoring_prompt": custom_prompt } } } ``` #### Contextual Relevance ```python theme={null} contextual_prompt = """ Rate how well this memory answers the specific question asked. Consider: - Direct relevance to the question - Completeness of information - Recency and accuracy - Practical usefulness Rate 0.0-1.0: 0.0 = Not relevant 0.25 = Slightly relevant 0.5 = Moderately relevant 0.75 = Very relevant 1.0 = Perfectly answers the question Query: "{query}" Document: "{document}" Score: """ ``` #### Conversational Context ```python theme={null} conversation_prompt = """ You are helping evaluate which memories are most useful for a conversational AI assistant. Rate how helpful this memory would be for generating a relevant response. Consider: - Direct relevance to user's intent - Emotional appropriateness - Factual accuracy - Conversation flow Rate 0.0-1.0: Query: "{query}" Document: "{document}" Score: """ ``` > [!NOTE] > > Custom prompts must include `{query}` and `{document}` placeholders. The LLM response should contain a numerical score which is automatically extracted. ## Usage Examples ### Basic Usage ```python theme={null} from mem0 import Memory m = Memory.from_config(config) # Add memories m.add("I'm allergic to peanuts", user_id="alice") m.add("I love Italian food", user_id="alice") m.add("I'm vegetarian", user_id="alice") # Search with LLM reranking results = m.search( "What foods should I avoid?", user_id="alice", rerank=True ) for result in results["results"]: print(f"Memory: {result['memory']}") print(f"LLM Score: {result['score']:.2f}") ``` ### Batch Processing with Error Handling ```python theme={null} def safe_llm_rerank_search(query, user_id, max_retries=3): for attempt in range(max_retries): try: return m.search(query, filters={"user_id": user_id}, rerank=True) except Exception as e: print(f"Attempt {attempt + 1} failed: {e}") if attempt == max_retries - 1: # Fall back to vector search return m.search(query, filters={"user_id": user_id}, rerank=False) # Use the safe function results = safe_llm_rerank_search("What are my preferences?", "alice") ``` ## Performance Considerations ### Speed vs Quality Trade-offs | Model Type | Speed | Quality | Cost | Best For | | - | - | - | - | - | | GPT-4o mini | Fast | Good | Low | High-volume applications | | GPT-4o | Medium | Excellent | Medium | Quality-critical applications | | Claude Sonnet | Medium | Excellent | Medium | Balanced performance | | Ollama Local | Variable | Good | Free | Privacy-sensitive applications | ### Optimization Strategies ```python theme={null} # Fast configuration for high-volume use fast_config = { "reranker": { "provider": "llm_reranker", "config": { "provider": "openai", "model": "gpt-5-mini", "api_key": "your-api-key", "top_k": 5, "temperature": 0.0 } } } # High-quality configuration quality_config = { "reranker": { "provider": "llm_reranker", "config": { "provider": "openai", "model": "gpt-4o", "api_key": "your-api-key", "top_k": 15, "temperature": 0.0 } } } ``` ## Advanced Use Cases ### Multi-Step Reasoning ```python theme={null} reasoning_prompt = """ Evaluate this memory's relevance using multi-step reasoning: 1. What is the main intent of the query? 2. What key information does the memory contain? 3. How directly does the memory address the query? 4. What additional context might be needed? Based on this analysis, rate relevance 0.0-1.0: Query: "{query}" Document: "{document}" Analysis: Step 1 (Intent): Step 2 (Information): Step 3 (Directness): Step 4 (Context): Final Score: """ ``` ## Error Handling and Fallbacks ```python theme={null} class RobustLLMReranker: def __init__(self, primary_config, fallback_config=None): self.primary = Memory.from_config(primary_config) self.fallback = Memory.from_config(fallback_config) if fallback_config else None def search(self, query, user_id, max_retries=2): # Try primary LLM reranker for attempt in range(max_retries): try: return self.primary.search(query, filters={"user_id": user_id}, rerank=True) except Exception as e: print(f"Primary reranker attempt {attempt + 1} failed: {e}") # Try fallback reranker if self.fallback: try: return self.fallback.search(query, filters={"user_id": user_id}, rerank=True) except Exception as e: print(f"Fallback reranker failed: {e}") # Final fallback: vector search only return self.primary.search(query, filters={"user_id": user_id}, rerank=False) # Usage primary_config = { "reranker": { "provider": "llm_reranker", "config": { "provider": "openai", "model": "gpt-4o", "api_key": "your-api-key" } } } fallback_config = { "reranker": { "provider": "llm_reranker", "config": { "provider": "openai", "model": "gpt-5-mini", "api_key": "your-api-key" } } } reranker = RobustLLMReranker(primary_config, fallback_config) results = reranker.search("What are my preferences?", "alice") ``` ## Best Practices 1. **Use Specific Prompts**: Tailor prompts to your domain and use case 2. **Set Temperature to 0**: Ensure consistent scoring across runs 3. **Limit Top-K**: Don't rerank too many candidates to control costs 4. **Implement Fallbacks**: Always have a backup plan for API failures 5. **Monitor Costs**: Track API usage, especially with expensive models 6. **Cache Results**: Consider caching reranking results for repeated queries 7. **Test Prompts**: Experiment with different prompts to find what works best ## Troubleshooting ### Common Issues **Inconsistent Scores** * Set temperature to 0.0 * Use more specific prompts * Consider using multiple calls and averaging **API Rate Limits** * Implement exponential backoff * Use cheaper models for high-volume scenarios * Add retry logic with delays **Poor Ranking Quality** * Refine your custom prompt * Try different LLM models * Add examples to your prompt ## Next Steps > **[Custom Prompts Guide](/components/rerankers/custom-prompts)** > > Learn to craft effective reranking prompts > **[Performance Optimization](/components/rerankers/optimization)** > > Optimize LLM reranker performance # Sentence Transformer Source: https://docs.mem0.ai/components/rerankers/models/sentence-transformer Local reranking with HuggingFace cross-encoder models Sentence Transformer reranker provides local reranking using HuggingFace cross-encoder models, perfect for privacy-focused deployments where you want to keep data on-premises. ## Models Any HuggingFace cross-encoder model can be used. Popular choices include: * **`cross-encoder/ms-marco-MiniLM-L-6-v2`**: Default, good balance of speed and accuracy * **`cross-encoder/ms-marco-TinyBERT-L-2-v2`**: Fastest, smaller model size * **`cross-encoder/ms-marco-electra-base`**: Higher accuracy, larger model * **`cross-encoder/stsb-distilroberta-base`**: Good for semantic similarity tasks ## Installation ```bash theme={null} pip install sentence-transformers ``` ## Configuration ```python Python theme={null} from mem0 import Memory config = { "vector_store": { "provider": "chroma", "config": { "collection_name": "my_memories", "path": "./chroma_db" } }, "llm": { "provider": "openai", "config": { "model": "gpt-5-mini" } }, "rerank": { "provider": "sentence_transformer", "config": { "model": "cross-encoder/ms-marco-MiniLM-L-6-v2", "device": "cpu", # or "cuda" for GPU "batch_size": 32, "show_progress_bar": False, "top_k": 5 } } } memory = Memory.from_config(config) ``` ## TypeScript (self-hosted) The [TypeScript OSS SDK](/open-source/features/reranker-search#typescript-sdk) (`mem0ai/oss`) runs this reranker locally with [Transformers.js](https://huggingface.co/docs/transformers.js). Because it executes ONNX weights, the default model is the ONNX mirror of the Python default: `Xenova/ms-marco-MiniLM-L-6-v2`. Point `model` at any ONNX-exported cross-encoder on the Hub (a raw `cross-encoder/...` PyTorch checkpoint will not load in this runtime). ```bash theme={null} pnpm add @huggingface/transformers ``` ```typescript theme={null} import { Memory } from "mem0ai/oss"; const memory = new Memory({ reranker: { provider: "sentence_transformer", config: { // model: "Xenova/ms-marco-MiniLM-L-6-v2", // default (ONNX) device: "cpu", // "cpu" | "wasm" | "webgpu" maxLength: 512, // max tokens per query-document pair normalize: true, // sigmoid-normalize logits to [0, 1] (default) topK: 5, }, }, }); const results = await memory.search("What books does the user like?", { filters: { userId: "charlie" }, rerank: true, }); ``` > [!NOTE] > > `batchSize` and `showProgressBar` are accepted for parity with the Python SDK but are no-ops in the TypeScript runtime, because a search reranks a small candidate set in a single in-process forward pass. The model downloads once and is cached in-process. ## GPU Acceleration For better performance, use GPU acceleration: ```python Python theme={null} config = { "rerank": { "provider": "sentence_transformer", "config": { "model": "cross-encoder/ms-marco-MiniLM-L-6-v2", "device": "cuda", # Use GPU "batch_size": 64 # high batch size for high memory GPUs } } } ``` ## Usage Example ```python Python theme={null} from mem0 import Memory # Initialize memory with local reranker config = { "vector_store": {"provider": "chroma"}, "llm": {"provider": "openai", "config": {"model": "gpt-5-mini"}}, "rerank": { "provider": "sentence_transformer", "config": { "model": "cross-encoder/ms-marco-MiniLM-L-6-v2", "device": "cpu" } } } memory = Memory.from_config(config) # Add memories messages = [ {"role": "user", "content": "I love reading science fiction novels"}, {"role": "user", "content": "My favorite author is Isaac Asimov"}, {"role": "user", "content": "I also enjoy watching sci-fi movies"} ] memory.add(messages, user_id="charlie") # Search with local reranking results = memory.search("What books does the user like?", filters={"user_id": "charlie"}) for result in results['results']: print(f"Memory: {result['memory']}") print(f"Vector Score: {result['score']:.3f}") print(f"Rerank Score: {result['rerank_score']:.3f}") print() ``` ## Custom Models You can use any HuggingFace cross-encoder model: ```python Python theme={null} # Using a different model config = { "rerank": { "provider": "sentence_transformer", "config": { "model": "cross-encoder/stsb-distilroberta-base", "device": "cpu" } } } ``` ## Configuration Parameters | Parameter | Description | Type | Default | | - | - | - | - | | `model` | HuggingFace cross-encoder model name | `str` | `"cross-encoder/ms-marco-MiniLM-L-6-v2"` | | `device` | Device to run model on (`cpu`, `cuda`, etc.) | `str` | `None` | | `batch_size` | Batch size for processing documents | `int` | `32` | | `show_progress_bar` | Show progress bar during processing | `bool` | `False` | | `top_k` | Maximum documents to return | `int` | `None` | ## Advantages * **Privacy**: Complete local processing, no external API calls * **Cost**: No per-token charges after initial model download * **Customization**: Use any HuggingFace cross-encoder model * **Offline**: Works without internet connection after model download ## Performance Considerations * **First Run**: Model download may take time initially * **Memory Usage**: Models require GPU/CPU memory * **Batch Size**: Optimize batch size based on available memory * **Device**: GPU acceleration significantly improves speed ## Best Practices 1. **Model Selection**: Choose model based on accuracy vs speed requirements 2. **Device Management**: Use GPU when available for better performance 3. **Batch Processing**: Process multiple documents together for efficiency 4. **Memory Monitoring**: Monitor system memory usage with larger models # Zero Entropy Source: https://docs.mem0.ai/components/rerankers/models/zero-entropy Configure Zero Entropy neural reranking models in Mem0 with zerank-1 and zerank-1-small support. [Zero Entropy](https://www.zeroentropy.dev) provides neural reranking models that significantly improve search relevance with fast performance. ## Models Zero Entropy offers two reranking models: * **`zerank-1`**: Flagship state-of-the-art reranker (non-commercial license) * **`zerank-1-small`**: Open-source model (Apache 2.0 license) ## Installation ```bash theme={null} pip install zeroentropy ``` ## Configuration ```python Python theme={null} from mem0 import Memory config = { "vector_store": { "provider": "chroma", "config": { "collection_name": "my_memories", "path": "./chroma_db" } }, "llm": { "provider": "openai", "config": { "model": "gpt-5-mini" } }, "rerank": { "provider": "zero_entropy", "config": { "model": "zerank-1", # or "zerank-1-small" "api_key": "your-zero-entropy-api-key", # or set ZERO_ENTROPY_API_KEY "top_k": 5 } } } memory = Memory.from_config(config) ``` ## TypeScript (self-hosted) The [TypeScript OSS SDK](/open-source/features/reranker-search#typescript-sdk) (`mem0ai/oss`) ships the Zero Entropy reranker under the same provider name as Python, `zero_entropy`. It reads the key from config or `ZERO_ENTROPY_API_KEY` and defaults to the `zerank-1` model. ```bash theme={null} pnpm add zeroentropy ``` ```typescript theme={null} import { Memory } from "mem0ai/oss"; const memory = new Memory({ reranker: { provider: "zero_entropy", config: { apiKey: process.env.ZERO_ENTROPY_API_KEY, // model: "zerank-1", // default (or "zerank-1-small") topK: 5, }, }, }); const results = await memory.search("What Italian food does the user like?", { filters: { userId: "alice" }, rerank: true, }); ``` ## Environment Variables Set your API key as an environment variable: ```bash theme={null} export ZERO_ENTROPY_API_KEY="your-api-key" ``` ## Usage Example ```python Python theme={null} import os from mem0 import Memory # Set API key os.environ["ZERO_ENTROPY_API_KEY"] = "your-api-key" # Initialize memory with Zero Entropy reranker config = { "vector_store": {"provider": "chroma"}, "llm": {"provider": "openai", "config": {"model": "gpt-5-mini"}}, "rerank": {"provider": "zero_entropy", "config": {"model": "zerank-1"}} } memory = Memory.from_config(config) # Add memories messages = [ {"role": "user", "content": "I love Italian pasta, especially carbonara"}, {"role": "user", "content": "Japanese sushi is also amazing"}, {"role": "user", "content": "I enjoy cooking Mediterranean dishes"} ] memory.add(messages, user_id="alice") # Search with reranking results = memory.search("What Italian food does the user like?", filters={"user_id": "alice"}) for result in results['results']: print(f"Memory: {result['memory']}") print(f"Vector Score: {result['score']:.3f}") print(f"Rerank Score: {result['rerank_score']:.3f}") print() ``` ## Configuration Parameters | Parameter | Description | Type | Default | | - | - | - | - | | `model` | Model to use: `"zerank-1"` or `"zerank-1-small"` | `str` | `"zerank-1"` | | `api_key` | Zero Entropy API key | `str` | `None` | | `top_k` | Maximum documents to return after reranking | `int` | `None` | ## Performance * **Fast**: Optimized neural architecture for low latency * **Accurate**: State-of-the-art relevance scoring * **Cost-effective**: \~\$0.025/1M tokens processed ## Best Practices 1. **Model Selection**: Use `zerank-1` for best quality, `zerank-1-small` for faster processing 2. **Batch Size**: Process multiple queries together when possible 3. **Top-k Limiting**: Set reasonable `top_k` values (5-20) for best performance 4. **API Key Management**: Use environment variables for secure key storage # Performance Optimization Source: https://docs.mem0.ai/components/rerankers/optimization Best practices for optimizing reranker performance in Mem0, covering candidate sizing, batching, and tuning. Optimizing reranker performance is crucial for maintaining fast search response times while improving result quality. This guide covers best practices for different reranker types. ## General Optimization Principles ### Candidate Set Size The number of candidates sent to the reranker significantly impacts performance: ```python theme={null} # Optimal candidate sizes for different rerankers config_map = { "cohere": {"initial_candidates": 100, "top_n": 10}, "sentence_transformer": {"initial_candidates": 50, "top_n": 10}, "huggingface": {"initial_candidates": 30, "top_n": 5}, "llm_reranker": {"initial_candidates": 20, "top_n": 5} } ``` ### Batching Strategy Process multiple queries efficiently: ```python theme={null} # Configure for batch processing config = { "reranker": { "provider": "sentence_transformer", "config": { "model": "cross-encoder/ms-marco-MiniLM-L-6-v2", "batch_size": 16, # Process multiple candidates at once "top_n": 10 } } } ``` ## Provider-Specific Optimizations ### Cohere Optimization ```python theme={null} # Optimized Cohere configuration config = { "reranker": { "provider": "cohere", "config": { "model": "rerank-v3.5", "top_n": 10, "max_chunks_per_doc": 10, # Limit chunk processing "return_documents": False # Reduce response size } } } ``` **Best Practices:** * Use v3.0 models for better speed/accuracy balance * Limit candidates to 100 or fewer * Cache API responses when possible * Monitor API rate limits ### Sentence Transformer Optimization ```python theme={null} # Performance-optimized configuration config = { "reranker": { "provider": "sentence_transformer", "config": { "model": "cross-encoder/ms-marco-MiniLM-L-6-v2", "device": "cuda", # Use GPU when available "batch_size": 32, "top_n": 10, "max_length": 512 # Limit input length } } } ``` **Device Optimization:** ```python theme={null} import torch # Auto-detect best device device = "cuda" if torch.cuda.is_available() else "mps" if torch.backends.mps.is_available() else "cpu" config = { "reranker": { "provider": "sentence_transformer", "config": { "device": device, "model": "cross-encoder/ms-marco-MiniLM-L-6-v2" } } } ``` ### Hugging Face Optimization ```python theme={null} # Optimized for Hugging Face models config = { "reranker": { "provider": "huggingface", "config": { "model": "BAAI/bge-reranker-base", "use_fp16": True, # Half precision for speed "max_length": 512, "batch_size": 8, "top_n": 10 } } } ``` ### LLM Reranker Optimization ```python theme={null} # Optimized LLM reranker configuration config = { "reranker": { "provider": "llm_reranker", "config": { "llm": { "provider": "openai", "config": { "model": "gpt-3.5-turbo", # Faster than gpt-4 "temperature": 0, # Deterministic results "max_tokens": 500 # Limit response length } }, "batch_ranking": True, # Rank multiple at once "top_n": 5, # Fewer results for faster processing "timeout": 10 # Request timeout } } } ``` ## Performance Monitoring ### Latency Tracking ```python theme={null} import time from mem0 import Memory def measure_reranker_performance(config, queries, user_id): memory = Memory.from_config(config) latencies = [] for query in queries: start_time = time.time() results = memory.search(query, filters={"user_id": user_id}) latency = time.time() - start_time latencies.append(latency) return { "avg_latency": sum(latencies) / len(latencies), "max_latency": max(latencies), "min_latency": min(latencies) } ``` ### Memory Usage Monitoring ```python theme={null} import psutil import os def monitor_memory_usage(): process = psutil.Process(os.getpid()) return { "memory_mb": process.memory_info().rss / 1024 / 1024, "memory_percent": process.memory_percent() } ``` ## Caching Strategies ### Result Caching ```python theme={null} from functools import lru_cache import hashlib class CachedReranker: def __init__(self, config): self.memory = Memory.from_config(config) self.cache_size = 1000 @lru_cache(maxsize=1000) def search_cached(self, query_hash, user_id): return self.memory.search(query, filters={"user_id": user_id}) def search(self, query, user_id): query_hash = hashlib.md5(f"{query}_{user_id}".encode()).hexdigest() return self.search_cached(query_hash, user_id) ``` ### Model Caching ```python theme={null} # Pre-load models to avoid initialization overhead config = { "reranker": { "provider": "sentence_transformer", "config": { "model": "cross-encoder/ms-marco-MiniLM-L-6-v2", "cache_folder": "/path/to/model/cache", "device": "cuda" } } } ``` ## Parallel Processing ### Async Configuration ```python theme={null} import asyncio from mem0 import Memory async def parallel_search(config, queries, user_id): memory = Memory.from_config(config) # Process multiple queries concurrently tasks = [ memory.search_async(query, user_id=user_id) for query in queries ] results = await asyncio.gather(*tasks) return results ``` ## Hardware Optimization ### GPU Configuration ```python theme={null} # Optimize for GPU usage import torch if torch.cuda.is_available(): torch.cuda.set_per_process_memory_fraction(0.8) # Reserve GPU memory config = { "reranker": { "provider": "sentence_transformer", "config": { "device": "cuda", "model": "cross-encoder/ms-marco-electra-base", "batch_size": 64, # Larger batch for GPU "fp16": True # Half precision } } } ``` ### CPU Optimization ```python theme={null} import torch # Optimize CPU threading torch.set_num_threads(4) # Adjust based on your CPU config = { "reranker": { "provider": "sentence_transformer", "config": { "device": "cpu", "model": "cross-encoder/ms-marco-MiniLM-L-6-v2", "num_workers": 4 # Parallel processing } } } ``` ## Benchmarking Different Configurations ```python theme={null} def benchmark_rerankers(): configs = [ {"provider": "cohere", "model": "rerank-v3.5"}, {"provider": "sentence_transformer", "model": "cross-encoder/ms-marco-MiniLM-L-6-v2"}, {"provider": "huggingface", "model": "BAAI/bge-reranker-base"} ] test_queries = ["sample query 1", "sample query 2", "sample query 3"] results = {} for config in configs: provider = config["provider"] performance = measure_reranker_performance( {"reranker": {"provider": provider, "config": config}}, test_queries, "test_user" ) results[provider] = performance return results ``` ## Production Best Practices 1. **Model Selection**: Choose the right balance of speed vs. accuracy 2. **Resource Allocation**: Monitor CPU/GPU usage and memory consumption 3. **Error Handling**: Implement fallbacks for reranker failures 4. **Load Balancing**: Distribute reranking load across multiple instances 5. **Monitoring**: Track latency, throughput, and error rates 6. **Caching**: Cache frequent queries and model predictions 7. **Batch Processing**: Group similar queries for efficient processing # Reranker Providers Overview Source: https://docs.mem0.ai/components/rerankers/overview Pick the right reranker path to boost Mem0 search relevance. Mem0 rerankers rescore vector search hits so your agents surface the most relevant memories. Use this hub to decide when reranking helps, configure a provider, and fine-tune performance. > [!NOTE] > > Reranking trades extra latency for better precision. Start once you have baseline search working and measure before/after relevance. ## Supported Rerankers > **[Cohere](/components/rerankers/models/cohere)** > **[Sentence Transformers](/components/rerankers/models/sentence-transformer)** > **[Hugging Face](/components/rerankers/models/huggingface)** > **[LLM Reranker](/components/rerankers/models/llm-reranker)** > **[Zero Entropy](/components/rerankers/models/zero-entropy)** > [!NOTE] > > All five rerankers are available in both the Python and the [TypeScript](/open-source/features/reranker-search#typescript-sdk) self-hosted SDKs. Each provider page has a **TypeScript (self-hosted)** section with the camelCase config. ## Reranking Workflow > **[Understand Reranking](/open-source/features/reranker-search)** > > See how reranker-enhanced search changes your retrieval flow. > **[Configure Providers](/components/rerankers/config)** > > Add reranker blocks to your memory configuration. > **[Optimize Performance](/components/rerankers/optimization)** > > Balance relevance, latency, and cost with tuning tactics. > **[Custom Prompts](/components/rerankers/custom-prompts)** > > Shape LLM-based reranking with tailored instructions. > **[Zero Entropy Guide](/components/rerankers/models/zero-entropy)** > > Adopt the managed neural reranker for production workloads. > **[Sentence Transformers](/components/rerankers/models/sentence-transformer)** > > Keep reranking on-device with cross-encoder models. ## Picking the Right Reranker * **API-first** when you need top quality and can absorb request costs (Cohere, Zero Entropy). * **Self-hosted** for privacy-sensitive deployments that must stay on your hardware (Sentence Transformer, Hugging Face). * **LLM-driven** when you need bespoke scoring logic or complex prompts. * **Hybrid** by enabling reranking only on premium journeys to control spend. ## Implementation Checklist 1. Confirm baseline search KPIs so you can measure uplift. 2. Select a provider and add the `reranker` block to your config. 3. Test latency impact with production-like query batches. 4. Decide whether to enable reranking globally or per-search via the `rerank` flag. > **[Set Up Reranking](/components/rerankers/config)** > > Walk through the configuration fields and defaults. > **[Example: Reranker Search](/open-source/features/reranker-search)** > > Follow the feature guide to see reranking in action. # Vector Store Configuration Reference Source: https://docs.mem0.ai/components/vectordbs/config Reference for vector database configuration options in Mem0, including provider selection and connection settings. ## How to define configurations? The `config` is defined as an object with two main keys: * `vector_store`: Specifies the vector database provider and its configuration * `provider`: The name of the vector database (e.g., "chroma", "pgvector", "qdrant", "milvus", "upstash\_vector", "azure\_ai\_search", "vertex\_ai\_vector\_search", "valkey", "oracledb") * `config`: A nested dictionary containing provider-specific settings ## How to Use Config Here's a general example of how to use the config with mem0: ```python Python theme={null} import os from mem0 import Memory os.environ["OPENAI_API_KEY"] = "sk-xx" config = { "vector_store": { "provider": "your_chosen_provider", "config": { # Provider-specific settings go here } } } m = Memory.from_config(config) m.add("Your text here", user_id="user", metadata={"category": "example"}) ``` ```typescript TypeScript theme={null} // Example for in-memory vector database (Only supported in TypeScript) import { Memory } from 'mem0ai/oss'; const configMemory = { vector_store: { provider: 'memory', config: { collectionName: 'memories', dimension: 1536, }, }, }; const memory = new Memory(configMemory); await memory.add("Your text here", { userId: "user", metadata: { category: "example" } }); ``` > [!NOTE] > > The in-memory vector database is only supported in the TypeScript implementation. ## Why is Config Needed? Config is essential for: 1. Specifying which vector database to use. 2. Providing necessary connection details (e.g., host, port, credentials). 3. Customizing database-specific settings (e.g., collection name, path). 4. Ensuring proper initialization and connection to your chosen vector store. ## Master List of All Params in Config Here's a comprehensive list of all parameters that can be used across different vector databases: **Python** | Parameter | Description | | - | - | | `collection_name` | Name of the collection | | `embedding_model_dims` | Dimensions of the embedding model | | `client` | Custom client for the database | | `path` | Path for the database | | `host` | Host where the server is running | | `port` | Port where the server is running | | `user` | Username for database connection | | `password` | Password for database connection | | `dbname` | Name of the database | | `url` | Full URL for the server | | `api_key` | API key for the server | | `on_disk` | Enable persistent storage | | `endpoint_id` | Endpoint ID (vertex\_ai\_vector\_search) | | `index_id` | Index ID (vertex\_ai\_vector\_search) | | `deployment_index_id` | Deployment index ID (vertex\_ai\_vector\_search) | | `project_id` | Project ID (vertex\_ai\_vector\_search) | | `project_number` | Project number (vertex\_ai\_vector\_search) | | `vector_search_api_endpoint` | Vector search API endpoint (vertex\_ai\_vector\_search) | | `connection_string` | PostgreSQL connection string (for Supabase/PGVector) | | `index_method` | Vector index method (for Supabase) | | `index_measure` | Distance measure for similarity search (for Supabase) | | `connection_params` | Connection settings for Oracle AI Vector Search | | `use_connection_pool` | Create an Oracle connection pool from `connection_params` | | `distance_metric` | Distance metric for Oracle vector indexing and search | | `index_type` | Oracle vector index type: `HNSW` or `IVF` | | `index_parameters` | Oracle vector-index parameters for the selected index type | **TypeScript** | Parameter | Description | | - | - | | `collectionName` | Name of the collection | | `embeddingModelDims` | Dimensions of the embedding model | | `dimension` | Dimensions of the embedding model (for memory provider) | | `host` | Host where the server is running | | `port` | Port where the server is running | | `url` | URL for the server | | `apiKey` | API key for the server | | `path` | Path for the database | | `onDisk` | Enable persistent storage | | `redisUrl` | URL for the Redis server | | `username` | Username for database connection | | `password` | Password for database connection | ## Customizing Config Each vector database has its own specific configuration requirements. To customize the config for your chosen vector store: 1. Identify the vector database you want to use from [supported vector databases](./overview). 2. Refer to the `Config` section in the respective vector database's documentation. 3. Include only the relevant parameters for your chosen database in the `config` dictionary. ## Supported Vector Databases For detailed information on configuring specific vector databases, please visit the [Supported Vector Databases](./overview) section. There you'll find individual pages for each supported vector store with provider-specific usage examples and configuration details. # Azure AI Search Source: https://docs.mem0.ai/components/vectordbs/dbs/azure Use Azure AI Search as a vector store in Mem0 for managed vector search with service name and API key setup. [Azure AI Search](https://learn.microsoft.com/azure/search/search-what-is-azure-search/) (formerly known as "Azure Cognitive Search") provides secure information retrieval at scale over user-owned content in traditional and generative AI search applications. ## Usage ```python theme={null} import os from mem0 import Memory os.environ["OPENAI_API_KEY"] = "sk-xx" # This key is used for embedding purpose config = { "vector_store": { "provider": "azure_ai_search", "config": { "service_name": "", "api_key": "", "collection_name": "mem0", "embedding_model_dims": 1536 } } } m = Memory.from_config(config) messages = [ {"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"}, {"role": "assistant", "content": "How about thriller movies? They can be quite engaging."}, {"role": "user", "content": "I'm not a big fan of thriller movies but I love sci-fi movies."}, {"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."} ] m.add(messages, user_id="alice", metadata={"category": "movies"}) ``` ## Using binary compression for large vector collections ```python theme={null} config = { "vector_store": { "provider": "azure_ai_search", "config": { "service_name": "", "api_key": "", "collection_name": "mem0", "embedding_model_dims": 1536, "compression_type": "binary", "use_float16": True # Use half precision for storage efficiency } } } ``` ## Using hybrid search ```python theme={null} config = { "vector_store": { "provider": "azure_ai_search", "config": { "service_name": "", "api_key": "", "collection_name": "mem0", "embedding_model_dims": 1536, "hybrid_search": True, "vector_filter_mode": "postFilter" } } } ``` ## Using Azure Identity for Authentication As an alternative to using an API key, the Azure Identity credential chain can be used to authenticate with Azure OpenAI. The list below shows the order of precedence for credential application: 1. **Environment Credential:** Azure client ID, secret, tenant ID, or certificate in environment variables for service principal authentication. 2. **Workload Identity Credential:** Utilizes Azure Workload Identity (relevant for Kubernetes and Azure workloads). 3. **Managed Identity Credential:** Authenticates as a Managed Identity (for apps/services hosted in Azure with Managed Identity enabled); this is the most secure production credential. 4. **Shared Token Cache Credential / Visual Studio Credential (Windows only):** Uses cached credentials from Visual Studio sign-ins (and sometimes VS Code if SSO is enabled). 5. **Azure CLI Credential:** Uses the currently logged-in user from the Azure CLI (`az login`); this is the most common development credential. 6. **Azure PowerShell Credential:** Uses the identity from Azure PowerShell (`Connect-AzAccount`). 7. **Azure Developer CLI Credential:** Uses the session from Azure Developer CLI (`azd auth login`). \[!NOTE] If an API key is provided, it will be used for authentication over an Azure Identity To enable Role-Based Access Control (RBAC) for Azure AI Search, follow these steps: 1. In the Azure Portal, navigate to your **Azure AI Search** service. 2. In the left menu, select **Settings** > **Keys**. 3. Change the authentication setting to **Role-based access control**, or **Both** if you need API key compatibility. The default is “Key-based authentication”: you must switch it to use Azure roles. 4. **Go to Access Control (IAM):** * In the Azure Portal, select your Search service. * Click **Access Control (IAM)** on the left. 5. **Add a Role Assignment:** * Click **Add** > **Add role assignment**. 6. **Choose Role:** * Mem0 requires the **Search Index Data Contributor** and **Search Service Contributor** role. 7. **Choose Member** * To assign to a User, Group, Service Principal or Managed Identity: * For production it is recommended to use a service principal or managed identity. * For a service principal: select **User, group, or service principal** and search for the service principal. * For a managed identity: select **Managed identity** and choose the managed identity. * For development, you can assign the role to a user account. * For development: select **User, group, or service principal** and pick an Azure Entra ID account (the same used with `az login`). 8. **Complete the Assignment:** * Click **Review + Assign**. If you are using Azure Identity, do not set the `api_key` in the configuration. ```python theme={null} config = { "vector_store": { "provider": "azure_ai_search", "config": { "service_name": "", "collection_name": "mem0", "embedding_model_dims": 1536, "compression_type": "binary", "use_float16": True # Use half precision for storage efficiency } } } ``` ### Environment Variables to Use Azure Identity Credential * For an Environment Credential, you will need to set up a Service Principal and set the following environment variables: * `AZURE_TENANT_ID`: Your Azure Active Directory tenant ID. * `AZURE_CLIENT_ID`: The client ID of your service principal or managed identity. * `AZURE_CLIENT_SECRET`: The client secret of your service principal. * For a User-Assigned Managed Identity, you will need to set the following environment variable: * `AZURE_CLIENT_ID`: The client ID of the user-assigned managed identity. * For a System-Assigned Managed Identity, no additional environment variables are needed. ### Developer Logins for Azure Identity Credential * For an Azure CLI Credential, you need to have the Azure CLI installed and logged in with `az login`. * For an Azure PowerShell Credential, you need to have the Azure PowerShell module installed and logged in with `Connect-AzAccount`. * For an Azure Developer CLI Credential, you need to have the Azure Developer CLI installed and logged in with `azd auth login`. Troubleshooting tips for [Azure Identity](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/identity/azure-identity/TROUBLESHOOTING.md#troubleshoot-environmentcredential-authentication-issues). ## Configuration Parameters | Parameter | Description | Default Value | Options | | - | - | - | - | | `service_name` | Azure AI Search service name | Required | - | | `api_key` | API key of the Azure AI Search service | Optional | If not present, the [Azure Identity](#using-azure-identity-for-authentication) credential chain will be used | | `collection_name` | The name of the collection/index to store vectors | `mem0` | Any valid index name | | `embedding_model_dims` | Dimensions of the embedding model | `1536` | Any integer value | | `compression_type` | Type of vector compression to use | `none` | `none`, `scalar`, `binary` | | `use_float16` | Store vectors in half precision (Edm.Half) | `False` | `True`, `False` | | `vector_filter_mode` | Vector filter mode to use | `preFilter` | `postFilter`, `preFilter` | | `hybrid_search` | Use hybrid search | `False` | `True`, `False` | ## Notes on Configuration Options * **compression\_type**: * `none`: No compression, uses full vector precision * `scalar`: Scalar quantization with reasonable balance of speed and accuracy * `binary`: Binary quantization for maximum compression with some accuracy trade-off * **vector\_filter\_mode**: * `preFilter`: Applies filters before vector search (faster) * `postFilter`: Applies filters after vector search (may provide better relevance) * **use\_float16**: Using half precision (float16) reduces storage requirements but may slightly impact accuracy. Useful for very large vector collections. * **Filterable Fields**: The implementation automatically extracts `user_id`, `run_id`, and `agent_id` fields from payloads for filtering. # Azure MySQL Source: https://docs.mem0.ai/components/vectordbs/dbs/azure-mysql Use Azure Database for MySQL as a vector store in Mem0 with JSON-based vector storage for semantic search. [Azure Database for MySQL](https://azure.microsoft.com/products/mysql) is a fully managed relational database service that provides enterprise-grade reliability and security. It supports JSON-based vector storage for semantic search capabilities in AI applications. ### Usage ```python theme={null} import os from mem0 import Memory os.environ["OPENAI_API_KEY"] = "sk-xx" config = { "vector_store": { "provider": "azure_mysql", "config": { "host": "your-server.mysql.database.azure.com", "port": 3306, "user": "your_username", "password": "your_password", "database": "mem0_db", "collection_name": "memories", } } } m = Memory.from_config(config) messages = [ {"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"}, {"role": "assistant", "content": "How about thriller movies? They can be quite engaging."}, {"role": "user", "content": "I'm not a big fan of thriller movies but I love sci-fi movies."}, {"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."} ] m.add(messages, user_id="alice", metadata={"category": "movies"}) ``` #### Using Azure Managed Identity For production deployments, use Azure Managed Identity instead of passwords: ```python theme={null} config = { "vector_store": { "provider": "azure_mysql", "config": { "host": "your-server.mysql.database.azure.com", "user": "your_username", "database": "mem0_db", "collection_name": "memories", "use_azure_credential": True, # Uses DefaultAzureCredential "ssl_disabled": False } } } ``` > [!NOTE] > > When `use_azure_credential` is enabled, the password is obtained via Azure DefaultAzureCredential (supports Managed Identity, Azure CLI, etc.) ### Config Here are the parameters available for configuring Azure MySQL: | Parameter | Description | Default Value | | - | - | - | | `host` | MySQL server hostname | Required | | `port` | MySQL server port | `3306` | | `user` | Database user | Required | | `password` | Database password (optional with Azure credential) | `None` | | `database` | Database name | Required | | `collection_name` | Table name for storing vectors | `"mem0"` | | `embedding_model_dims` | Dimensions of embedding vectors | `1536` | | `use_azure_credential` | Use Azure DefaultAzureCredential | `False` | | `ssl_ca` | Path to SSL CA certificate | `None` | | `ssl_disabled` | Disable SSL (not recommended) | `False` | | `minconn` | Minimum connections in pool | `1` | | `maxconn` | Maximum connections in pool | `5` | ### Setup #### Create MySQL Flexible Server using Azure CLI: ```bash theme={null} # Create resource group az group create --name mem0-rg --location eastus # Create MySQL Flexible Server az mysql flexible-server create \ --resource-group mem0-rg \ --name mem0-mysql-server \ --location eastus \ --admin-user myadmin \ --admin-password \ --version 8.0.21 # Create database az mysql flexible-server db create \ --resource-group mem0-rg \ --server-name mem0-mysql-server \ --database-name mem0_db # Configure firewall az mysql flexible-server firewall-rule create \ --resource-group mem0-rg \ --name mem0-mysql-server \ --rule-name AllowMyIP \ --start-ip-address \ --end-ip-address ``` #### Enable Azure AD Authentication: 1. In Azure Portal, navigate to your MySQL Flexible Server 2. Go to **Security** > **Authentication** and enable Azure AD 3. Add your application's managed identity as a MySQL user: ```sql theme={null} CREATE AADUSER 'your-app-identity' IDENTIFIED BY 'your-client-id'; GRANT ALL PRIVILEGES ON mem0_db.* TO 'your-app-identity'@'%'; FLUSH PRIVILEGES; ``` > [!TIP] > > For production, use [Managed Identity](https://learn.microsoft.com/azure/active-directory/managed-identities-azure-resources/) to eliminate password management. # Baidu VectorDB (Mochow) Source: https://docs.mem0.ai/components/vectordbs/dbs/baidu Use Baidu Mochow as an enterprise vector database in Mem0 for high-performance vector storage and retrieval. [Baidu VectorDB](https://cloud.baidu.com/doc/VDB/index.html) is an enterprise-level distributed vector database service developed by Baidu Intelligent Cloud. It is powered by Baidu's proprietary "Mochow" vector database kernel, providing high performance, availability, and security for vector search. ### Installation ```bash Python theme={null} pip install pymochow ``` ```bash TypeScript theme={null} npm install @mochow/mochow-sdk-node ``` ### Usage ```python theme={null} from mem0 import Memory config = { "vector_store": { "provider": "baidu", "config": { "endpoint": "http://your-mochow-endpoint:8287", "account": "root", "api_key": "your-api-key", "database_name": "mem0", "table_name": "mem0_table", "embedding_model_dims": 1536, "metric_type": "COSINE" } } } m = Memory.from_config(config) messages = [ {"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"}, {"role": "assistant", "content": "How about a thriller movie? They can be quite engaging."}, {"role": "user", "content": "I'm not a big fan of thriller movies but I love sci-fi movies."}, {"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."} ] m.add(messages, user_id="alice", metadata={"category": "movies"}) ``` ```typescript theme={null} import { Memory } from "mem0ai/oss"; const memory = new Memory({ embedder: { provider: "openai", config: { apiKey: process.env.OPENAI_API_KEY || "", model: "text-embedding-3-small", embeddingDims: 1536, }, }, vectorStore: { provider: "baidu", config: { endpoint: process.env.BAIDU_ENDPOINT || "", account: process.env.BAIDU_ACCOUNT || "root", apiKey: process.env.BAIDU_API_KEY || "", databaseName: "mem0", tableName: "mem0_table", embeddingModelDims: 1536, metricType: "COSINE", }, }, llm: { provider: "openai", config: { apiKey: process.env.OPENAI_API_KEY || "", model: "gpt-5-mini", }, }, }); ``` ### Config Here are the parameters available for configuring Baidu VectorDB: | Parameter | Description | Default Value | | - | - | - | | `endpoint` | Endpoint URL for your Baidu VectorDB instance | Required | | `account` | Baidu VectorDB account name | `root` | | `api_key` | API key for accessing Baidu VectorDB | Required | | `database_name` | Name of the database | `mem0` | | `table_name` | Name of the table | `mem0` | | `embedding_model_dims` | Dimensions of the embedding model | `1536` | | `metric_type` | Distance metric for similarity search | `L2` | | `client` | Prebuilt Mochow client (TypeScript SDK only) | `None` | For the TypeScript OSS SDK, use the camelCase equivalents: * `databaseName` * `tableName` * `embeddingModelDims` * `metricType` For OSS TS usage, `endpoint`, `account`, `apiKey`, `databaseName`, `tableName`, and `embeddingModelDims` are required unless you inject a prebuilt client. `metricType` defaults to `L2`, matching the Python SDK. ### Distance Metrics The following distance metrics are supported: * `L2`: Euclidean distance (default) * `IP`: Inner product * `COSINE`: Cosine similarity ### Index Configuration The vector index is automatically configured with the following HNSW parameters: * `m`: 16 (number of connections per element) * `efconstruction`: 200 (size of the dynamic candidate list) * `auto_build`: true (automatically build index) * `auto_build_index_policy`: Incremental build with 10000 rows increment The TypeScript provider also creates a BM25 inverted index over a `textLemmatized` column so `keywordSearch()` runs against a real full-text index. Mem0 lemmatizes the query before it reaches the vector store, so only the lemmatized form of each memory is indexed. If you point `tableName` at a table created before this index existed, `keywordSearch()` returns `null` and search falls back to vector similarity alone; recreate the table to enable it. # Apache Cassandra Source: https://docs.mem0.ai/components/vectordbs/dbs/cassandra Use Apache Cassandra as a distributed vector store in Mem0 with semantic search over large-scale datasets. [Apache Cassandra](https://cassandra.apache.org/) is a highly scalable, distributed NoSQL database designed for handling large amounts of data across many commodity servers with no single point of failure. It supports vector storage for semantic search capabilities in AI applications and can scale to massive datasets with linear performance improvements. ### Usage ```python Python theme={null} import os from mem0 import Memory os.environ["OPENAI_API_KEY"] = "sk-xx" config = { "vector_store": { "provider": "cassandra", "config": { "contact_points": ["127.0.0.1"], "port": 9042, "username": "cassandra", "password": "cassandra", "keyspace": "mem0", "collection_name": "memories", } } } m = Memory.from_config(config) messages = [ {"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"}, {"role": "assistant", "content": "How about thriller movies? They can be quite engaging."}, {"role": "user", "content": "I'm not a big fan of thriller movies but I love sci-fi movies."}, {"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."} ] m.add(messages, user_id="alice", metadata={"category": "movies"}) ``` ```typescript TypeScript theme={null} import { Memory } from 'mem0ai/oss'; // Set OPENAI_API_KEY in your environment for the default embedder const config = { vectorStore: { provider: 'cassandra', config: { contactPoints: ['127.0.0.1'], localDataCenter: 'datacenter1', // required with contactPoints; "datacenter1" is the default for a single-node cluster port: 9042, username: 'cassandra', password: 'cassandra', keyspace: 'mem0', collectionName: 'memories', }, }, }; const memory = new Memory(config); const messages = [ {"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"}, {"role": "assistant", "content": "How about thriller movies? They can be quite engaging."}, {"role": "user", "content": "I'm not a big fan of thriller movies but I love sci-fi movies."}, {"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."} ] await memory.add(messages, { userId: "alice", metadata: { category: "movies" } }); ``` #### Using DataStax Astra DB For managed Cassandra with DataStax Astra DB: ```python Python theme={null} config = { "vector_store": { "provider": "cassandra", "config": { "contact_points": ["dummy"], # Not used with secure connect bundle "username": "token", "password": "AstraCS:...", # Your Astra DB application token "keyspace": "mem0", "collection_name": "memories", "secure_connect_bundle": "/path/to/secure-connect-bundle.zip" } } } ``` ```typescript TypeScript theme={null} const config = { vectorStore: { provider: 'cassandra', config: { username: 'token', password: 'AstraCS:...', // Your Astra DB application token keyspace: 'mem0', collectionName: 'memories', secureConnectBundle: '/path/to/secure-connect-bundle.zip', }, }, }; ``` > [!NOTE] > > When using DataStax Astra DB, provide the secure connect bundle path. Contact points and `localDataCenter` are not needed when a secure connect bundle is provided. ### Config Here are the parameters available for configuring Apache Cassandra: | Parameter | Description | Default Value | | - | - | - | | `contact_points` | List of contact point IP addresses | Required | | `port` | Cassandra port | `9042` | | `username` | Database username | `None` | | `password` | Database password | `None` | | `keyspace` | Keyspace name | `"mem0"` | | `collection_name` | Table name for storing vectors | `"memories"` | | `embedding_model_dims` | Dimensions of embedding vectors | `1536` | | `secure_connect_bundle` | Path to Astra DB secure connect bundle | `None` | | `protocol_version` | CQL protocol version | `4` | | `load_balancing_policy` | Custom load balancing policy | `None` | > [!NOTE] > > The TypeScript SDK uses camelCase keys: `contactPoints`, `collectionName`, `embeddingModelDims`, `secureConnectBundle`, `protocolVersion`, and `loadBalancingPolicy`. It also requires `localDataCenter` (for example, `datacenter1`) when you connect with `contactPoints` instead of a secure connect bundle. The Node.js driver needs this to route queries; it has no default. ### Setup #### Option 1: Local Cassandra Setup using Docker: ```bash theme={null} # Pull and run Cassandra container docker run --name mem0-cassandra \ -p 9042:9042 \ -e CASSANDRA_CLUSTER_NAME="Mem0Cluster" \ -d cassandra:latest # Wait for Cassandra to start (may take 1-2 minutes) docker exec -it mem0-cassandra cqlsh # Create keyspace CREATE KEYSPACE IF NOT EXISTS mem0 WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1}; ``` #### Option 2: DataStax Astra DB (Managed Cloud): 1. Sign up at [DataStax Astra](https://astra.datastax.com/) 2. Create a new database 3. Download the secure connect bundle 4. Generate an application token > [!TIP] > > For production deployments, use DataStax Astra DB for fully managed Cassandra with automatic scaling, backups, and security. #### Option 3: Install Cassandra Locally: **Ubuntu/Debian:** ```bash theme={null} # Add Apache Cassandra repository echo "deb https://downloads.apache.org/cassandra/debian 40x main" | sudo tee -a /etc/apt/sources.list.d/cassandra.sources.list curl https://downloads.apache.org/cassandra/KEYS | sudo apt-key add - # Install Cassandra sudo apt-get update sudo apt-get install cassandra # Start Cassandra sudo systemctl start cassandra # Verify installation nodetool status ``` **macOS:** ```bash theme={null} # Using Homebrew brew install cassandra # Start Cassandra brew services start cassandra # Connect to CQL shell cqlsh ``` ### Client Installation Install the driver for your SDK: ```bash Python theme={null} pip install cassandra-driver ``` ```bash TypeScript theme={null} npm install cassandra-driver ``` ### Performance Considerations * **Replication Factor**: For production, use replication factor of at least 3 * **Consistency Level**: Balance between consistency and performance (QUORUM recommended) * **Partitioning**: Cassandra automatically distributes data across nodes * **Scaling**: Add nodes to linearly increase capacity and performance ### Advanced Configuration ```python Python theme={null} from cassandra.policies import DCAwareRoundRobinPolicy config = { "vector_store": { "provider": "cassandra", "config": { "contact_points": ["node1.example.com", "node2.example.com", "node3.example.com"], "port": 9042, "username": "mem0_user", "password": "secure_password", "keyspace": "mem0_prod", "collection_name": "memories", "protocol_version": 4, "load_balancing_policy": DCAwareRoundRobinPolicy(local_dc='DC1') } } } ``` ```typescript TypeScript theme={null} // The Node.js driver routes to localDataCenter by default, so set it to your // primary DC for datacenter-aware routing. Pass loadBalancingPolicy only when // you need a custom policy from the cassandra-driver package. const config = { vectorStore: { provider: 'cassandra', config: { contactPoints: ['node1.example.com', 'node2.example.com', 'node3.example.com'], localDataCenter: 'DC1', port: 9042, username: 'mem0_user', password: 'secure_password', keyspace: 'mem0_prod', collectionName: 'memories', protocolVersion: 4, }, }, }; ``` > [!WARNING] > > For production use, configure appropriate replication strategies and consistency levels based on your availability and consistency requirements. # Chroma Source: https://docs.mem0.ai/components/vectordbs/dbs/chroma Use Chroma as a vector database in Mem0 for local or cloud-hosted vector storage with built-in embedding support. [Chroma](https://www.trychroma.com/) is an AI-native open-source vector database that simplifies building LLM apps by providing tools for storing, embedding, and searching embeddings with a focus on simplicity and speed. It supports both local deployment and cloud hosting through ChromaDB Cloud. ### Usage ```python Python theme={null} import os from mem0 import Memory os.environ["OPENAI_API_KEY"] = "sk-xx" config = { "vector_store": { "provider": "chroma", "config": { "collection_name": "test", "path": "db", # Optional: ChromaDB Cloud configuration # "api_key": "your-chroma-cloud-api-key", # "tenant": "your-chroma-cloud-tenant-id", } } } m = Memory.from_config(config) messages = [ {"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"}, {"role": "assistant", "content": "How about thriller movies? They can be quite engaging."}, {"role": "user", "content": "I’m not a big fan of thriller movies but I love sci-fi movies."}, {"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."} ] m.add(messages, user_id="alice", metadata={"category": "movies"}) ``` ```typescript TypeScript theme={null} import { Memory } from 'mem0ai/oss'; // The Node.js client connects to a running Chroma server. // Start one locally with: chroma run --host localhost --port 8000 const config = { vectorStore: { provider: 'chroma', config: { collectionName: 'memories', host: 'localhost', port: 8000, // Optional: ChromaDB Cloud configuration // apiKey: 'your-chroma-cloud-api-key', // tenant: 'your-chroma-cloud-tenant-id', }, }, }; const memory = new Memory(config); const messages = [ {"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"}, {"role": "assistant", "content": "How about thriller movies? They can be quite engaging."}, {"role": "user", "content": "I’m not a big fan of thriller movies but I love sci-fi movies."}, {"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."} ] await memory.add(messages, { userId: "alice", metadata: { category: "movies" } }); ``` > [!NOTE] > > The Node.js SDK uses the `chromadb` v3 client, which talks to a Chroma server over HTTP (local server or ChromaDB Cloud). Install it with `npm install chromadb`. Mem0 supplies the embeddings, so the collection is created without an embedding function. ### Config Here are the parameters available for configuring Chroma: **Python** | Parameter | Description | Default Value | | - | - | - | | `collection_name` | The name of the collection | `mem0` | | `client` | Custom client for Chroma | `None` | | `path` | Path for the Chroma database | `db` | | `host` | The host where the Chroma server is running | `None` | | `port` | The port where the Chroma server is running | `None` | | `api_key` | ChromaDB Cloud API key (for cloud usage) | `None` | | `tenant` | ChromaDB Cloud tenant ID (for cloud usage) | `None` | **TypeScript** | Parameter | Description | Default Value | | - | - | - | | `collectionName` | The name of the collection | `mem0` | | `client` | Pre-configured `ChromaClient` or `CloudClient` instance | `None` | | `host` | The host where the Chroma server is running | `None` | | `port` | The port where the Chroma server is running | `None` | | `ssl` | Whether to use SSL when connecting to the Chroma server | `false` | | `path` | Full URL of a Chroma server, e.g. `http://localhost:8000` (alternative to `host` and `port`) | `None` | | `apiKey` | ChromaDB Cloud API key (for cloud usage) | `None` | | `tenant` | ChromaDB Cloud tenant ID (for cloud usage) | `None` | | `database` | ChromaDB Cloud database name (for cloud usage) | `mem0` | # Databricks Source: https://docs.mem0.ai/components/vectordbs/dbs/databricks Use Databricks Vector Search as a serverless vector store in Mem0 with auto-updating indexes from Delta tables. [Databricks Vector Search](https://docs.databricks.com/en/generative-ai/vector-search.html) is a serverless similarity search engine that allows you to store a vector representation of your data, including metadata, in a vector database. With Vector Search, you can create auto-updating vector search indexes from Delta tables managed by Unity Catalog and query them with a simple API to return the most similar vectors. ### Usage ```python Python theme={null} import os from mem0 import Memory config = { "vector_store": { "provider": "databricks", "config": { "workspace_url": "https://your-workspace.databricks.com", "access_token": "your-access-token", "endpoint_name": "your-vector-search-endpoint", "catalog": "your_catalog", "schema": "your_schema", "table_name": "your_table", "collection_name": "your_index_name", "embedding_dimension": 1536 } } } m = Memory.from_config(config) messages = [ {"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"}, {"role": "assistant", "content": "How about thriller movies? They can be quite engaging."}, {"role": "user", "content": "I'm not a big fan of thriller movies but I love sci-fi movies."}, {"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."} ] m.add(messages, user_id="alice", metadata={"category": "movies"}) ``` ```typescript TypeScript theme={null} // Requires the Databricks SQL driver (peer dependency): pnpm add @databricks/sql import { Memory } from 'mem0ai/oss'; const config = { vectorStore: { provider: 'databricks', config: { workspaceUrl: 'https://your-workspace.databricks.com', // SQL warehouse HTTP path, used for index writes (required) httpPath: '/sql/1.0/warehouses/your-warehouse-id', accessToken: 'your-access-token', catalog: 'your_catalog', schema: 'your_schema', tableName: 'your_table', collectionName: 'your_index_name', embeddingModelDims: 1536, }, }, }; const memory = new Memory(config); const messages = [ {"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"}, {"role": "assistant", "content": "How about thriller movies? They can be quite engaging."}, {"role": "user", "content": "I'm not a big fan of thriller movies but I love sci-fi movies."}, {"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."} ] await memory.add(messages, { userId: "alice", metadata: { category: "movies" } }); ``` ### Config Here are the parameters available for configuring Databricks Vector Search: **Python** | Parameter | Description | Default Value | | - | - | - | | `workspace_url` | The URL of your Databricks workspace | **Required** | | `access_token` | Personal Access Token for authentication | `None` | | `client_id` | Service principal client ID (alternative to access\_token) | `None` | | `client_secret` | Service principal client secret (required with client\_id) | `None` | | `azure_client_id` | Azure AD application client ID (for Azure Databricks) | `None` | | `azure_client_secret` | Azure AD application client secret (for Azure Databricks) | `None` | | `endpoint_name` | Name of the Vector Search endpoint | **Required** | | `catalog` | Unity Catalog catalog name | **Required** | | `schema` | Unity Catalog schema name | **Required** | | `table_name` | Source Delta table name | **Required** | | `collection_name` | Vector search index name | `mem0` | | `index_type` | Index type: `DELTA_SYNC` or `DIRECT_ACCESS` | `DELTA_SYNC` | | `embedding_model_endpoint_name` | Databricks serving endpoint for embeddings | `None` | | `embedding_dimension` | Dimension of self-managed embeddings | `1536` | | `endpoint_type` | Type of endpoint (`STANDARD` or `STORAGE_OPTIMIZED`) | `STANDARD` | | `pipeline_type` | Sync pipeline type: `TRIGGERED` or `CONTINUOUS` | `TRIGGERED` | | `warehouse_name` | Databricks SQL warehouse name (if using SQL warehouse) | `None` | | `query_type` | Query type: `ANN` or `HYBRID` | `ANN` | **TypeScript** | Parameter | Description | Default Value | | - | - | - | | `workspaceUrl` | The URL of your Databricks workspace (or pass `host`) | **Required** | | `httpPath` | SQL warehouse HTTP path, used for index writes | **Required** | | `accessToken` | Personal Access Token for authentication | `None` | | `clientId` | Service principal client ID (alternative to `accessToken`) | `None` | | `clientSecret` | Service principal client secret (required with `clientId`) | `None` | | `endpointName` | Name of the Vector Search endpoint | `mem0_vector_search` | | `endpointType` | Type of endpoint (`STANDARD` or `STORAGE_OPTIMIZED`) | `STANDARD` | | `pipelineType` | Delta Sync pipeline type: `TRIGGERED` or `CONTINUOUS` | `TRIGGERED` | | `queryType` | Query type: `ANN` or `HYBRID` | `ANN` | | `catalog` | Unity Catalog catalog name | `main` | | `schema` | Unity Catalog schema name | `default` | | `collectionName` | Vector Search index name | `mem0` | | `tableName` | Source Delta table name | falls back to `collectionName` | | `embeddingModelDims` | Dimension of self-managed embeddings | `1536` | | `syncPollIntervalMs` | Poll interval while waiting for a `TRIGGERED` sync | `1000` | | `syncTimeoutMs` | Timeout while waiting for an index sync | `300000` | > [!NOTE] > > The TypeScript provider uses `DELTA_SYNC` indexes with self-managed embeddings: pass vectors directly. `DIRECT_ACCESS` indexes, Databricks-computed embeddings (`embedding_model_endpoint_name`), and Azure AD auth are Python-only today. It writes to the index through a SQL warehouse, so `httpPath` is required, and `@databricks/sql` must be installed as a peer dependency. ### Authentication Databricks Vector Search supports two authentication methods: #### Service Principal (Recommended for Production) ```python theme={null} config = { "vector_store": { "provider": "databricks", "config": { "workspace_url": "https://your-workspace.databricks.com", "client_id": "your-service-principal-id", "client_secret": "your-service-principal-secret", "endpoint_name": "your-endpoint", "catalog": "your_catalog", "schema": "your_schema", "table_name": "your_table", "collection_name": "your_index_name", } } } ``` #### Personal Access Token (for Development) ```python theme={null} config = { "vector_store": { "provider": "databricks", "config": { "workspace_url": "https://your-workspace.databricks.com", "access_token": "your-personal-access-token", "endpoint_name": "your-endpoint", "catalog": "your_catalog", "schema": "your_schema", "table_name": "your_table", "collection_name": "your_index_name", } } } ``` ### Embedding Options #### Self-Managed Embeddings (Default) Use your own embedding model and provide vectors directly: ```python theme={null} config = { "vector_store": { "provider": "databricks", "config": { # ... authentication config ... "embedding_dimension": 768, # Match your embedding model } } } ``` #### Databricks-Computed Embeddings Let Databricks compute embeddings from text using a serving endpoint: ```python theme={null} config = { "vector_store": { "provider": "databricks", "config": { # ... authentication config ... "embedding_model_endpoint_name": "e5-small-v2" } } } ``` ### Important Notes * **Index Types**: This implementation supports both `DELTA_SYNC` (auto-syncs with source Delta table) and `DIRECT_ACCESS` (manage vectors directly) index types. * **Unity Catalog**: The source table and index are created under the specified `catalog.schema` namespace. * **Endpoint Auto-Creation**: If the specified endpoint doesn't exist, it will be created automatically. * **Index Auto-Creation**: If the specified index doesn't exist, it will be created automatically with the provided configuration. * **Filter Support**: Supports filtering by metadata fields, with different syntax for STANDARD vs STORAGE\_OPTIMIZED endpoints. # Elasticsearch Source: https://docs.mem0.ai/components/vectordbs/dbs/elasticsearch Use Elasticsearch as a vector database in Mem0 for distributed vector search using dense vectors and k-NN queries. [Elasticsearch](https://www.elastic.co/) is a distributed, RESTful search and analytics engine that can efficiently store and search vector data using dense vectors and k-NN search. ### Installation Elasticsearch support requires the Elasticsearch client as an extra dependency. ```bash Python theme={null} pip install elasticsearch>=8.0.0 ``` ```bash TypeScript theme={null} npm install mem0ai @elastic/elasticsearch ``` ### Usage ```python Python theme={null} import os from mem0 import Memory os.environ["OPENAI_API_KEY"] = "sk-xx" config = { "vector_store": { "provider": "elasticsearch", "config": { "collection_name": "mem0", "host": "localhost", "port": 9200, "embedding_model_dims": 1536 } } } m = Memory.from_config(config) messages = [ {"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"}, {"role": "assistant", "content": "How about thriller movies? They can be quite engaging."}, {"role": "user", "content": "I'm not a big fan of thriller movies but I love sci-fi movies."}, {"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."} ] m.add(messages, user_id="alice", metadata={"category": "movies"}) ``` ```typescript TypeScript theme={null} import { Memory } from "mem0ai/oss"; // Set OPENAI_API_KEY in your environment. const config = { embedder: { provider: "openai", config: { apiKey: process.env.OPENAI_API_KEY, model: "text-embedding-3-small", }, }, vectorStore: { provider: "elasticsearch", config: { collectionName: "mem0", embeddingModelDims: 1536, host: "localhost", port: 9200, // For Elastic Cloud, pass cloudId and apiKey instead of host/port. // For basic auth, pass username and password. }, }, }; const memory = new Memory(config); const messages = [ { role: "user", content: "I'm planning to watch a movie tonight. Any recommendations?" }, { role: "assistant", content: "How about thriller movies? They can be quite engaging." }, { role: "user", content: "I'm not a big fan of thriller movies but I love sci-fi movies." }, { role: "assistant", content: "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future." }, ]; await memory.add(messages, { userId: "alice", metadata: { category: "movies" } }); ``` > [!NOTE] > > The TypeScript SDK uses camelCase config keys: `collectionName`, `embeddingModelDims`, `cloudId`, `apiKey`, `useSsl`, `verifyCerts`, `caCerts`, `autoCreateIndex`, and `username` (in place of the Python `user`). `collectionName` and `embeddingModelDims` are required. Because the vector store embeds text with your configured embedder before writing, set an `embedder` in the config as shown above. ### Config Here are the parameters available for configuring Elasticsearch: | Parameter | Description | Default Value | | - | - | - | | `collection_name` | The name of the index to store the vectors | `mem0` | | `embedding_model_dims` | Dimensions of the embedding model | `1536` | | `host` | The host where the Elasticsearch server is running | `localhost` | | `port` | The port where the Elasticsearch server is running | `9200` | | `cloud_id` | Cloud ID for Elastic Cloud deployment | `None` | | `api_key` | API key for authentication | `None` | | `user` | Username for basic authentication | `None` | | `password` | Password for basic authentication | `None` | | `use_ssl` | Whether to use SSL for the connection | `True` | | `ca_certs` | Path to CA bundle for SSL certificate verification | `None` | | `verify_certs` | Whether to verify SSL certificates | `True` | | `auto_create_index` | Whether to automatically create the index | `True` | | `custom_search_query` | Function returning a custom search query | `None` | | `headers` | Custom headers to include in requests | `None` | ### Features * Efficient vector search using Elasticsearch's native k-NN search * Support for both local and cloud deployments (Elastic Cloud) * Multiple authentication methods (Basic Auth, API Key) * Automatic index creation with optimized mappings for vector search * Memory isolation through payload filtering * Custom search query function to customize the search query ### Custom Search Query > [!NOTE] > > `custom_search_query` is available in the Python SDK only. The TypeScript SDK runs a fixed k-NN query with optional metadata filters. The `custom_search_query` parameter allows you to customize the search query when `Memory.search` is called. **Example** ```python theme={null} import os from typing import List, Optional, Dict from mem0 import Memory def custom_search_query(query: List[float], limit: int, filters: Optional[Dict]) -> Dict: return { "knn": { "field": "vector", "query_vector": query, "k": limit, "num_candidates": limit * 2 } } os.environ["OPENAI_API_KEY"] = "sk-xx" config = { "vector_store": { "provider": "elasticsearch", "config": { "collection_name": "mem0", "host": "localhost", "port": 9200, "embedding_model_dims": 1536, "custom_search_query": custom_search_query } } } ``` It should be a function that takes the following parameters: * `query`: a query vector used in `Memory.search` * `limit`: a number of results used in `Memory.search` * `filters`: a dictionary of key-value pairs used in `Memory.search`. You can add custom pairs for the custom search query. The function should return a query body for the Elasticsearch search API. # FAISS Source: https://docs.mem0.ai/components/vectordbs/dbs/faiss Use Facebook FAISS as a high-performance vector store in Mem0, optimized for memory usage and fast similarity search. [FAISS](https://github.com/facebookresearch/faiss) is a library for efficient similarity search and clustering of dense vectors. It is designed to work with large-scale datasets and provides a high-performance search engine for vector data. FAISS is optimized for memory usage and search speed, making it an excellent choice for production environments. ### Usage ```python theme={null} import os from mem0 import Memory os.environ["OPENAI_API_KEY"] = "sk-xx" config = { "vector_store": { "provider": "faiss", "config": { "collection_name": "test", "path": "/tmp/faiss_memories", "distance_strategy": "euclidean" } } } m = Memory.from_config(config) messages = [ {"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"}, {"role": "assistant", "content": "How about thriller movies? They can be quite engaging."}, {"role": "user", "content": "I'm not a big fan of thriller movies but I love sci-fi movies."}, {"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."} ] m.add(messages, user_id="alice", metadata={"category": "movies"}) ``` ### Installation To use FAISS in your mem0 project, you need to install the appropriate FAISS package for your environment: ```bash theme={null} # For CPU version pip install faiss-cpu # For GPU version (requires CUDA) pip install faiss-gpu ``` ### Config Here are the parameters available for configuring FAISS: | Parameter | Description | Default Value | | - | - | - | | `collection_name` | The name of the collection | `mem0` | | `path` | Path to store FAISS index and metadata | `/tmp/faiss/` | | `distance_strategy` | Distance metric strategy to use (options: 'euclidean', 'inner\_product', 'cosine') | `euclidean` | | `normalize_L2` | Whether to normalize L2 vectors (only applicable for euclidean distance) | `False` | | `embedding_model_dims` | Dimensions of the embedding model | `1536` | ### Performance Considerations FAISS offers several advantages for vector search: 1. **Efficiency**: FAISS is optimized for memory usage and speed, making it suitable for large-scale applications. 2. **Offline Support**: FAISS works entirely locally, with no need for external servers or API calls. 3. **Storage Options**: Vectors can be stored in-memory for maximum speed or persisted to disk. 4. **Multiple Index Types**: FAISS supports different index types optimized for various use cases (though mem0 currently uses the basic flat index). ### Distance Strategies FAISS in mem0 supports three distance strategies: * **euclidean**: L2 distance, suitable for most embedding models * **inner\_product**: Dot product similarity, useful for some specialized embeddings * **cosine**: Cosine similarity, best for comparing semantic similarity regardless of vector magnitude When using `cosine` or `inner_product` with normalized vectors, you may want to set `normalize_L2=True` for better results. # LangChain as Vector Store Provider Source: https://docs.mem0.ai/components/vectordbs/dbs/langchain Use LangChain as a unified vector store provider in Mem0 to access multiple vector databases through one interface. Mem0 supports LangChain as a provider for vector store integration. LangChain provides a unified interface to various vector databases, making it easy to integrate different vector store providers through a consistent API. > [!NOTE] > > When using LangChain as your vector store provider, you must set the collection name to "mem0". This is a required configuration for proper integration with Mem0. ## Usage ```python Python theme={null} import os from mem0 import Memory from langchain_chroma import Chroma from langchain_openai import OpenAIEmbeddings # Initialize a LangChain vector store embeddings = OpenAIEmbeddings() vector_store = Chroma( persist_directory="./chroma_db", embedding_function=embeddings, collection_name="mem0" # Required collection name ) # Pass the initialized vector store to the config config = { "vector_store": { "provider": "langchain", "config": { "client": vector_store } } } m = Memory.from_config(config) messages = [ {"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"}, {"role": "assistant", "content": "How about thriller movies? They can be quite engaging."}, {"role": "user", "content": "I'm not a big fan of thriller movies but I love sci-fi movies."}, {"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."} ] m.add(messages, user_id="alice", metadata={"category": "movies"}) ``` ```typescript TypeScript theme={null} import { Memory } from "mem0ai/oss"; import { OpenAIEmbeddings } from "@langchain/openai"; import { MemoryVectorStore } from "langchain/vectorstores/memory"; const embeddings = new OpenAIEmbeddings(); const vectorStore = new MemoryVectorStore(embeddings); const config = { "vector_store": { "provider": "langchain", "config": { "client": vectorStore } } } const memory = new Memory(config); const messages = [ { role: "user", content: "I'm planning to watch a movie tonight. Any recommendations?" }, { role: "assistant", content: "How about thriller movies? They can be quite engaging." }, { role: "user", content: "I'm not a big fan of thriller movies but I love sci-fi movies." }, { role: "assistant", content: "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future." } ] await memory.add(messages, { userId: "alice", metadata: { category: "movies" } }); ``` ## Supported LangChain Vector Stores LangChain supports a wide range of vector store providers, including: * Chroma * FAISS * Pinecone * Weaviate * Milvus * Qdrant * And many more You can use any of these vector store instances directly in your configuration. For a complete and up-to-date list of available providers, refer to the [LangChain Vector Stores documentation](https://python.langchain.com/docs/integrations/vectorstores). ## Limitations When using LangChain as a vector store provider, there are some limitations to be aware of: 1. **Bulk Operations**: The `get_all` and `delete_all` operations are not supported when using LangChain as the vector store provider. This is because LangChain's vector store interface doesn't provide standardized methods for these bulk operations across all providers. 2. **Provider-Specific Features**: Some advanced features may not be available depending on the specific vector store implementation you're using through LangChain. ## Provider-Specific Configuration When using LangChain as a vector store provider, you'll need to: 1. Set the appropriate environment variables for your chosen vector store provider 2. Import and initialize the specific vector store class you want to use 3. Pass the initialized vector store instance to the config > [!NOTE] > > Make sure to install the necessary LangChain packages and any provider-specific dependencies. ## Config All available parameters for the `langchain` vector store config are present in [Master List of All Params in Config](../config). # Milvus Source: https://docs.mem0.ai/components/vectordbs/dbs/milvus Use Milvus as an open-source vector database in Mem0, scalable from local development to production workloads. [Milvus](https://milvus.io/) is an open-source vector database that suits AI applications of every size, from running a demo chatbot in a Jupyter notebook to building web-scale search that serves billions of users. ### Usage The TypeScript SDK loads the Milvus client lazily. Install it alongside `mem0ai` when you use this provider: ```bash theme={null} npm install @zilliz/milvus2-sdk-node ``` ```python Python theme={null} import os from mem0 import Memory config = { "vector_store": { "provider": "milvus", "config": { "collection_name": "test", "embedding_model_dims": 1536, "url": "127.0.0.1", "token": "8e4b8ca8cf2c67", "db_name": "my_database", } } } m = Memory.from_config(config) messages = [ {"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"}, {"role": "assistant", "content": "How about thriller movies? They can be quite engaging."}, {"role": "user", "content": "I’m not a big fan of thriller movies but I love sci-fi movies."}, {"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."} ] m.add(messages, user_id="alice", metadata={"category": "movies"}) ``` ```typescript TypeScript theme={null} import { Memory } from 'mem0ai/oss'; const config = { vectorStore: { provider: 'milvus', config: { collectionName: 'test', embeddingModelDims: 1536, url: 'http://localhost:19530', token: '8e4b8ca8cf2c67', dbName: 'my_database', }, }, }; const memory = new Memory(config); const messages = [ { role: "user", content: "I'm planning to watch a movie tonight. Any recommendations?" }, { role: "assistant", content: "How about thriller movies? They can be quite engaging." }, { role: "user", content: "I'm not a big fan of thriller movies but I love sci-fi movies." }, { role: "assistant", content: "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future." }, ]; await memory.add(messages, { userId: "alice", metadata: { category: "movies" } }); ``` ### Config Here are the parameters available for configuring Milvus: **Python** | Parameter | Description | Default Value | | - | - | - | | `url` | Full URL/Uri for Milvus/Zilliz server | `http://localhost:19530` | | `token` | Token for Zilliz server / for local setup defaults to None. | `None` | | `collection_name` | The name of the collection | `mem0` | | `embedding_model_dims` | Dimensions of the embedding model | `1536` | | `metric_type` | Metric type for similarity search | `L2` | | `db_name` | Name of the database | `""` | **TypeScript** | Parameter | Description | Default Value | | - | - | - | | `url` | Full URL/Uri for Milvus/Zilliz server | `http://localhost:19530` | | `token` | Token for Zilliz Cloud (optional for a local setup) | `undefined` | | `collectionName` | The name of the collection | `mem0` | | `embeddingModelDims` | Dimensions of the embedding model | `1536` | | `metricType` | Metric type for similarity search (`L2`, `IP`, `COSINE`, `HAMMING`, `JACCARD`) | `L2` | | `dbName` | Name of the database | `undefined` | # MongoDB Source: https://docs.mem0.ai/components/vectordbs/dbs/mongodb Use MongoDB as a vector database in Mem0 with built-in vector search for high-dimensional similarity queries. # MongoDB [MongoDB](https://www.mongodb.com/) is a versatile document database that supports vector search capabilities, allowing for efficient high-dimensional similarity searches over large datasets with robust scalability and performance. ## Usage ```python Python theme={null} import os from mem0 import Memory os.environ["OPENAI_API_KEY"] = "sk-xx" config = { "vector_store": { "provider": "mongodb", "config": { "db_name": "mem0-db", "collection_name": "mem0-collection", "mongo_uri": "mongodb://username:password@localhost:27017" } } } m = Memory.from_config(config) messages = [ { "role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?", }, { "role": "assistant", "content": "How about thriller movies? They can be quite engaging.", }, { "role": "user", "content": "I’m not a big fan of thriller movies but I love sci-fi movies.", }, { "role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future.", }, ] m.add(messages, user_id="alice", metadata={"category": "movies"}) ``` ```typescript TypeScript theme={null} import { Memory } from "mem0ai/oss"; const config = { vectorStore: { provider: "mongodb", config: { dbName: "mem0-db", collectionName: "mem0-collection", url: "mongodb://username:password@localhost:27017", }, }, }; const memory = new Memory(config); const messages = [ { role: "user", content: "I'm planning to watch a movie tonight. Any recommendations?", }, { role: "assistant", content: "How about thriller movies? They can be quite engaging.", }, { role: "user", content: "I’m not a big fan of thriller movies but I love sci-fi movies.", }, { role: "assistant", content: "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future.", }, ]; await memory.add(messages, { userId: "alice", metadata: { category: "movies", }, }); ``` ## Config Here are the parameters available for configuring MongoDB: | Python | TypeScript | Description | Default Value | | - | - | - | - | | db\_name | dbName | Name of the MongoDB database | "mem0\_db" | | collection\_name | collectionName | Name of the MongoDB collection | "mem0" | | embedding\_model\_dims | embeddingModelDims | Dimensions of the embedding vectors | 1536 | | mongo\_uri | url | The MongoDB URI connection string | mongodb://localhost:27017 | > **Note**: If `mongo_uri` (Python) or `url` (TypeScript) is not provided, it defaults to `mongodb://localhost:27017`. A local instance must be running MongoDB v8.2+ for vector search to work. > **Note**: The vector search index builds asynchronously after the first write. A search issued right after the first `add()` may return no results (and log an "index not initialized" message) until the index finishes building. This takes a few seconds on a local deployment and up to about a minute on Atlas. This is expected; the search returns results once the index is ready. # Neon Source: https://docs.mem0.ai/components/vectordbs/dbs/neon Use Neon as a vector store in Mem0, powered by PostgreSQL and pgvector. Use [Neon](https://neon.com/) as a vector store in Mem0, powered by PostgreSQL and the [pgvector extension](https://neon.com/docs/extensions/pgvector). Neon is a serverless Postgres platform. Since Mem0 supports Postgres through the `pgvector` provider, Neon can be used with a standard Postgres connection string. ## Usage ```python Python theme={null} import os from dotenv import load_dotenv from mem0 import Memory load_dotenv() config = { "vector_store": { "provider": "pgvector", "config": { "connection_string": os.environ["DATABASE_URL"], "collection_name": "memories", "embedding_model_dims": 1536, "hnsw": True, }, }, } m = Memory.from_config(config) messages = [ {"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"}, {"role": "assistant", "content": "How about thriller movies? They can be quite engaging."}, {"role": "user", "content": "I'm not a big fan of thriller movies but I love sci-fi movies."}, {"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."}, ] m.add(messages, user_id="alice", metadata={"category": "movies"}) results = m.search( "What movies should I recommend?", filters={"user_id": "alice"}, ) print(results) ``` ```typescript TypeScript theme={null} import "dotenv/config"; import { Memory } from "mem0ai/oss"; const m = new Memory({ vectorStore: { provider: "pgvector", config: { connectionString: process.env.DATABASE_URL!, ssl: { rejectUnauthorized: false, }, collectionName: "memories", dimension: 1536, embeddingModelDims: 1536, hnsw: true, }, }, }); const messages = [ { role: "user" as const, content: "I'm planning to watch a movie tonight. Any recommendations?" }, { role: "assistant" as const, content: "How about thriller movies? They can be quite engaging." }, { role: "user" as const, content: "I'm not a big fan of thriller movies but I love sci-fi movies." }, { role: "assistant" as const, content: "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future." }, ]; await m.add(messages, { userId: "alice", metadata: { category: "movies" }, }); const results = await m.search("What movies should I recommend?", { filters: { user_id: "alice" }, }); console.log(results); ``` ## SQL Migration You don't need to run any SQL migrations. Mem0 creates the collection table when it initializes the `pgvector` store. ## Environment ```env theme={null} OPENAI_API_KEY=sk-xx... DATABASE_URL=postgresql://user:password@ep-example.us-east-2.aws.neon.tech/neondb?sslmode=require ``` ## Config **Python** | Parameter | Description | Default Value | | - | - | - | | `connection_string` | Neon Postgres connection string. | Required | | `collection_name` | Name for the vector collection. | `mem0` | | `embedding_model_dims` | Embedding model dimensions. | `1536` | | `hnsw` | Enables HNSW indexing. | `False` | | `sslmode` | PostgreSQL SSL mode. Use `require` for Neon. | Driver default | **TypeScript** Use the Neon `DATABASE_URL` directly with `connectionString`. Set `ssl` if your runtime needs an explicit TLS config object. | Parameter | Description | Default | | - | - | - | | `connectionString` | Neon Postgres connection string. | Required | | `ssl` | Optional TLS settings passed directly to `pg`. | Driver default | | `collectionName` | Name for the vector collection. | `memories` | | `dimension` | Vector dimension for Mem0 config. | Auto-detected | | `embeddingModelDims` | Embedding model dimensions for table creation. | Required | | `hnsw` | Enables HNSW indexing. | `false` | **TLS note:** `ssl: true` is sufficient for most Neon connections since Neon uses valid certificates. Use `ssl: { rejectUnauthorized: false }` only when connecting through Neon's connection pooler on certain edge runtimes (e.g. Cloudflare Workers) that require it, or when your environment does not trust the Neon CA chain. ### Indexing The `pgvector` provider can create an HNSW index for faster vector search. * Set `hnsw` to `true` to enable a Hierarchical Navigable Small World index. * Leave `hnsw` as `false` if you want to create or manage indexes yourself. ### Similarity Search The `pgvector` provider uses cosine similarity for vector search. Make sure your embedding dimensions match the configured `embedding_model_dims` value. ### Best Practices 1. **Index Selection**: * Use `hnsw` for faster search performance when memory usage is not a constraint * Manage indexes manually if you need a different pgvector index strategy 2. **Connection String**: * Always use environment variables or even better, a secret manager for sensitive information in the connection string * Format: `postgresql://user:password@host:port/database` # Neptune Analytics Source: https://docs.mem0.ai/components/vectordbs/dbs/neptune-analytics Use AWS Neptune Analytics as a vector store in Mem0, combining graph analytics with vector search capabilities. [Neptune Analytics](https://docs.aws.amazon.com/neptune-analytics/latest/userguide/what-is-neptune-analytics.html) is a memory-optimized graph database engine for analytics. With Neptune Analytics, you can get insights and find trends by processing large amounts of graph data in seconds, including vector search. ### Installation The Neptune Analytics provider needs the AWS Neptune Graph client. Install it alongside `mem0ai`: ```bash Python theme={null} pip install mem0ai[vector-stores] ``` ```bash TypeScript theme={null} npm install @aws-sdk/client-neptune-graph ``` ### Usage Configure AWS credentials in your environment (environment variables, shared config file, an IAM role, or an instance profile). Both SDKs pick them up automatically through the standard AWS credential chain. ```python Python theme={null} from mem0 import Memory config = { "vector_store": { "provider": "neptune", "config": { "collection_name": "mem0", "endpoint": "neptune-graph://g-abc123xyz0", }, }, } m = Memory.from_config(config) messages = [ {"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"}, {"role": "assistant", "content": "How about a thriller movie? They can be quite engaging."}, {"role": "user", "content": "I'm not a big fan of thriller movies but I love sci-fi movies."}, {"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."} ] m.add(messages, user_id="alice", metadata={"category": "movies"}) ``` ```typescript TypeScript theme={null} import { Memory } from 'mem0ai/oss'; const config = { vectorStore: { provider: 'neptune', config: { collectionName: 'mem0', graphIdentifier: 'g-abc123xyz0', // Any other key here (region, credentials, maxAttempts, ...) is // forwarded to the underlying NeptuneGraphClient constructor. region: 'us-east-1', }, }, }; const memory = new Memory(config); const messages = [ { role: "user", content: "I'm planning to watch a movie tonight. Any recommendations?" }, { role: "assistant", content: "How about a thriller movie? They can be quite engaging." }, { role: "user", content: "I'm not a big fan of thriller movies but I love sci-fi movies." }, { role: "assistant", content: "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future." }, ]; await memory.add(messages, { userId: "alice", metadata: { category: "movies" } }); ``` ### Config **Python** | Parameter | Description | Default Value | | - | - | - | | `collection_name` | The name of the collection to store the vectors | `mem0` | | `endpoint` | Connection URL for the Neptune Analytics service, must be `neptune-graph://` | Required | **TypeScript** | Parameter | Description | Default Value | | - | - | - | | `collectionName` | The name of the collection to store the vectors | `memories` | | `graphIdentifier` | Graph ID, e.g. `g-abc123xyz0`. Takes priority over `endpoint`. | Required, unless `endpoint` supplies it | | `endpoint` | Either `neptune-graph://` (or a bare graph ID) to supply the graph ID, or an `https://` service endpoint to override the AWS endpoint. An `https://` value must be paired with `graphIdentifier`. | `undefined` | | `dimension` | Embedding vector dimension | Auto-detected from the embedder when omitted | | `client` | A pre-built `NeptuneGraphClient` to use instead of constructing one | `undefined` | | any other key | Forwarded as-is to the [`NeptuneGraphClient`](https://www.npmjs.com/package/@aws-sdk/client-neptune-graph) constructor, e.g. `region`, `credentials`, `maxAttempts` | N/A | Both SDKs store vectors on graph nodes labeled `MEM0_VECTOR_`. Point them at the same graph with the same `collection_name` (the defaults differ, `mem0` in Python and `memories` in TypeScript) and `get()`, `list()`, and `delete()` interoperate across SDKs. > [!NOTE] > > `search()` is not currently cross-SDK compatible. The TypeScript provider filters on Neptune's reserved > `~label` metafield, while the Python provider filters on a synthetic `label` property that only Python's > own `insert()` writes. Python's `search()` therefore cannot see nodes written by the TypeScript provider. ### IAM Permissions Your AWS identity (user or role) needs a policy that allows the [`ExecuteQuery`](https://docs.aws.amazon.com/neptune-analytics/latest/apiref/API_ExecuteQuery.html) actions used for reads, writes, and deletes: ```json theme={null} { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "neptune-graph:ReadDataViaQuery", "neptune-graph:WriteDataViaQuery", "neptune-graph:DeleteDataViaQuery" ], "Resource": "*" } ] } ``` For production, scope the resource ARN down to your specific graph. # OpenSearch Source: https://docs.mem0.ai/components/vectordbs/dbs/opensearch Use OpenSearch as a vector database in Mem0 with k-NN search support via AWS OpenSearch Service serverless collections. [OpenSearch](https://opensearch.org/) is an enterprise-grade search and observability suite that brings order to unstructured data at scale. OpenSearch supports k-NN (k-Nearest Neighbors) and allows you to store and retrieve high-dimensional vector embeddings efficiently. ### Installation OpenSearch support requires an additional client library. Install the one for your SDK: ```bash Python theme={null} pip install opensearch-py ``` ```bash TypeScript theme={null} npm install @opensearch-project/opensearch ``` ### Prerequisites Before using OpenSearch with Mem0, you need to set up a collection in AWS OpenSearch Service. #### AWS OpenSearch Service You can create a collection through the AWS Console: * Navigate to [OpenSearch Service Console](https://console.aws.amazon.com/aos/home) * Click "Create collection" * Select "Serverless collection" and then enable "Vector search" capabilities * Once created, note the endpoint URL (host) for your configuration ### Usage ```python Python theme={null} import os from mem0 import Memory import boto3 from opensearchpy import OpenSearch, RequestsHttpConnection, AWSV4SignerAuth # For AWS OpenSearch Service with IAM authentication region = 'us-west-2' service = 'aoss' credentials = boto3.Session().get_credentials() auth = AWSV4SignerAuth(credentials, region, service) config = { "vector_store": { "provider": "opensearch", "config": { "collection_name": "mem0", "host": "your-domain.us-west-2.aoss.amazonaws.com", "port": 443, "http_auth": auth, "embedding_model_dims": 1024, "connection_class": RequestsHttpConnection, "pool_maxsize": 20, "use_ssl": True, "verify_certs": True } } } ``` ```typescript TypeScript theme={null} import { Memory } from 'mem0ai/oss'; // Basic self-hosted OpenSearch. For AWS OpenSearch Serverless, build an // @opensearch-project/opensearch Client with AwsSigv4Signer and pass it as // `client` instead of host/port/user/password. const config = { vectorStore: { provider: 'opensearch', config: { collectionName: 'mem0', embeddingModelDims: 1024, host: 'localhost', port: 9200, user: 'admin', password: 'admin', useSSL: false, verifyCerts: false, }, }, }; const memory = new Memory(config); const messages = [ { role: "user", content: "I'm planning to watch a movie tonight. Any recommendations?" }, { role: "assistant", content: "How about thriller movies? They can be quite engaging." }, { role: "user", content: "I'm not a big fan of thriller movies but I love sci-fi movies." }, { role: "assistant", content: "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future." }, ]; await memory.add(messages, { userId: "alice", metadata: { category: "movies" } }); ``` ### Configuration Options **Python** | Parameter | Type | Default | Description | | - | - | - | - | | `collection_name` | string | required | Name of the OpenSearch index | | `host` | string | required | OpenSearch endpoint URL | | `port` | int | 9200 | Port number | | `http_auth` | object | None | Authentication credentials (e.g., AWSV4SignerAuth) | | `embedding_model_dims` | int | 1536 | Dimension of embedding vectors | | `use_ssl` | bool | False | Enable SSL/TLS connection | | `verify_certs` | bool | False | Verify SSL certificates | | `auto_refresh` | bool | False | Automatically refresh index after insert. OpenSearch refreshes every \~1 second by default, so this is rarely needed. | **TypeScript** | Parameter | Type | Default | Description | | - | - | - | - | | `collectionName` | string | required | Name of the OpenSearch index | | `embeddingModelDims` | number | 1536 | Dimension of embedding vectors | | `host` | string | `localhost` | OpenSearch endpoint host | | `port` | number | 9200 | Port number | | `httpAuth` | object | None | Authentication credentials, an object or `[user, password]` tuple | | `user` | string | None | Username for basic auth (used together with `password`) | | `password` | string | None | Password for basic auth (used together with `user`) | | `useSSL` | boolean | false | Enable SSL/TLS connection | | `verifyCerts` | boolean | false | Verify SSL certificates | | `autoRefresh` | boolean | false | Refresh the index after each write so new memories are searchable immediately. Not supported on AWS Serverless. | | `client` | object | None | Preconfigured OpenSearch client, e.g. one built with AwsSigv4Signer for AWS auth | > [!NOTE] > > The defaults above match a local OpenSearch instance. The AWS OpenSearch Serverless > example earlier on this page intentionally overrides them with `port=443`, `use_ssl=True`, > and `verify_certs=True`, which are required when connecting to a Serverless collection. > [!NOTE] > > For **AWS OpenSearch Serverless**, keep `auto_refresh=False` (the default). > The `indices.refresh()` API is not supported on Serverless collections. ### Add Memories ```python theme={null} m = Memory.from_config(config) messages = [ {"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"}, {"role": "assistant", "content": "How about thriller movies? They can be quite engaging."}, {"role": "user", "content": "I'm not a big fan of thriller movies but I love sci-fi movies."}, {"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."} ] m.add(messages, user_id="alice", metadata={"category": "movies"}) ``` ### Search Memories ```python theme={null} results = m.search("What kind of movies does Alice like?", filters={"user_id": "alice"}) ``` ### Features * Fast and Efficient Vector Search * Can be deployed on-premises, in containers, or on cloud platforms like AWS OpenSearch Service * Multiple authentication and security methods (Basic Authentication, API Keys, LDAP, SAML, and OpenID Connect) * Automatic index creation with optimized mappings for vector search * Memory optimization through disk-based vector search and quantization * Real-time analytics and observability # Oracle AI Vector Search Source: https://docs.mem0.ai/components/vectordbs/dbs/oracledb Use Oracle Database AI Vector Search as a vector store in Mem0 for semantic and relational queries. [Oracle AI Vector Search](https://www.oracle.com/database/ai-vector-search/) stores embeddings in an Oracle table using the native `VECTOR` data type, so you can combine semantic search over unstructured data with relational queries over business data in a single database. ### Requirements * Oracle Database 23.4 or later, with a user that can create tables and vector indexes * The `python-oracledb` or `node-oracledb` driver. In thick mode, Oracle Client 23.4 or later is also required. ```bash Python theme={null} pip install mem0ai ``` ```bash TypeScript theme={null} npm install oracledb ``` ### Usage ```python Python theme={null} import os from mem0 import Memory os.environ["OPENAI_API_KEY"] = "sk-xx" config = { "vector_store": { "provider": "oracledb", "config": { "collection_name": "mem0", "embedding_model_dims": 1536, "connection_params": { "user": "mem0_user", "password": "your-password", "dsn": "localhost:1521/FREEPDB1", }, } } } m = Memory.from_config(config) messages = [ {"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"}, {"role": "assistant", "content": "How about thriller movies? They can be quite engaging."}, {"role": "user", "content": "I'm not a big fan of thriller movies but I love sci-fi movies."}, {"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."} ] m.add(messages, user_id="alice", metadata={"category": "movies"}) ``` ```typescript TypeScript theme={null} import { Memory } from "mem0ai/oss"; const config = { vectorStore: { provider: "oracledb", config: { collectionName: "mem0", embeddingModelDims: 1536, connectionParams: { user: "mem0_user", password: "your-password", connectString: "localhost:1521/FREEPDB1", }, }, }, }; const memory = new Memory(config); const messages = [ { role: "user", content: "I'm planning to watch a movie tonight. Any recommendations?", }, { role: "assistant", content: "How about thriller movies? They can be quite engaging.", }, { role: "user", content: "I'm not a big fan of thriller movies but I love sci-fi movies.", }, { role: "assistant", content: "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future.", }, ]; await memory.add(messages, { userId: "alice", metadata: { category: "movies" }, }); ``` To reuse a connection or pool you already manage, pass it as `client` instead of the connection parameters: ```python Python theme={null} import oracledb pool = oracledb.create_pool(user="mem0_user", password="your-password", dsn="localhost:1521/FREEPDB1") config = { "vector_store": { "provider": "oracledb", "config": {"client": pool}, } } ``` ```typescript TypeScript theme={null} import oracledb from "oracledb"; const pool = await oracledb.createPool({ user: "mem0_user", password: "your-password", connectString: "localhost:1521/FREEPDB1", }); const config = { vectorStore: { provider: "oracledb", config: { client: pool }, }, }; ``` ### Config Here are the parameters available for configuring Oracle AI Vector Search: Provide either `connection_params`/`connectionParams` or an existing connection or pool as `client`. | Python | TypeScript | Description | Default Value | | - | - | - | - | | `connection_params` | `connectionParams` | Connection settings passed to the Oracle driver, such as `user`, `password` and `dsn` (`connectString` in TypeScript). Required unless `client` is provided. See the [Python](https://python-oracledb.readthedocs.io/en/latest/user_guide/connection_handling.html) or [Node.js](https://node-oracledb.readthedocs.io/en/latest/user_guide/connection_handling.html) connection handling guide. | `None` | | `use_connection_pool` | `useConnectionPool` | Create a connection pool from the connection parameters instead of a single connection | `True` | | `client` | `client` | An existing Oracle connection or pool to use instead of building one from the connection parameters. Required unless connection parameters are provided. | `None` | | `collection_name` | `collectionName` | Name of the Oracle table that stores vectors and payloads | `mem0` | | `embedding_model_dims` | `embeddingModelDims` | Dimension of your embedding vectors, must be greater than 0 | `1536` | | `distance_metric` | `distanceMetric` | Distance function used for indexing and search: `COSINE`, `EUCLIDEAN`, `EUCLIDEAN_SQUARED`, `DOT`, `HAMMING` or `MANHATTAN` | `COSINE` | | `do_create_index` | `doCreateIndex` | Whether to create a vector index on the collection | `True` | | `index_type` | `indexType` | Vector index type: `HNSW` or `IVF` | `HNSW` | | `index_name` | `indexName` | Name of the vector index | `_VEC_IDX` | | `index_parameters` | `indexParameters` | Index tuning parameters. For `HNSW`: `neighbors`, `efconstruction`. For `IVF`: `neighbor partitions`, `samples_per_partition`, `min_vectors_per_partition`. | `None` | | `index_accuracy` | `indexAccuracy` | Target index accuracy from 1 to 100, applied as `WITH TARGET ACCURACY ` | `None` | > [!NOTE] > > When you pass a pre-built `client`, Mem0 uses it as-is and ignores the connection parameters and pooling options. Mem0 does not close a client it did not create. ### Vector indexes Set the index type with `index_type` and tune it with `index_parameters`: ```python Python theme={null} config = { "vector_store": { "provider": "oracledb", "config": { "connection_params": {"user": "mem0_user", "password": "your-password", "dsn": "localhost:1521/FREEPDB1"}, "index_type": "HNSW", "index_parameters": {"neighbors": 32, "efconstruction": 200}, "index_accuracy": 95, } } } ``` ```typescript TypeScript theme={null} const config = { vectorStore: { provider: "oracledb", config: { connectionParams: { user: "mem0_user", password: "your-password", connectString: "localhost:1521/FREEPDB1", }, indexType: "HNSW", indexParameters: { neighbors: 32, efconstruction: 200 }, indexAccuracy: 95, }, }, }; ``` For the full list of supported options, see the Oracle [`CREATE VECTOR INDEX`](https://docs.oracle.com/en/database/oracle/oracle-database/26/sqlrf/create-vector-index.html) reference. ### Search scores Oracle returns a distance from `VECTOR_DISTANCE`, which Mem0 converts to a `score` where higher means more similar. `COSINE` and the other non-negative metrics produce scores in the range `[0, 1]`. `DOT` returns the inner product, which can fall outside that range. ### Metadata filters Filters run against the JSON `payload` column and support: | Filter type | Examples | | - | - | | Scalar equality | `{"user_id": "alice"}` | | Field existence | `{"agent_id": "*"}` | | Comparison | `{"score": {"gte": 0.5}}`, also `eq`, `ne`, `gt`, `lt`, `lte` | | Membership | `{"category": {"in": ["movies", "books"]}}`, also `nin` | | String matching | `{"title": {"contains": "sci-fi"}}`, also `icontains` for case-insensitive | | Logical groups | `{"AND": [...]}`, `{"OR": [...]}`, `{"NOT": [...]}`, also `$and`, `$or`, `$not` | Multiple fields at the top level are combined with `AND`: ```python Python theme={null} m.search( "movie recommendations", filters={ "user_id": "alice", "category": {"in": ["movies", "books"]}, "rating": {"gte": 4}, }, ) ``` ```typescript TypeScript theme={null} await memory.search("movie recommendations", { filters: { user_id: "alice", category: { in: ["movies", "books"] }, rating: { gte: 4 }, }, }); ``` # pgvector Source: https://docs.mem0.ai/components/vectordbs/dbs/pgvector Use pgvector as a vector store in Mem0 for PostgreSQL-based vector similarity search with open-source simplicity. [pgvector](https://github.com/pgvector/pgvector) is an open-source vector similarity search extension for Postgres. After connecting to Postgres, run `CREATE EXTENSION IF NOT EXISTS vector;` to create the vector extension. The TypeScript SDK loads the `pg` driver only when you use this store, so install it alongside `mem0ai`: ```bash theme={null} npm install pg ``` ### Usage ```python Python theme={null} import os from mem0 import Memory os.environ["OPENAI_API_KEY"] = "sk-xx" config = { "vector_store": { "provider": "pgvector", "config": { "user": "test", "password": "123", "host": "127.0.0.1", "port": "5432", }, } } m = Memory.from_config(config) messages = [ {"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"}, {"role": "assistant", "content": "How about thriller movies? They can be quite engaging."}, {"role": "user", "content": "I'm not a big fan of thriller movies but I love sci-fi movies."}, {"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."}, ] m.add(messages, user_id="alice", metadata={"category": "movies"}) ``` ```typescript TypeScript theme={null} import { Memory } from "mem0ai/oss"; const config = { vectorStore: { provider: "pgvector", config: { collectionName: "memories", embeddingModelDims: 1536, connectionString: "postgresql://test:123@localhost:5432/vector_store", diskann: false, // Optional, requires pgvectorscale extension hnsw: false, // Optional, for HNSW indexing }, }, }; const memory = new Memory(config); const messages = [ { role: "user", content: "I'm planning to watch a movie tonight. Any recommendations?" }, { role: "assistant", content: "How about thriller movies? They can be quite engaging." }, { role: "user", content: "I'm not a big fan of thriller movies but I love sci-fi movies." }, { role: "assistant", content: "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future." }, ]; await memory.add(messages, { userId: "alice", metadata: { category: "movies" } }); ``` ### Config Here are the parameters available for configuring pgvector: | Parameter | SDK | Description | Default Value | | - | - | - | - | | `connectionString` | TypeScript OSS | PostgreSQL connection string for direct connections. When set, Mem0 connects to the target database directly and skips the bootstrap `postgres` database flow. | `None` | | `ssl` | TypeScript OSS | SSL option passed directly to `pg`, either `true` or an SSL config object, for both `connectionString` and split-field connections. | `None` | | `dbname` | TypeScript OSS | Split-field database name. This is only used when `connectionString` is absent. | `vector_store` | | `collectionName` | TypeScript OSS | Collection name. | `memories` | | `embeddingModelDims` | TypeScript OSS | Dimensions of the embedding model. | Required | | `user` | TypeScript OSS + Python | Database user for split-field connections. | `None` | | `password` | TypeScript OSS + Python | Database password for split-field connections. | `None` | | `host` | TypeScript OSS + Python | Database host for split-field connections. | `None` | | `port` | TypeScript OSS + Python | Database port for split-field connections. | `None` | | `diskann` | TypeScript OSS + Python | Whether to use DiskANN for vector similarity search, requires pgvectorscale. | `False` | | `hnsw` | TypeScript OSS + Python | Whether to use HNSW for vector similarity search. | TypeScript OSS: `False`, Python: `True` | | `connection_string` | Python only | PostgreSQL connection string, overrides individual connection parameters. | `None` | | `sslmode` | Python only | SSL mode for PostgreSQL connections, such as `require`, `prefer`, or `disable`. | `None` | | `connection_pool` | Python only | psycopg connection pool object, overrides connection string and individual connection parameters. | `None` | **TypeScript OSS:** Use `connectionString` plus optional `ssl` for managed Postgres setups. If you omit `connectionString`, Mem0 falls back to split fields and uses `dbname`, `user`, `password`, `host`, `port`, and optional `ssl`. **Python:** The Python SDK uses snake\_case keys such as `connection_string`, `sslmode`, `collection_name`, and `embedding_model_dims`. **Python connection priority**: 1. `connection_pool` (highest priority) 2. `connection_string` 3. Individual connection parameters (`user`, `password`, `host`, `port`, `sslmode`) # Pinecone Source: https://docs.mem0.ai/components/vectordbs/dbs/pinecone Use Pinecone as a fully managed vector database in Mem0 with serverless deployment and namespace-based multi-tenancy. [Pinecone](https://www.pinecone.io/) is a fully managed vector database designed for machine learning applications, offering high performance vector search with low latency at scale. It's particularly well-suited for semantic search, recommendation systems, and other AI-powered applications. > **New**: Pinecone integration now supports custom namespaces! Use the `namespace` parameter to logically separate data within the same index. This is especially useful for multi-tenant or multi-user applications. > **Note**: Before configuring Pinecone, you need to select an embedding model (e.g., OpenAI, Cohere, or custom models) and ensure the `embedding_model_dims` in your config matches your chosen model's dimensions. For example, OpenAI's text-embedding-3-small uses 1536 dimensions. ### Usage ```python Python theme={null} import os from mem0 import Memory os.environ["OPENAI_API_KEY"] = "sk-xx" os.environ["PINECONE_API_KEY"] = "your-api-key" # Example using serverless configuration config = { "vector_store": { "provider": "pinecone", "config": { "collection_name": "testing", "embedding_model_dims": 1536, # Matches OpenAI's text-embedding-3-small "namespace": "my-namespace", # Optional: specify a namespace for multi-tenancy "serverless_config": { "cloud": "aws", # Choose between 'aws' or 'gcp' or 'azure' "region": "us-east-1" }, "metric": "cosine" } } } m = Memory.from_config(config) messages = [ {"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"}, {"role": "assistant", "content": "How about thriller movies? They can be quite engaging."}, {"role": "user", "content": "I'm not a big fan of thriller movies but I love sci-fi movies."}, {"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."} ] m.add(messages, user_id="alice", metadata={"category": "movies"}) ``` ```typescript TypeScript theme={null} import { Memory } from 'mem0ai/oss'; // Set OPENAI_API_KEY and PINECONE_API_KEY in your environment const config = { vectorStore: { provider: 'pinecone', config: { collectionName: 'testing', embeddingModelDims: 1536, // Matches OpenAI's text-embedding-3-small namespace: 'my-namespace', // Optional: specify a namespace for multi-tenancy serverlessConfig: { cloud: 'aws', // 'aws' | 'gcp' | 'azure' region: 'us-east-1', }, metric: 'cosine', }, }, }; const memory = new Memory(config); const messages = [ {"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"}, {"role": "assistant", "content": "How about thriller movies? They can be quite engaging."}, {"role": "user", "content": "I'm not a big fan of thriller movies but I love sci-fi movies."}, {"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."} ] await memory.add(messages, { userId: "alice", metadata: { category: "movies" } }); ``` ### Config Here are the parameters available for configuring Pinecone: **Python** | Parameter | Description | Default Value | | - | - | - | | `collection_name` | Name of the index/collection | Required | | `embedding_model_dims` | Dimensions of the embedding model (must match your chosen embedding model) | Required | | `client` | Existing Pinecone client instance | `None` | | `api_key` | API key for Pinecone | Environment variable: `PINECONE_API_KEY` | | `environment` | Pinecone environment | `None` | | `serverless_config` | Configuration for serverless deployment (AWS or GCP or Azure) | `None` | | `pod_config` | Configuration for pod-based deployment | `None` | | `hybrid_search` | Whether to enable hybrid search | `False` | | `metric` | Distance metric for vector similarity | `"cosine"` | | `batch_size` | Batch size for operations | `100` | | `extra_params` | Additional keyword arguments passed to the `Pinecone` client constructor. Ignored when `client` is supplied. | `None` | | `namespace` | Namespace for the collection, useful for multi-tenancy. | `None` | **TypeScript** | Parameter | Description | Default Value | | - | - | - | | `collectionName` | Name of the index/collection | Required | | `embeddingModelDims` | Dimensions of the embedding model (must match your chosen embedding model) | `1536` | | `client` | Existing Pinecone client instance | `undefined` | | `apiKey` | API key for Pinecone | Environment variable: `PINECONE_API_KEY` | | `serverlessConfig` | Configuration for serverless deployment (`cloud`, `region`) | `undefined` | | `podConfig` | Configuration for pod-based deployment (`environment`, `podType`, `pods`, `replicas`, `shards`) | `undefined` | | `metric` | Distance metric for vector similarity (`cosine`, `dotproduct`, `euclidean`) | `"cosine"` | | `batchSize` | Batch size for insert operations | `100` | | `namespace` | Namespace for the collection, useful for multi-tenancy. | `undefined` | | `extraParams` | Extra parameters spread into the Pinecone `createIndex` call | `{}` | > **Important**: You must choose either `serverless_config` or `pod_config` for your deployment, but not both. #### Serverless Config Example ```python Python theme={null} config = { "vector_store": { "provider": "pinecone", "config": { "collection_name": "memory_index", "embedding_model_dims": 1536, # For OpenAI's text-embedding-3-small "namespace": "my-namespace", # Optional: custom namespace "serverless_config": { "cloud": "aws", # or "gcp" or "azure" "region": "us-east-1" # Choose appropriate region } } } } ``` ```typescript TypeScript theme={null} const config = { vectorStore: { provider: 'pinecone', config: { collectionName: 'memory_index', embeddingModelDims: 1536, // For OpenAI's text-embedding-3-small namespace: 'my-namespace', // Optional: custom namespace serverlessConfig: { cloud: 'aws', // 'gcp' | 'azure' region: 'us-east-1', // Choose appropriate region }, }, }, }; ``` #### Pod Config Example ```python Python theme={null} config = { "vector_store": { "provider": "pinecone", "config": { "collection_name": "memory_index", "embedding_model_dims": 1536, # For OpenAI's text-embedding-ada-002 "namespace": "my-namespace", # Optional: custom namespace "pod_config": { "environment": "gcp-starter", "replicas": 1, "pod_type": "starter" } } } } ``` ```typescript TypeScript theme={null} const config = { vectorStore: { provider: 'pinecone', config: { collectionName: 'memory_index', embeddingModelDims: 1536, // For OpenAI's text-embedding-ada-002 namespace: 'my-namespace', // Optional: custom namespace podConfig: { environment: 'gcp-starter', replicas: 1, podType: 'starter', }, }, }, }; ``` # Qdrant Source: https://docs.mem0.ai/components/vectordbs/dbs/qdrant Use Qdrant as an open-source vector search engine in Mem0 for high-performance similarity search at scale. [Qdrant](https://qdrant.tech/) is an open-source vector search engine. It is designed to work with large-scale datasets and provides a high-performance search engine for vector data. ### Usage ```python Python theme={null} import os from mem0 import Memory os.environ["OPENAI_API_KEY"] = "sk-xx" config = { "vector_store": { "provider": "qdrant", "config": { "collection_name": "test", "host": "localhost", "port": 6333, } } } m = Memory.from_config(config) messages = [ {"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"}, {"role": "assistant", "content": "How about thriller movies? They can be quite engaging."}, {"role": "user", "content": "I’m not a big fan of thriller movies but I love sci-fi movies."}, {"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."} ] m.add(messages, user_id="alice", metadata={"category": "movies"}) ``` ```typescript TypeScript theme={null} import { Memory } from 'mem0ai/oss'; const config = { vectorStore: { provider: 'qdrant', config: { collectionName: 'memories', dimension: 1536, host: 'localhost', port: 6333, }, }, }; const memory = new Memory(config); const messages = [ {"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"}, {"role": "assistant", "content": "How about thriller movies? They can be quite engaging."}, {"role": "user", "content": "I’m not a big fan of thriller movies but I love sci-fi movies."}, {"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."} ] await memory.add(messages, { userId: "alice", metadata: { category: "movies" } }); ``` ### Hybrid keyword search Mem0 blends semantic similarity with BM25 keyword scoring. On the TypeScript SDK, Qdrant computes the BM25 vectors server-side, which requires Qdrant 1.15.2 or newer with inference enabled. Qdrant Cloud enables inference by default only for clusters created after 2025-07-07; older clusters must activate it from the Cluster Detail page. The Python SDK encodes BM25 locally instead and needs the `fastembed` package, so scores are not numerically comparable between the two SDKs. When BM25 is unavailable, or when the collection was created before hybrid search was added, Mem0 logs a warning and falls back to semantic-only search. Writes are unaffected. To enable keyword scoring on an older collection, use a fresh collection name. ### Config Let's see the available parameters for the `qdrant` config: **Python** | Parameter | Description | Default Value | | - | - | - | | `collection_name` | The name of the collection to store the vectors | `mem0` | | `embedding_model_dims` | Dimensions of the embedding model | `1536` | | `client` | Custom client for qdrant | `None` | | `host` | The host where the qdrant server is running | `None` | | `port` | The port where the qdrant server is running | `None` | | `path` | Path for the qdrant database | `/tmp/qdrant` | | `url` | Full URL for the qdrant server | `None` | | `api_key` | API key for the qdrant server | `None` | | `https` | Whether to force HTTPS on or off. `None` lets the client decide; set `False` for plain HTTP Qdrant with API key authentication. | `None` | | `on_disk` | For enabling persistent storage | `False` | **TypeScript** | Parameter | Description | Default Value | | - | - | - | | `collectionName` | The name of the collection to store the vectors | `mem0` | | `dimension` | Dimensions of the embedding model | `1536` | | `host` | The host where the Qdrant server is running | `None` | | `port` | The port where the Qdrant server is running | `None` | | `path` | Path for the Qdrant database | `/tmp/qdrant` | | `url` | Full URL for the Qdrant server | `None` | | `apiKey` | API key for the Qdrant server | `None` | | `onDisk` | For enabling persistent storage | `False` | # Redis Source: https://docs.mem0.ai/components/vectordbs/dbs/redis Use Redis as a real-time vector database in Mem0 for fast vector search using Redis Stack and redisvl. [Redis](https://redis.io/) is a scalable, real-time database that can store, search, and analyze vector data. ### Installation ```bash theme={null} pip install redis redisvl ``` Redis Stack using Docker: ```bash theme={null} docker run -d --name redis-stack -p 6379:6379 -p 8001:8001 redis/redis-stack:latest ``` ### Usage ```python Python theme={null} import os from mem0 import Memory os.environ["OPENAI_API_KEY"] = "sk-xx" config = { "vector_store": { "provider": "redis", "config": { "collection_name": "mem0", "embedding_model_dims": 1536, "redis_url": "redis://localhost:6379" } }, "version": "v1.1" } m = Memory.from_config(config) messages = [ {"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"}, {"role": "assistant", "content": "How about thriller movies? They can be quite engaging."}, {"role": "user", "content": "I’m not a big fan of thriller movies but I love sci-fi movies."}, {"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."} ] m.add(messages, user_id="alice", metadata={"category": "movies"}) ``` ```typescript TypeScript theme={null} import { Memory } from 'mem0ai/oss'; const config = { vectorStore: { provider: 'redis', config: { collectionName: 'memories', embeddingModelDims: 1536, redisUrl: 'redis://localhost:6379', username: 'your-redis-username', password: 'your-redis-password', }, }, }; const memory = new Memory(config); const messages = [ {"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"}, {"role": "assistant", "content": "How about thriller movies? They can be quite engaging."}, {"role": "user", "content": "I’m not a big fan of thriller movies but I love sci-fi movies."}, {"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."} ] await memory.add(messages, { userId: "alice", metadata: { category: "movies" } }); ``` ### Config Let's see the available parameters for the `redis` config: **Python** | Parameter | Description | Default Value | | - | - | - | | `collection_name` | The name of the collection to store the vectors | `mem0` | | `embedding_model_dims` | Dimensions of the embedding model | `1536` | | `redis_url` | The URL of the Redis server | `None` | **TypeScript** | Parameter | Description | Default Value | | - | - | - | | `collectionName` | The name of the collection to store the vectors | `mem0` | | `embeddingModelDims` | Dimensions of the embedding model | `1536` | | `redisUrl` | The URL of the Redis server | `None` | | `username` | Username for Redis connection | `None` | | `password` | Password for Redis connection | `None` | # Amazon S3 Vectors Source: https://docs.mem0.ai/components/vectordbs/dbs/s3-vectors Use Amazon S3 Vectors as a cost-optimized vector storage service in Mem0 with AWS credential authentication. [Amazon S3 Vectors](https://aws.amazon.com/s3/features/vectors/) is a purpose-built, cost-optimized vector storage and query service for semantic search and AI applications. It provides S3-level elasticity and durability with sub-second query performance. ### Installation S3 Vectors support requires additional dependencies. Install them with: ```bash Python theme={null} pip install boto3 ``` ```bash TypeScript theme={null} npm install @aws-sdk/client-s3vectors ``` ### Usage To use Amazon S3 Vectors with Mem0, you need to have an AWS account and the necessary IAM permissions (`s3vectors:*`). Ensure your environment is configured with AWS credentials (e.g., via `~/.aws/credentials` or environment variables). ```python Python theme={null} import os from mem0 import Memory # Ensure your AWS credentials are configured in your environment # e.g., by setting AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, and AWS_DEFAULT_REGION config = { "vector_store": { "provider": "s3_vectors", "config": { "vector_bucket_name": "my-mem0-vector-bucket", "collection_name": "my-memories-index", "embedding_model_dims": 1536, "distance_metric": "cosine", "region_name": "us-east-1" } } } m = Memory.from_config(config) messages = [ {"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"}, {"role": "assistant", "content": "How about a thriller movie? They can be quite engaging."}, {"role": "user", "content": "I'm not a big fan of thriller movies but I love sci-fi movies."}, {"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."} ] m.add(messages, user_id="alice", metadata={"category": "movies"}) ``` ```typescript TypeScript theme={null} import { Memory } from 'mem0ai/oss'; // Ensure your AWS credentials are configured in your environment // e.g., by setting AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, and AWS_DEFAULT_REGION const config = { vectorStore: { provider: 's3_vectors', config: { vectorBucketName: 'my-mem0-vector-bucket', collectionName: 'my-memories-index', embeddingModelDims: 1536, distanceMetric: 'cosine', region: 'us-east-1', }, }, }; const memory = new Memory(config); const messages = [ {"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"}, {"role": "assistant", "content": "How about a thriller movie? They can be quite engaging."}, {"role": "user", "content": "I'm not a big fan of thriller movies but I love sci-fi movies."}, {"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."} ] await memory.add(messages, { userId: "alice", metadata: { category: "movies" } }); ``` ### Config Here are the parameters available for configuring Amazon S3 Vectors: | Parameter | Description | Default Value | | - | - | - | | `vector_bucket_name` | The name of the S3 Vector bucket to use. It will be created if it doesn't exist. | Required | | `collection_name` | The name of the vector index within the bucket. | `mem0` | | `embedding_model_dims` | Dimensions of the embedding model. Must match your embedder. | `1536` | | `distance_metric` | Distance metric for similarity search. Options: `cosine`, `euclidean`. | `cosine` | | `region_name` | The AWS region where the bucket and index reside. | `None` (uses default from AWS config) | ### IAM Permissions Your AWS identity (user or role) needs permissions to perform actions on S3 Vectors. A minimal policy would look like this: ```json theme={null} { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": "s3vectors:*", "Resource": "*" } ] } ``` For production, it is recommended to scope down the resource ARN to your specific buckets and indexes. # Supabase Source: https://docs.mem0.ai/components/vectordbs/dbs/supabase Use Supabase as a vector store in Mem0, powered by PostgreSQL and pgvector with HNSW indexing support. [Supabase](https://supabase.com/) is an open-source Firebase alternative that provides a PostgreSQL database with pgvector extension for vector similarity search. It offers a powerful and scalable solution for storing and querying vector embeddings. Create a [Supabase](https://supabase.com/dashboard/projects) account and project, then get your connection string from Project Settings > Database. See the [docs](https://supabase.github.io/vecs/hosting/) for details. ### Usage ```python Python theme={null} import os from mem0 import Memory os.environ["OPENAI_API_KEY"] = "sk-xx" config = { "vector_store": { "provider": "supabase", "config": { "connection_string": "postgresql://user:password@host:port/database", "collection_name": "memories", "index_method": "hnsw", # Optional: defaults to "auto" "index_measure": "cosine_distance" # Optional: defaults to "cosine_distance" } } } m = Memory.from_config(config) messages = [ {"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"}, {"role": "assistant", "content": "How about thriller movies? They can be quite engaging."}, {"role": "user", "content": "I'm not a big fan of thriller movies but I love sci-fi movies."}, {"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."} ] m.add(messages, user_id="alice", metadata={"category": "movies"}) ``` ```typescript Typescript theme={null} import { Memory } from "mem0ai/oss"; const config = { vectorStore: { provider: "supabase", config: { collectionName: "memories", embeddingModelDims: 1536, supabaseUrl: process.env.SUPABASE_URL || "", supabaseKey: process.env.SUPABASE_KEY || "", tableName: "memories", }, }, } const memory = new Memory(config); const messages = [ {"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"}, {"role": "assistant", "content": "How about thriller movies? They can be quite engaging."}, {"role": "user", "content": "I'm not a big fan of thriller movies but I love sci-fi movies."}, {"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."} ] await memory.add(messages, { userId: "alice", metadata: { category: "movies" } }); ``` ### SQL Migrations for TypeScript Implementation The following SQL migrations are required to enable the vector extension and create the memories table: ```sql theme={null} -- Enable the vector extension create extension if not exists vector; -- Create the memories table create table if not exists memories ( id text primary key, embedding vector(1536), metadata jsonb, created_at timestamp with time zone default timezone('utc', now()), updated_at timestamp with time zone default timezone('utc', now()) ); -- Create the vector similarity search function create or replace function match_vectors( query_embedding vector(1536), match_count int, filter jsonb default '{}'::jsonb ) returns table ( id text, similarity float, metadata jsonb ) language plpgsql as $$ begin return query select t.id::text, 1 - (t.embedding <=> query_embedding) as similarity, t.metadata from memories t where case when filter::text = '{}'::text then true else t.metadata @> filter end order by t.embedding <=> query_embedding limit match_count; end; $$; ``` Go to [Supabase](https://supabase.com/dashboard/projects) and run the above SQL migrations in the SQL Editor. ### Row Level Security Tables created through the Supabase dashboard have Row Level Security (RLS) enabled by default with no policies attached. With RLS on and no policies, the TypeScript SDK's queries return zero rows with an HTTP 200 (no error is raised), which looks like an empty memory store rather than a permissions problem. If you use the SQL migrations above (via the SQL Editor), RLS is left in its default off state and this does not apply. If your table has RLS enabled, add policies for the key your app uses (the example below grants full access to the `service_role` key; scope it down for anon/authenticated keys as needed): ```sql theme={null} alter table memories enable row level security; create policy "Allow service role full access to memories" on memories for all to service_role using (true) with check (true); ``` ### PostgREST Row Limits Supabase's PostgREST layer caps the number of rows returned by a single request at `db-max-rows` (1000 by default), for both `.select()` queries and RPC function calls like `match_vectors`. Requesting a `topK` above this limit for `search()` or `list()` will not raise an error, results are capped at `db-max-rows` instead. The TypeScript `list()` method paginates internally to work around this, but `search()` cannot since `match_vectors` has no offset parameter; it logs a warning when it detects a truncated result. Raise `db-max-rows` in your Supabase project settings if you need more than 1000 results per search. ### Config Here are the parameters available for configuring Supabase: **Python** | Parameter | Description | Default Value | | - | - | - | | `connection_string` | PostgreSQL connection string (required) | None | | `collection_name` | Name for the vector collection | `mem0` | | `embedding_model_dims` | Dimensions of the embedding model | `1536` | | `index_method` | Vector index method to use | `auto` | | `index_measure` | Distance measure for similarity search | `cosine_distance` | **TypeScript** | Parameter | Description | Default Value | | - | - | - | | `collectionName` | Name for the vector collection | `mem0` | | `embeddingModelDims` | Dimensions of the embedding model | `1536` | | `supabaseUrl` | Supabase URL | None | | `supabaseKey` | Supabase key | None | | `tableName` | Name for the vector table | `memories` | ### Index Methods The following index methods are supported: * `auto`: Automatically selects the best available index method * `hnsw`: Hierarchical Navigable Small World graph index (faster search, more memory usage) * `ivfflat`: Inverted File Flat index (good balance of speed and memory) ### Distance Measures Available distance measures for similarity search: * `cosine_distance`: Cosine similarity (recommended for most embedding models) * `l2_distance`: Euclidean distance * `l1_distance`: Manhattan distance * `max_inner_product`: Maximum inner product similarity ### Best Practices 1. **Index Method Selection**: * Use `hnsw` for fastest search performance when memory is not a constraint * Use `ivfflat` for a good balance of search speed and memory usage * Use `auto` if unsure, it will select the best method based on your data 2. **Distance Measure Selection**: * Use `cosine_distance` for most embedding models (OpenAI, Hugging Face, etc.) * Use `max_inner_product` if your vectors are normalized * Use `l2_distance` or `l1_distance` if working with raw feature vectors 3. **Connection String**: * Always use environment variables for sensitive information in the connection string * Format: `postgresql://user:password@host:port/database` # Turbopuffer Source: https://docs.mem0.ai/components/vectordbs/dbs/turbopuffer Use Turbopuffer as a serverless vector database in Mem0 for low-latency search at scale with native metadata filtering. [Turbopuffer](https://turbopuffer.com) is a serverless vector database optimized for low-latency search at scale. It offers cost-effective vector storage with native metadata filtering. ### Usage ```python Python theme={null} import os from mem0 import Memory os.environ["OPENAI_API_KEY"] = "sk-xx" os.environ["TURBOPUFFER_API_KEY"] = "tpuf_xxxxxxxxxxxx" config = { "vector_store": { "provider": "turbopuffer", "config": { "collection_name": "movie_preferences", "embedding_model_dims": 1536, "region": "gcp-us-central1", } } } m = Memory.from_config(config) messages = [ {"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"}, {"role": "assistant", "content": "How about thriller movies? They can be quite engaging."}, {"role": "user", "content": "I'm not a big fan of thrillers but I love sci-fi."}, {"role": "assistant", "content": "Got it! I'll suggest sci-fi movies instead."} ] m.add(messages, user_id="alice", metadata={"category": "movies"}) # Search memories results = m.search(query="sci-fi recommendations", filters={"user_id": "alice"}) ``` ```typescript TypeScript theme={null} import { Memory } from "mem0ai/oss"; // Set TURBOPUFFER_API_KEY in your environment, or pass it as config.apiKey below. const config = { vectorStore: { provider: "turbopuffer", config: { collectionName: "movie_preferences", region: "gcp-us-central1", }, }, }; const memory = new Memory(config); const messages = [ { role: "user", content: "I'm planning to watch a movie tonight. Any recommendations?" }, { role: "assistant", content: "How about thriller movies? They can be quite engaging." }, { role: "user", content: "I'm not a big fan of thrillers but I love sci-fi." }, { role: "assistant", content: "Got it! I'll suggest sci-fi movies instead." }, ]; await memory.add(messages, { userId: "alice", metadata: { category: "movies" } }); // Search memories const results = await memory.search("sci-fi recommendations", { userId: "alice" }); ``` ### Config Here are the parameters available for configuring Turbopuffer: | Parameter | Description | Default Value | | - | - | - | | `collection_name` | Name of the namespace/collection | `mem0` | | `embedding_model_dims` | Dimensions of the embedding model (must match your chosen embedding model) | `1536` | | `api_key` | Turbopuffer API key | Environment variable: `TURBOPUFFER_API_KEY` | | `region` | Turbopuffer region | `gcp-us-central1` | | `distance_metric` | Distance metric for vector similarity (`cosine_distance` or `euclidean_squared`) | `cosine_distance` | | `batch_size` | Batch size for bulk operations | `100` | | `extra_params` | Additional parameters for the Turbopuffer client | `None` | > [!NOTE] > > **TypeScript (Node.js) config keys** are camelCase: `collectionName`, `apiKey`, `region`, `distanceMetric`, and `batchSize`. The TypeScript SDK infers the vector dimension from your embedder, so `embeddingModelDims` is not required. ### Regions | Region | Location | | - | - | | `gcp-us-central1` | Iowa, USA (Default) | | `aws-us-west-2` | Oregon, USA | ### Config Example ```python Python theme={null} config = { "vector_store": { "provider": "turbopuffer", "config": { "collection_name": "my_memories", "embedding_model_dims": 1536, "api_key": "tpuf_xxxxxxxxxxxx", "region": "aws-us-west-2", "distance_metric": "cosine_distance", "batch_size": 200, } } } ``` ```typescript TypeScript theme={null} const config = { vectorStore: { provider: "turbopuffer", config: { collectionName: "my_memories", apiKey: "tpuf_xxxxxxxxxxxx", region: "aws-us-west-2", distanceMetric: "cosine_distance", batchSize: 200, }, }, }; ``` # Upstash Vector Source: https://docs.mem0.ai/components/vectordbs/dbs/upstash-vector Use Upstash Vector as a serverless vector database in Mem0 with optional built-in embedding models. [Upstash Vector](https://upstash.com/docs/vector) is a serverless vector database with built-in embedding models. ### Usage with Upstash embeddings You can enable the built-in embedding models by setting `enable_embeddings` to `True`. This allows you to use Upstash's embedding models for vectorization. > [!NOTE] > > Server-side Upstash embeddings (`enable_embeddings`) are available in the Python SDK only. The TypeScript SDK always embeds text with your configured embedder before writing to Upstash, so use the external embedding provider setup below. ```python theme={null} import os from mem0 import Memory os.environ["UPSTASH_VECTOR_REST_URL"] = "..." os.environ["UPSTASH_VECTOR_REST_TOKEN"] = "..." config = { "vector_store": { "provider": "upstash_vector", "config": { "enable_embeddings": True, } } } m = Memory.from_config(config) m.add("Likes to play cricket on weekends", user_id="alice", metadata={"category": "hobbies"}) ``` > [!NOTE] > > Setting `enable_embeddings` to `True` will bypass any external embedding provider you have configured. ### Usage with external embedding providers ```python Python theme={null} import os from mem0 import Memory os.environ["OPENAI_API_KEY"] = "..." os.environ["UPSTASH_VECTOR_REST_URL"] = "..." os.environ["UPSTASH_VECTOR_REST_TOKEN"] = "..." config = { "vector_store": { "provider": "upstash_vector", }, "embedder": { "provider": "openai", "config": { "model": "text-embedding-3-large" }, } } m = Memory.from_config(config) m.add("Likes to play cricket on weekends", user_id="alice", metadata={"category": "hobbies"}) ``` ```typescript TypeScript theme={null} import { Memory } from "mem0ai/oss"; // Set OPENAI_API_KEY, UPSTASH_VECTOR_REST_URL, and UPSTASH_VECTOR_REST_TOKEN in your environment. const config = { embedder: { provider: "openai", config: { apiKey: process.env.OPENAI_API_KEY, model: "text-embedding-3-large", }, }, vectorStore: { provider: "upstash_vector", config: { collectionName: "memories", url: process.env.UPSTASH_VECTOR_REST_URL, token: process.env.UPSTASH_VECTOR_REST_TOKEN, }, }, }; const memory = new Memory(config); await memory.add("Likes to play cricket on weekends", { userId: "alice", metadata: { category: "hobbies" }, }); ``` ### Config Here are the parameters available for configuring Upstash Vector: | Parameter | Description | Default Value | | - | - | - | | `url` | URL for the Upstash Vector index | `None` | | `token` | Token for the Upstash Vector index | `None` | | `client` | An `upstash_vector.Index` instance | `None` | | `collection_name` | The default namespace used | `"mem0"` | | `enable_embeddings` | Whether to use Upstash embeddings | `False` | > [!NOTE] > > When `url` and `token` are not provided, the `UPSTASH_VECTOR_REST_URL` and > `UPSTASH_VECTOR_REST_TOKEN` environment variables are used. > [!NOTE] > > The TypeScript SDK uses camelCase config keys (`collectionName`, `url`, `token`), where `collectionName` is required. Pass `url` and `token` (or a preconfigured `client`) explicitly, since the TypeScript SDK does not read them from environment variables. `enable_embeddings` is not supported in TypeScript. # Valkey Source: https://docs.mem0.ai/components/vectordbs/dbs/valkey Use Valkey as an open-source vector store in Mem0 for high-performance key-value storage with vector search. # Valkey Vector Store [Valkey](https://valkey.io/) is an open source (BSD) high-performance key/value datastore that supports a variety of workloads and rich datastructures including vector search. ## Installation ```bash theme={null} pip install mem0ai[vector-stores] ``` ## Usage ```python Python theme={null} config = { "vector_store": { "provider": "valkey", "config": { "collection_name": "test", "valkey_url": "valkey://localhost:6379", "embedding_model_dims": 1536, "index_type": "flat" } } } m = Memory.from_config(config) messages = [ {"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"}, {"role": "assistant", "content": "How about thriller movies? They can be quite engaging."}, {"role": "user", "content": "I'm not a big fan of thriller movies but I love sci-fi movies."}, {"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."} ] m.add(messages, user_id="alice", metadata={"category": "movies"}) ``` ```typescript TypeScript theme={null} import { Memory } from 'mem0ai/oss'; const config = { vectorStore: { provider: 'valkey', config: { collectionName: 'test', valkeyUrl: 'valkey://localhost:6379', embeddingModelDims: 1536, indexType: 'flat', }, }, }; const memory = new Memory(config); const messages = [ { role: 'user', content: "I'm planning to watch a movie tonight. Any recommendations?" }, { role: 'assistant', content: 'How about thriller movies? They can be quite engaging.' }, { role: 'user', content: "I'm not a big fan of thriller movies but I love sci-fi movies." }, { role: 'assistant', content: "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future." }, ]; await memory.add(messages, { userId: 'alice', metadata: { category: 'movies' } }); ``` ## Parameters **Python** Here are the parameters available for configuring Valkey: | Parameter | Description | Default Value | | - | - | - | | `collection_name` | The name of the collection to store the vectors | `mem0` | | `valkey_url` | Connection URL for the Valkey server | `valkey://localhost:6379` | | `embedding_model_dims` | Dimensions of the embedding model | `1536` | | `index_type` | Vector index algorithm (`hnsw` or `flat`) | `hnsw` | | `hnsw_m` | Number of bi-directional links for HNSW | `16` | | `hnsw_ef_construction` | Size of dynamic candidate list for HNSW | `200` | | `hnsw_ef_runtime` | Size of dynamic candidate list for search | `10` | | `cluster_mode` | Enable cluster mode for Valkey cluster (CME) deployments | `false` | | `timezone` | Timezone for timestamp handling | `UTC` | **TypeScript** | Parameter | Description | Default Value | | - | - | - | | `collectionName` | The name of the collection to store the vectors | `mem0` | | `valkeyUrl` | Connection URL for the Valkey server | `valkey://localhost:6379` | | `embeddingModelDims` | Dimensions of the embedding model | `1536` | | `indexType` | Vector index algorithm (`hnsw` or `flat`) | `hnsw` | | `hnswM` | Number of bi-directional links for HNSW | `16` | | `hnswEfConstruction` | Size of dynamic candidate list for HNSW | `200` | | `hnswEfRuntime` | Size of dynamic candidate list for search | `10` | | `clusterMode` | Enable cluster mode for Valkey cluster (CME) deployments | `false` | | `timezone` | Timezone for timestamp handling | `UTC` | ## Cluster Mode To use Valkey with cluster mode enabled (CME), set `cluster_mode` to `true`: ```python theme={null} config = { "vector_store": { "provider": "valkey", "config": { "collection_name": "memories", "valkey_url": "valkey://cluster-endpoint:6379", "embedding_model_dims": 1536, "cluster_mode": True } } } ``` When cluster mode is enabled, the connector uses `ValkeyCluster` instead of the standalone client, which handles `MOVED`/`ASK` redirections automatically. Search queries are coordinated across all shards by the valkey-search module's built-in coordinator. See the [valkey-search documentation](https://github.com/valkey-io/valkey-search) for details on cluster mode behavior. # Cloudflare Vectorize Source: https://docs.mem0.ai/components/vectordbs/dbs/vectorize Use Cloudflare Vectorize as a vector database in Mem0 for building AI-powered applications at the edge. [Cloudflare Vectorize](https://developers.cloudflare.com/vectorize/) is a vector database offering from Cloudflare, allowing you to build AI-powered applications with vector embeddings. ### Usage ```typescript TypeScript theme={null} import { Memory } from 'mem0ai/oss'; const config = { vectorStore: { provider: 'vectorize', config: { indexName: 'my-memory-index', accountId: 'your-cloudflare-account-id', apiKey: 'your-cloudflare-api-key', dimension: 1536, // Optional: defaults to 1536 }, }, }; const memory = new Memory(config); const messages = [ {"role": "user", "content": "I'm looking for a good book to read."}, {"role": "assistant", "content": "Sure, what genre are you interested in?"}, {"role": "user", "content": "I enjoy fantasy novels with strong world-building."}, {"role": "assistant", "content": "Great! I'll keep that in mind for future recommendations."} ] await memory.add(messages, { userId: "bob", metadata: { interest: "books" } }); ``` ### Config Here are the parameters available for configuring Vectorize: **TypeScript** | Parameter | Description | Default Value | | - | - | - | | `indexName` | The name of the Vectorize index | `None` (Required) | | `accountId` | Your Cloudflare account ID | `None` (Required) | | `apiKey` | Your Cloudflare API token | `None` (Required) | | `dimension` | Dimensions of the embedding model | `1536` | # Vertex AI Vector Search Source: https://docs.mem0.ai/components/vectordbs/dbs/vertex-ai Use Google Cloud Vertex AI Vector Search as a managed vector store in Mem0 with endpoint and index configuration. ### Usage To use Google Cloud Vertex AI Vector Search with `mem0`, you need to configure the `vector_store` in your `mem0` config: ```python Python theme={null} import os from mem0 import Memory os.environ["GOOGLE_API_KEY"] = "sk-xx" config = { "vector_store": { "provider": "vertex_ai_vector_search", "config": { "endpoint_id": "YOUR_ENDPOINT_ID", # Required: Vector Search endpoint ID "index_id": "YOUR_INDEX_ID", # Required: Vector Search index ID "deployment_index_id": "YOUR_DEPLOYMENT_INDEX_ID", # Required: Deployment-specific ID "project_id": "YOUR_PROJECT_ID", # Required: Google Cloud project ID "project_number": "YOUR_PROJECT_NUMBER", # Required: Google Cloud project number "region": "YOUR_REGION", # Required: Google Cloud region "credentials_path": "path/to/credentials.json", # Optional: Defaults to GOOGLE_APPLICATION_CREDENTIALS "vector_search_api_endpoint": "YOUR_API_ENDPOINT" # Required for get operations } } } m = Memory.from_config(config) m.add("Your text here", user_id="user", metadata={"category": "example"}) ``` ```typescript TypeScript theme={null} import { Memory } from "mem0ai/oss"; // Authenticate with GOOGLE_APPLICATION_CREDENTIALS in your environment, // or pass credentialsPath / serviceAccountJson in the config below. const config = { vectorStore: { provider: "vertex_ai_vector_search", config: { endpointId: "YOUR_ENDPOINT_ID", // Required: Vector Search endpoint ID indexId: "YOUR_INDEX_ID", // Required: Vector Search index ID deploymentIndexId: "YOUR_DEPLOYMENT_INDEX_ID", // Required: Deployment-specific ID projectId: "YOUR_PROJECT_ID", // Required: Google Cloud project ID projectNumber: "YOUR_PROJECT_NUMBER", // Required: Google Cloud project number region: "YOUR_REGION", // Required: Google Cloud region credentialsPath: "path/to/credentials.json", // Optional: defaults to GOOGLE_APPLICATION_CREDENTIALS vectorSearchApiEndpoint: "YOUR_API_ENDPOINT", // Required for search/get operations }, }, }; const memory = new Memory(config); await memory.add("Your text here", { userId: "user", metadata: { category: "example" }, }); ``` ### Required Parameters **Python** | Parameter | Description | Required | | - | - | - | | `endpoint_id` | Vector Search endpoint ID | Yes | | `index_id` | Vector Search index ID | Yes | | `deployment_index_id` | Deployment-specific index ID | Yes | | `project_id` | Google Cloud project ID | Yes | | `project_number` | Google Cloud project number | Yes | | `vector_search_api_endpoint` | Vector search API endpoint | Yes (for get operations) | | `region` | Google Cloud region | Yes | | `credentials_path` | Path to service account credentials | No (defaults to GOOGLE\_APPLICATION\_CREDENTIALS) | | `service_account_json` | Service account credentials as a dictionary (alternative to `credentials_path`) | `None` | **TypeScript** | Parameter | Description | Required | | - | - | - | | `endpointId` | Vector Search endpoint ID | Yes | | `indexId` | Vector Search index ID | Yes | | `deploymentIndexId` | Deployment-specific index ID | Yes | | `projectId` | Google Cloud project ID | Yes | | `projectNumber` | Google Cloud project number | Yes | | `vectorSearchApiEndpoint` | Vector search API endpoint | Yes (for get operations) | | `region` | Google Cloud region | Yes | | `credentialsPath` | Path to service account credentials | No (defaults to GOOGLE\_APPLICATION\_CREDENTIALS) | | `serviceAccountJson` | Service account credentials as an object (alternative to `credentialsPath`) | No | # Weaviate Source: https://docs.mem0.ai/components/vectordbs/dbs/weaviate Use Weaviate as an open-source vector search engine in Mem0 for storing and retrieving vector embeddings. [Weaviate](https://weaviate.io/) is an open-source vector search engine. It allows efficient storage and retrieval of high-dimensional vector embeddings, enabling powerful search and retrieval capabilities. ### Installation ```bash Python theme={null} pip install weaviate-client ``` ```bash TypeScript theme={null} npm install weaviate-client ``` ### Usage ```python Python theme={null} import os from mem0 import Memory os.environ["OPENAI_API_KEY"] = "sk-xx" config = { "vector_store": { "provider": "weaviate", "config": { "collection_name": "test", "cluster_url": "http://localhost:8080", "auth_client_secret": None, } } } m = Memory.from_config(config) messages = [ {"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"}, {"role": "assistant", "content": "How about a thriller movie? They can be quite engaging."}, {"role": "user", "content": "I'm not a big fan of thriller movies but I love sci-fi movies."}, {"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."} ] m.add(messages, user_id="alice", metadata={"category": "movies"}) ``` ```typescript TypeScript theme={null} import { Memory } from "mem0ai/oss"; const config = { vectorStore: { provider: "weaviate", config: { collectionName: "test", embeddingModelDims: 1536, clusterUrl: "http://localhost:8080", }, }, }; const memory = new Memory(config); const messages = [ { role: "user", content: "I'm planning to watch a movie tonight. Any recommendations?", }, { role: "assistant", content: "How about a thriller movie? They can be quite engaging.", }, { role: "user", content: "I'm not a big fan of thriller movies but I love sci-fi movies.", }, { role: "assistant", content: "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future.", }, ]; await memory.add(messages, { userId: "alice", metadata: { category: "movies", }, }); ``` The TypeScript SDK picks the connection mode from the config you pass: * `clusterUrl` pointing at `localhost` connects to a local instance. * `clusterUrl` plus `apiKey` connects to a Weaviate Cloud cluster (for example `https://my-cluster.weaviate.cloud`). * Any other `clusterUrl` without an `apiKey` connects to a custom deployment, using the host and port from the URL. You can also pass a pre-configured `client` (a `WeaviateClient` instance) to reuse an existing connection. ### Config Here are the parameters available for configuring Weaviate: | Python | TypeScript | Description | Default Value | | - | - | - | - | | `collection_name` | `collectionName` | The name of the collection to store the vectors | `mem0` | | `embedding_model_dims` | `embeddingModelDims` | Dimensions of the embedding model | `1536` | | `cluster_url` | `clusterUrl` | URL for the Weaviate server | `None` | | `auth_client_secret` | `apiKey` | API key for Weaviate authentication | `None` | | `additional_headers` | `additionalHeaders` | Additional headers to include in requests | `None` | # Vector Store Providers Overview Source: https://docs.mem0.ai/components/vectordbs/overview Overview of all supported vector databases in Mem0, including Qdrant, Chroma, PGVector, Pinecone, Oracle, and more. Mem0 includes built-in support for various popular databases. Memory can utilize the database provided by the user, ensuring efficient use for specific needs. ## Supported Vector Databases See the list of supported vector databases below. > [!NOTE] > > The following vector databases are supported in the Python implementation. The TypeScript implementation currently supports Qdrant, Redis, PGVector, Supabase, LangChain, Oracle AI Vector Search, Azure AI Search, Vectorize, Amazon S3 Vectors, Milvus, Neptune Analytics, and an in-memory store. > **[Qdrant](/components/vectordbs/dbs/qdrant)** > **[Chroma](/components/vectordbs/dbs/chroma)** > **[PGVector](/components/vectordbs/dbs/pgvector)** > **[Upstash Vector](/components/vectordbs/dbs/upstash-vector)** > **[Milvus](/components/vectordbs/dbs/milvus)** > **[Pinecone](/components/vectordbs/dbs/pinecone)** > **[MongoDB](/components/vectordbs/dbs/mongodb)** > **[Oracle AI Vector Search](/components/vectordbs/dbs/oracledb)** > **[Azure](/components/vectordbs/dbs/azure)** > **[Redis](/components/vectordbs/dbs/redis)** > **[Valkey](/components/vectordbs/dbs/valkey)** > **[Elasticsearch](/components/vectordbs/dbs/elasticsearch)** > **[OpenSearch](/components/vectordbs/dbs/opensearch)** > **[Supabase](/components/vectordbs/dbs/supabase)** > **[Vertex AI](/components/vectordbs/dbs/vertex-ai)** > **[Weaviate](/components/vectordbs/dbs/weaviate)** > **[FAISS](/components/vectordbs/dbs/faiss)** > **[LangChain](/components/vectordbs/dbs/langchain)** > **[Amazon S3 Vectors](/components/vectordbs/dbs/s3-vectors)** > **[Neptune Analytics](/components/vectordbs/dbs/neptune-analytics)** > **[Databricks](/components/vectordbs/dbs/databricks)** > **[Turbopuffer](/components/vectordbs/dbs/turbopuffer)** ## Usage To utilize a vector database, you must provide a configuration to customize its usage. If no configuration is supplied, a default configuration will be applied, and `Qdrant` will be used as the vector database. For a comprehensive list of available parameters for vector database configuration, please refer to [Config](./config). ## Common issues ### Using Model with Different Dimensions If you are using a customized model with different dimensions other than 1536 (for example, 768), you may encounter the following error: `ValueError: shapes (0,1536) and (768,) not aligned: 1536 (dim 1) != 768 (dim 0)` You can add `"embedding_model_dims": 768,` to the config of the vector\_store to resolve this issue. # Development Source: https://docs.mem0.ai/contributing/development Guide to contributing code to Mem0, covering the issue-first workflow, the CLA, environment setup for the Python and TypeScript SDKs, and code quality checks. # Development Contributions We strive to make contributions **easy, collaborative, and enjoyable**. Mem0 is a polyglot monorepo containing the **Python SDK** (`mem0/`), the **TypeScript SDK** (`mem0-ts/`), CLIs, integrations, the self-hosted server, and the docs site. Follow the steps below for a smooth contribution process. > [!NOTE] > > For the complete contributor checklist, see > [CONTRIBUTING.md](https://github.com/mem0ai/mem0/blob/main/CONTRIBUTING.md) in > the repository root. By participating you agree to our > [Code of Conduct](https://github.com/mem0ai/mem0/blob/main/CODE_OF_CONDUCT.md). ## Before You Start ### 1. Open an Issue First **Always open an issue before opening a pull request.** This lets us discuss the change, avoid duplicate work, and agree on the approach before you write code. * Search [existing issues](https://github.com/mem0ai/mem0/issues) first. * If none match, open a [bug report](https://github.com/mem0ai/mem0/issues/new?template=bug_report.yml) or [feature request](https://github.com/mem0ai/mem0/issues/new?template=feature_request.yml). * For anything beyond a trivial fix, wait for a maintainer to confirm the approach. Every pull request must link to an issue using `Closes #`, and that issue must carry the `accepted` label. A maintainer applies `accepted` once we agree the change is worth making. Pull requests that do not link an accepted issue are closed automatically, with instructions to reopen once the label is applied. Documentation-only changes are exempt. > [!NOTE] > > Closed does not mean rejected. Getting the label and reopening takes about a > minute, and the check reruns on reopen. ### Show Your Work Both issue forms ask how you verified the problem: what you ran, the real output you saw, and why it is a bug rather than expected behavior. Reports without that are hard to act on and usually sit unanswered. They also ask whether AI was involved. That question is about how the problem was found and confirmed, not about how the text was written: drafting the write-up with a model is fine. The same applies to pull requests, where the AI disclosure covers the code in the diff. We ask because it tells reviewers where to look, not because it counts against you. ### 2. Sign the Contributor License Agreement (CLA) **We cannot merge any pull request until you have signed our Contributor License Agreement (CLA).** When you open your first PR, the CLA bot will comment with a link to sign: it takes less than a minute and only needs to be done once. ## Submitting Your Contribution through a PR 1. **Fork & Clone** the repository: [Mem0 on GitHub](https://github.com/mem0ai/mem0) 2. **Create a Feature Branch**: Use a dedicated branch, e.g., `feature/my-new-feature` 3. **Implement Changes**: If adding a feature or fixing a bug, be sure to: * Write necessary **tests** * Add **documentation, docstrings, and runnable examples** 4. **Code Quality Checks**: * Run **linting** to catch style issues * Ensure **all tests pass** 5. **Commit** using [Conventional Commits](https://www.conventionalcommits.org/) (`feat:`, `fix:`, `docs:`, `refactor:`, `test:`) 6. **Submit a Pull Request** against `main`, linking the issue and filling out the PR template. For detailed guidance on pull requests, refer to [GitHub's documentation](https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/creating-a-pull-request). *** ## Installing from Source If you just want to run the latest, unreleased SDK code instead of the published `mem0ai` package, for example to try out a fix before it ships, or to depend on a fork, install directly from a local clone rather than setting up the full contributor environment below. ### Python SDK ```bash theme={null} git clone https://github.com/mem0ai/mem0.git cd mem0 pip install -e . ``` This installs `mem0ai` in editable mode, so edits under `mem0/` take effect immediately without reinstalling. Add an extra if you need one, e.g. `pip install -e ".[vector-stores]"` (see `pyproject.toml` for the full list). If you are contributing to the SDK itself and need every optional dependency for the test suite, use `hatch` instead, see [Dependency Management](#dependency-management). ### TypeScript SDK ```bash theme={null} git clone https://github.com/mem0ai/mem0.git cd mem0/mem0-ts pnpm install pnpm run build ``` This builds `mem0-ts/dist` (CJS + ESM). To use it from another local project, add it as a `file:` dependency pointing at `mem0-ts`, or run `pnpm link --global` inside `mem0-ts` and `pnpm link --global mem0ai` in the consuming project. *** ## Python SDK (`mem0/`) ### Dependency Management We use `hatch` as our package manager. Install it by following the [official instructions](https://hatch.pypa.io/latest/install/). **Do NOT use `pip` or `conda` for dependency management.** Instead, follow these steps in order: ```bash theme={null} # 1. Install base dependencies make install # 2. Activate virtual environment (this will install dependencies) hatch shell # For default environment hatch -e dev_py_3_11 shell # For dev_py_3_11 (differences are mentioned in pyproject.toml) # 3. Install all optional dependencies make install_all ``` ### Pre-commit Hooks Ensure `pre-commit` is installed before contributing (hooks run ruff + isort): ```bash theme={null} pre-commit install ``` ### Linting with `ruff` Run the linter and fix any reported issues before submitting your PR (line length **120**): ```bash theme={null} make lint ``` ### Code Formatting To maintain a consistent code style, format your code and sort imports (isort, `profile = "black"`): ```bash theme={null} make format make sort ``` ### Testing with `pytest` Run tests to verify functionality before submitting your PR: ```bash theme={null} make test ``` **Note:** Some dependencies have been removed from the main dependencies to reduce package size. Run `make install_all` to install necessary dependencies before running tests. *** ## TypeScript SDK (`mem0-ts/`) We use [`pnpm`](https://pnpm.io/) (v10+) for all TypeScript packages. **Do NOT use `npm` or `yarn`.** ```bash theme={null} cd mem0-ts pnpm install pnpm run build # tsup (CJS + ESM) pnpm run test # jest (all tests) pnpm run test:unit # unit tests with coverage ``` ### Standards * **Build:** tsup * **Formatter:** Prettier * **Tests:** jest * Always run type checking after changes: `pnpm run typecheck` (or `tsc --noEmit`) * Use ES module `import` syntax: never `require()` *** ## Reporting Security Issues **Do not report security vulnerabilities through public issues or pull requests.** Please follow our [Security Policy](https://github.com/mem0ai/mem0/blob/main/SECURITY.md) to report them privately. *** ## Release Process Packages are published automatically via GitHub Actions when a GitHub Release is created with the correct tag prefix (e.g. `v*` for the Python SDK, `ts-v*` for the TypeScript SDK). See [CONTRIBUTING.md](https://github.com/mem0ai/mem0/blob/main/CONTRIBUTING.md#releasing) for the full tag-prefix table and publishing details. *** Thank you for contributing to Mem0! # Documentation Source: https://docs.mem0.ai/contributing/documentation Guide to contributing documentation to Mem0, including Mintlify setup, prerequisites, and local preview steps. # Documentation Contributions ## Prerequisites Before getting started, ensure you have **Node.js (version 23.6.0 or higher)** installed on your system. *** ## Setting Up Mintlify ### Step 1: Install Mintlify Install Mintlify globally using your preferred package manager: ```bash npm theme={null} npm i -g mintlify ``` ```bash yarn theme={null} yarn global add mintlify ``` ### Step 2: Run the Documentation Server Navigate to the `docs/` directory (where `docs.json` is located) and start the development server: ```bash theme={null} mintlify dev ``` The documentation website will be available at: `http://localhost:3000`. *** ## Custom Ports By default, Mintlify runs on **port 3000**. To use a different port, add the `--port` flag: ```bash theme={null} mintlify dev --port 3333 ``` *** By following these steps, you can efficiently contribute to Mem0's documentation. # Personalized AI Tutor Source: https://docs.mem0.ai/cookbooks/companions/ai-tutor Keep student progress and preferences persistent across tutoring sessions. > [!NOTE] > > **Works with:** Mem0 OSS (`Memory`) You can create a personalized AI Tutor using Mem0. This guide will walk you through the necessary steps and provide the complete code to get you started. ## Overview The Personalized AI Tutor leverages Mem0 to retain information across interactions, enabling a tailored learning experience. By integrating with OpenAI's GPT-4 model, the tutor can provide detailed and context-aware responses to user queries. ## Setup Before you begin, ensure you have the required dependencies installed. You can install the necessary packages using pip: ```bash theme={null} pip install openai mem0ai ``` ## Full Code Example Below is the complete code to create and interact with a Personalized AI Tutor using Mem0: ```python theme={null} import os from openai import OpenAI from mem0 import Memory # Set the OpenAI API key os.environ['OPENAI_API_KEY'] = 'sk-xxx' # Initialize the OpenAI client client = OpenAI() class PersonalAITutor: def __init__(self): """ Initialize the PersonalAITutor with memory configuration and OpenAI client. """ config = { "vector_store": { "provider": "qdrant", "config": { "host": "localhost", "port": 6333, } }, } self.memory = Memory.from_config(config) self.client = client self.app_id = "app-1" def ask(self, question, user_id=None): """ Ask a question to the AI and store the relevant facts in memory :param question: The question to ask the AI. :param user_id: Optional user ID to associate with the memory. """ # Start a streaming response request to the AI response = self.client.responses.create( model="gpt-5-mini", instructions="You are a personal AI Tutor.", input=question, stream=True ) # Store the question in memory self.memory.add(question, user_id=user_id, metadata={"app_id": self.app_id}) # Print the response from the AI in real-time for event in response: if event.type == "response.output_text.delta": print(event.delta, end="") def get_memories(self, user_id=None): """ Retrieve all memories associated with the given user ID. :param user_id: Optional user ID to filter memories. :return: List of memories. """ return self.memory.get_all(filters={"user_id": user_id}) # Instantiate the PersonalAITutor ai_tutor = PersonalAITutor() # Define a user ID user_id = "john_doe" # Ask a question ai_tutor.ask("I am learning introduction to CS. What is queue? Briefly explain.", user_id=user_id) ``` ### Fetching Memories You can fetch all the memories at any point in time using the following code: ```python theme={null} memories = ai_tutor.get_memories(user_id=user_id) for m in memories['results']: print(m['memory']) ``` ## Key Points * **Initialization**: The PersonalAITutor class is initialized with the necessary memory configuration and OpenAI client setup * **Asking Questions**: The ask method sends a question to the AI and stores the relevant information in memory * **Retrieving Memories**: The get\_memories method fetches all stored memories associated with a user ## Conclusion As the conversation progresses, Mem0's memory automatically updates based on the interactions, providing a continuously improving personalized learning experience. This setup ensures that the AI Tutor can offer contextually relevant and accurate responses, enhancing the overall educational process. *** > **[Build a Mem0 Companion](/cookbooks/essentials/building-ai-companion)** > > Learn the foundations of memory-powered companions with production-ready patterns. > **[Travel Assistant with Mem0](/cookbooks/companions/travel-assistant)** > > Build a travel companion that remembers preferences and past conversations. # Self-Hosted AI Companion Source: https://docs.mem0.ai/cookbooks/companions/local-companion-ollama Run Mem0 end-to-end on your machine using Ollama-powered LLMs and embedders. > [!NOTE] > > **Works with:** Mem0 OSS (`Memory`) Mem0 can be utilized entirely locally by leveraging Ollama for both the embedding model and the language model (LLM). This guide will walk you through the necessary steps and provide the complete code to get you started. ## Overview By using Ollama, you can run Mem0 locally, which allows for greater control over your data and models. This setup uses Ollama for both the embedding model and the language model, providing a fully local solution. ## Setup Before you begin, ensure you have Mem0 and Ollama installed and properly configured on your local machine. ## Full Code Example Below is the complete code to set up and use Mem0 locally with Ollama: ```python theme={null} from mem0 import Memory config = { "vector_store": { "provider": "qdrant", "config": { "collection_name": "test", "host": "localhost", "port": 6333, "embedding_model_dims": 768, # Change this according to your local model's dimensions }, }, "llm": { "provider": "ollama", "config": { "model": "llama3.1:latest", "temperature": 0, "max_tokens": 2000, "ollama_base_url": "http://localhost:11434", # Ensure this URL is correct }, }, "embedder": { "provider": "ollama", "config": { "model": "nomic-embed-text:latest", # Alternatively, you can use "snowflake-arctic-embed:latest" "ollama_base_url": "http://localhost:11434", }, }, } # Initialize Memory with the configuration m = Memory.from_config(config) # Add a memory m.add("I'm visiting Paris", user_id="john") # Retrieve memories memories = m.get_all(filters={"user_id": "john"}) ``` ## Key Points * **Configuration**: The setup involves configuring the vector store, language model, and embedding model to use local resources * **Vector Store**: Qdrant is used as the vector store, running on localhost * **Language Model**: Ollama is used as the LLM provider, with the `llama3.1:latest` model * **Embedding Model**: Ollama is also used for embeddings, with the `nomic-embed-text:latest` model ## Conclusion This local setup of Mem0 using Ollama provides a fully self-contained solution for memory management and AI interactions. It allows for greater control over your data and models while still leveraging the powerful capabilities of Mem0. *** > **[Configure Open Source](/open-source/configuration)** > > Explore advanced configuration options for vector stores, LLMs, and embedders. > **[Build a Mem0 Companion](/cookbooks/essentials/building-ai-companion)** > > Learn core companion patterns that work with any LLM provider. # Build a Node.js Companion Source: https://docs.mem0.ai/cookbooks/companions/nodejs-companion Build a JavaScript fitness coach that remembers user goals run after run. > [!NOTE] > > **Works with:** Mem0 OSS (`Memory`) You can create a personalized AI Companion using Mem0. This guide will walk you through the necessary steps and provide the complete code to get you started. ## Overview The Personalized AI Companion leverages Mem0 to retain information across interactions, enabling a tailored learning experience. It creates memories for each user interaction and integrates with OpenAI's GPT models to provide detailed and context-aware responses to user queries. ## Setup Before you begin, ensure you have Node.js installed and create a new project. Install the required dependencies using npm: ```bash theme={null} npm install openai mem0ai ``` ## Full Code Example Below is the complete code to create and interact with an AI Companion using Mem0: ```javascript theme={null} import { OpenAI } from 'openai'; import { Memory } from 'mem0ai/oss'; import * as readline from 'readline'; const openaiClient = new OpenAI(); const memory = new Memory(); async function chatWithMemories(message, userId = "default_user") { const relevantMemories = await memory.search(message, { filters: { user_id: userId } }); const memoriesStr = relevantMemories.results .map(entry => `- ${entry.memory}`) .join('\n'); const systemPrompt = `You are a helpful AI. Answer the question based on query and memories. User Memories: ${memoriesStr}`; const messages = [ { role: "system", content: systemPrompt }, { role: "user", content: message } ]; const response = await openaiClient.chat.completions.create({ model: "gpt-5-mini", messages: messages }); const assistantResponse = response.choices[0].message.content || ""; messages.push({ role: "assistant", content: assistantResponse }); await memory.add(messages, { userId: userId }); return assistantResponse; } async function main() { const rl = readline.createInterface({ input: process.stdin, output: process.stdout }); console.log("Chat with AI (type 'exit' to quit)"); const askQuestion = () => { return new Promise((resolve) => { rl.question("You: ", (input) => { resolve(input.trim()); }); }); }; try { while (true) { const userInput = await askQuestion(); if (userInput.toLowerCase() === 'exit') { console.log("Goodbye!"); rl.close(); break; } const response = await chatWithMemories(userInput, "sample_user"); console.log(`AI: ${response}`); } } catch (error) { console.error("An error occurred:", error); rl.close(); } } main().catch(console.error); ``` ### Key Components 1. **Initialization** * The code initializes both OpenAI and Mem0 Memory clients * Uses Node.js's built-in readline module for command-line interaction 2. **Memory Management (chatWithMemories function)** * Retrieves relevant memories using Mem0's search functionality * Constructs a system prompt that includes past memories * Makes API calls to OpenAI for generating responses * Stores new interactions in memory 3. **Interactive Chat Interface (main function)** * Creates a command-line interface for user interaction * Handles user input and displays AI responses * Includes graceful exit functionality ### Environment Setup Make sure to set up your environment variables: ```bash theme={null} export OPENAI_API_KEY=your_api_key ``` ### Conclusion This implementation demonstrates how to create an AI Companion that maintains context across conversations using Mem0's memory capabilities. The system automatically stores and retrieves relevant information, creating a more personalized and context-aware interaction experience. As users interact with the system, Mem0's memory system continuously learns and adapts, making future responses more relevant and personalized. This setup is ideal for creating long-term learning AI assistants that can maintain context and provide increasingly personalized responses over time. *** > **[Partition Memories by Entity](/cookbooks/essentials/entity-partitioning-playbook)** > > Separate user, agent, and session context to keep your companion consistent. > **[Quickstart Demo with Mem0](/cookbooks/companions/quickstart-demo)** > > Run the full showcase app to see memory-powered companions in action. # Interactive Memory Demo Source: https://docs.mem0.ai/cookbooks/companions/quickstart-demo Spin up the showcase companion app to see Mem0 memories in action. > [!NOTE] > > **Works with:** Mem0 Platform You can create a personalized AI Companion using Mem0. This guide will walk you through the necessary steps and provide the complete setup instructions to get you started.