# MemOS Overview (/memos_cloud/getting_started/overview) MemOS is a managed memory platform for AI applications and Agents. After information is written to MemOS, the system automatically produces, recalls, and updates memories, then keeps providing concise and accurate context in later requests. You do not need to repeatedly solve the problem of "how AI remembers." By calling the cloud service APIs, you can add long-term memory to your application. ## What MemOS Gives You - **Long-term continuity for AI**: preserve user facts, preferences, and task progress across sessions, so AI does not start from zero every time. - **Useful memories over time**: continuously extract, deduplicate, update, and correct memories to keep them accurate and effective. - **Lower engineering cost**: use a production memory platform that manages memory production, scheduling, recall, and lifecycle management instead of building the full memory stack yourself. - **Room to extend**: support knowledge bases, Skills, tool memories, multimodal input, and Agent workflows for broader business scenarios. ## Core Workflow ![How MemOS Works](https://cdn.memtensor.com.cn/img/1779432830540_evti9q_compressed.png) ### Add Raw Information Pass user chats, behavior events, knowledge files, images, Skills, and other raw information into MemOS. ### Produce and Update Memories MemOS processes raw information in the background into retrievable memory content, then continuously updates memories, schedules them in real time, corrects them with natural-language feedback, and manages their full lifecycle. ### Retrieve Memories When retrieving memories, MemOS filters and recalls the most relevant memories for model responses, Agent decisions, or business workflows, helping AI maintain continuous understanding in later requests. ## Choose How to Start - [Quick Start](/memos_cloud/getting_started/quick_start): Create your first project from here - [How MemOS Works](/memos_cloud/introduction/mem_production): Understand the memory mechanism before integration - [Cloud Service & Open Source](/memos_cloud/getting_started/cloud_and_opensource): Compare cloud service and open-source self-hosting options - [Use in Agents](/memos_cloud/getting_started/agent_usage): Integrate with OpenClaw, Hermes, or other AI tools --- # Cloud Service & Open Source (/memos_cloud/getting_started/cloud_and_opensource) ## 1. Choose the MemOS Solution That Fits You MemOS provides two memory solutions for AI applications: - **MemOS Cloud Service**: a managed service that simplifies development and daily operation. It is suitable when you want to quickly build and iterate AI applications. - **MemOS Open Source**: a self-hosted solution that you deploy in your own environment. It is suitable when you need deeper customization, secondary development, or full infrastructure control. > Whether you choose the cloud service or the open-source framework, MemOS helps your AI application gain persistent memory. > You can start with the cloud service for a quick trial, then switch to self-hosted deployment when your business needs it. ## 2. Selection Guide ### Choose MemOS Cloud Service - **Fast integration**: enable memory for your AI application in a few minutes, so you can focus on business logic and product features instead of maintaining storage and memory management infrastructure. - **Low-cost validation**: use free trial quotas to validate the solution and product effect before deeper integration. - **Logs and monitoring**: view call logs in the console and inspect the request chain for debugging, monitoring, and optimization. - **Advanced API capabilities**: knowledge bases and continuous dialogue are available through APIs for more flexible customization and integration. ### Choose MemOS Open Source - **Custom configuration**: freely choose LLM providers, inference backends, deployment strategies, and related infrastructure. - **Code extension**: modify the codebase directly, extend features as needed, and contribute improvements back to the community. ## 3. Still Not Sure? - [Try the free platform](/memos_cloud/getting_started/quick_start): register and sign in to [MemOS Cloud](https://memos-dashboard.openmem.net/quickstart) to try the core features. - [Explore the open-source solution](/open_source/getting_started/installation): clone the repository and run MemOS locally. --- # Use in Agents (/memos_cloud/getting_started/agent_usage) In addition to calling the cloud APIs directly, you can connect MemOS to your AI workflow through plugins, MCP, CLI, and other integration methods if you use: - Agent frameworks such as OpenClaw and Hermes. - AI clients such as Cursor, VS Code, Claude Desktop, Cline, and Chatbox. - Any Agent or development environment that can execute shell commands. These integration methods help you save tokens while adding long-term memory to your Agent workflows. ## Quick Integration (Recommended) You can connect MemOS automatically by chatting with your Agent in natural language. Once it is done, you can start chatting right away with no extra setup. ### Use the Plugin MemOS currently provides a cloud plugin deeply integrated with **OpenClaw**. If you use OpenClaw, prefer the plugin integration. Copy the following prompt and paste it into your OpenClaw chat: **View the OpenClaw plugin setup prompt** ```text api-key Help me set up the MemOS OpenClaw plugin. Follow these steps: 1. Verify the API Key Check the value of MEMOS_API_KEY in the commands of step 2: - If it is already a real API Key starting with mpg-, go straight to step 2 - If it is still a placeholder, guide the user to open https://memos-dashboard.openmem.net/quickstart/ to get an API Key, then replace the placeholder in the commands with the real Key 2. Configure the API Key environment variable Detect the current operating system first, then write it accordingly: macOS / Linux: mkdir -p ~/.openclaw echo 'MEMOS_API_KEY=YOUR_API_KEY' >> ~/.openclaw/.env Windows PowerShell: [System.Environment]::SetEnvironmentVariable("MEMOS_API_KEY", "YOUR_API_KEY", "User") 3. Install and enable the plugin openclaw plugins install @memtensor/memos-cloud-openclaw-plugin@latest openclaw gateway restart 4. Verify the installation Read ~/.openclaw/openclaw.json (%USERPROFILE%\.openclaw\openclaw.json on Windows), and confirm that under plugins.entries, memos-cloud-openclaw-plugin has enabled set to true ``` OpenClaw will install the plugin, prompt you to get an API Key, and complete all the configuration. ### Use the MemOS CLI The MemOS CLI provides a more universal way to integrate with Agents and works with any Agent framework that can execute shell commands. Copy the following prompt and send it to your Agent: **View the CLI setup prompt** ```text api-key Help me set up the MemOS CLI development environment. Follow these steps: 1. Install the MemOS CLI globally npm i -g @memtensor/memos-cloud-cli 2. Initialize the CLI configuration memos init --api-key YOUR_API_KEY --agent For step 2, pass the --agent parameter matching the Agent the user is using. If the value of --api-key is already a real Key starting with mpg-, run it directly; if it is still a placeholder, first guide the user to open https://memos-dashboard.openmem.net/ to get an API Key and replace it. ``` Your Agent will install the MemOS CLI and configure the corresponding Skill automatically ([View supported Agents](/mcp_agent/cli/guide#_31-use-with-agents)). ## Manual Configuration ### 1. Before You Start - Register and sign in to the [MemOS Cloud platform](https://memos-dashboard.openmem.net/quickstart). - Get an API Key from the [API Key page](https://memos-dashboard.openmem.net/apikeys). ### 2. Use the Plugin #### Configure the API Key The plugin reads OpenClaw-related environment variables or `.env` files. The minimal configuration is: ```env MEMOS_API_KEY=YOUR_API_KEY ``` You can also write it directly into the OpenClaw environment file: ```bash [macOS / Linux] mkdir -p ~/.openclaw echo 'MEMOS_API_KEY=YOUR_API_KEY' >> ~/.openclaw/.env ``` ```powershell [Windows PowerShell] [System.Environment]::SetEnvironmentVariable("MEMOS_API_KEY", "YOUR_API_KEY", "User") ``` #### Install and enable the plugin ```bash openclaw plugins install @memtensor/memos-cloud-openclaw-plugin@latest openclaw gateway restart ``` > **Tip**: Windows users: if you encounter `Error: spawn EINVAL`, see [OpenClaw Cloud Plugin - Manual Install](/openclaw/guide) for an alternative method. Confirm that the plugin is enabled in `~/.openclaw/openclaw.json`: ```json { "plugins": { "entries": { "memos-cloud-openclaw-plugin": { "enabled": true } } } } ``` #### Start chatting You can now have multi-turn conversations with OpenClaw: - First session: "I prefer using Python." - Second session after restart: "Do you remember which programming language I like?" > **Tip**: The OpenClaw plugin also supports multi-Agent isolation, Config UI, filters, and more detailed configuration. See the [OpenClaw Cloud Plugin](/openclaw/guide) for full configuration. ### 3. Use MCP Mainstream clients that support MCP include **Cursor, Claude Desktop, Cline, VS Code / Trae, and Chatbox**. Taking Cursor as an example, after configuration, Cursor can directly call MemOS memory tools and use memory across clients. #### Add an MCP Server In Cursor, go to: ```text Cursor Settings → Tools & MCP → Add Custom MCP ``` Then add this to `mcp.json`: ```json { "mcpServers": { "memos-api-mcp": { "timeout": 60, "type": "stdio", "command": "npx", "args": [ "-y", "@memtensor/memos-api-mcp@latest" ], "env": { "MEMOS_API_KEY": "YOUR_API_KEY", "MEMOS_USER_ID": "your-user-id", "MEMOS_CHANNEL": "MODELSCOPE" } } } } ``` After configuration, confirm that Cursor's MCP tool list shows tools such as `add_message` and `search_memory`. #### Cursor Rules To make Cursor use memories more reliably, add rules like these to User Rules: ```text Before answering the user's question, call MemOS search_memory to search long-term memories related to the current task. After answering, if this turn contains new user facts, preferences, project background, or other information useful in the long term, call add_message to write it into MemOS. Only use memories relevant to the current task. Ignore memories that are irrelevant, outdated, or about the wrong subject. Do not expose internal implementation details such as "memory store" or "retrieval results" to the user. ``` #### Start chatting - First session: tell it who you are, your hobbies, and your profession, and ask it to remember. - Second session after restart: ask it who you are. > **Tip**: Claude Desktop, Cline, Chatbox, and other clients are configured similarly, though the entry points differ. For more examples, see the [MCP Guide](/mcp_agent/mcp/guide). ### 4. Use CLI + Skill If your Agent framework can execute shell commands (e.g. Cursor, Codex, Claude Code, Hermes, or DeepSeek Harness), you can use the MemOS CLI to install a memory Skill with one command, enabling your Agent to automatically search and write memories. > **Tip**: Using OpenClaw as an example, in the LOCOMO evaluation, using MemOS CLI alone reduced token usage by about 65.5%; integrating MemOS Cloud + CLI improved accuracy from 66.60% to 77.27%. #### Install the CLI ```bash npm install -g @memtensor/memos-cloud-cli ``` #### Initialize and install Skill ```bash memos init --agent cursor memos init --api-key YOUR_API_KEY --agent cursor ``` `--agent` installs the MemOS memory Skill into the corresponding Agent's skills directory. `--agent` is currently required; if it is omitted, the command fails because the CLI needs to know where to install the Skill. Supported targets: ```bash memos init --agent cursor # ~/.cursor/skills/memos/ memos init --agent codex # ~/.codex/skills/memos/ memos init --agent claude # ~/.claude/skills/memos/ memos init --agent openclaw # ~/.openclaw/skills/memos/ memos init --agent hermes # ~/.hermes/skills/memos/ memos init --agent deepseek # ~/.dsh/skills/memos-memory/ ``` For DeepSeek Harness, initialization also registers a native lifecycle plugin. It retrieves relevant memories and injects them into context before each turn, then writes new memories after a normally completed turn. When `DSH_HOME` is set, the Skill is installed at `$DSH_HOME/skills/memos-memory/`. Restart DeepSeek Harness after initialization. #### Start chatting Once installed, the Agent will automatically load the Skill. During each conversation turn, the Agent will: 1. **Before answering** — automatically run `memos search` to retrieve long-term memories related to the current task 2. **After answering** — automatically run `memos add` to write new facts, preferences, etc. into MemOS You can verify the same way: - First session: "I prefer using Python." - Second session after restart: "Do you remember which programming language I like?" > **Tip**: The CLI also supports manual memory operations in a terminal (`add`, `search`, `get`, `origin`, `delete`, etc.). If you only use the CLI in a terminal and do not install an Agent Skill, configure the API Key, default user ID, and default conversation ID with `memos config set`. See [MemOS CLI](/mcp_agent/cli/guide) for the full command reference. ### Which Integration Should You Choose? | Integration | Best for | Priority | | --- | --- | --- | | Plugin | OpenClaw and other Agent environments deeply integrated with MemOS | Prefer first; highest automation | | CLI + Skill | Any Agent framework that can execute shell commands | Most portable; works across frameworks | | MCP | Cursor, Claude Desktop, Cline, Chatbox, and other AI clients | Use when the client supports MCP | | API / SDK | Self-built Agents, chatbots, or business applications | Most control; best for production integration | ### Next Steps - [OpenClaw Cloud Plugin](/openclaw/guide): View full installation, enabling, and advanced configuration for the OpenClaw plugin - [MemOS CLI](/mcp_agent/cli/guide): View the full CLI command reference and Skill installation guide - [MCP Guide](/mcp_agent/mcp/guide): Learn how to configure MCP in Cursor, Claude Desktop, Cline, and other clients - [API / SDK](/memos_cloud/getting_started/quick_start): Start here if you are building your own Agent or application --- # Integrate into Your App (/memos_cloud/getting_started/quick_start) ## Use MemOS Skill to Quickly Integrate MemOS Cloud into Your AI App (Recommended) If you are building your AI application with Agent tools such as Claude Code or Cursor, copy the prompt below and send it to your tool: **Expand to view the Skill setup prompt** ```text Help me integrate MemOS Cloud into this project to add long-term memory to my Agent product. Please follow these steps: 1. Install MemOS Skill (skip if already installed): npx skills add https://github.com/MemTensor/MemOS-Cloud-Skill --skill memos-cloud -g -y Auto-fill the --agent argument based on the current Agent environment. 2. Read SKILL.md under the Skill's install path, and strictly follow its instructions in order. 3. Generate complete MemOS Cloud integration code based on this project's actual tech stack and architecture. ``` Your Agent tool will automatically install and use MemOS Skill and integrate MemOS Cloud into your AI application. ## Manual Integration When you integrate MemOS into an AI application, the full flow looks like this. MemOS provides two core APIs: [see API docs](/api_docs/core/add_message). - `addMessage`: send raw conversations to MemOS. MemOS automatically processes and stores them as memories. - `searchMemory`: recall memories in later conversations, so AI responses better match user needs. ![image.svg](https://cdn.memtensor.com.cn/img/1762434889291_h9co0h_compressed.png) ### 1. Before Calling the API - Register and sign in to [MemOS Cloud](https://memos-dashboard.openmem.net/quickstart). - Get an API Key from the [API Key page](https://memos-dashboard.openmem.net/apikeys). - Prepare an environment that can send HTTP requests, such as Python or cURL. ### 2. Create a Memory #### Install the SDK If you choose the Python SDK, make sure Python 3.10+ is installed, then run: ```bash pip install MemoryOS -U ``` #### Set the API Key ```python [Python (HTTP)] import requests API_KEY = "YOUR_API_KEY" BASE_URL = "https://memos.memtensor.cn/api/openmem/v1" ``` ```python [Python (SDK)] from memos.api.client import MemOSClient client = MemOSClient(api_key="YOUR_API_KEY") ``` ```bash [Curl] export MEMOS_API_KEY="YOUR_API_KEY" export MEMOS_BASE_URL="https://memos.memtensor.cn/api/openmem/v1" ``` #### Add Raw Information Session A happened on 2025-06-10. The user chose 7 Days Inn as the hotel for a summer trip to Guangzhou. You only need to pass the raw conversation records to MemOS. ```python [Python (HTTP)] data = { "user_id": "memos_user_123", "conversation_id": "0610", "messages": [ {"role": "user", "content": "I have booked a summer trip to Guangzhou. Which hotel chains are available?"}, {"role": "assistant", "content": "You can consider 7 Days Inn, Ji Hotel, Hilton, and others."}, {"role": "user", "content": "I will choose 7 Days Inn."}, {"role": "assistant", "content": "Got it. Feel free to ask if you have other questions."} ] } res = requests.post( f"{BASE_URL}/add/message", headers={"Authorization": f"Token {API_KEY}"}, json=data ) print(res.json()) ``` ```python [Python (SDK)] messages = [ {"role": "user", "content": "I have booked a summer trip to Guangzhou. Which hotel chains are available?"}, {"role": "assistant", "content": "You can consider 7 Days Inn, Ji Hotel, Hilton, and others."}, {"role": "user", "content": "I will choose 7 Days Inn."}, {"role": "assistant", "content": "Got it. Feel free to ask if you have other questions."} ] res = client.add_message( messages=messages, user_id="memos_user_123", conversation_id="0610" ) print(res) ``` ```bash [Curl] curl "$MEMOS_BASE_URL/add/message" \ -H "Authorization: Token $MEMOS_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "user_id": "memos_user_123", "conversation_id": "0610", "messages": [ {"role": "user", "content": "I have booked a summer trip to Guangzhou. Which hotel chains are available?"}, {"role": "assistant", "content": "You can consider 7 Days Inn, Ji Hotel, Hilton, and others."}, {"role": "user", "content": "I will choose 7 Days Inn."}, {"role": "assistant", "content": "Got it. Feel free to ask if you have other questions."} ] }' ``` #### Search Relevant Memories Session B happened on 2025-09-28. The user asks the AI to recommend a National Day travel destination and hotel. Use the user's message as the query to search MemOS memories. ```python [Python (HTTP)] data = { "query": "I want to travel during the National Day holiday. Please recommend a city I have not been to and a hotel brand I have not stayed at.", "user_id": "memos_user_123", "conversation_id": "0928" } res = requests.post( f"{BASE_URL}/search/memory", headers={"Authorization": f"Token {API_KEY}"}, json=data ) print(res.json()) ``` ```python [Python (SDK)] res = client.search_memory( query="I want to travel during the National Day holiday. Please recommend a city I have not been to and a hotel brand I have not stayed at.", user_id="memos_user_123", conversation_id="0928" ) print(res) ``` ```bash [Curl] curl "$MEMOS_BASE_URL/search/memory" \ -H "Authorization: Token $MEMOS_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "query": "I want to travel during the National Day holiday. Please recommend a city I have not been to and a hotel brand I have not stayed at.", "user_id": "memos_user_123", "conversation_id": "0928" }' ``` ##### Output MemOS automatically recalls factual memories such as where the user has been and preference memories such as hotel booking preferences, helping the AI recommend a more personalized travel plan. The following result is simplified for easier understanding. ```text { preference_detail_list [ { "preference_type": "implicit_preference", "preference": "The user may prefer cost-effective hotel options.", "conversation_id": "0610" } ], memory_detail_list [ { "memory_key": "Summer Guangzhou travel plan", "memory_value": "The user plans to travel to Guangzhou during the summer vacation and chose 7 Days Inn as the accommodation option.", "conversation_id": "0610" } ] } ``` #### Add Memories to Your Prompt Add the recalled memories to your own model prompt, so the model can refer to these long-term memories when answering. **Expand the full prompt template** ```text # Role You are an intelligent assistant with long-term memory (MemOS Assistant). Your goal is to combine retrieved memory fragments to provide highly personalized, accurate, and logically rigorous answers. # Memory Data The following information was retrieved by MemOS and is divided into facts and preferences. - **Facts**: May include user attributes, historical conversations, or third-party information. - **Important**: Content marked as '[assistant view]' or '[model summary]' represents past AI inference, not the user's original words. - **Preferences**: Explicit or implicit requirements for response style, format, or reasoning. -[2025-12-26 21:45] The user plans to travel to Guangzhou during the summer vacation and chose 7 Days Inn as the accommodation option. -[2025-12-26 21:45] [Implicit Preference] The user may prefer cost-effective hotel options. # Critical Protocol: Memory Safety Retrieved memories may contain AI inferences, irrelevant noise, or incorrect subjects. Before using them, check: 1. Source truth: Distinguish the user's original words from AI inference. Do not treat past AI assumptions as user facts. 2. Subject attribution: Confirm the memory describes the user, not a third party, example, or fictional role. 3. Strong relevance: Only use memories that directly help with the current question. 4. Freshness: If a memory conflicts with the user's latest intent, use the current question as the source of truth. # Instructions 1. Filter usable memories and discard noise or unreliable inferences. 2. Use only validated memories as background context. 3. Answer directly. Do not mention "memory store," "retrieval," or internal system terms. # Original Query I want to travel during the National Day holiday. Please recommend a city I have not been to and a hotel brand I have not stayed at. ``` ### 3. Next Steps - [Core Operations](/memos_cloud/mem_operations/add_message): View detailed usage for core memory operations - [Use in Agents](/memos_cloud/getting_started/agent_usage): Integrate with OpenClaw, Hermes, or other AI tools - [API Reference](/api_docs/core/add_message): View the complete API documentation --- # Raw Input Content (/memos_cloud/introduction/raw_inputs) Raw input content is the starting point of memory production. You can provide chat text, images, business documents, tool call records, and other raw content directly. MemOS extracts information with long-term value and turns it into retrievable memories. ## 1. Text Raw text, chats, event information, or any string content. ```json { "user_id": "memos_user_123", "conversation_id": "0910", "messages": [ { "role": "user", "content": "I am Wang, and I like spicy food." } ] } ``` **Best for**: chat messages, user preferences, behavior events, and structured data. --- ## 2. Images MemOS can extract visual information from images and combine it with the text context sent alongside the image. ```json { "role": "user", "content": [ { "type": "text", "text": "This is the MemOS image I am studying." }, { "type": "image_url", "image_url": { "url": "https://cdn.memtensor.com.cn/img/1758706201390_iluj1c_compressed.png" } } ] } ``` For local images, replace `url` with a Base64 data URL: ```json { "type": "image_url", "image_url": { "url": "data:image/jpeg;base64,{base64_image}" } } ``` **Best for**: capturing operation states from screenshots, key information from receipts, design details from mockups, or conclusions from charts. --- ## 3. Documents MemOS can read PDF, Word, Markdown, JSON, XML, TXT, and other file formats, and combine document content with the text context sent alongside the file. ```json { "role": "user", "content": [ { "type": "file", "file": { "file_data": "https://cdn.memtensor.com.cn/file/MemOS 2.pdf" } } ] } ``` For local documents, set `file_data` to a Base64 string. **Best for**: extracting conclusions from reports, constraints from requirement documents, rules from policy materials, or key settings from configuration files. --- ## 4. Tool Calls Agent tool decisions and tool results. MemOS generates tool memories so the Agent can call tools more reliably later. ```json { "messages": [ { "role": "assistant", "tool_calls": [{ "id": "call_123", "type": "function", "function": { "name": "get_weather", "arguments": "{\"location\":\"Beijing\"}" } }] }, { "role": "tool", "tool_call_id": "call_123", "content": [{ "type": "text", "text": "{\"temperature\":\"7°C\"}" }] } ] } ``` **Best for**: recording tool selection, parameters, and returned results to improve future tool call success. See [Tool Memory](/memos_cloud/features/tool_calling). --- ## 5. Natural Language Feedback Corrections and supplements from users about answers, memories, or knowledge. You can pass the feedback text directly without locating a specific memory. ```json { "user_id": "memos_user_123", "feedback_content": "The purchase limit for office software is 600 yuan, not 800 yuan.", "allow_knowledgebase_ids": ["kb_xxx"] } ``` **Best for**: correcting wrong memories, updating outdated information, and filling missing details. See [Add Feedback](/memos_cloud/mem_operations/add_feedback). --- ## 6. Knowledge Bases and Skills Project-level knowledge documents or Agent skill packages. These are managed separately from user memories. ```json { "knowledgebase_id": "kb_xxx", "file": [ { "type": "document", "content": "https://cdn.memtensor.com.cn/file/MemOS 2.pdf" }, { "type": "skill", "name": "return_process.md", "content": "data:text/markdown;base64,{base64_skill}" } ] } ``` **Best for**: importing product documentation, policies, SOPs, FAQs, or Agent skill packages. See [Knowledge Base](/memos_cloud/features/knowledge_base) and [Self-Evolving](/memos_cloud/features/self-evolving). --- ## 7. Content Limits | Type | Limit | | --- | --- | | Text messages | 40,000 tokens per request | | Files | URL and Base64 supported, ≤ 20 files per request, each file ≤ 100 MB / 500 pages | | Images | URL and Base64 data URL supported | | Knowledge Base documents | URL and Base64 supported, ≤ 20 files per request, each file ≤ 100 MB / 500 pages | | Single Skill file | URL and Base64 supported, ≤ 100 KB, must include `name` and `description` | | Skill ZIP package | URL and Base64 supported, ≤ 20 MB, ≤ 200 files after extraction, must include `SKILL.md` | --- ## 8. API Overview | Entry | Accepted content | Typical use | | --- | --- | --- | | `add/message` | Text, images, documents, Tool Calls | Write user memories such as facts, preferences, and tool experience | | `chat` | Current user query | Recall memories + generate an answer + write the new conversation | | `extract/memory` | Plain text messages | Extract facts/preferences only, without writing to the long-term memory store | | `add/feedback` | Natural language feedback | Correct or supplement existing memories | | `add/knowledgebase-file` | Knowledge documents, Skill files | Build project knowledge bases and Agent skill libraries | --- ## 9. Explore Different APIs - [Add Message](/memos_cloud/mem_operations/add_message): Write text, images, documents, and Tool Calls - [Chat](/memos_cloud/mem_operations/chat): Use the conversation API with memory recall - [Knowledge Base](/memos_cloud/features/knowledge_base): Manage project documents, policies, and SOPs - [Add Feedback](/memos_cloud/mem_operations/add_feedback): Correct wrong memories or fill missing information --- # Memory Categories (/memos_cloud/introduction/memory_types) MemOS generates and uses different categories of memories. They play different roles during recall: some confirm facts, some describe preferences, some summarize user profiles and complete events, some guide how an Agent should complete a task, and some provide supporting knowledge. Distinguishing memory categories helps retrieval return more relevant content and gives the model more accurate context. ## 1. Fact Memories Fact memories describe relatively objective information, usually from explicit user statements, behavior events, files, or feedback. Common examples: - The user lives in Shanghai. - The user's device is a 13-inch Intel MacBook Pro. Fact memories are useful for answering questions such as "who is the user", "what has the user done", "what state is the user currently in", and "whether something happened". > **Note**: Memories may change over time. MemOS combines [Time Awareness](/memos_cloud/introduction/time_awareness) and [Memory Lifecycle Management](/memos_cloud/introduction/mem_lifecycle) to handle these changes. ## 2. Preference Memories Preference memories describe long-term or stage-specific user tendencies. They may come from explicit user statements, or from summaries and inferences based on repeated behavior. Common examples: - The user prefers concise and direct answers. - When planning trips, the user prefers cultural attractions and dislikes shopping malls. - When buying pet food, the user needs to avoid chicken flavor. Preference memories are useful for recommendation, generation, ranking, and personalized decisions. They do more than answer "what did the user say"; they help the Agent decide "what would better fit this user". ## 3. Profile Profile memories build a structured picture of a user. Scattered information from conversations is extracted and mapped to predefined attribute fields, then automatically updated and completed as the conversation continues. Core characteristics include: - **Structured**: the profile is made up of predefined fields, stored centrally and ready to use directly, instead of being scattered across separate memories. - **Continuously updated**: as the conversation continues, MemOS automatically updates attribute fields so the profile always reflects the user's latest state. - **Field-level control**: you can configure whether each field allows automatic updates. Key fields can be locked to keep core settings stable. Example structure: ```plaintext Basic Info Name: Zhang San Occupation: Engineer Location: Hangzhou Interests Hobbies: camping, indie games Favorite music: folk Personality Tags Three keywords: cheerful, curious, meticulous ``` Suitable for scenarios such as personal assistants and emotional companion / virtual characters, to strengthen conversation consistency and stability and let AI remember who the user is over the long term. See [Profile](/memos_cloud/features/profile). ## 4. Event Memory Event memory extracts structured events from conversations, keeping key elements such as time, location, and participants. Common examples: - On June 14, Zhang San went camping with friends by West Lake, watched the stars together at night, and talked about life plans. - On June 10, customer Li Si submitted a return request. The support agent approved it, and it was completed on June 13. Event memory summarizes and organizes a segment of conversation, preserving the key timeline, location, and participants. See [Event Memory](/memos_cloud/features/event_memory). ## 5. Self-Evolving Skills MemOS automatically extracts skills from historical messages to enable self-evolving memory. You can also upload existing skill packages to a knowledge base. Tasks with stable steps, such as travel planning, reimbursement review, and customer issue triage, are good candidates for skills. See [Self-Evolving](/memos_cloud/features/self-evolving). ## 6. Tool Memories Tool memories record "how to use tools". They are distilled from Tool Schemas, tool call parameters, tool results, and tool trajectories. They help the Agent select tools, fill parameters, and use returned results more reliably. See [Tool Memory](/memos_cloud/features/tool_calling). ## 7. Knowledge Base Memories Knowledge Base memories come from project-level documents, policies, manuals, FAQs, process files, or Skill files. They are not part of a single user's personal history and are better shared by multiple users or Agents. Common examples: - Company reimbursement policy. - Product manual. - Return and after-sales policy. Knowledge Base memories can participate in recall together with user memories. For example, when an employee asks "The intranet proxy does not open. Which version should I reinstall?", the knowledge base provides installation instructions, while user fact memory adds that the employee uses an Intel MacBook Pro. Combining both leads to a more accurate answer. See [Knowledge Base](/memos_cloud/features/knowledge_base). ## 8. How to Generate and Use Them ### Generating memories Currently, MemOS generates all memory categories by default. You can use `allow_memory_view` to control which categories are allowed to be generated: - Fact, preference, event, and skill memories are automatically extracted and updated after adding messages. - Profile memories require creating a template and binding it to the user first. They are then automatically extracted and updated when messages are added. - Tool memories require Tool Call information with `"role": "tool"` when adding messages. - Knowledge Base memories require creating a knowledge base and uploading documents. ### Using memories When searching memories, use `include_memory_view` to control which memory categories can be retrieved. If omitted, fact memories and preference memories are recalled by default. The mapping between values is as follows: | Memory Category | Value | | --- | --- | | Fact Memory | `detail_factual` | | Preference Memory | `preference` | | Profile | `profile` | | Event Memory | `event` | | Skill Memory | `skill` | | Tool Memory | `tool_memory` | For Knowledge Base memories, pass `knowledgebase_ids` when searching to specify which knowledge bases participate in recall. Example usage: ```json { "user_id": "memos_user_123", "query": "What is coming up recently?", "knowledgebase_ids": ["memos_kb_001"] } ``` > **Note**: For the full field list, request format, and response format, see the [Search Memory API documentation](/memos_cloud/mem_operations/search_memory). ## 9. Start Using Directly - [Add Message](/memos_cloud/mem_operations/add_message): Write user conversations, files, and tool call traces - [Search Memory](/memos_cloud/mem_operations/search_memory): Retrieve different categories of memories --- # Multi-user / Multi-Agent Isolation (/memos_cloud/introduction/isolation_filters) If your product is used by multiple users, Agents, projects, or business scenarios, memories need clear boundaries. - Project boundaries separate different products or business spaces. - User boundaries separate personal memories for different users within the same project. - Agent / application boundaries separate memories produced by different Agents or apps for the same user. - Conversation context marks which conversation or task a memory came from. - Shared project knowledge can be placed in a knowledge base or public memory, and used by authorized users. ## 1. Project Boundary: Create a Project and Use an API Key If you have not registered for the cloud service, first sign in to the [MemOS Console](https://memos-dashboard.openmem.net/quickstart). New users get a default project. If you need to isolate different products or business spaces, create a new project in the console. Each project has its own API Key list. When you use an API Key from a project, your requests access memories under that project. Go to the [API Key page](https://memos-dashboard.openmem.net/apikeys) to get an API key quickly. > **Note**: For project creation, switching, and API key management, see [Project Configuration](/api_docs/start/configuration). ## 2. User Memories: Use Different `user_id` Values Each user should have a unique `user_id`. The same user can keep using the same `user_id` across different entries or applications, so MemOS can build continuous long-term memories. Write a memory for user A: ```json { "user_id": "memos_user_A", "messages": [ { "role": "user", "content": "I like spicy food." } ] } ``` Search memories for user B: ```json { "user_id": "memos_user_B", "query": "Recommend food for me" } ``` This search only looks in user B's personal memories. It will not retrieve user A's memories. Even if both users are in the same project and talk to the same Agent, different `user_id` values keep the memory boundary clear. ### Multi-User Memory in Group Chat: Pass a `user_id` List NEW When multiple users talk in the same conversation, `user_id` can accept a list, and MemOS extracts and maintains memory for each participant. ```json { "user_id": ["memos_user_1", "memos_user_2"], "agent_id": "memos_agent", "messages": [ { "role": "user", "role_id": "memos_user_1", "role_name": "Alex", "content": "Does next Tuesday work for everyone for the proposal review?" }, { "role": "user", "role_id": "memos_user_2", "role_name": "Jordan", "content": "Works for me. How about 2pm?" }, { "role": "assistant", "role_id": "memos_agent", "content": "Got it. Proposal review next Tuesday at 2pm." } ] } ``` Use `role_id` and `role_name` to identify the speaker of each message so memory text can distinguish who said what. > **Note**: For more on group chat, see [Group Chat](/memos_cloud/features/group_chat). ## 3. Multi-Agent Isolation: Use `agent_id` If the same user uses multiple Agents, such as a customer service assistant, health assistant, and coding assistant, assign different `agent_id` values to different Agents. When adding messages for a health assistant, pass `"agent_id": "health_assistant"`: ```json { "user_id": "memos_user_123", "agent_id": "health_assistant", "messages": [ { "role": "user", "content": "I ran 5 km today, and my knee feels a little sore." } ] } ``` When searching memories, use `filter` to limit memories to the corresponding Agent: ```json { "user_id": "memos_user_123", "query": "Give me advice based on my recent exercise.", "filter": { "and": [ { "agent_id": "health_assistant" } ] } } ``` This keeps the user's long-term memory under the same person while still allowing memories from different Agents to be filtered when needed. > **Note**: For more filtering options, see [Memory Filters](/memos_cloud/features/filters). ### Create Independent Memory for an Agent NEW Enable "Create Independent Memory for Agent" when creating or editing a project in the console to give each Agent its own memory. - Better preserve an AI character's experience, cognition, and state. - Support scenarios where multiple users share the same Agent, such as a household assistant or a company group-chat assistant. After enabling this feature: - When adding messages, MemOS extracts and updates memories for the user and the Agent separately. - When searching memories, you can search the Agent's independent memory using `agent_id` as the subject. - The Agent accumulates its own long-term memory, keeping the character consistent across different users and conversations. This feature is disabled by default. In that case, `agent_id` can still be used for filtering and tagging, but no independent memory instance is created for the Agent. ## 4. Current Conversation: Use `conversation_id` To help MemOS understand context, you can pass a `conversation_id` when adding user messages. It indicates which conversation or task the message belongs to. If omitted, the system generates one automatically. ```json { "user_id": "memos_user_123", "conversation_id": "order_refund_001", "messages": [ { "role": "user", "content": "I want to ask about my refund progress." }, { "role": "assistant", "content": "The refund is still being processed and is expected to arrive within 24 hours." } ] } ``` When searching memories, `conversation_id` is not a mandatory filter. Passing it clarifies the current conversation and gives memories from this conversation higher weight. If you do not pass it, MemOS still searches the user's historical memories. ## 5. Shared Knowledge: Use Knowledge Bases or Public Memory Not everything should be written into a user's personal memory. Project documents, policies, product manuals, SOPs, and other shared knowledge are better placed in a knowledge base or public memory. ### Knowledge Base For project documents, policies, and product manuals, create a knowledge base and upload documents. See [Knowledge Base](/memos_cloud/features/knowledge_base) for the full workflow. During search, pass `knowledgebase_ids` in addition to user memory so the answer can also refer to project-level knowledge. ```json { "user_id": "memos_user_123", "query": "Based on my situation and the company policy, can this expense be reimbursed?", "knowledgebase_ids": ["kb_finance_policy"] } ``` ### Public Memory Public memory is suitable for lightweight shared information such as project announcements, team experience, and general rules. If a message should be shared by all users under the project, enable `allow_public` when writing it. ```json { "user_id": "memos_user_123", "allow_public": true, "messages": [ { "role": "user", "content": "The reimbursement deadline for this quarter is June 25." } ] } ``` During retrieval, user personal memories and public memories are searched together and relevant content is recalled. --- # Time Awareness (/memos_cloud/introduction/time_awareness) We treat memories as objects that evolve over time, not as static text. A user's preferences, state, and facts may change; one-time events also need to keep when they happened. With time awareness, MemOS can decide when to use the latest current understanding and when to trace back to historical versions. ## 1. What Problems It Solves ### New and old information conflicts - The user first says "I like apples", and later says "I don't like apples anymore". - **How MemOS handles it**: MemOS automatically detects the change. During retrieval, it returns only the currently valid understanding: "does not like apples". Historical versions are not deleted and can still be traced when needed. ### "Now" and "before" should return different answers - The user used to live in Beijing, then moved to Shanghai. - **How MemOS handles it**: MemOS understands time clues in the question. When the user asks "Where do I live now?", it retrieves Shanghai. When the user asks "Where did I live before?", it retrieves Beijing. ### Events should not be forcibly merged - The user traveled to Xi'an during last year's National Day holiday and to Hangzhou during this year's May Day holiday. - **How MemOS handles it**: MemOS keeps the complete information for each event instead of merging everything into "the user likes travel". When the user asks "Where did I travel recently?", it can prioritize Hangzhou. ## 2. Processing Flow ### At write time: use `chat_time` to anchor historical time Real-time conversations usually do not require a timestamp. MemOS uses the message ingestion time. If you import historical data, pass `chat_time` so memories are anchored to when the event actually happened. ```json { "user_id": "memos_user_123", "messages": [ { "role": "user", "content": "I like spicy food.", "chat_time": "2025-09-12 08:00:00" }, { "role": "user", "content": "I can't eat very oily or spicy food now, and I prefer something lighter.", "chat_time": "2025-09-25 12:00:00" } ] } ``` ### Time handling for two kinds of memories MemOS handles memories differently: - **States that may change**, such as where the user lives, what they like, or their current stage goal, keep different time versions. This lets retrieval use the current version while still allowing historical recall. - **One-time events**, such as where the user went or what they did, keep the details of each event. This lets retrieval return complete event information. ### At search time: understand the time target in the question - **No explicit time target**: retrieve normally and prefer currently valid memories. - **With time clues**: understand the time target and select the corresponding version or event. If you already know the time range, you can also combine [Memory Filters](/memos_cloud/features/filters) with `create_time` to narrow candidate memories: ```json { "user_id": "memos_user_123", "query": "Summarize my reading-related records in December 2025", "filter": { "and": [ { "create_time": { "gte": "2025-12-01" } } ] } } ``` ## 3. Example Try writing a set of events with time information: ```json { "user_id": "test_user", "messages": [ { "role": "user", "content": "I live in Beijing.", "chat_time": "2025-01-10 10:00:00" }, { "role": "user", "content": "I moved to Shanghai.", "chat_time": "2025-06-01 10:00:00" }, { "role": "user", "content": "I traveled to Xi'an during last year's National Day holiday.", "chat_time": "2025-10-08 10:00:00" }, { "role": "user", "content": "I traveled to Hangzhou during this year's May Day holiday.", "chat_time": "2026-05-02 10:00:00" } ] } ``` | Type | Search query | Expected result | | --- | --- | --- | | Current state | "Where do I live now?" | Shanghai, using the latest state | | Historical state | "Where did I live before?" | Beijing, tracing back to the historical version | | Up to now | "Where have I traveled?" | Xi'an and Hangzhou, with Hangzhou ranked first | ## 4. Usage Suggestions - Pass accurate `chat_time` when importing historical data; otherwise, old events may be treated as if they just happened. - For current-state information, let users naturally express updates. MemOS will update the current understanding automatically. ## 5. Next Steps - [Add Message](/memos_cloud/mem_operations/add_message): Write historical messages with timestamps - [Search Memory](/memos_cloud/mem_operations/search_memory): Search and verify time-related memories --- # FAQ (/memos_cloud/introduction/faq) This page answers product-level and concept-level questions about MemOS. If you are already using MemOS Cloud and need help with projects, API Keys, quotas, or API calls, see [Cloud FAQs](/memos_cloud/support/faq) and [Quotas and Limits](/memos_cloud/support/limit). ## How is MemOS different from a standard RAG framework? | Dimension | RAG | MemOS | | --- | --- | --- | | Managed content | Static knowledge chunks or document passages | Memories that evolve with users, tasks, and time | | Content shape | Usually recalls raw text passages | Converts raw input into memory units such as facts and preferences | | Update model | Depends on document updates or re-indexing | Supports continuous writing, updates, feedback correction, and lifecycle management | | Recall goal | Help the model know external knowledge | Help the model understand user state, preferences, and context | RAG is better for stable external knowledge. MemOS is better for user memories that continuously change during conversations and business workflows. They can be used together. ## Can MemOS work with existing RAG systems or knowledge graphs? Yes. RAG handles factual retrieval and knowledge augmentation, while MemOS handles continuous memory and state management. In a business application, you can keep stable content such as policies and product documentation in a knowledge base or RAG system, and let MemOS manage dynamic information such as user conversations, preferences, and task progress. During response generation, the application can use both external knowledge and user memories. ## How does MemOS work? The basic workflow is: 1. Write raw information through `add/message`, knowledge bases, feedback, or related capabilities. 2. MemOS processes raw input into searchable and updateable memories. 3. Later requests recall relevant memories through `search/memory`, `chat`, or Agent integrations. 4. Memories continue to update through new input, feedback, and lifecycle policies. If you only want to integrate the cloud service quickly, start with [Integrate into Your App](/memos_cloud/getting_started/quick_start). ## What are the core capabilities of MemOS? - **User / Agent memory management**: store user-AI interactions and isolate memories across users and Agents. - **Memory production and updates**: generate reusable memories from conversations, behavior events, and knowledge content. - **Memory recall and scheduling**: select memories based on relevance, freshness, and context. - **Memory lifecycle management**: control memory quality and scale through updates, merging, and archiving. - **Cloud and open source options**: use the managed cloud service, or self-host and extend the open-source project. ## How should I choose between Cloud and Open Source? Use [MemOS Cloud](/memos_cloud/getting_started/quick_start) if you want quick validation, lower operational cost, and built-in console, API Key, knowledge base, and quota management. Use [Open Source](/open_source/getting_started/installation) if you need to manage your own deployment environment, modify lower-level implementation, connect custom inference backends, or do deeper secondary development. For a fuller comparison, see [Cloud Service & Open Source](/memos_cloud/getting_started/cloud_and_opensource). ## Does MemOS support private deployment? Yes. For private deployment, commercial customization, or deeper business-specific adaptation, contact the MemOS team to confirm deployment mode, data boundaries, and feature scope. Teams that want to explore and modify MemOS themselves can also start from the open-source project. ## What is the relationship between lifecycle and scheduling? Lifecycle management controls how memory units change over time, such as updates, merging, consolidation, or archiving. Scheduling decides which memories should enter the current context for a specific request. In short: lifecycle management maintains memories over the long term; scheduling decides which memories to use now. ## How does MemOS avoid memory bloat? MemOS does not append all raw history directly into model context. It processes raw input into shorter memory units and controls memory scale through updates, merging, and archiving. During recall, MemOS selects only memories relevant to the current request, reducing unrelated context. ## Are KV-Cache and activating memory the same thing? No. KV-Cache is a model inference-level computation cache. Activating memory is a MemOS product concept for describing recently reusable memory state. In implementation, activating memory can use lower-level cache capabilities to improve recent-context reuse, but the two are not equivalent. ## Will MemOS slow down inference? MemOS aims to reduce irrelevant context through memory processing and recall, instead of sending all history to the model. Actual latency depends on write volume, recall scope, filters, model calls, and business concurrency. If you encounter quota or latency issues in cloud API calls, see [Quotas and Limits](/memos_cloud/support/limit) and [Cloud FAQs](/memos_cloud/support/faq). ## If the information is recent, such as “what I did yesterday,” is scheduling still needed? Yes. Recent information is not always relevant, and it should not always be sent in full. Scheduling considers the current question, conversation, user memories, and relevance to choose the best memories for the current turn. ## What business scenarios is MemOS suitable for? MemOS is suitable for AI applications that need long-term memory and continuous personalization, such as companionship, games, travel, customer service, knowledge management, investment advisory, production operations, and AI learning assistants. You can first validate a specific scenario with Cloud APIs, then decide whether to do deeper integration or private deployment. --- # Memory Production (/memos_cloud/introduction/mem_production) ## 1. What Is Memory Production Memory production is the write and processing stage of the MemOS workflow. After developers submit raw information, MemOS extracts facts, preferences, tool usage processes, skill clues, and knowledge content, then generates memory units that can later be searched, filtered, scheduled, and updated. Raw information may be stored in full first, but what enters later reasoning is usually not the whole original text. It is the memory produced after extraction, denoising, structuring, and version governance. ## 2. Why Not Just Store Raw Text If all raw information is stored directly and pasted into the model next time, three problems appear: - **High context cost**: raw conversations, logs, and files often contain greetings, repetition, and irrelevant details. Pasting them directly wastes tokens. - **Unstable retrieval quality**: long unprocessed text lacks clear topics and structure, so it can recall fragments that look relevant but do not help. - **Hard long-term consistency**: user preferences, locations, and states change. Raw text alone cannot clearly express "what should be trusted now". The goal of memory production is to turn "what happened" into "what can be used later". ## 3. Key Processing Stages From raw input to usable memory, the middle step is not simple text saving. It is an ongoing process of organizing information into long-term usable understanding. It usually includes: | Stage | Role | | --- | --- | | Extraction | Identify information worth keeping long term from raw conversations, events, or documents | | Structuring | Organize information into distinguishable memory categories such as facts, preferences, tools, skills, and knowledge | | Denoising | Filter greetings, repeated content, temporary context, and low-value logs | | Merging | Merge identical or similar information to reduce duplicate memories | | Evolution | Update currently trusted memories when user state or preferences change, while keeping necessary history | ## 4. Example: From Conversation to Memory Raw conversation: ```text User: I have booked a summer trip to Guangzhou. Which hotel chains are available? Assistant: You can consider 7 Days Inn, Ji Hotel, Hilton, and others. User: I'll choose 7 Days Inn. Assistant: Got it. Feel free to ask if you have other questions. ``` Possible generated memories: - Fact memories come from explicit statements in the original text. - Preference memories combine context and reasoning to summarize user preferences. ```text - Fact memory: The user plans to travel to Guangzhou during the summer vacation. - Fact memory: The user chose 7 Days Inn from the accommodation options in Guangzhou. - Implicit preference: The user may prefer economical and practical hotels. ``` ## 5. Next Steps - [Raw Input Content](/memos_cloud/introduction/raw_inputs): Confirm what content can be written - [Memory Categories](/memos_cloud/introduction/memory_types): Understand facts, preferences, tools, skills, and other memory categories - [Add Message](/memos_cloud/mem_operations/add_message): View how message writing and memory production are integrated --- # Memory Scheduling (/memos_cloud/introduction/mem_schedule) ## 1. What Is Memory Scheduling Memory scheduling is MemOS's runtime ability to manage memory availability. It is not just about "which memory is found". Based on the current task, user state, historical topics, and memory heat, it decides which memories should stay closer to model context and which can remain in low-frequency storage. You can think of memory scheduling as attention management in the memory system. When a user enters a task scenario, the system prepares the memories most likely to be needed and reduces interference from irrelevant history. ## 2. Why Scheduling Is Needed If every request only performs a full retrieval, the system faces three problems: - **Slower response**: waiting until the user asks before searching all history increases first-token latency. - **Context overload**: recalling too much history may bury the information actually needed for the current task. - **Unnatural topic switching**: when the user's recent focus changes, the system needs to raise the priority of the new topic and downgrade the old one. The goal of scheduling is not to store more content, but to make the right memories available at the right time. ## 3. What Scheduling Looks At | Signal | Role | | --- | --- | | Current task | Determines which topic or scenario the user is working on | | Memory relevance | Identifies which memories are closer to the current input, conversation, and business goal | | Freshness | Prioritizes information that is still valid and reduces the impact of outdated content | | Usage frequency | Frequently used memories are more likely to be prepared in advance or kept active | | Permission scope | Ensures scheduling respects user, Agent, tenant, and business isolation rules | Scheduling affects later recall and context injection. Relevant, active, and trustworthy memories are more likely to be used first; low-frequency, outdated, or context-inappropriate memories are delayed. ## 4. Example: From Buying a Home to Renovation **Earlier stage: buying a home is the core topic** **User input**: "Help me check the average second-hand home price around Binjiang." "Remind me to view houses on Saturday." "Record the latest mortgage rate changes." **Scheduling result**: Generate memories about communities, house-viewing schedules, and mortgage rates. Determine that "home buying" is a recent high-frequency topic. Keep home-buying memories at a higher priority. **Recently: renovation becomes the new active topic** **User input**: "I'm going to look at tiles this weekend." "Remind me to confirm plumbing and electrical work with the contractor." "Note next week's furniture delivery time." **Scheduling result**: Continue generating renovation-related memories. Determine that "renovation" has become the new high-frequency topic. Move renovation memories to a higher priority. Keep home-buying memories, but gradually downgrade them. The user casually says: "I feel like a lot of things are piling up. Please sort them out for me." **Without scheduling: temporary full retrieval**: Needs to retrieve from all memories on the spot. May mix in low-relevance items such as checking housing prices, viewing houses, grocery shopping, or watching movies. The answer is slower and more likely to drift away from the current task. **With scheduling: prepare the current topic first**: Prioritize renovation memories such as looking at tiles, confirming plumbing and electrical work, and furniture delivery. No need to re-evaluate the full history every time. Responses are faster and closer to what the user is currently worried about. ## 5. Relationship with Recall Scheduling and recall are not the same thing: | Capability | Focus | | --- | --- | | Memory scheduling | Which memories should be more active and closer to model context at the current stage | | Memory recall | Which memories should be retrieved and used in a specific request | Scheduling is runtime preparation and priority management. Recall is retrieval and selection for one request. When scheduling works well, recall is usually faster, more accurate, and less affected by irrelevant history. --- # Memory Recall (/memos_cloud/introduction/mem_recall) ## 1. What Is Memory Recall Memory recall is the core ability of MemOS when reading memories. After a user sends a new request, MemOS combines the input, conversation context, filters, and memory states to find memories that can help the model complete the current task. The goal is not to return all history. It is to put the most useful facts, preferences, tool experience, skill clues, or knowledge content into the limited context window. ## 2. Why Context Alone Is Not Enough If a model only relies on the current conversation window, three problems appear: - **Users must repeat themselves**: preferences, background, and long-term matters cannot continue naturally. - **Historical information is easily lost**: earlier conversations, cross-session behavior, and tool results do not automatically appear in the current context. - **Input becomes overloaded**: adding all raw history is costly and makes answers less stable. The value of memory recall is to turn long-term memories into usable input for the current task when needed. ## 3. What Recall Returns | Memory category | Typical use | | --- | --- | | Fact memories | Add clear facts such as user identity, long-term matters, and business status | | Preference memories | Continue the user's tone, style, choice habits, or constraints | | Tool memories | Help Agents select the right tool and invocation pattern in similar tasks | | Skill memories | Reuse execution steps and constraints distilled from multi-turn tasks | | Knowledge content | Provide documents, images, multimodal content, or knowledge base evidence | Recall results usually include source, time, type, tags, confidence, and status. Developers can further filter, rank, or decide whether to inject them into downstream models. ## 4. Key Stages in Recall | Stage | Role | | --- | --- | | Understand the request | Decide what background, preferences, or knowledge the current input needs | | Filter the scope | Limit candidate memories by user, conversation, time, tags, type, and other conditions | | Retrieve candidates | Find semantically relevant or condition-matched memories from the memory base | | Rank and select | Combine relevance, confidence, freshness, and status to choose more reliable results | | Govern injection | Control which memories enter model context, avoiding excessive, outdated, or non-compliant content | Together, these stages determine whether recalled memories are actually useful. Too little recall leaves the model without background; too much recall adds noise and cost. ## 5. Next Steps - [Memory Filters](/memos_cloud/features/filters): Use filters to control recall scope and reduce irrelevant memories - [Search Memory](/memos_cloud/mem_operations/search_memory): View how to integrate memory recall --- # Memory Lifecycle Management (/memos_cloud/introduction/mem_lifecycle) ## 1. What Is Memory Lifecycle Management A memory is not a record that stays unchanged forever after it is written. As user states, task stages, and business facts change, the same kind of memory may need to be updated, merged, downgraded, archived, or cleaned up. Memory lifecycle management focuses on long-term evolution at the storage layer: which memories are still trustworthy, which are outdated, which need historical traces, and which can be removed from the active index. ## 2. Why Lifecycle Management Is Needed If memories only grow without governance, three problems appear: - **Duplicate memories increase**: similar facts and preferences are written repeatedly, increasing recall noise. - **Outdated information interferes**: old addresses, old preferences, and completed tasks are still treated as current facts. - **Conflicts are hard to judge**: when new and old information conflict, the system needs to know which one should be trusted now. The goal of lifecycle management is to preserve memories long term without continuously bringing outdated, duplicate, or low-value information into reasoning. ## 3. Key Lifecycle States | State | Meaning | Common handling | | --- | --- | --- | | Generated | A new memory is written with source, time, type, confidence, and other metadata | Enters the memory base and waits for future use | | Activated | A memory is frequently used in recent tasks or scheduled to a higher priority | Easier to recall and inject into context | | Merged | Similar or complementary memories are integrated into a more stable expression | Reduces duplication and forms an updated trusted memory | | Archived | Long-term low-frequency memories, or memories not suitable for the current task, are downgraded | Participates less in reasoning by default, but remains traceable | | Expired | A memory exceeds its validity period or is judged unusable by policy | Removed from the active index; minimal audit info may be retained | | Frozen | Compliance, audit, or business-critical memories cannot be automatically rewritten | Preserves full history and limits updates or deletion | Specific state names and policies may vary by integration, but the core idea is the same: memories need continuous governance based on time and usage. ## 4. Example: Changing Learning Preferences Suppose you are building an online education assistant with MemOS to help students solve math problems. #### Generated The student says for the first time: "I always confuse quadratic functions with linear functions." The system extracts a memory: ```json { "content": "The student often confuses quadratic functions with linear functions", "confidence": 0.99, "create_time": "2025-09-11" } ``` State: `Generated` Behavior: stored in the memory base, waiting for future use. #### Activated In the next several problem-solving sessions, the system frequently uses this memory to assist with answers. State: `Activated` Behavior: prioritized by the scheduling mechanism to improve later retrieval and context injection efficiency. #### Merged With more interactions, the system discovers that the student not only confuses linear and quadratic functions, but also struggles with exponential functions. The system merges multiple similar memories into a new one: ```json { "content": "The student is confused about function concepts, especially linear, quadratic, and exponential functions", "history": "The student often confuses quadratic functions with linear functions", "version": "v1" } ``` State: `Merged` Behavior: old entries are compressed into a more complete new version, reducing redundancy. #### Archived Three months later, the student has mastered function-related concepts, and this memory has not been scheduled for a long time. State: `Archived` Behavior: downgraded to a low-frequency state. It does not participate in reasoning by default, but can be used in "learning trajectory backtracking". #### Expired Another year later, the student advances to a new grade. The old "junior high function confusion" memory is judged invalid by policy. State: `Expired` Behavior: removed from the index, retaining only minimal audit information. ```json { "deleted_fact_id": "12345", "deleted_at": "2026-09-11" } ``` #### Frozen (special state) At the same time, the student's "final exam evaluation report" is a compliance file and must not be automatically modified. State: `Frozen` Behavior: locked against automatic updates, with full modification history retained for audit and compliance review. ## 5. Relationship with Production, Scheduling, and Recall | Capability | Focus | | --- | --- | | Memory production | How raw input is processed into usable memories | | Lifecycle management | How memories are updated, merged, archived, and cleaned after writing | | Memory scheduling | Which memories should be more active at the current stage | | Memory recall | Which memories should be retrieved and used for one request | Lifecycle management provides memory state for scheduling and recall. Active, trustworthy, and unexpired memories are better suited for current reasoning. Archived, expired, or frozen memories need to be handled carefully according to policy. --- # MemOS Algorithm Overview (/memos_cloud/introduction/algorithm) > **Note**: Reference: Paper link https://arxiv.org/abs/2507.03724 ## 1. What is MemOS? Today’s large language models (LLMs) have demonstrated strong generative and reasoning capabilities, but they generally lack true “memory.” * In multi-turn conversations, they often forget earlier information; * In application scenarios, they fail to retain users’ personalized preferences; * During knowledge iteration, they update slowly and cannot flexibly adapt to new requirements. This makes LLMs “smart,” but not yet capable of becoming true **teachers, colleagues, or assistants**. **MemOS (Memory Operating System)** was created to address this fundamental gap. It elevates “memory” from a fragmented function to a **system resource** as important as computation, providing LLMs with: * **A unified memory layer**: supporting long-term knowledge retention and context management beyond single conversations; * **Persistence and structuring**: enabling memory to be stored, traced, and reused; * **Memory-augmented reasoning**: recalling historical experiences and preferences during inference to generate answers better aligned with user needs. Compared with traditional approaches (e.g., purely relying on parameter memory or temporary KV cache), the value of MemOS lies in: * Allowing AI to continuously evolve and learn instead of “forgetting after seeing”; * Not only answering the present question, but also improving future performance through accumulated knowledge; * Providing developers with unified APIs that turn “memory” from complex self-built logic into standardized capabilities. In short, MemOS aims to: **Transform large models from disposable dialogue tools into intelligent agents with true long-term memory and adaptive capabilities.** ## 2. MemOS Architecture Design At its core, MemOS treats “memory” as an independent system layer—like computation and storage—becoming a fundamental capability for AI applications. Its overall architecture can be summarized as a **three-layer structure**: **API & Application Interface Layer, Memory Scheduling & Management Layer, Memory Storage & Infrastructure Layer** ![art.gif](https://statics.memtensor.com.cn/memos/art.gif) * In the **API & Application Interface Layer**, MemOS provides standardized Memory APIs. Developers can perform operations such as **memory creation, deletion, and updating** through simple interfaces, giving large models persistent memory capabilities for multi-turn conversations, long-term tasks, and cross-session personalization. > Here, the `API layer` refers to standardized interface design within the framework, illustrating system principles and capability boundaries. **This is different from cloud service developer APIs** (e.g., simplified wrappers like `add`, `search`), which serve as unified endpoints abstracted from MemOS backend capabilities. * In the Memory Scheduling & Management Layer, MemOS introduces a new paradigm of **Memory Scheduling**, enabling context-based **“Next-Scene Prediction”**. This allows memory fragments likely to be needed to be preloaded during generation, significantly reducing response latency and improving inference efficiency. * In the **Memory Storage & Infrastructure Layer**, MemOS integrates plaintext memory, activating memory, and parameter memory through the standardized **MemCube**. It supports multiple persistent storage methods, including graph databases and vector databases, and offers **cross-model memory transfer and reuse**.
Basic structure of standardized MemCube (Memory Cube)
Basic structure of standardized MemCube (Memory Cube)
## 3. Why is MemOS Efficient? > **Note**: From Next-Token Prediction to Next-Scene Prediction * In traditional LLM Q&A systems, the generation process still follows the **synchronous Next-Token mechanism**: the model receives the user’s query → retrieves external fragments in real time → generates the answer token by token. * Any pauses caused by retrieval or computation directly extend the reasoning chain, tightly coupling knowledge injection and generation. This leads to GPU idle waiting and noticeable response delays for users. * Unlike this traditional paradigm, MemOS approaches from the perspective of memory modeling and introduces a **memory scheduling paradigm**. By designing an asynchronous scheduling framework, it predicts memory information likely to be needed, significantly reducing efficiency loss during real-time generation. * MemOS jointly schedules the three core memory types in MemCube (parameter memory, activating memory, plaintext memory) along with external knowledge bases (including internet retrieval and massive local knowledge). * With precise awareness of conversation turns and time gaps, the system intelligently predicts which memory elements may be needed in the next scene. It dynamically routes and preloads the required plaintext, parameter, and activating memories, ensuring immediate hits during generation and maximizing efficiency and fluency of reasoning. ![640.gif](https://statics.memtensor.com.cn/memos/ani.gif)
Core idea of memory scheduling
Core idea of memory scheduling
## 4. MemOS-Preview Performance Evaluation ### 4.1 LoCoMo Memory Benchmark * To systematically validate MemOS in real application scenarios, the MemOS team conducted comprehensive evaluations using the **LoCoMo dataset**. * As an industry-recognized benchmark for memory management, LoCoMo has been adopted by multiple mainstream frameworks to test models’ memory access and multi-turn dialogue consistency. * Public results show that **MemOS achieves significant improvements in both accuracy and computational efficiency**. Compared with OpenAI’s global memory approach, it demonstrates superior performance on key metrics, further verifying its technological leadership in memory scheduling, management, and reasoning integration. ![image.png](https://cdn.memtensor.com.cn/img/1758687655761_blkqnr_compressed.png) ### 4.2 KV Cache Memory Evaluation * Beyond general memory ability assessments, the research team specifically examined the effectiveness of MemOS’s KV Cache mechanism in accelerating inference. * Tests were conducted across different context lengths (Short/Medium/Long) and model sizes (8B/32B/72B), systematically evaluating cache build time (Build), **Time-To-First-Token (TTFT), and overall Speedup**. * Results (see Figure 10) show that **MemOS significantly optimizes KV Cache build and reuse efficiency across configurations**, making inference more efficient and smooth. This reduces user waiting latency and achieves substantial performance acceleration in large-scale model scenarios. ![image.png](https://cdn.memtensor.com.cn/img/1758687596553_iptom0_compressed.png) ## 5. Next Steps * Learn about [Cloud Platform & Open Source](/memos_cloud/getting_started/cloud_and_opensource) and experience the power of MemOS! --- # Add Message (/memos_cloud/mem_operations/add_message) > **Note**: **Why memory matters** > > - Long-term continuity: preserve information across sessions so it is not lost after one conversation ends. > - Better understanding of user preferences: as interactions accumulate, AI can understand the user more accurately. > - Continuous evolution over time: user memories can be updated dynamically during conversations. > - Cross-product experience: share the same user's memories across multiple applications or products for a consistent experience. ## 1. Key Parameters - **User ID (`user_id`)**: identifies which user the messages belong to. Every added message must be associated with a unique user identifier. - **Conversation ID (`conversation_id`)**: identifies which conversation the messages belong to. When passed, multiple turns of messages under the same `conversation_id` are recognized as the same context. - **Messages (`messages`)**: an ordered list of user and AI messages to add to MemOS. ## 2. How It Works - **Information extraction**: MemOS extracts information from messages and processes it into memories, including facts, preferences, [Profile](/memos_cloud/features/profile), [Event Memory](/memos_cloud/features/event_memory), tool memories, and more. - **Conflict resolution**: existing memories are checked for duplication or contradiction and updated when needed. - **Memory storage**: generated memories are stored with vector and graph databases so they can be recalled efficiently later. All of these steps are triggered by calling the `add/message` API. You do not need to manually operate on user memories. ## 3. Quick Start ```python [Python (HTTP)] import requests API_KEY = "YOUR_API_KEY" BASE_URL = "https://memos.memtensor.cn/api/openmem/v1" data = { "user_id": "memos_user_123", "conversation_id": "0610", "messages": [ {"role": "user", "content": "I have booked a summer trip to Guangzhou. Which hotel chains are available?"}, {"role": "assistant", "content": "You can consider 7 Days Inn, Ji Hotel, Hilton, and others."}, {"role": "user", "content": "I choose 7 Days Inn."}, {"role": "assistant", "content": "Got it. Feel free to ask if you have other questions."} ] } res = requests.post( f"{BASE_URL}/add/message", headers={"Authorization": f"Token {API_KEY}"}, json=data ) print(res.json()) ``` ```python [Python (SDK)] from memos.api.client import MemOSClient client = MemOSClient(api_key="YOUR_API_KEY") messages = [ {"role": "user", "content": "I have booked a summer trip to Guangzhou. Which hotel chains are available?"}, {"role": "assistant", "content": "You can consider 7 Days Inn, Ji Hotel, Hilton, and others."}, {"role": "user", "content": "I choose 7 Days Inn."}, {"role": "assistant", "content": "Got it. Feel free to ask if you have other questions."} ] res = client.add_message( messages=messages, user_id="memos_user_123", conversation_id="0610" ) print(res) ``` ```bash [Curl] export MEMOS_API_KEY="YOUR_API_KEY" export MEMOS_BASE_URL="https://memos.memtensor.cn/api/openmem/v1" curl "$MEMOS_BASE_URL/add/message" \ -H "Authorization: Token $MEMOS_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "user_id": "memos_user_123", "conversation_id": "0610", "messages": [ {"role": "user", "content": "I have booked a summer trip to Guangzhou. Which hotel chains are available?"}, {"role": "assistant", "content": "You can consider 7 Days Inn, Ji Hotel, Hilton, and others."}, {"role": "user", "content": "I choose 7 Days Inn."}, {"role": "assistant", "content": "Got it. Feel free to ask if you have other questions."} ] }' ``` > **Note**: Want to know which memories were generated? Copy and run the code above, then continue to [Search Memory](/memos_cloud/mem_operations/search_memory). Need the complete field list, request format, and response format? See the [Add Message API documentation](/api_docs/core/add_message). ## 4. When Should You Add Messages? Raw message content is the foundation of memory. MemOS processes added messages into memories for later retrieval and use. You can choose the right timing based on your scenario: - **One-time import**: import existing user conversation history into MemOS to quickly build initial memories. - **Real-time add**: add messages to MemOS whenever the user sends a message. - **Add by turns**: add user messages every few conversation turns based on your business needs. ## 5. More Usage The fields below are used to add time, categories, isolation, and business context when adding messages. You can use them separately or combine them as needed. ### Write User Preferences or Behavior Data Besides conversations, user preferences, behavior data, and any other text information can be written to MemOS as raw content. ```python data = { "user_id": "memos_user_123", "conversation_id": "0901", "messages": [ { "role": "user", "content": """ Favorite movie genres: sci-fi, action, comedy Favorite TV genres: mystery, historical drama Favorite book genres: popular science, technology, self-growth Preferred chat style: humorous, warm, casual Types of AI help wanted: suggestions, information lookup, inspiration Topics I care about most: artificial intelligence, future technology, film reviews What I want AI to help with: daily study planning, movie and book recommendations, emotional companionship """ } ] } ``` ### Write Multimodal Content Besides text, MemOS also supports extracting multimodal memories. When a message contains multimodal content, MemOS extracts text, visual information, and other content, then processes it into user memories. ```python data = { "user_id": "memos_user_123", "conversation_id": "1211", "messages": [ { "role": "user", "content": [ { "type": "text", "text": "I am researching MemOS." }, { "type": "image_url", "image_url": { "url": "https://cdn.memtensor.com.cn/img/1758706201390_iluj1c_compressed.png" } } ] }, {"role": "assistant", "content": "Sure, would you like me to explain it?"} ] } ``` ### `chat_time`: specify when the conversation happened By default, MemOS uses the Beijing time when a message is submitted as the memory time. If you are importing historical conversations in bulk, pass `chat_time` for each message so generated memories keep a more accurate timeline. ```python data = { "user_id": "memos_user_123", "conversation_id": "0930", "messages": [ {"role": "user", "content": "I like spicy food.", "chat_time": "2025-09-12 08:00:00"}, {"role": "assistant", "content": "I have noted that you like spicy flavors.", "chat_time": "2025-09-12 08:01:00"}, {"role": "user", "content": "I do not like heavy oil.", "chat_time": "2025-09-25 12:00:00"}, {"role": "assistant", "content": "Got it. You prefer spicy food with a lighter taste.", "chat_time": "2025-09-25 12:01:00"} ] } ``` ### `agent_id`: isolate memories by Agent When adding messages, pass `agent_id` to identify which Agent the current conversation belongs to. This helps distinguish memories produced by the same user under different Agents. ```python data = { "user_id": "memos_user_123", "conversation_id": "0610", "agent_id": "health_assistant", "messages": [ {"role": "user", "content": "I ran 5 kilometers today and my knee feels a bit sore."}, {"role": "assistant", "content": "I suggest lowering the intensity tomorrow."} ] } ``` > **Note**: During later retrieval, you can pass `"agent_id":"health_assistant"` in the `filter` parameter to retrieve memories from this user's conversations with that assistant. See [Memory Filters](/memos_cloud/features/filters). #### Create Memory for the Agent If [Create Independent Memory for an Agent](/memos_cloud/introduction/isolation_filters#create-independent-memory-for-an-agent) is enabled, MemOS not only extracts memories for the user, but also generates a separate memory for the Agent under that `agent_id`. This gives the Agent its own long-term memory, while still supporting simultaneous conversations and memory for multiple users. ### `tags`: classify memories semantically MemOS automatically generates tags for every memory. If your business already has a tag system, you can also pass custom `tags` when adding messages, so memories better match your business classification. See [Custom Tags](/memos_cloud/features/custom_tags). ```python data = { "user_id": "memos_user_123", "conversation_id": "0610", "tags": ["exercise advice", "fitness planning"], "messages": [ {"role": "user", "content": "I ran 5 kilometers today and my knee feels a bit sore."}, {"role": "assistant", "content": "I suggest lowering the intensity tomorrow."} ] } ``` > **Note**: During later retrieval, you can pass `"tags":"exercise advice"` in the `filter` parameter to retrieve user memories around that tag. See [Memory Filters](/memos_cloud/features/filters). ### `info`: pass custom information When adding messages, include `info` to write structured information such as business scenario, source, or status. It can later be used for precise filtering during retrieval. Common fields include: | Field | Use | | --- | --- | | `business_type` | Business type | | `biz_id` | Unique business identifier | | `scene` | Business or conversation scenario | | `custom_status` | Custom status | You can also pass other custom key-value pairs. All fields can be stored and retrieved normally. ```python data = { "user_id": "memos_user_123", "conversation_id": "0610", "messages": [ {"role": "user", "content": "Help me find flights with suitable times."}, {"role": "assistant", "content": "I found several flights from Beijing to Shanghai."} ], "info": { "scene": "flight" } } ``` > **Note**: During later retrieval, you can pass `"scene":"flight"` in the `filter` parameter to retrieve user memories around that scenario. See [Memory Filters](/memos_cloud/features/filters). ### `allow_memory_view`: control which memory categories are generated Use `allow_memory_view` to specify which [memory categories](/memos_cloud/introduction/memory_types) are allowed to be generated after this add-message call. If omitted, all categories are generated by default. As shown below, only event memory and Profile are generated. Fact memories, preference memories, and others are not generated. ```python data = { "user_id": "memos_user_123", "conversation_id": "0624", "allow_memory_view": ["event", "profile"], "messages": [ {"role": "user", "content": "Last Tuesday afternoon, Li Si and I did a proposal review, and the customer was satisfied with the second version."}, {"role": "assistant", "content": "Got it. Would you like me to summarize the review conclusions?"} ] } ``` ### `custom_extract_prompt`: customize extraction prompts By default, MemOS uses built-in strategies to extract memories from messages. If the default strategy does not fit your business needs, you can pass custom extraction prompts via `custom_extract_prompt` to specify "what to extract" for a given stage. This configuration only takes effect for the current request and is not saved. Supported keys fall into two categories: | Category | Values | Stage | | --- | --- | --- | | Memory category | `detail_factual`, `preference`, `skill`, `profile`, `event`, `tool_memory` | Extraction of the corresponding [memory category](/memos_cloud/introduction/memory_types) | | Input modality | `image`, `document` | Extraction of image content and file content | Note the following when using this field: * A custom prompt only replaces the default extraction strategy of the corresponding stage. Output formats and other protocol constraints are still enforced by the server, and memories are returned in the default structure. * If `document` is not configured, file content falls back to the custom prompt of `detail_factual`. * A memory-category key takes effect only when that category is allowed by `allow_memory_view`. `image` and `document` are not affected by `allow_memory_view`. As shown below, this call only extracts facts related to travel arrangements, and only visible text is extracted from images: ```python data = { "user_id": "memos_user_123", "conversation_id": "0827", "custom_extract_prompt": { "detail_factual": "Extract only facts related to travel arrangements, and ignore greetings and small talk.", "image": "Extract only visible text and ticket information from the image." }, "messages": [ { "role": "user", "content": [ {"type": "text", "text": "Please take a look at this flight itinerary."}, {"type": "image_url", "image_url": {"url": "https://example.com/itinerary.png"}} ] } ] } ``` ### Group Chat: Pass a List for `user_id` When multiple users talk in the same conversation, `user_id` can accept a list, indicating the subjects that own the memories. Use `role_id` and `role_name` to identify the speaker of each message. See [Group Chat](/memos_cloud/features/group_chat). ```python data = { "user_id": ["memos_user_1", "memos_user_2"], "agent_id": "memos_agent", "conversation_id": "group_conv_001", "messages": [ {"role": "user", "role_id": "memos_user_1", "role_name": "Alex", "content": "Does next Tuesday work for the proposal review?"}, {"role": "user", "role_id": "memos_user_2", "role_name": "Jordan", "content": "Works for me, 2pm."}, {"role": "assistant", "role_id": "memos_agent", "content": "Got it. Proposal review next Tuesday at 2pm."} ] } ``` ## 6. Common Errors and Troubleshooting | Error Code | Common Cause | How to Fix | | --- | --- | --- | | `40000` | The request JSON structure is invalid, or a field type is incorrect | Check whether `messages` is an array, and whether `role` / `content` are inside each message object | | `40002` | A required field is empty | Check that `user_id`, `conversation_id`, and `messages` are all provided and non-empty | | `40011` | `conversation_id` is too long | Use a short ID. Do not put full conversations, user input, or JSON into `conversation_id` | | `40013` | Total `messages` length exceeds the limit | Split historical conversations and write them in multiple requests | | `40305` | A single request exceeds the token limit | Shorten the content in one write request and keep the key user facts and preferences first | | `40309` | Token usage exceeds the per-time-window limit | Lower concurrency and bulk import speed, then retry in batches | | `50143` / `50144` | Memory or message writing failed | Check the request content and retry later. If it persists, contact support | ## 7. More Features If you need more complex write methods, continue with these extended capabilities. - [Multimodal Messages](/memos_cloud/features/multimodal): Support text, images, documents, and other input content. - [Async Mode](/memos_cloud/features/async_mode): Control how messages are processed after writing. - [Group Chat](/memos_cloud/features/group_chat): Multiple users in the same conversation; memory is extracted for each participant. --- # Search Memory (/memos_cloud/mem_operations/search_memory) ## 1. What Is Memory Retrieval? Memory retrieval means that when a user asks a question, MemOS recalls the most relevant and important memories from the memory store, combined with filters predefined by developers. The model can then refer to these memories when generating an answer, making the response more accurate, contextual, and aligned with the user. > **Note**: **Why memory retrieval is needed** > > - Get correct and reliable memories directly instead of rebuilding context from scratch. > - Use filters and other controls to keep recalled memories highly relevant to the current question. ## 2. Key Parameters - **Query (`query`)**: the user's question or statement used for retrieval. MemOS uses semantic matching to find related memories. - **Memory categories to retrieve (`include_memory_view`)**: controls which [memory categories](/memos_cloud/introduction/memory_types) are allowed to be retrieved. - **Recall limit (`memory_limit_number`)**: the maximum number of memories returned after all memories are ranked by relevance. - **Memory filter (`filter`)**: JSON-based logical conditions used to filter fields such as `agent_id`, `create_time`, `tags`, and `info`, narrowing the retrieval scope. You can also set separate filters for user/Agent memories, public memories, and knowledge base memories. - **Relevance threshold (`relativity`)**: how semantically relevant a recalled memory is to the user's question. The higher the relevance score, the more relevant the memory is to the current question. The relevance threshold constrains this match level; memories below the threshold are filtered out. ## 3. How It Works - **Query rewriting**: MemOS cleans and semantically enhances the natural-language query, supplementing key information and retrieval intent to improve retrieval accuracy. - **Memory recall** - **Hybrid retrieval and ranking**: based on the rewritten query, the system generates embeddings and combines keyword retrieval with vector semantic retrieval to recall candidate memories, then ranks candidate memories by relevance. - **Memory filtering and screening**: structured filters and comparison operators narrow the retrieval scope; the configured relevance threshold filters the ranked memories to control result quality. - **Result deduplication**: candidate memories are deduplicated and semantically aggregated across sources. - **Memory output**: final results are returned according to the configured memory limit, within 600 ms, for later reasoning and answer generation. All of these steps are triggered by calling the `search/memory` API. You do not need to manually operate on user memories. ## 4. Quick Start ```python [Python (HTTP)] import requests API_KEY = "YOUR_API_KEY" BASE_URL = "https://memos.memtensor.cn/api/openmem/v1" data = { "query": "I want to travel during the National Day holiday. Please recommend a city I have not been to and a hotel brand I have not stayed at.", "user_id": "memos_user_123", "conversation_id": "0928" } res = requests.post( f"{BASE_URL}/search/memory", headers={"Authorization": f"Token {API_KEY}"}, json=data ) print(res.json()) ``` ```python [Python (SDK)] from memos.api.client import MemOSClient client = MemOSClient(api_key="YOUR_API_KEY") res = client.search_memory( query="I want to travel during the National Day holiday. Please recommend a city I have not been to and a hotel brand I have not stayed at.", user_id="memos_user_123", conversation_id="0928" ) print(res) ``` ```bash [Curl] curl --request POST \ --url https://memos.memtensor.cn/api/openmem/v1/search/memory \ --header 'Authorization: Token YOUR_API_KEY' \ --header 'Content-Type: application/json' \ --data '{ "query": "I want to travel during the National Day holiday. Please recommend a city I have not been to and a hotel brand I have not stayed at.", "user_id": "memos_user_123", "conversation_id": "0928" }' ``` > **Note**: If [Independent Memory for an Agent](/memos_cloud/introduction/isolation_filters#create-independent-memory-for-an-agent) is enabled, you can pass `agent_id` alone to search that Agent's memory. Otherwise, `user_id` is required. Need the complete field list, request format, and response format? See the [Search Memory API documentation](/api_docs/core/search_memory). ## 5. Prompt Template with Memories Recalled memories can be added directly to the prompt of your AI application. The following template is a practical reference. **Expand the full prompt template** ```text # Role You are an intelligent assistant with long-term memory (MemOS Assistant). Your goal is to combine retrieved memory fragments to provide highly personalized, accurate, and logically rigorous answers. # System Context - Current time: 2026-01-06 15:05 (use this as the baseline for judging memory freshness) # Memory Data The following information was retrieved by MemOS and is divided into facts and preferences. - **Facts**: May include user attributes, historical conversations, or third-party information. - **Important**: Content marked as '[assistant view]' or '[model summary]' represents past AI inference, not the user's original words. - **Preferences**: Explicit or implicit requirements for response style, format, or reasoning. -[2025-12-26 21:45] The user plans to travel to Guangzhou during the summer vacation and chose 7 Days Inn as the accommodation option. -[2025-12-26 14:26] The user's name is Grace. -[2026-01-04 20:41] [Explicit Preference] The user likes traveling to southern regions. -[2025-12-26 21:45] [Implicit Preference] The user may prefer cost-effective hotel options. # Critical Protocol: Memory Safety Retrieved memories may contain AI inferences, irrelevant noise, or incorrect subjects. You must apply the following four checks. If a memory fails any check, discard it. 1. Source verification: - Distinguish the user's original words from AI inference. - If a memory is marked as '[assistant view]', treat it as a past hypothesis, not an absolute user fact. - Example: if a memory says '[assistant view] the user loves mangoes' but the user never said so, do not assume the user likes mangoes. - Principle: AI summaries are only references and have much lower authority than direct user statements. 2. Attribution check: - Is the subject of the memory definitely the user? - If the memory describes a third party, candidate, fictional role, or case data, never attribute those traits to the user. 3. Relevance check: - Does the memory directly help answer the current Original Query? - If it is only a keyword match with a different context, ignore it. 4. Freshness check: - Does the memory conflict with the user's latest intent? Treat the current Original Query as the highest-priority source of truth. # Instructions 1. Review first, apply the four checks, and remove noise and unreliable AI views. 2. Use only validated memories as background context. 3. Follow the style requirements in . 4. Answer directly. Do not mention "memory store," "retrieval," or "AI views." # Original Query I want to travel during the National Day holiday. Please recommend a city I have not been to and a hotel brand I have not stayed at. ``` ## 6. More Usage ### `conversation_id`: prioritize memories from the current conversation When searching memories, you can pass a specific `conversation_id`. MemOS prioritizes memories related to the current conversation. If you omit it, MemOS searches the user's long-term memories globally, which is suitable when you need the user's overall profile. ```python data = { "user_id": "memos_user_123", "query": "Help me continue planning my National Day trip.", "conversation_id": "0928" } ``` ### `include_memory_view`: specify which memory categories to retrieve Use `include_memory_view` to control which [memory categories](/memos_cloud/introduction/memory_types) can be returned by this search. If omitted, fact memories and preference memories are recalled by default. ```python data = { "user_id": "memos_user_123", "query": "What happened last week?", "include_memory_view": ["event", "profile"] # search only Event Memory and Profile } ``` > **Warning**: When this field is passed, older parameters such as `include_preference`, `include_skill`, and `include_tool_memory` no longer take effect. In this case, `memory_limit_number` refers to the total number of results returned after all memory categories are merged and ranked together. ### `filter`: precisely narrow the retrieval scope MemOS supports `filter` to narrow retrieval by tags, time, business fields, and other conditions. You can also set separate filters for user memories, knowledge base memories, and public memories. Example 1: retrieve all conversation memories related to reading in 2025. ```python data = { "user_id": "memos_user_123", "query": "Summarize my reading-related points this year.", "filter": { "and": [ {"tags": {"contains": "reading"}}, {"create_time": {"gte": "2025-01-01"}}, {"create_time": {"lte": "2025-12-31"}}, {"scene": "chat"}, ], }, } ``` Example 2: filter knowledge base, user, and public memories separately. ```python data = { "user_id": "memos_user_123", "query": "Combine knowledge base policies, my conversation records, and project announcements to summarize compliance points.", "knowledgebase_ids": ["kb_xxx"], "filter": { "knowledgebase": { "and": [ {"tags": {"contains": "policy"}}, {"create_time": {"gte": "2025-01-01"}}, {"create_time": {"lte": "2025-12-31"}}, ] }, "user": { "and": [ {"agent_id": "compliance_assistant"}, {"scene": "chat"}, {"create_time": {"gte": "2025-06-01"}}, ] }, "public": { "and": [ {"tags": {"contains": "announcement"}}, ] }, }, } ``` > **Note**: For more filter conditions and nested syntax, see [Memory Filters](/memos_cloud/features/filters). ### `relativity` / `memory_limit_number`: control recall quality and quantity - Pass `relativity` to raise the relevance threshold for recall. - Pass `memory_limit_number` to limit the total number of returned memories after all memories are merged and ranked. ```python data = { "user_id": "memos_user_123", "query": "Plan a 5-day trip to Chengdu for me.", "relativity": 0.8, # default 0.45, range 0-1 "memory_limit_number": 9 # default 9, max 25 } ``` ## 7. Common Errors and Troubleshooting | Error Code | Common Cause | How to Fix | | --- | --- | --- | | `40000` | The request body structure is invalid, or a field type is incorrect | Check whether `query` is a string and whether `knowledgebase_ids` is a string array | | `40002` | A required field is missing | Check that both `user_id` and `query` are provided and non-empty | | `40011` | `conversation_id` is too long | Use a short ID. Do not put the full question or chat history into `conversation_id` | | `40012` | `relativity` is invalid | Pass a number between 0 and 1 | | `40305` | A single request exceeds the token limit | Shorten `query`; do not put long documents directly into the search query | | `50123` | The knowledge base is not associated with the current project | Go to [Project Configuration](/api_docs/start/configuration) and confirm the knowledge base is associated with the project that owns the API Key | | `50005` | Search service is temporarily unavailable | Retry later. If it persists, contact support | ## 8. More Features - [Delete Memory](/memos_cloud/mem_operations/delete_memory): Delete specific memory entries or all memories for a user. - [Memory Filters](/memos_cloud/features/filters): Filter recalled memories by tags, time, and other conditions. - [Knowledge Base](/memos_cloud/features/knowledge_base): Specify which knowledge bases can be searched. --- # Delete Memory (/memos_cloud/mem_operations/delete_memory) ## 1. Choose a Deletion Method MemOS Cloud currently supports the following three deletion methods. Choose one based on your scenario. | Deletion method | Field | Use case | | :--- | :--- | :--- | | Delete specific memories | `memory_ids[]` | Delete one or more memories. The `memory_id` comes from the `id` field returned by `search/memory` or `get/memory` | | Delete user memories | `user_id` | Clear all memories for a user in the current project | | Delete Agent memories | `agent_id` | Clear all memories for an Agent in the current project | > **Warning**: Note > > - The three parameters are mutually exclusive. Only one deletion method can be used per call. > > - Deletion only applies within the project scope of the current API Key. Before deleting, make sure the API Key, project, and target memories belong to the same project. > > - Do not pass `conversation_id`, `knowledgebase_id`, or other IDs. Deletion by those dimensions is not supported. ## 2. Delete Specific Memories Use specific-memory deletion when you need to remove a memory that was written incorrectly, is outdated, was assigned to the wrong user, or must be deleted at the user's request. ### 2.1 Find the Memory to Delete When you call [Search Memory](/memos_cloud/mem_operations/search_memory) or get memories and find a memory that should be deleted, copy the `id` of that memory. This value is the `memory_id` used for deletion. ```json { "memory_detail_list": [ { "id": "e2a7c194-7062-4fa5-a6c0-bbe554d05d60", "memory_key": "User ice cream preference", "memory_value": "[user opinion] The user likes ice cream.", "memory_type": "WorkingMemory", "memory_time": null, "conversation_id": "0610", "status": "activated", "confidence": 0, "tags": [ "food", "preference", "ice cream" ], "update_time": 1761315278665, "relativity": 0.7524414 } ] } ``` ### 2.2 Call the Delete API ```python [Python (HTTP)] import requests API_KEY = "YOUR_API_KEY" BASE_URL = "https://memos.memtensor.cn/api/openmem/v1" data = { "memory_ids": ["6b23b583-f4c4-4a8f-b345-58d0c48fea04"] } res = requests.post( f"{BASE_URL}/delete/memory", headers={"Authorization": f"Token {API_KEY}"}, json=data ) print(res.json()) ``` ```python [Python (SDK)] from memos.api.client import MemOSClient client = MemOSClient(api_key="YOUR_API_KEY") res = client.delete_memory( memory_ids=["6b23b583-f4c4-4a8f-b345-58d0c48fea04"] ) print(res) ``` ```bash [Curl] curl --request POST \ --url https://memos.memtensor.cn/api/openmem/v1/delete/memory \ --header 'Authorization: Token YOUR_API_KEY' \ --header 'Content-Type: application/json' \ --data '{ "memory_ids": ["6b23b583-f4c4-4a8f-b345-58d0c48fea04"] }' ``` ### 2.3 Verify the Result The API returns `data.success: true` when the delete request succeeds. After deletion, call [Search Memory](/memos_cloud/mem_operations/search_memory) again to check whether the memory still appears. ```json { "code": 0, "data": { "success": true }, "message": "ok" } ``` ## 3. Delete All Memories for a User When you need to clear all memories for a user in the current project, pass `user_id`. > **Warning**: Before running this operation, make sure: > > - `user_id` is the end-user ID whose memories you want to clear. > - The API Key belongs to the project this user belongs to. > - You no longer need this user's fact, preference, Profile, Event Memory, skill, or tool memories in the current project. ```python [Python (HTTP)] import requests API_KEY = "YOUR_API_KEY" BASE_URL = "https://memos.memtensor.cn/api/openmem/v1" data = { "user_id": "memos_user_123" } res = requests.post( f"{BASE_URL}/delete/memory", headers={"Authorization": f"Token {API_KEY}"}, json=data ) print(res.json()) ``` ```python [Python (SDK)] from memos.api.client import MemOSClient client = MemOSClient(api_key="YOUR_API_KEY") res = client.delete_memory(user_id="memos_user_123") print(res) ``` ```bash [Curl] curl --request POST \ --url https://memos.memtensor.cn/api/openmem/v1/delete/memory \ --header 'Authorization: Token YOUR_API_KEY' \ --header 'Content-Type: application/json' \ --data '{ "user_id": "memos_user_123" }' ``` After deleting all memories for a user, search again with the same `user_id` for that user's previous facts or preferences to confirm that old memories are no longer returned. ## 4. Delete All Memories for an Agent When you need to clear all memories for an Agent in the current project, pass `agent_id`. > **Warning**: Before running this operation, make sure: > > - This Agent has [Independent Memory](/memos_cloud/introduction/isolation_filters#create-independent-memory-for-an-agent) enabled. > - `agent_id` is the Agent ID whose memories you want to clear. > - The API Key belongs to the project this Agent belongs to. > - You no longer need this Agent's fact, preference, Profile, Event Memory, skill, or tool memories in the current project. ```python [Python (HTTP)] import requests API_KEY = "YOUR_API_KEY" BASE_URL = "https://memos.memtensor.cn/api/openmem/v1" data = { "agent_id": "memos_agent" } res = requests.post( f"{BASE_URL}/delete/memory", headers={"Authorization": f"Token {API_KEY}"}, json=data ) print(res.json()) ``` ```python [Python (SDK)] from memos.api.client import MemOSClient client = MemOSClient(api_key="YOUR_API_KEY") res = client.delete_memory(agent_id="memos_agent") print(res) ``` ```bash [Curl] curl --request POST \ --url https://memos.memtensor.cn/api/openmem/v1/delete/memory \ --header 'Authorization: Token YOUR_API_KEY' \ --header 'Content-Type: application/json' \ --data '{ "agent_id": "memos_agent" }' ``` After deleting all memories for an Agent, search again with the same `agent_id` to confirm that old memories for that Agent are no longer returned. ## 5. Delete Memories in the Console If you only need to delete one or a few memories temporarily, you can delete them directly in the console: 1. Log in to the [MemOS Console](https://memos-dashboard.openmem.net/en/memoryList) and make sure the current project is the one you want to operate on. 2. Go to "Memory List" and use the search box, subject ID, subject type, or time range to find the target memory. 3. Click "View Details" and check the memory ID and memory content. Make sure it is not a similar memory under the same user. 4. Click "Delete" and confirm in the second confirmation dialog. To delete multiple memories, select multiple records first, then click "Batch Delete". 5. Refresh the list after deletion, or search again with the same conditions to confirm that the memory no longer appears. > **Note**: To delete memories automatically from your business system, or to batch-process `memory_id` values copied from logs or search results, call the `delete/memory` API instead. ![Delete memories in the console](https://cdn.memtensor.com.cn/img/1781505894179_et8gm6_compressed.png) ## 6. Common Errors and Troubleshooting | Error code | Common cause | How to fix | | :--- | :--- | :--- | | `40000` | The request body is invalid, or unsupported fields are passed together | Pass only one of `memory_ids`, `user_id`, or `agent_id` (the three are mutually exclusive); `memory_ids` must be a non-empty string array | | `40002` | A required field is empty | Check whether `memory_ids` / `user_id` / `agent_id` is missing, or whether you passed an empty string or empty array | | `40103` / `40132` | The API Key is invalid, expired, or cannot access the current project | Go back to [Project Configuration](/api_docs/start/configuration) and check whether the current project matches the API Key | | `40306` | Delete-memory authentication failed | Make sure the memory belongs to the project of the current API Key and that you have permission to delete it | | `40307` | The `memory_id` does not exist | Get the latest `id` from `search/memory` or `get/memory`; do not use `conversation_id`, `user_id`, or a knowledge base ID | | `40308` | The `user_id` or `agent_id` does not exist | Confirm that this user/Agent has written memories in the current project. If passing `agent_id`, confirm that this Agent has independent memory enabled and has written memories | For more error code details, see [Error Codes](/api_docs/help/error_codes). Need the complete field list, request format, and response format? See the [Delete Memory API documentation](/api_docs/core/delete_memory). --- # Update Memory (/memos_cloud/mem_operations/update_memory) ## 1. Overview This API manually updates an existing memory. Typical use cases include correcting memory content and archiving outdated memories. ## 2. Key Parameters | Field | Type | Required | Description | | :--- | :--- | :--- | :--- | | `memory_id` | string | Yes | The memory ID, from the `id` field returned by `search/memory` or `get/memory` | | `content` | string | No | The updated memory content | | `title` | string | No | The updated memory title | | `status` | string | No | Memory status | ## 3. Usage Example ### 3.1 Find the Memory to Update When you call [Search Memory](/memos_cloud/mem_operations/search_memory) or get memories, each returned memory has its own `id`. Use that `id` as `memory_id` when updating. ### 3.2 Call the Update API ```python [Python (HTTP)] import requests API_KEY = "YOUR_API_KEY" BASE_URL = "https://memos.memtensor.cn/api/openmem/v1" data = { "memory_id": "mem_event_001", "title": "Camping at West Lake with Chen Mo", "content": "Last Saturday I went camping by West Lake with my friend Chen Mo. The weather was great and we watched the stars together at night." } res = requests.post( f"{BASE_URL}/update/memory", headers={"Authorization": f"Token {API_KEY}"}, json=data ) print(res.json()) ``` ```python [Python (SDK)] # Make sure MemOS is installed (pip install MemoryOS -U) from memos.api.client import MemOSClient client = MemOSClient(api_key="YOUR_API_KEY") res = client.update_memory( memory_id="mem_event_001", title="Camping at West Lake with Chen Mo", content="Last Saturday I went camping by West Lake with my friend Chen Mo. The weather was great and we watched the stars together at night." ) print(res) ``` ```bash [Curl] curl --request POST \ --url https://memos.memtensor.cn/api/openmem/v1/update/memory \ --header 'Authorization: Token YOUR_API_KEY' \ --header 'Content-Type: application/json' \ --data '{ "memory_id": "mem_event_001", "title": "Camping at West Lake with Chen Mo", "content": "Last Saturday I went camping by West Lake with my friend Chen Mo. The weather was great and we watched the stars together at night." }' ``` ## 4. Response The API returns `code: 0` when the update succeeds. After updating, you can verify the result with [Search Memory](/memos_cloud/mem_operations/search_memory) or `get/memory/{memory_id}`. ```json { "code": 0, "message": "ok", "data": { "success": true } } ``` > **Note**: To permanently delete a memory, use the [Delete Memory](/memos_cloud/mem_operations/delete_memory) API. ## 5. Common Errors and Troubleshooting | Error Code | Common Cause | How to Fix | | :--- | :--- | :--- | | `40000` | The request body is invalid, or a field type is incorrect | Confirm `memory_id` is a string and `status` is one of the allowed values | | `40002` | A required field is empty | Check whether `memory_id` was passed | | `40103` / `40132` | The API Key is invalid, expired, or cannot access the current project | Go back to [Project Configuration](/api_docs/start/configuration) and check whether the API Key matches the project | | `40307` | The `memory_id` does not exist | Get the latest `id` from `search/memory` or `get/memory` | For more error code details, see [Error Codes](/api_docs/help/error_codes). --- # Add Feedback (/memos_cloud/mem_operations/add_feedback) ## 1. When Should You Add Feedback? MemOS feedback receives natural-language feedback from users about model answers, knowledge content, or historical memories, then automatically corrects and updates memories. You do not need to manually locate a specific memory item. Just pass the user's feedback to `add/feedback`. | Comparison | Natural-language feedback | Direct memory edit | | --- | --- | --- | | How to use | Describe the problem or correction in natural language | Specify a memory item and edit it directly | | User barrier | Low, suitable for non-technical users | Higher, usually handled by developers or admins | | System role | The system parses, locates, links, and updates automatically | Humans lead the update | | Typical use | Conversation correction, outdated knowledge, business rule changes | Precise revision, structured maintenance | ## 2. Key Parameters - **Feedback content (`feedback_content`)**: the user's natural-language feedback on a model answer, knowledge content, or memory result. - **User ID (`user_id`)**: the unique user identifier associated with the feedback. - **Conversation ID (`conversation_id`)**: the unique conversation identifier associated with the feedback, used to provide context. - **Knowledge base scope (`allow_knowledgebase_ids`)**: the list of knowledge bases that new memories from this feedback can be written into. ## 3. How It Works In a chatbot scenario, the user can click "report an issue" below a model answer, enter feedback, and submit it. ![Feedback UI](https://cdn.memtensor.com.cn/img/1770716602140_1z3yi5_compressed.png) Based on the feedback content, your backend calls the MemOS `add/feedback` API and triggers a memory update. - **Validity analysis**: parse the feedback with the current conversation context and decide whether it is valid and related to the conversation. - **Update type recognition**: classify the requested update as keyword replacement or semantic update. - **Memory update**: write new memories and update or override existing memories that are conflicting, outdated, or corrected. ## 4. Quick Start ### Semantic Update of Knowledge Base Memory When enterprise policies, knowledge base content, or business rules change, you can pass the user's natural-language feedback directly to MemOS. The system generates a new high-priority memory. #### Submit Natural-language Feedback A finance manager gives feedback in the conversation: the purchase limit for office software should be 600 CNY, not 800 CNY. ```python [Python (HTTP)] import requests API_KEY = "YOUR_API_KEY" BASE_URL = "https://memos.memtensor.cn/api/openmem/v1" data = { "user_id": "memos_user_123", "conversation_id": "memos_feedback_conv", "feedback_content": "The purchase limit for office software is 600 CNY, not 800 CNY.", "allow_knowledgebase_ids": ["basee5ec9050-c964-484f-abf1-ce3e8e2aa5b7"] } res = requests.post( f"{BASE_URL}/add/feedback", headers={"Authorization": f"Token {API_KEY}"}, json=data ) print(res.json()) ``` ```python [Python (SDK)] from memos.api.client import MemOSClient client = MemOSClient(api_key="YOUR_API_KEY") res = client.add_feedback( user_id="memos_user_123", conversation_id="memos_feedback_conv", feedback_content="The purchase limit for office software is 600 CNY, not 800 CNY.", allow_knowledgebase_ids=["basee5ec9050-c964-484f-abf1-ce3e8e2aa5b7"] ) print(res) ``` ```bash [Curl] curl --request POST \ --url https://memos.memtensor.cn/api/openmem/v1/add/feedback \ --header 'Authorization: Token YOUR_API_KEY' \ --header 'Content-Type: application/json' \ --data '{ "user_id": "memos_user_123", "conversation_id": "memos_feedback_conv", "feedback_content": "The purchase limit for office software is 600 CNY, not 800 CNY.", "allow_knowledgebase_ids": ["basee5ec9050-c964-484f-abf1-ce3e8e2aa5b7"] }' ``` #### Verify the Update Through Search After feedback is processed, when another user searches for the software reimbursement policy, the result can include a new high-priority memory: the purchase limit for office software is 600 CNY, not 800 CNY. ```python [Python (HTTP)] import requests API_KEY = "YOUR_API_KEY" BASE_URL = "https://memos.memtensor.cn/api/openmem/v1" data = { "user_id": "memos_user_123", "conversation_id": "memos_feedback_check", "query": "Help me check the reimbursement limit for software purchases.", "knowledgebase_ids": ["basee5ec9050-c964-484f-abf1-ce3e8e2aa5b7"] } res = requests.post( f"{BASE_URL}/search/memory", headers={"Authorization": f"Token {API_KEY}"}, json=data ) print(res.json()) ``` ```python [Python (SDK)] from memos.api.client import MemOSClient client = MemOSClient(api_key="YOUR_API_KEY") res = client.search_memory( user_id="memos_user_123", conversation_id="memos_feedback_check", query="Help me check the reimbursement limit for software purchases.", knowledgebase_ids=["basee5ec9050-c964-484f-abf1-ce3e8e2aa5b7"] ) print(res) ``` ```bash [Curl] curl --request POST \ --url https://memos.memtensor.cn/api/openmem/v1/search/memory \ --header 'Authorization: Token YOUR_API_KEY' \ --header 'Content-Type: application/json' \ --data '{ "user_id": "memos_user_123", "conversation_id": "memos_feedback_check", "query": "Help me check the reimbursement limit for software purchases.", "knowledgebase_ids": ["basee5ec9050-c964-484f-abf1-ce3e8e2aa5b7"] }' ``` ##### Output ```python "memory_detail_list": [ { "id": "8a4f3d2e-c417-4e53-bc25-54451abd5ac8", "memory_key": "Software purchase reimbursement policy trial version", "memory_value": "The policy requires the purchase limit for office software to be 800 CNY and applies to document editing and spreadsheet tools.", "memory_type": "LongTermMemory", "conversation_id": "default_session", "relativity": 0.8931847 }, { "id": "a72a04d1-d7ba-4ebd-9410-0097bfa6c20d", "memory_key": "Office software purchase limit", "memory_value": "The user confirmed that the purchase limit for office software is 600 CNY, not 800 CNY.", "memory_type": "WorkingMemory", "conversation_id": "memos_feedback_conv", "relativity": 0.7196722 } ] ``` The [Knowledge Base console](https://memos-dashboard.openmem.net/knowledgeBase/) also shows knowledge base memories corrected or supplemented through natural-language interaction. ![Knowledge base correction](https://cdn.memtensor.com.cn/img/1765970178683_5tuxe4_compressed.png) ### Keyword Replacement Memory If the user clearly indicates that a name, rule, or field should be replaced globally, you can also describe the replacement intent in natural language. ```python data = { "user_id": "memos_user_123", "conversation_id": "memos_feedback_conv", "feedback_content": "From now on, I changed my name. Replace User 1 with User 2 everywhere.", "allow_knowledgebase_ids": ["basee5ec9050-c964-484f-abf1-ce3e8e2aa5b7"] } ``` ## 5. Common Errors and Troubleshooting | Error Code | Common Cause | How to Fix | | --- | --- | --- | | `40000` | The request JSON structure is invalid, or a field type is incorrect | Check whether `feedback_content` is a string and whether `allow_knowledgebase_ids` is a string array | | `40002` | A required field is empty | Check that `user_id`, `conversation_id`, and `feedback_content` are all provided and non-empty | | `40011` | `conversation_id` is too long | Use a short ID. Do not put full conversations, user input, or JSON into `conversation_id` | | `40305` | A single request exceeds the token limit | Shorten the feedback content and keep the key correction information | | `40309` | Token usage exceeds the per-time-window limit | Lower feedback write concurrency and retry in batches | | `50123` | The knowledge base is not associated with the current project | Go to [Project Configuration](/api_docs/start/configuration) and confirm the knowledge base is associated with the project that owns the API Key | | `50145` | Failed to save feedback and write memory | Check the request content and retry later. If it persists, contact support | Need the complete field list, request format, and response format? See the [Add Feedback API documentation](/api_docs/message/add_feedback). --- # Continuous Conversation Chat (/memos_cloud/mem_operations/chat) ## 1. When to Use the Chat API The Chat API is suitable for quickly building AI conversation applications with long-term memory. You only pass the user's current message; MemOS automatically handles memory recall, prompt assembly, model response generation, and conversation writing. - **Integrated conversational AI**: one API completes conversation generation without a complex custom pipeline. - **Automatic memory handling**: automatically extracts, updates, and retrieves memories, reducing manual maintenance. - **Continuous context**: keeps understanding coherent across turns, days, and even sessions. ## 2. Compared with Memory Operation APIs **Use Chat**: Best for general AI conversations, business PoCs, and quick validation **Use Memory Operation APIs**: Best for complex Agents and deeper business-system integration | Dimension | Chat API | Memory operation APIs | | --- | --- | --- | | Integration complexity | Low, ready to use | Medium, requires orchestration | | Memory management | Automatic | Manually add, search, and assemble | | Model response | Generated by MemOS built-in model | Call your own external model | | Control | Good for common configuration | Good for complex pipelines and fine-grained control | ## 3. How It Works ![Chat API flow](https://cdn.memtensor.com.cn/img/1765973438090_tskx7x_compressed.png) 1. If historical user messages exist, call `add/message` to write them into MemOS first. 2. When the end user sends a message, your AI application calls `chat` with the user message and related parameters. 3. MemOS recalls historical memories related to the current user message and assembles custom instructions, current conversation context, and user memories. 4. MemOS calls the model to generate an answer and returns the result to your AI application. 5. By default, MemOS asynchronously processes the user message and model response in the background and writes them as memories. ## 4. Quick Start ### Optional: add historical messages If you already have conversation history, call `add/message` first. For a new user or a new conversation, skip this step and call Chat directly. ```python [Python (HTTP)] import requests API_KEY = "YOUR_API_KEY" BASE_URL = "https://memos.memtensor.cn/api/openmem/v1" data = { "user_id": "memos_user_123", "conversation_id": "0610", "messages": [ {"role": "user", "content": "I booked a summer trip to Guangzhou. Which hotel chains are available?"}, {"role": "assistant", "content": "You can consider 7 Days Inn, Ji Hotel, Hilton, and others."}, {"role": "user", "content": "I'll choose 7 Days Inn."}, {"role": "assistant", "content": "Got it. Feel free to ask if you have other questions."} ] } res = requests.post( f"{BASE_URL}/add/message", headers={"Authorization": f"Token {API_KEY}"}, json=data ) print(res.json()) ``` ```python [Python (SDK)] from memos.api.client import MemOSClient client = MemOSClient(api_key="YOUR_API_KEY") messages = [ {"role": "user", "content": "I booked a summer trip to Guangzhou. Which hotel chains are available?"}, {"role": "assistant", "content": "You can consider 7 Days Inn, Ji Hotel, Hilton, and others."}, {"role": "user", "content": "I'll choose 7 Days Inn."}, {"role": "assistant", "content": "Got it. Feel free to ask if you have other questions."} ] res = client.add_message( messages=messages, user_id="memos_user_123", conversation_id="0610" ) print(res) ``` ### Call Chat When you call `chat`, MemOS automatically retrieves relevant memories and generates an answer. ```python [Python (HTTP)] import requests API_KEY = "YOUR_API_KEY" BASE_URL = "https://memos.memtensor.cn/api/openmem/v1" data = { "user_id": "memos_user_123", "conversation_id": "0928", "query": "I want to travel during National Day. Recommend a city I have not visited and a hotel brand I have not stayed at." } res = requests.post( f"{BASE_URL}/chat", headers={"Authorization": f"Token {API_KEY}"}, json=data ) print(res.json()) ``` ```python [Python (SDK)] from memos.api.client import MemOSClient client = MemOSClient(api_key="YOUR_API_KEY") res = client.chat( user_id="memos_user_123", conversation_id="0928", query="I want to travel during National Day. Recommend a city I have not visited and a hotel brand I have not stayed at." ) print(res) ``` ```bash [Curl] curl --request POST \ --url https://memos.memtensor.cn/api/openmem/v1/chat \ --header 'Authorization: Token YOUR_API_KEY' \ --header 'Content-Type: application/json' \ --data '{ "user_id": "memos_user_123", "conversation_id": "0928", "query": "I want to travel during National Day. Recommend a city I have not visited and a hotel brand I have not stayed at." }' ``` For the full field list, request format, and response format, see the [Chat API documentation](/api_docs/chat/chat). ## 5. Limits - Input limit: 8,000 tokens. - Output limit: up to 25 fact memories and up to 25 preference memories can be recalled. ## 6. More Usage Options The Chat API works out of the box. The following parameters are optional and only needed when you want to control memory recall, model responses, or memory writing. ### Control memory recall scope Use these fields to control which memories are considered and how many are recalled: - `filter`: filter memories by tags, time, business fields, and other conditions. - `knowledgebase_ids`: specify which knowledge bases Chat can search. - `relativity`: control the relevance threshold for recalled memories. - `memory_limit_number`: limit the number of fact memories passed to the model. ```python data = { "user_id": "memos_user_123", "conversation_id": "0928", "query": "Use the knowledge base to summarize travel reimbursement rules.", "knowledgebase_ids": ["kb_xxx"], "filter": { "and": [ {"tags": {"contains": "travel"}}, {"create_time": {"gte": "2025-01-01"}} ] }, "relativity": 0.8, "memory_limit_number": 9 } ``` ### Control model response behavior Use these fields to specify the model, enable streaming, or adjust generation parameters: - `model_name`: specify the conversation model. - `stream`: control whether to stream the response. - `temperature`: control randomness. - `top_p`: control candidate token selection. - `max_tokens`: limit the maximum generated length. ```python data = { "user_id": "memos_user_123", "conversation_id": "0928", "query": "Summarize my travel preferences in a concise tone.", "model_name": "qwen2.5-72b-instruct", "stream": False, "temperature": 0.7, "top_p": 0.95, "max_tokens": 1024 } ``` To fully customize model behavior, pass `system_prompt` to override the default system prompt. ### Control whether new memories are written automatically By default, Chat writes the current user message and model response into memory. If you only want to generate an answer and do not want this turn to enter memory processing, pass: - `add_message_on_answer`: whether to write this user message and model response into memory. ```python data = { "user_id": "memos_user_123", "conversation_id": "0928", "query": "Answer this once, but do not write this turn into memory.", "add_message_on_answer": False } ``` For ordinary conversations, you can ignore these fields. When you want new memories generated by Chat to carry business ownership or control where they are written, use: - `agent_id`: mark which Agent the conversation belongs to. - `app_id`: mark which application the conversation comes from. - `tags`: add tags for future retrieval and filtering. - `info`: write custom business metadata such as scene, order ID, or status. - `allow_public`: whether to allow writing to project-level public memory. - `allow_knowledgebase_ids`: which knowledge bases can be written. ## 7. Common Errors and Troubleshooting | Error Code | Common Cause | How to Fix | | --- | --- | --- | | `40000` | The request JSON structure is invalid, or a field type is incorrect | Check whether `query` is a string, `filter` is an object, and `knowledgebase_ids` / `allow_knowledgebase_ids` are string arrays | | `40002` | A required field is empty | Check that `user_id`, `conversation_id`, and `query` are all provided and non-empty | | `40010` | `user_id` is too long | Use a stable and shorter end-user ID. The length cannot exceed 100 characters | | `40011` | `conversation_id` is too long | Use a short conversation ID. Do not put full conversations, user input, or JSON into `conversation_id` | | `40301` / `40305` | Input content or request tokens exceed the limit | Shorten `query`, `system_prompt`, and filter conditions. Do not put long documents directly into the Chat request | | `40302` / `40303` | Generated content or chat length exceeds the model limit | Lower `max_tokens`, shorten the expected output, or split the request into multiple turns | | `50123` | The knowledge base is not associated with the current project | Go to [Project Configuration](/api_docs/start/configuration) and confirm the knowledge base is associated with the project that owns the API Key | | `50144` | Message writing after the Chat response failed | If `add_message_on_answer` is enabled, check the request content and retry later. If it persists, contact support | For more error code details, see [Error Codes](/api_docs/help/error_codes). For the full field list, request format, and response format, see the [Chat API documentation](/api_docs/chat/chat). --- # Memory Filters (/memos_cloud/features/filters) > **Warning**: Note > > You need to pass the relevant fields when calling the [Add Message API](/api_docs/core/add_message) before you can use them as filter conditions in the [Search Memory API](/api_docs/core/search_memory). > > This page focuses on the feature behavior. For complete API fields and limits, see the API documentation above. ## 1. When to Use Memory Filters When the memory set grows large, or when a single retrieval request accesses user memories, public memories, and Knowledge Base memories at the same time, you often need to narrow the candidate scope before MemOS performs semantic retrieval. Memory Filters are used for this precise pre-retrieval filtering step. Common scenarios include: - Retrieve only memories generated by a specific Agent or App. - Retrieve only memories created or updated within a specific time range. - Retrieve only memories that contain specific tags. - Filter by business fields written when adding messages, such as `scene`, `biz_id`, or `business_type`. - Apply different filters to user memories, public memories, and Knowledge Base memories. ## 2. How It Works 1. **Filter the scope first**: MemOS strictly filters candidate memories based on the conditions in `filter`. 2. **Then perform semantic retrieval**: Within the filtered candidates, MemOS runs [memory retrieval](/memos_cloud/mem_operations/search_memory) and returns the fragments most relevant to `query`. This means Filter is not keyword search. It is a scope control mechanism before retrieval. The stricter the filter, the fewer candidate memories enter semantic retrieval. ## 3. Two Filtering Modes ### Global Filter If you do not need to distinguish memory sources, you can put logical conditions directly at the root of `filter`. The condition applies to the memory scope involved in the current retrieval. ```json "filter": { "and": [ {"tags": {"contains": "reading"}}, {"create_time": {"gte": "2025-01-01"}}, {"create_time": {"lte": "2025-12-31"}}, {"scene": "chat"} ] } ``` ### Source-Specific Filter If one retrieval request accesses multiple memory types, you can set separate filter conditions for each source inside `filter`. | Source | Description | | --- | --- | | `user` | User-specific memories accumulated from the user's conversation history | | `agent` | Agent memories, available after enabling [Create Independent Memory for an Agent](/memos_cloud/introduction/isolation_filters#create-independent-memory-for-an-agent) | | `public` | Project-level public memories shared across users in the project | | `knowledgebase` | Knowledge Base memories created from uploaded documents or Skills | Source-specific filters are useful for more precise retrieval strategies, such as filtering user memories by recency, filtering Knowledge Base memories by tags, and leaving public memories unfiltered. Sources not included in `filter` will not receive extra filter conditions. #### Example: Source-Specific Retrieval Across User, Knowledge Base, and Public Memories The example below retrieves the user's and Agent's memories since June 1, 2025, and also retrieves Knowledge Base and public memories tagged with "policy". ```json "filter": { "user": { "and": [ {"agent_id": "memos_agent"}, {"create_time": {"gte": "2025-06-01"}} ] }, "knowledgebase": { "and": [ {"tags": {"contains": "policy"}} ] }, "public": { "and": [ {"tags": {"contains": "policy"}} ] } } ``` > **Note**: Use either a global filter or a source-specific filter. If different memory sources need different conditions, prefer source-specific filtering. ## 4. Available Fields and Operators The root of each filter group must be `and` or `or`, followed by a list of field conditions. ### Instance Fields | Field | Type | Operator | Example | | --- | --- | --- | --- | | `agent_id` | string | `=` | `{"agent_id":"memos_agent"}` | | `app_id` | string | `=` | `{"app_id":"app_123"}` | | `related_id` | list | `=` | `{"related_id": ["memos_user_1", "memos_user_2"]}` | > **Note**: More about `related_id`: > > - Supports passing multiple `agent_id` and `user_id` values at once, to filter memories related to the specified Agents or users. > - Multiple IDs in the array are OR'd together — matching any one of them is enough. > - This field can be used in both global filters and source-specific filters. ### Metadata Fields When adding messages, you can write business metadata through `info`. During retrieval, use those fields directly by name in `filter`; do not wrap them in another `info` object. | Field | Type | Operator | Example | | --- | --- | --- | --- | | `business_type` | string | `=` | `{"business_type":"shopping"}` | | `biz_id` | string | `=` | `{"biz_id":"order_123456"}` | | `scene` | string | `=` | `{"scene":"payment"}` | | `custom_status` | string | `=` | `{"custom_status":"VIP3"}` | ```json // Recommended {"scene": "chat"} // Do not write it like this {"info": {"scene": "chat"}} ``` ### Tag Fields | Field | Type | Operator | Example | | --- | --- | --- | --- | | `tags` | list | `contains` | `{"tags": {"contains": "finance"}}` | ### Time Fields | Field | Type | Operator | Example | | --- | --- | --- | --- | | `create_time` | string | `lt`, `gt`, `lte`, `gte` | `{"create_time": {"gte": "2025-12-10"}}` | | `update_time` | string | `lt`, `gt`, `lte`, `gte` | `{"update_time": {"lte": "2025-12-10"}}` | ## 5. Usage Examples The filters below cover common filtering needs, so you don't have to build the filter logic from scratch. --- - **Agents** ```json // Filter memories related to any of the following Agents "filter" : { "or": [ {"agent_id": "agent_123"}, {"agent_id": "agent_456"} ] } ``` - **Metadata** ```json // Filter by custom metadata fields written via info (write the field name directly in filter, without wrapping it in info) "filter" : { "and": [ {"business_type":"travel"}, {"biz_id":"travel_001"}, {"scene":"payment"}, {"custom_status":"v1"} ] } ``` - **Tags** ```json // Filter memories that contain a specific tag "filter" : { "and": [ {"tags": {"contains": "weather"}} ] } ``` - **Date range** ```json // Filter memories from December 2025 "filter" : { "and": [ {"create_time": {"gt": "2025-12-01"}}, {"create_time": {"lt": "2026-01-01"}} ] } // Filter memories updated recently "filter" : { "and": [ {"update_time": {"gt": "2025-12-10"}} ] } ``` - **Multiple dimensions** ```json // Filter a user's Q4 billing-related memories with the customer service Agent "filter" : { "and": [ {"agent_id": "customer_service"}, {"scene":"billing"}, {"create_time": {"gt": "2025-10-01"}}, {"create_time": {"lt": "2026-01-01"}} ] } ``` - **Retrieve memories related to multiple Agents or users** ```json "filter" : { "and": [ {"related_id": ["memos_agent_1", "memos_agent_2"]} ] } ``` --- # Async Mode (/memos_cloud/features/async_mode) > **Warning**: **[This article expands on the async mode in the [Add Memory - addMessage API], click here to view the detailed API documentation directly](/api_docs/core/add_message)** > **Note**: The `async_mode` parameter currently defaults to `true`. Memory addition operations are processed asynchronously by default, queued for background execution instead of waiting for processing to complete before returning a response. ## 1. Using Async Mode ### Processing Flow When the `async_mode` parameter is set to `true`, the API returns a response immediately and queues the memory for processing in the background: ```json { "code": 0, "data": { "success": true, "task_id": "c464e17e-f2ff-4e9a-a2c2-41cc55ab43b9", "status": "running" }, "message": "ok" } ``` In async mode, memory writing is split into two stages: "rough processing" and "refined processing". The system first performs millisecond-level rough processing on the current turn of messages, so they can already be retrieved in the next turn of conversation; Refined processing (seconds or longer) then continues in the background to improve memory quality. You can check progress via the [get/status](/api_docs/message/get_status) interface: the task status is `running` during rough processing and updates to `completed` once refined processing finishes. Once the task completes, `memory_views` in the response summarizes how many memories were added/updated/deleted in this turn, along with the memory IDs touched under each memory category. ```python import os import requests import json os.environ["MEMOS_API_KEY"] = "YOUR_API_KEY" os.environ["MEMOS_BASE_URL"] = "https://memos.memtensor.cn/api/openmem/v1" data = { "task_id": "c464e17e-f2ff-4e9a-a2c2-41cc55ab43b9" } headers = { "Content-Type": "application/json", "Authorization": f"Token {os.environ['MEMOS_API_KEY']}" } url = f"{os.environ['MEMOS_BASE_URL']}/get/status" res = requests.post(url=url, headers=headers, data=json.dumps(data)) print(f"result: {res.json()}") ``` ```json { "code": 0, "message": "ok", "data": { "task_id": "c464e17e-f2ff-4e9a-a2c2-41cc55ab43b9", "status": "completed", "memory_views": { "added": 1, "updated": 1, "deleted": 0, "detail_factual": { "memory_ids": ["memos_mem_001"] }, "preference": { "memory_ids": ["memos_mem_002"] } } } } ``` ### When to Use Async Mode * **Reduce Interface Response Latency**: Users do not need to wait and can continuously use memory within the application; * **Batch Add Memories**: Process large amounts of data simultaneously to avoid blocking the application; * **Background Task Processing**: Offload time-consuming memory processing operations to the background to improve system concurrency capabilities. > **Note**: Note > When a message contains multimodal content, since file memory processing takes a long time, the `async_mode` field you pass becomes invalid, and "Async Mode" is used by default. You can query the processing progress of file memory via the `get/status` interface. ## 2. Using Sync Mode ### Processing Flow When the `async_mode` parameter is set to `false`, the API returns the result after memory processing is completed: ```json { "code": 0, "data": { "success": true, "task_id": "c464e17e-f2ff-4e9a-a2c2-41cc55ab43b9", "status": "completed" }, "message": "ok" } ``` At this point, retrieving memory will return memories that have been fully processed: ```json "memory_detail_list":[ { "memory_key": "Summer Vacation Guangzhou Travel Plan", "memory_value": "The user plans to travel to Guangzhou during the summer vacation and has chosen 7 Days Inn as the accommodation option.", "conversation_id": "0610", "tags": [ "Travel", "Guangzhou", "Accommodation", "Hotel" ] } ], "preference_detail_list":[ { "preference_type": "implicit_preference", "preference": "The user may prefer high cost-performance hotel choices.", "reasoning": "7 Days Inn is usually known for being economical. The user's choice of 7 Days Inn may indicate a preference for high cost-performance options in accommodation. Although the user did not explicitly mention budget constraints or specific hotel preferences, choosing 7 Days Inn among the provided options may reflect an emphasis on price and practicality.", "conversation_id": "0610" } ] ``` ### When to Use Sync Mode * **Debugging and Development Phase**: View the results after memory processing directly, facilitating memory retrieval debugging; * **Instant Query**: Need to confirm that memory has been created or updated when the API call returns, such as in performance testing, functional verification, etc. * **Small-scale Operations**: Sync mode can be used when the data volume is small and latency impact is minimal. ### Important Notes * The default behavior for async processing is now `async_mode=true`. * If you need sync mode, please set `async_mode=false` when adding messages. --- # Custom Tags (/memos_cloud/features/custom_tags) > **Warning**: Note > > > > **[You need to pass the tag list when calling addMessage (Click here for detailed API documentation)](/api_docs/core/add_message)** > > > **[Only then can you use tags for filtering when calling searchMemory (Click here for detailed API documentation)](/api_docs/core/search_memory)** > > > > **This article focuses on functional description. For detailed API fields and limits, please click the text links above.** MemOS automatically generates tags for each memory, but these tags may not be completely consistent with the tags used in your business. You can pass a list of custom tags when adding messages, and MemOS will automatically apply relevant tags to the memory content based on the meaning of the tags you provide. > **Note**: When to use custom tags? > > You want MemOS to use the product team's existing tag system to label memory content. > > You need to apply these tags to generate structured content. ## 1. Tag Mechanism * **Automatic Tag Generation**: MemOS analyzes semantics when processing memories and automatically generates relevant tags for subsequent retrieval and filtering. * **Custom Tags**: When adding messages, you can pass a set of custom tags through the `tags` field as a candidate tag set. * **Semantic Matching**: MemOS will judge the semantic similarity between the memory content and the tag list provided by the developer, select matching tags from them, and write them into the `tags` field of the memory along with the system-generated tags. ## 2. Usage Example > **Note**: Tip > * Tag content should be concise while clearly distinguishing the meanings of different categories to facilitate identification and matching. > > * Use a unified list under the same project dimension and do not replace it easily to ensure consistency in retrieval and filtering. ## 3. Add Message ```python import os import json import requests # Replace with your MemOS API Key os.environ["MEMOS_API_KEY"] = "YOUR_API_KEY" os.environ["MEMOS_BASE_URL"] = "https://memos.memtensor.cn/api/openmem/v1" data = { "user_id": "memos_user_123", "conversation_id": "1210", "messages": [ {"role": "user","content": "How is the weather today?"}, {"role": "assistant","content": "Shanghai, December 10th, cloudy, temperature 8-12 degrees."} ], "tags":["Weather","Cloudy"], "async_mode":False } headers = { "Content-Type": "application/json", "Authorization": f"Token {os.environ['MEMOS_API_KEY']}" } url = f"{os.environ['MEMOS_BASE_URL']}/add/message" res = requests.post(url=url, headers=headers, data=json.dumps(data)) print(f"result: {res.json()}") ``` ### Search Memory ```python import os import json import requests # Replace with your MemOS API Key os.environ["MEMOS_API_KEY"] = "YOUR_API_KEY" os.environ["MEMOS_BASE_URL"] = "https://memos.memtensor.cn/api/openmem/v1" data = { "user_id": "memos_user_123", "query": "Shanghai Weather" } headers = { "Content-Type": "application/json", "Authorization": f"Token {os.environ['MEMOS_API_KEY']}" } url = f"{os.environ['MEMOS_BASE_URL']}/search/memory" res = requests.post(url=url, headers=headers, data=json.dumps(data)) print(f"result: {res.json()}") ``` ### Output Result ```json "memory_detail_list": [ { "id": "9bc102cb-76d8-4a59-86d7-8fd1c4542407", "memory_key": "Weather Conditions", "memory_value": "On December 10, 2025, the weather in Shanghai was cloudy with temperatures between 8 and 12 degrees.", "memory_type": "WorkingMemory", "create_time": 1765376340736, "conversation_id": "1210", "status": "activated", "confidence": 0.99, "tags": [ "Weather", "Cloudy", "Temperature" ], "update_time": 1765376340737, "relativity": 0.82587826 } ] ``` --- # Knowledge Base (/memos_cloud/features/knowledge_base) > **Warning**: **[This article is an introduction to the [MemOS Knowledge Base] feature. Click here to view the detailed API documentation directly.](/api_docs/knowledge/create_kb)** ## 1. MemOS Knowledge Base vs Traditional RAG MemOS Knowledge Base supports developers in integrating business knowledge into the long-term memory system of intelligent applications. The system uses uploaded documents as the underlying data source to build and maintain an independent memory layer, supporting natural language interaction applications such as Q&A. As end-users continue to use it, MemOS dynamically evolves and updates memories based on conversation content, thereby promoting automatic iteration and self-evolution of the knowledge base. Unlike the static storage of traditional RAG, MemOS makes the knowledge base part of "memory". AI applications with "memory" can not only query information more accurately but also better understand the background and the user. Let's look at two real scenarios to compare the two solutions: **Shopping Customer Service Robot** **Background** ```python DAY 1 User asks: I have a three-month-old Golden Retriever. Which dog food is better? By the way, it doesn't eat chicken flavor. DAY 1 User bought A lamb puppy food under the assistant's recommendation. DAY 10 User asks: The dog has diarrhea eating this dog food. I want to change to another one. ``` **RAG Solution** ```python # Retrieve snippets related to "puppy food recommendation" and "diarrhea" based on user input, but fail to recall "user's dog doesn't eat chicken flavor". Retrieved knowledge: 1. Common reasons for dog food diarrhea: Can switch to hypoallergenic dog food. 2. Hypoallergenic puppy food recommendation: B (Chicken), C (Salmon). # 🤦 Shopping Assistant: If diarrhea occurs now, you can try B (Chicken flavor), C (Salmon). ``` **MemOS Solution** ```python # Retrieve relevant memories based on user input, perceive that the user's dog is a three-month-old Golden Retriever puppy, dislikes chicken, and needs a recommendation for puppy food that won't cause diarrhea. Retrieved memories: 1. The user has a three-month-old Golden Retriever weighing about 12 catties. 2. The user's dog does not eat chicken-flavored dog food. 3. The user previously purchased lamb puppy food. 4. Common reasons for dog food diarrhea: Can switch to hypoallergenic dog food. 5. Hypoallergenic puppy food recommendation: B (Chicken), C (Salmon). # ✅ Shopping Assistant: You mentioned before that the dog is a 3-month-old Golden Retriever and cannot eat chicken flavor, so I have excluded all chicken-flavored puppy foods for you. You bought lamb + salmon puppy food before. If diarrhea occurs now, you can try the milder C (Salmon Puppy Hypoallergenic). ``` **Enterprise Knowledge Base Assistant** **Background** ```python DAY 1 Employee asks: My computer is a MacBook Pro 13-inch, Intel chip. How do I install the company intranet proxy? DAY 1 Assistant provided the installation steps for the Intel version. DAY 20 Employee asks: The intranet proxy won't open. Which version should I reinstall? ``` **RAG Solution** ```python # Retrieve content related to "intranet proxy" and "won't open" based on user input, but fail to recall "user's device model". Retrieved knowledge: 1. Intranet proxy common troubleshooting 2. Intranet proxy installation instructions for M1/M2 (ARM) versions 3. Windows intranet proxy client installation instructions 4. Network connection and certificate issues 5. General FAQ # 🤦 Knowledge Base Assistant: Please try to re-download and install the latest Mac M1/M2 (ARM) version or Windows intranet proxy client. Here are the installation steps: ... ``` **MemOS Solution** ```python # Retrieve memories related to "intranet proxy" and "won't open" based on the employee's question, automatically identify the employee's device model. Retrieved memories: 1. The user installed the company intranet proxy 20 days ago, and his device is MacBook Pro 13 (Intel). 2. Intranet proxy common troubleshooting 3. Intranet proxy installation instructions for Intel version # ✅ Knowledge Base Assistant: You are using a MacBook Pro with an Intel chip. It is recommended to reinstall the Intel version of the intranet proxy client. Here are the download link and installation steps for the Intel version: ... ``` > **Note**: ** Advantage Summary** > RAG is good at retrieving information semantically similar to the query from the knowledge base, but it is **stateless**: every query is independent, lacking understanding of the specific user and context. > > MemOS can understand information such as **relationships, time, and preferences**, linking current questions with historical memories, and finding and using knowledge with "context": > > * **Understand Users**: MemOS knows "who you are" and "what you are doing". Just ask a question, and MemOS will automatically complete the context. > > * **Personalization**: For different positions and work habits, MemOS can remember "this client dislikes overly aggressive sales", "you use Python more often than Java", "you consulted the reimbursement policy last time, do you need to enter the application process this time". > > * **Knowledge Evolution**: When there are "rules of thumb" not written in documents in the actual process, MemOS will precipitate them into new memories, continuously supplementing and perfecting the knowledge system. ## 2. How it Works 1. **Upload**: Create a knowledge base and upload documents via the console or API. 2. **Validation**: Complete authentication and verify compliance of document format, size, etc. 3. **Storage**: After successful upload, documents are saved by MemOS and enter the processing queue. 4. **Parsing**: Parse original document content according to different file types. 5. **Intelligent Segmentation**: Split documents into finer-grained content fragments based on title, structure, and semantics. 6. **Generate Memory**: MemOS generates knowledge memories based on fragments, forming a complete project memory bank together with user long-term memories. 7. **Embedding and Indexing**: Write all memory content into the database and establish embedding indexes to support millisecond-level retrieval. ## 3. Knowledge Base Requirements ### Capacity Limits MemOS Cloud Service currently offers multiple pricing plans from free to enterprise versions for all developers. Different versions have different limits on knowledge base capacity and quantity. > **Note**: Currently, all versions are free for a limited time. Visit [Official Website - Pricing](https://memos.openmem.net/pricing) to apply for the version that suits your needs. | **Version** | **Knowledge Base Storage Limit** | | ---------- | ----------------------------------------- | | **Free** | Knowledge Base Count: 10; Single KB Storage: 1G | | **Starter** | Knowledge Base Count: 30; Single KB Storage: 10G | | **Pro** | Knowledge Base Count: 100; Single KB Storage: 100G | > **Warning**:  Note > When your service level is downgraded, if the existing knowledge base exceeds the capacity limit of the current version, MemOS **will not clear existing knowledge base data**, but will restrict the following operations: > > * Cannot create new knowledge bases > * Cannot continue to upload new documents > > Relevant functions will be restored after usage is adjusted to within the capacity range of the current version. ### Document Limits 1. Supported document types: PDF, DOCX, DOC, TXT, JSON, MD, XML 2. Single file size limit: Not exceeding 100 MB, 500 pages 3. Single upload file quantity limit: Not exceeding 20 > **Warning**:  Note > When the number of files, single file size, or number of pages in a single upload exceeds the above limits, the upload task will be judged as **processing failed**. > Please adjust the files according to the requirements and re-initiate the upload request. ### Skill Document Limits In addition to regular knowledge documents, a knowledge base also supports uploading custom Skill documents. Skill documents are used to capture reusable task-handling workflows and can be returned to the Agent together with other memories during retrieval. The format requirements are as follows: 1. **Single `.md` file** * Size limit: ≤ 100KB * File content: must include `name` and `description` 2. **Skill package `.zip`** | Constraint | Requirement | | --- | --- | | Format | Standard ZIP, no rar/7z | | Zip size | ≤ 20MB | | File count after extraction | ≤ 200 | | Single file after extraction | ≤ 10MB | | SKILL.md | ≤ 100KB, `name`/`description` required, must be at the first level of the archive | ## 4. Usage Example Here is a complete knowledge base usage example to help you quickly get started with building your exclusive "Knowledge Base Assistant". ### Create Knowledge Base: Financial Reimbursement Knowledge Base ```python [Python (HTTP)] import os import requests import json # Replace with your MemOS API Key os.environ["MEMOS_API_KEY"] = "YOUR_API_KEY" os.environ["MEMOS_BASE_URL"] = "https://memos.memtensor.cn/api/openmem/v1" data = { "knowledgebase_name": "Financial Reimbursement Knowledge Base", "knowledgebase_description": "Summary of all financial reimbursement related knowledge of the company" } headers = { "Content-Type": "application/json", "Authorization": f"Token {os.environ['MEMOS_API_KEY']}" } url = f"{os.environ['MEMOS_BASE_URL']}/create/knowledgebase" res = requests.post(url=url, headers=headers, data=json.dumps(data)) print(f"result: {res.json()}") ``` ```text [Output] "result": { "code": 0, "data": { "id": "idxxxxx" #Replace with the Knowledge Base ID created above }, "message": "ok" } ``` ### Upload Document: Software Procurement Reimbursement Policy ```python [Python (HTTP)] import os import requests import json # Replace with your MemOS API Key os.environ["MEMOS_API_KEY"] = "YOUR_API_KEY" os.environ["MEMOS_BASE_URL"] = "https://memos.memtensor.cn/api/openmem/v1" data = { "knowledgebase_id": "idxxxxx", #Replace with the Knowledge Base ID created above "file": [ {"content": "https://cdn.memtensor.com.cn/file/Software_Procurement_Reimbursement_Policy.pdf"} ] } headers = { "Content-Type": "application/json", "Authorization": f"Token {os.environ['MEMOS_API_KEY']}" } url = f"{os.environ['MEMOS_BASE_URL']}/add/knowledgebase-file" res = requests.post(url=url, headers=headers, data=json.dumps(data)) print(f"result: {res.json()}") ``` ```text [Output] "result": { "code": 0, "data": [ { "id": "1f35642253606ed1e9dd8cd8113a8998", "name": "Software_Procurement_Reimbursement_Policy.pdf", "sizeMB": 0.06331157684326172, "status": "running" } ], "message": "ok" } ``` ### Update or Download a Document A document keeps the same file ID across versions: submit new content to update it, or download the current version for preview and editing. | Operation | API | Notes | | --- | --- | --- | | Update a document | [Update Knowledgebase File](/api_docs/knowledge/update_kb_doc) | Creates the next version of an existing file. Only files whose current version has finished processing can be updated, and the file type cannot be changed. | | Download a document | [Download Knowledgebase File](/api_docs/knowledge/download_kb_doc) | Returns the raw content of the current version; the file name is provided in the `Content-Disposition` header. | > **Note**: A successful update switches the file list to the new name, size, and version immediately, while parsing and indexing continue in the background. Track progress with `POST /get/status` using the returned `task_id`, or with `POST /get/knowledgebase-file`, before submitting the next update. ### Add User Conversation > **Note**:  Session A: Occurred on 2025-06-10 > > The designer indicated in the chat that they are a [Designer in the Creative Platform Department]. > ```python import os import requests import json # Replace with your MemOS API Key os.environ["MEMOS_API_KEY"] = "YOUR_API_KEY" os.environ["MEMOS_BASE_URL"] = "https://memos.memtensor.cn/api/openmem/v1" data = { "user_id": "memos_user_123", "conversation_id": "0610", "messages": [ { "role": "user", "content": "I am a designer in the Creative Platform Department." }, { "role": "assistant", "content": "Okay, I've noted that." } ] } headers = { "Content-Type": "application/json", "Authorization": f"Token {os.environ['MEMOS_API_KEY']}" } url = f"{os.environ['MEMOS_BASE_URL']}/add/message" res = requests.post(url=url, headers=headers, data=json.dumps(data)) print(f"result: {res.json()}") ``` ### Retrieve Knowledge Base Memory > **Note**:  Session A: Occurred on 2025-12-12 > > In a new session, the user asks about [Software Reimbursement Policy]. MemOS will automatically recall [Knowledge Base Memory: Software Reimbursement Policy Content] and [User Memory: Creative Platform Designer], thereby providing a more specific and "user-understanding" answer about software reimbursement. > ```python [Python (HTTP)] import os import requests import json # Replace with your MemOS API Key os.environ["MEMOS_API_KEY"] = "YOUR_API_KEY" os.environ["MEMOS_BASE_URL"] = "https://memos.memtensor.cn/api/openmem/v1" data = { "user_id": "memos_user_123", "conversation_id": "1211", "query": "Check the software procurement reimbursement limit for me.", "knowledgebase_ids":["idxxxxx"] #Replace with the Knowledge Base ID created above } headers = { "Content-Type": "application/json", "Authorization": f"Token {os.environ['MEMOS_API_KEY']}" } url = f"{os.environ['MEMOS_BASE_URL']}/search/memory" res = requests.post(url=url, headers=headers, data=json.dumps(data)) # Prettify JSON output json_res = res.json() print(json.dumps(json_res, indent=2, ensure_ascii=False)) ``` ```text [Output] "memory_detail_list": [ { "id": "2c760355-de4b-4a8f-b98d-b92851d23fa7", "memory_key": "Software Procurement Reimbursement Policy (Trial Version)", "memory_value": "This policy aims to standardize the procurement and reimbursement process for various software in the company, requiring all software procurement to follow the procurement amount limits for specific categories. The procurement limit for design software is 1000 yuan, applicable to graphic design, video editing, and prototype design, with examples including Photoshop and Premiere. The procurement limit for code/development software is 1500 yuan, applicable to IDEs and development frameworks, with examples like PyCharm and Visual Studio. The procurement limit for office software is 800 yuan, applicable to document editing and spreadsheet processing, with examples including Office Suite and WPS. The procurement limit for data analysis software is 1200 yuan, applicable to data statistics and visualization, with examples including Tableau and Power BI. The procurement limit for security and protection software is 1000 yuan, applicable to antivirus and firewalls. The procurement limit for collaboration/project management software is 900 yuan, with examples including Jira and Slack. The procurement limit for special industry software is 2000 yuan, requiring special approval. All procurement must comply with company budget and information security requirements; software exceeding the limit requires a business explanation and special approval.", "memory_type": "WorkingMemory", "create_time": 1765525947718, "conversation_id": "default_session", "status": "activated", "confidence": 0.99, "tags": [ "Software Procurement", "Reimbursement Policy", "Approval Process", "Budget", "Information Security", "mode:fine", "multimodal:file" ], "update_time": 1765525947720, "relativity": 0.89308184 }, { "id": "81fd1e79-65be-4d4e-81e0-8f76ba697c55", "memory_key": "Position Information", "memory_value": "User is a designer in the Creative Platform Department.", "memory_type": "WorkingMemory", "create_time": 1765526247112, "conversation_id": "0610", "status": "activated", "confidence": 0.99, "tags": [ "Position", "Department", "Design" ], "update_time": 1765526247113, "relativity": 1.6319022e-05 } ] ``` ### Feedback to Optimize Knowledge Base In enterprises, it is common for company policies/knowledge to be updated while the knowledge base is not updated in time. Currently, MemOS supports feedback on knowledge base memories through **natural language conversation**, used to quickly update knowledge base memories, thereby improving accuracy and timeliness. Try it out, drive the knowledge base to always stay up-to-date with the simplest interaction method. > **Note**:  Session A: Occurred on 2025-12-12 > > In another new session, the financial supervisor provides feedback that [The procurement limit for office software is 600 yuan, not 800 yuan]. > ```python import os import requests import json # Replace with your MemOS API Key os.environ["MEMOS_API_KEY"] = "YOUR_API_KEY" os.environ["MEMOS_BASE_URL"] = "https://memos.memtensor.cn/api/openmem/v1" data = { "user_id": "memos_user_123", "conversation_id": "1212", "feedback_content": "The procurement limit for office software is 600 yuan, not 800 yuan.", "allow_knowledgebase_ids":["idxxxxx"] #Replace with the Knowledge Base ID created above } headers = { "Content-Type": "application/json", "Authorization": f"Token {os.environ['MEMOS_API_KEY']}" } url = f"{os.environ['MEMOS_BASE_URL']}/add/feedback" res = requests.post(url=url, headers=headers, data=json.dumps(data)) print(f"result: {res.json()}") ``` > **Note**:  Session A: Occurred on 2025-12-12 > > When any other user searches for [Software Reimbursement Policy], they get a newly added high-weight memory [The procurement limit for office software is 600 yuan, not 800 yuan]. > ```python import os import requests import json # Replace with your MemOS API Key os.environ["MEMOS_API_KEY"] = "YOUR_API_KEY" os.environ["MEMOS_BASE_URL"] = "https://memos.memtensor.cn/api/openmem/v1" data = { "user_id": "memos_user_123", "conversation_id": "1211", "query": "Check the software procurement reimbursement limit for me.", "knowledgebase_ids":["idxxxxx"] #Replace with the Knowledge Base ID created above } headers = { "Content-Type": "application/json", "Authorization": f"Token {os.environ['MEMOS_API_KEY']}" } url = f"{os.environ['MEMOS_BASE_URL']}/search/memory" res = requests.post(url=url, headers=headers, data=json.dumps(data)) # Prettify JSON output json_res = res.json() print(json.dumps(json_res, indent=2, ensure_ascii=False)) ``` The output result is as follows (Simplified): ```python "memory_detail_list": [ { "id": "8a4f3d2e-c417-4e53-bc25-54451abd5ac8", "memory_key": "Software Procurement Reimbursement Policy (Trial Version)", "memory_value": "This policy aims to standardize the procurement and reimbursement process for various software in the company, requiring all software procurement to follow the procurement amount limits for specific categories. The procurement limit for design software is 1000 yuan, applicable to graphic design, video editing, and prototype design, with examples including Photoshop and Premiere. The procurement limit for code/development software is 1500 yuan, applicable to IDEs and development frameworks, with examples like PyCharm and Visual Studio. The procurement limit for office software is 800 yuan, applicable to document editing and spreadsheet processing, with examples including Office Suite and WPS. The procurement limit for data analysis software is 1200 yuan, applicable to data statistics and visualization, with examples including Tableau and Power BI. The procurement limit for security and protection software is 1000 yuan, applicable to antivirus and firewalls. The procurement limit for collaboration/project management software is 900 yuan, with examples including Jira and Slack. The procurement limit for special industry software is 2000 yuan, requiring special approval. All procurement must comply with company budget and information security requirements; software exceeding the limit requires a business explanation and special approval.", "memory_type": "LongTermMemory", "create_time": 1765525947718, "conversation_id": "default_session", "status": "activated", "confidence": 0.99, "tags": [ "Software Procurement", "Reimbursement Policy", "Approval Process", "Budget", "Information Security", "mode:fine", "multimodal:file" ], "update_time": 1765525947720, "relativity": 0.8931847 }, { "id": "a72a04d1-d7ba-4ebd-9410-0097bfa6c20d", "memory_key": "Office Software Procurement Limit", "memory_value": "User confirmed that the procurement limit for office software is 600 yuan, not 800 yuan.", "memory_type": "WorkingMemory", "create_time": 1765531700539, "conversation_id": "1212", "status": "activated", "confidence": 0.99, "tags": [ "Procurement", "Office Software", "Budget" ], "update_time": 1765531700540, "relativity": 0.7196722 } ] ``` The [Console - Knowledge Base](https://memos-dashboard.openmem.net/knowledgeBase/) displays details of all corrections or completions of knowledge base memories through natural language interaction. ![image.png](https://cdn.memtensor.com.cn/img/1766634697599_d1j187_compressed.png) > **Note**: For a complete list of feedback API fields, formats, etc., please refer to [Add Feedback API Documentation](/api_docs/message/add_feedback). ## 5. More: Upload Skill Documents If you want the knowledge base to return not only knowledge content but also reusable task-handling workflows, you can upload Skill documents to the knowledge base. Unlike regular documents, Skill documents must be marked with `type: "skill"` when uploaded. After upload succeeds, pass `knowledgebase_ids` and enable `include_skill` during retrieval to return both knowledge base memories and matching skills. > **Note**: For the detailed workflow and usage examples of Skill files, see the complete examples in [Self-Evolving](/memos_cloud/features/self-evolving). ```python [Python (HTTP)] import os import requests import json # Replace with your MemOS API Key os.environ["MEMOS_API_KEY"] = "YOUR_API_KEY" os.environ["MEMOS_BASE_URL"] = "https://memos.memtensor.cn/api/openmem/v1" data = { "knowledgebase_id": "idxxxxx", # Replace with your knowledge base ID "file": [ { "type": "skill", "content": "https://cdn.memtensor.com.cn/file/SKILL.md" } ] } headers = { "Content-Type": "application/json", "Authorization": f"Token {os.environ['MEMOS_API_KEY']}" } url = f"{os.environ['MEMOS_BASE_URL']}/add/knowledgebase-file" res = requests.post(url=url, headers=headers, data=json.dumps(data)) print(f"result: {res.json()}") ``` ## 6. Common Errors and Troubleshooting | Error Code | Common Cause | How to Fix | | --- | --- | --- | | `40002` / `40003` | Missing `knowledgebase_id`, `file`, or the file list is empty | Check whether the request body is complete. `file` must be a non-empty array | | `40007` / `50107` | Unsupported file type | Use PDF, DOCX, DOC, TXT, JSON, MD, or XML. For Skill files, use `.md` or `.zip` | | `40008` / `40009` | Invalid or malformed Base64 content | Make sure the Base64 content is not truncated and does not include invalid characters or an incorrect prefix | | `40305` | A single request exceeds the token limit | Split large files and reduce the content uploaded in one request | | `40309` | Token usage exceeds the per-time-window limit | Lower upload concurrency and retry in batches | | `50123` | The knowledge base is not associated with the current project | Go to [Project Configuration](/api_docs/start/configuration) and confirm the knowledge base is associated with the project that owns the API Key | --- # Profile (/memos_cloud/features/profile) ## 1. What is Profile? AI applications often try to achieve a sense of "memory and personalization" through a fixed persona passed in the prompt, combined with predefined tags that route different users to different canned replies. But as conversations continue, users keep changing — manually maintained tags can't keep up, and the feeling of being personally known never really lands. Profile lets you build a structured picture of a user or AI Agent. Scattered pieces of information from conversations are extracted and mapped onto predefined fields, then automatically updated and completed as the conversation deepens. Key characteristics include: - **Structured**: the profile is made up of predefined fields, stored together and directly usable, instead of being scattered across individual memories; - **Continuously updated**: as conversations continue, MemOS automatically updates the fields so the profile keeps catching up with the user's latest state — no manual maintenance required; - **Field-level control**: you can configure whether each field can be updated automatically. Open fields evolve with the conversation, while key fields can be locked to stay stable and avoid drifting with conversational noise. Profile fits scenarios such as smart home, brand customer service, and financial advisory — anywhere that benefits from consistent, stable conversations where the AI remembers who the user is over the long term. An example structure: ```plaintext Basic Info Name: Alex Occupation: Engineer Location: Hangzhou Interests Hobbies: camping, indie games Favorite music: folk Personality Tags Three keywords: outgoing, curious, meticulous ``` > **Note**: Profile can also be bound to an AI Agent to maintain a stable persona for that Agent. After enabling [Create Independent Memory for an Agent](/memos_cloud/introduction/isolation_filters#create-independent-memory-for-an-agent), each Agent gets its own Profile. ## 2. Key Concepts - **Template (`profile_template`)**: defines the field structure of a Profile, including field names, hierarchy, default values, and whether algorithmic updates are allowed. A single template can be bound to multiple users or Agents. - **Instance (`profile`)**: the Profile created when a user or Agent is bound to a template; it stores that user's or Agent's own field values. - **Attribute**: a specific field in an instance, such as relationship, interests, communication style, or anniversaries. - **Value (`value`)**: the value of a field in an instance. When messages are added, MemOS updates the corresponding field value based on the message content. - **Algorithm-updatable flag (`algorithm_updatable`)**: controls whether a field can be automatically updated by the algorithm. - **Subject (`user_id`/`agent_id`)**: each user has their own Profile instance. After enabling [Create Independent Memory for an Agent](/memos_cloud/introduction/isolation_filters#create-independent-memory-for-an-agent), you can also create Profile instances for Agents. ## 3. How It Works ```mermaid sequenceDiagram autonumber participant Dev as Developer participant User as End user participant App as AI product participant Mem as MemOS participant LLM as LLM used by the product Dev->>Mem: Create a template defining the Profile structure Dev->>Mem: Bind the template to a user, generating an instance User->>App: Send message / chat App->>Mem: searchMemory Mem-->>App: Recall Profile + other memories App->>LLM: Build context and generate a more personalized reply LLM-->>App: Return reply App-->>User: Show reply App->>Mem: addMessage Mem->>Mem: Extract info from the conversation, update Profile fields ``` The diagram above shows the full interaction flow between the developer, end user, AI product, and MemOS: 1. **Prepare a template**: create a Profile template in the dashboard or via API and define the field structure; 2. **Bind to a subject**: bind the template to a user or Agent to create their own Profile instance; 3. **Retrieve and use**: recall memories relevant to the current question, including the Profile, and add them to the LLM context to generate a reply that better understands the user; 4. **Auto-update**: as more messages are added, MemOS extracts information from the conversation and updates the corresponding fields in the instance. > **Note**: Binding a template currently does **not** retroactively fill in field values from past conversations. We recommend binding the template as soon as the user is created. ## 4. Examples > **Note**: For the complete list of API fields, formats, and other details, see the [Bind Profile Template](/api_docs/core/bind_profile_template) API documentation. ### Create a template Profile templates can be created and maintained in the [MemOS Dashboard](https://memos-dashboard.openmem.net) or via API. Templates are described in JSON, with **up to three levels** of nesting: ```json { "Basic Info": { "Name": { "value": "", "algorithm_updatable": false }, "Occupation": { "value": "", "algorithm_updatable": true }, "Location": { "value": "", "algorithm_updatable": true } }, "Personality Tags": { "Three keywords": { "value": "", "algorithm_updatable": true } } } ``` - `value`: the field's value; leave it empty or provide a default; - `algorithm_updatable`: marks whether the field can be automatically updated by the algorithm from conversations. Create a template via API: ```python [Python (HTTP)] import requests API_KEY = "YOUR_API_KEY" BASE_URL = "https://memos.memtensor.cn/api/openmem/v1" data = { "name": "User Profile", "metadata": { "Basic Info": { "Name": {"value": "", "algorithm_updatable": False}, "Occupation": {"value": "", "algorithm_updatable": True}, "Location": {"value": "", "algorithm_updatable": True} }, "Personality Tags": { "Three keywords": {"value": "", "algorithm_updatable": True} } } } res = requests.post( f"{BASE_URL}/add/profile_template", headers={"Authorization": f"Token {API_KEY}"}, json=data ) print(res.json()) ``` ```bash [Curl] curl --request POST \ --url https://memos.memtensor.cn/api/openmem/v1/add/profile_template \ --header 'Authorization: Token YOUR_API_KEY' \ --header 'Content-Type: application/json' \ --data '{ "name": "User Profile", "metadata": { "Basic Info": { "Name": {"value": "", "algorithm_updatable": false}, "Occupation": {"value": "", "algorithm_updatable": true}, "Location": {"value": "", "algorithm_updatable": true} }, "Personality Tags": { "Three keywords": {"value": "", "algorithm_updatable": true} } } }' ``` Example response: ```json { "code": 0, "data": { "profile_template_id": "tpl_user_001" }, "message": "ok" } ``` Once created, use the returned template ID to bind, query, update, and delete the template. The full set of template management APIs: | Operation | API | Description | | --- | --- | --- | | Create a template | [Add Profile Template](/api_docs/core/add_profile_template) | Define the attribute structure, default values, and per-field auto-update settings | | List templates | [List Profile Templates](/api_docs/core/list_profile_template) | Paginated list of templates in the project | | Get template details | [Get Profile Template](/api_docs/core/get_profile_template) | Full template structure and binding count | | Update a template | [Update Profile Template](/api_docs/core/update_profile_template) | Update the name or attribute structure; behaves the same as editing in the dashboard | | Delete a template | [Delete Profile Template](/api_docs/core/delete_profile_template) | Delete the template along with all bound instances | > **Note**: Python SDK methods for template management are under development. Please call the template management APIs over HTTP for now; SDK examples for binding, editing, and deleting instances are shown below. > **Warning**: Editing or deleting a field in a template affects that field across every Profile instance already bound to the template. Be careful when modifying a template that has bound instances. Deleting a template also deletes all of its bound instances; to delete only the instance of a specific user or Agent, use [Delete Profile](/api_docs/core/delete_profile). ### Bind a user to a template After you bind a template to a user, MemOS creates a Profile instance for that user. As messages are added, MemOS automatically updates the corresponding field values, keeping the profile up to date. ```python [Python (HTTP)] import requests API_KEY = "YOUR_API_KEY" BASE_URL = "https://memos.memtensor.cn/api/openmem/v1" data = { "bind_list": [ {"user_id": "memos_user_123", "profile_template_id": "tpl_user_001"} ] } res = requests.post( f"{BASE_URL}/bind/profile_template", headers={"Authorization": f"Token {API_KEY}"}, json=data ) print(res.json()) ``` ```python [Python (SDK)] # Make sure MemOS is installed (pip install MemoryOS -U) from memos.api.client import MemOSClient client = MemOSClient(api_key="YOUR_API_KEY") res = client.bind_profile_template( bind_list=[{"user_id": "memos_user_123", "profile_template_id": "tpl_user_001"}] ) print(res) ``` ```bash [Curl] curl --request POST \ --url https://memos.memtensor.cn/api/openmem/v1/bind/profile_template \ --header 'Authorization: Token YOUR_API_KEY' \ --header 'Content-Type: application/json' \ --data '{ "bind_list": [ { "user_id": "memos_user_123", "profile_template_id": "tpl_user_001" } ] }' ``` ### Add a conversation The user mentions their job and hobbies in conversation, and MemOS automatically extracts the information and updates the Profile. ```python [Python (HTTP)] import requests API_KEY = "YOUR_API_KEY" BASE_URL = "https://memos.memtensor.cn/api/openmem/v1" data = { "user_id": "memos_user_123", "conversation_id": "conv_0624", "allow_memory_view": ["profile", "detail_factual", "preference"], "messages": [ {"role": "user", "content": "I'm a product manager based in Hangzhou. I usually enjoy reading sci-fi novels and camping."}, {"role": "assistant", "content": "Got it — Hangzhou is a great place, with plenty of camping spots nearby."} ] } res = requests.post( f"{BASE_URL}/add/message", headers={"Authorization": f"Token {API_KEY}"}, json=data ) print(res.json()) ``` ```python [Python (SDK)] # Make sure MemOS is installed (pip install MemoryOS -U) from memos.api.client import MemOSClient client = MemOSClient(api_key="YOUR_API_KEY") res = client.add_message( user_id="memos_user_123", conversation_id="conv_0624", allow_memory_view=["profile", "detail_factual", "preference"], messages=[ {"role": "user", "content": "I'm a product manager based in Hangzhou. I usually enjoy reading sci-fi novels and camping."}, {"role": "assistant", "content": "Got it — Hangzhou is a great place, with plenty of camping spots nearby."} ] ) print(res) ``` ```bash [Curl] curl --request POST \ --url https://memos.memtensor.cn/api/openmem/v1/add/message \ --header 'Authorization: Token YOUR_API_KEY' \ --header 'Content-Type: application/json' \ --data '{ "user_id": "memos_user_123", "conversation_id": "conv_0624", "allow_memory_view": ["profile", "detail_factual", "preference"], "messages": [ {"role": "user", "content": "I'\''m a product manager based in Hangzhou. I usually enjoy reading sci-fi novels and camping."}, {"role": "assistant", "content": "Got it — Hangzhou is a great place, with plenty of camping spots nearby."} ] }' ``` ### Search Profile When you ask about the user in a new session, call Search Memory and pass `"profile"` in `include_memory_view` to recall Profile. ```python [Python (HTTP)] import requests API_KEY = "YOUR_API_KEY" BASE_URL = "https://memos.memtensor.cn/api/openmem/v1" data = { "user_id": "memos_user_123", "query": "What's this user's basic background?", "include_memory_view": ["profile"] } res = requests.post( f"{BASE_URL}/search/memory", headers={"Authorization": f"Token {API_KEY}"}, json=data ) print(res.json()) ``` ```python [Python (SDK)] # Make sure MemOS is installed (pip install MemoryOS -U) from memos.api.client import MemOSClient client = MemOSClient(api_key="YOUR_API_KEY") res = client.search_memory( user_id="memos_user_123", query="What's this user's basic background?", include_memory_view=["profile"] ) print(res) ``` ```bash [Curl] curl --request POST \ --url https://memos.memtensor.cn/api/openmem/v1/search/memory \ --header 'Authorization: Token YOUR_API_KEY' \ --header 'Content-Type: application/json' \ --data '{ "user_id": "memos_user_123", "query": "What'\''s this user'\''s basic background?", "include_memory_view": ["profile"] }' ``` Example response: ```json { "code": 0, "message": "ok", "data": { "profile_detail_list": [ { "id": "memos97701df652bb42cf8fe276b0da1441f3_tpl_bb0948b22fe7_e6a0dbfb3d47", "memory": "Basic Info.Occupation: Product Manager", "memory_type": "ProfileMemory", "template_id": "tpl_bb0948b22fe7", "profile_category": "Basic Info", "profile_field": "Occupation", "profile_path": "Basic Info.Occupation", "status": "activated", "confidence": 0.99, "relativity": 0.6782, "algorithm_updatable": true }, { "id": "memos97701df652bb42cf8fe276b0da1441f3_tpl_bb0948b22fe7_2785203c3b81", "memory": "Basic Info.Location: Hangzhou", "memory_type": "ProfileMemory", "template_id": "tpl_bb0948b22fe7", "profile_category": "Basic Info", "profile_field": "Location", "profile_path": "Basic Info.Location", "status": "activated", "confidence": 0.99, "relativity": 0.6808, "algorithm_updatable": true } ] } } ``` ### Edit a Profile value The user moved to Shanghai. Manually update the "Location" field and lock it so it isn't overwritten automatically in later conversations. ```python [Python (HTTP)] import requests API_KEY = "YOUR_API_KEY" BASE_URL = "https://memos.memtensor.cn/api/openmem/v1" data = { "user_id": "memos_user_123", "profile_template_id": "tpl_user_001", "metadata": { "Basic Info": { "Location": { "value": "Shanghai", "algorithm_updatable": False } } } } res = requests.post( f"{BASE_URL}/edit/profile", headers={"Authorization": f"Token {API_KEY}"}, json=data ) print(res.json()) ``` ```python [Python (SDK)] # Make sure MemOS is installed (pip install MemoryOS -U) from memos.api.client import MemOSClient client = MemOSClient(api_key="YOUR_API_KEY") res = client.edit_profile( user_id="memos_user_123", profile_template_id="tpl_user_001", metadata={ "Basic Info": { "Location": { "value": "Shanghai", "algorithm_updatable": False } } } ) print(res) ``` ```bash [Curl] curl --request POST \ --url https://memos.memtensor.cn/api/openmem/v1/edit/profile \ --header 'Authorization: Token YOUR_API_KEY' \ --header 'Content-Type: application/json' \ --data '{ "user_id": "memos_user_123", "profile_template_id": "tpl_user_001", "metadata": { "Basic Info": { "Location": { "value": "Shanghai", "algorithm_updatable": false } } } }' ``` ### Delete an instance When you no longer need a user's Profile, delete the instance. This removes the binding and clears all field values. ```python [Python (HTTP)] import requests API_KEY = "YOUR_API_KEY" BASE_URL = "https://memos.memtensor.cn/api/openmem/v1" data = { "user_id": "memos_user_123", "profile_template_id": "tpl_user_001" } res = requests.post( f"{BASE_URL}/delete/profile", headers={"Authorization": f"Token {API_KEY}"}, json=data ) print(res.json()) ``` ```python [Python (SDK)] # Make sure MemOS is installed (pip install MemoryOS -U) from memos.api.client import MemOSClient client = MemOSClient(api_key="YOUR_API_KEY") res = client.delete_profile( user_id="memos_user_123", profile_template_id="tpl_user_001" ) print(res) ``` ```bash [Curl] curl --request POST \ --url https://memos.memtensor.cn/api/openmem/v1/delete/profile \ --header 'Authorization: Token YOUR_API_KEY' \ --header 'Content-Type: application/json' \ --data '{ "user_id": "memos_user_123", "profile_template_id": "tpl_user_001" }' ``` ## 5. Related Features - [Memory Categories](/memos_cloud/introduction/memory_types): How Profile differs from other memory categories - [Event Memory](/memos_cloud/features/event_memory): Extract structured events with time, location, and participants from conversations --- # Event Memory (/memos_cloud/features/event_memory) ## 1. What is Event Memory? Event Memory extracts structured events from conversations and keeps key elements such as time, location, and participants, so the AI can accurately recall and reference past experiences with better continuity. > **Note**: Typical scenarios > > - Schedule tracking: remember which project was finished last week, or which exam is coming next month; > - Customer service history: trace complaints, inquiries, returns, and other key events; > - Game / role-play story memory: keep critical plot nodes the character has experienced. > > Event Memory complements Profile — Profile maintains a stable picture of who someone is, while Event Memory records what they went through. ## 2. Key Concepts - **Event(event)**: A structured event extracted from conversation; the basic unit of Event Memory. - **Title(title)**: A short description of the event, such as "camping by West Lake with friends". - **Content(content)**: A detailed summary of the event, including key information. - **Event time**: When the event happened; prefers `chat_time` from the message when available. - **Participants**: People involved in the event, identified from conversation context. - **Custom extraction config**: Supports a custom Event Memory extraction prompt to control how events are extracted and what to focus on. ## 3. Workflow ```mermaid sequenceDiagram autonumber participant User as End user participant App as AI product participant Mem as MemOS participant LLM as LLM used by the product User->>App: Send message / chat App->>Mem: searchMemory Mem-->>App: Recall event memory + other memories App->>LLM: Build context and generate reply LLM-->>App: Return reply App-->>User: Show reply App->>Mem: addMessage Mem->>Mem: Extract structured events from the conversation ``` Flow summary: 1. **Retrieve**: During chat, recall relevant Event Memory and other [memory categories](/memos_cloud/introduction/memory_types), then inject them into the LLM context; 2. **Generate**: The LLM generates a reply with the recalled events; 3. **Extract**: After messages are added, MemOS automatically extracts structured events and stores them. ## 4. Examples ### Add messages Include `"event"` in `allow_memory_view` when adding messages to trigger Event Memory extraction. ```python [Python (HTTP)] import requests API_KEY = "YOUR_API_KEY" BASE_URL = "https://memos.memtensor.cn/api/openmem/v1" data = { "user_id": "memos_user_123", "conversation_id": "conv_0624", "allow_memory_view": ["event", "detail_factual", "preference"], "messages": [ {"role": "user", "content": "Last Tuesday afternoon I did a proposal review with Li Si. The customer liked the second version and wants delivery moved up to the end of July."}, {"role": "assistant", "content": "Got it. Want me to summarize the key conclusions from the review?"} ] } res = requests.post( f"{BASE_URL}/add/message", headers={"Authorization": f"Token {API_KEY}"}, json=data ) print(res.json()) ``` ```python [Python (SDK)] # Make sure MemOS is installed (pip install MemoryOS -U) from memos.api.client import MemOSClient client = MemOSClient(api_key="YOUR_API_KEY") res = client.add_message( user_id="memos_user_123", conversation_id="conv_0624", allow_memory_view=["event", "detail_factual", "preference"], messages=[ {"role": "user", "content": "Last Tuesday afternoon I did a proposal review with Li Si. The customer liked the second version and wants delivery moved up to the end of July."}, {"role": "assistant", "content": "Got it. Want me to summarize the key conclusions from the review?"} ] ) print(res) ``` ```bash [Curl] curl --request POST \ --url https://memos.memtensor.cn/api/openmem/v1/add/message \ --header 'Authorization: Token YOUR_API_KEY' \ --header 'Content-Type: application/json' \ --data '{ "user_id": "memos_user_123", "conversation_id": "conv_0624", "allow_memory_view": ["event", "detail_factual", "preference"], "messages": [ {"role": "user", "content": "Last Tuesday afternoon I did a proposal review with Li Si. The customer liked the second version and wants delivery moved up to the end of July."}, {"role": "assistant", "content": "Got it. Want me to summarize the key conclusions from the review?"} ] }' ``` ### Search Event Memory When calling searchMemory, pass `"event"` in `include_memory_view` to recall Event Memory (not included by default). Related events are returned in `event_detail_list`. ```python [Python (HTTP)] import requests API_KEY = "YOUR_API_KEY" BASE_URL = "https://memos.memtensor.cn/api/openmem/v1" data = { "user_id": "memos_user_123", "query": "Any recent reviews or meetings?", "include_memory_view": ["event"] } res = requests.post( f"{BASE_URL}/search/memory", headers={"Authorization": f"Token {API_KEY}"}, json=data ) print(res.json()) ``` ```python [Python (SDK)] # Make sure MemOS is installed (pip install MemoryOS -U) from memos.api.client import MemOSClient client = MemOSClient(api_key="YOUR_API_KEY") res = client.search_memory( user_id="memos_user_123", query="Any recent reviews or meetings?", include_memory_view=["event"] ) print(res) ``` ```bash [Curl] curl --request POST \ --url https://memos.memtensor.cn/api/openmem/v1/search/memory \ --header 'Authorization: Token YOUR_API_KEY' \ --header 'Content-Type: application/json' \ --data '{ "user_id": "memos_user_123", "query": "Any recent reviews or meetings?", "include_memory_view": ["event"] }' ``` Example response: ```json { "code": 0, "message": "ok", "data": { "event_detail_list": [ { "id": "d7785b39-1374-4738-b449-3e86ab1f8b2f", "event_key": "方案评审与交付调整", "event_value": "用户与李四于上周二下午完成方案评审,客户对第二版方案表示满意,并希望将交付时间提前至七月底。", "event_type": "EventMemory", "create_time": 1783929751765, "conversation_id": "conv_event_verify_001", "status": "activated", "update_time": 1783929757755, "relativity": 0.6364, "event_time": ["上周二下午", "七月底"], "event_location": [], "event_roles": ["用户", "李四", "客户"] } ] } } ``` ### Get event details Use `get/memory/{memory_id}` to fetch a single Event Memory. ```python [Python (HTTP)] import requests API_KEY = "YOUR_API_KEY" BASE_URL = "https://memos.memtensor.cn/api/openmem/v1" memory_id = "d7785b39-1374-4738-b449-3e86ab1f8b2f" res = requests.get( f"{BASE_URL}/get/memory/{memory_id}", headers={"Authorization": f"Token {API_KEY}"} ) print(res.json()) ``` ```python [Python (SDK)] # Make sure MemOS is installed (pip install MemoryOS -U) from memos.api.client import MemOSClient client = MemOSClient(api_key="YOUR_API_KEY") res = client.get_memory_by_id(memory_id="d7785b39-1374-4738-b449-3e86ab1f8b2f") print(res) ``` ```bash [Curl] curl --request GET \ --url https://memos.memtensor.cn/api/openmem/v1/get/memory/d7785b39-1374-4738-b449-3e86ab1f8b2f \ --header 'Authorization: Token YOUR_API_KEY' ``` Unlike Profile Memory, Event Memory can be retrieved with `GET /get/memory/{id}`. ### Custom extraction config Event Memory supports a custom extraction prompt in the dashboard when you need finer control over extraction granularity or focus: 1. Sign in to the [MemOS Dashboard](https://memos-dashboard.openmem.net/quickstart), open your project, and go to **Custom Extraction**; 2. Edit the Event Memory prompt — manually or with AI assistance; 3. Use **Quick Debug** to validate: enter sample dialogue, click **Run Extraction**, and check whether the extracted events look right; 4. Save when ready. ![Custom Extraction: Event Memory prompt and Quick Debug](https://cdn.memtensor.com.cn/img/1783930386239_vzui8u_compressed.png) ## 5. Related features - [Profile](/memos_cloud/features/profile): Maintain a structured profile for a user or AI Agent; complements Event Memory - [Memory Categories](/memos_cloud/introduction/memory_types): How Event Memory differs from other memory types --- # Self-Evolving (/memos_cloud/features/self-evolving) ## What is Self-Evolving? In the context of AI Agents, a **Skill** is a reusable task-handling method. It tells an Agent "what to do when it encounters a certain type of task", for example: - How to plan a trip - How to process a return ticket - How to generate a weekly report following company standards Skills help compensate for the fact that execution experience is hard to accumulate in long-running LLM applications: - Maintainable: turn stable real-world workflows into structured methods that can be iterated over time. - On-demand: let the Agent retrieve relevant skills for the current task, instead of placing every workflow into the context. - Personalized: turn different users' preferences, habits, and constraints into reusable execution methods. By distilling reusable Skills from conversations, MemOS enables memory self-evolution, continuously enhancing Agent capabilities. --- ## How MemOS Provides Self-Evolving Capabilities for Agents ### 1. Auto-generate Personalized Skills MemOS believes "memory is an asset". The solution paths and user preferences accumulated in real conversations are the most valuable raw material for skills. You do not need to prepare any files. As long as you add the original conversation history between the user and the Agent, MemOS **automatically extracts skills from user memories** and turns scattered interaction history into reusable, personalized professional capabilities. ### 2. Upload Custom Skills MemOS also supports uploading existing skill files directly. Upload a Markdown file or ZIP package to a knowledge base, and MemOS can return relevant skills to the Agent during retrieval. --- ## Auto-generate Personalized Skills ### How It Works ![image.png](https://cdn.memtensor.com.cn/img/1769759436251_3tx57c_compressed.png) The diagram above shows the full interaction flow between end users, the AI Agent you build, and MemOS: 1. Call the `add/message` API to send the user's conversation messages to MemOS. 2. After receiving the request, MemOS processes the messages in sequence and generates Skill files: a. **Intelligent chunking**: identify task boundaries in historical conversations and split them into task text chunks. b. **Cluster extraction**: cluster similar task text chunks and combine them with the user's historical memories to extract structured skill text. c. **Skill conversion**: convert the skill into a runnable and recognizable Skill file. 3. Call the `search/memory` API to retrieve memories. MemOS returns user facts, preferences, tool memories, and matching Skill files related to the current context in a unified response. 4. Download the Skill file and pass both memories and the Skill file to your self-hosted LLM, enabling effective use of long-term experience and automatically generated skills. The entire process does not require manually uploading any skill files. ### Travel Planning Example Using "Travel Planning" as an example to show how the same task generates different skills for different users. #### 1. Add Conversations The user expresses travel planning preferences in conversation: no backtracking, compact routes, cultural attractions, and weather checks in advance. ```python import os import json import requests os.environ["MEMOS_API_KEY"] = "YOUR_API_KEY" os.environ["MEMOS_BASE_URL"] = "https://memos.memtensor.cn/api/openmem/v1" data = { "user_id": "memos_user_j", "conversation_id": "travel_0127", "messages": [ { "role": "user", "content": "I'm going to Chengdu next week for 5 days. I like intense, no-backtracking trips. Also mark the must-try food along the route." }, {"role": "assistant", "content": "...omitted..."}, { "role": "user", "content": "I prefer cultural attractions. Not interested in shopping malls." }, {"role": "assistant", "content": "...omitted..."}, { "role": "user", "content": "Check the weather and temperature in advance so I can pack properly." }, {"role": "assistant", "content": "...omitted..."} ] } headers = { "Content-Type": "application/json", "Authorization": f"Token {os.environ['MEMOS_API_KEY']}" } url = f"{os.environ['MEMOS_BASE_URL']}/add/message" res = requests.post(url=url, headers=headers, data=json.dumps(data)) print(f"result: {res.json()}") ``` #### 2. Retrieve Skills When the same user makes a similar request next time, pass `include_skill=true`: ```python data = { "query": "I'm planning a 7-day trip to Yunnan for the spring holiday.", "user_id": "memos_user_j", "conversation_id": "travel_0301", "include_skill": True } res = requests.post( url=f"{os.environ['MEMOS_BASE_URL']}/search/memory", headers=headers, data=json.dumps(data) ) print(f"result: {res.json()}") ``` #### 3. Generated Skill Example For the same "Travel Planning" task, MemOS does not apply one template to every user. It turns each user's long-term conversational preferences into a dedicated, reusable capability. As shown below, MemOS may generate a skill like this for the high-energy planner: ```markdown --- name: Travel Itinerary Planning description: Design multi-day itineraries for high-energy travelers, including efficient routes, cultural attractions, food spots, and weather-adapted suggestions. --- ## Procedure 1. Determine trip duration, destination, and user preferences 2. Collect cultural attractions, food spots, and transit info 3. Plan daily routes by area to avoid backtracking 4. Weave food spots into the transit route 5. Check weather forecast and adjust routes and packing advice ## Experience - Prioritize cultural attractions over shopping - Keep routes compact for high-energy travel - Plan each day geographically to move forward ## User Preferences - No backtracking - Prefers cultural attractions - Wants weather checked in advance ``` If another user is a "low-energy relaxed traveler" who mentions being a night owl, hating early mornings, not wanting long commutes, and preferring hidden gems, MemOS generates a noticeably different skill: ```markdown --- name: Travel Itinerary Planning description: Help low-energy travelers plan relaxed, flexible itineraries focused on afternoon and evening experiences. --- ## Procedure 1. Confirm user's energy level, wake-up time, and max commute tolerance 2. Prioritize nearby, easy-access spots that don't require early starts 3. Focus activities on afternoon, evening, and nighttime 4. Include hidden gems, avoid overly popular crowded routes 5. Keep flexible time slots for spontaneous changes ## Experience - Avoid scheduling early-morning activities - Avoid long commutes and packed schedules - Recommend places reachable by subway or short taxi rides ## User Preferences - Night owl, can't wake up early - Dislikes long commutes - Likes niche, less conventional experiences ``` --- ## Upload Custom Skills ### Customer Return Example When you already have a clear standard workflow, upload the skill file directly to a knowledge base. MemOS will retrieve and return relevant skills in a unified way. The following example uses "Customer Service Agent Return Processing" to walk through the full flow from skill upload to retrieval. #### 1. Upload to the Knowledge Base via API Upload a skill file that guides a customer service Agent to help users complete product returns. ```python [URL Upload] import os import json import requests os.environ["MEMOS_API_KEY"] = "YOUR_API_KEY" os.environ["MEMOS_BASE_URL"] = "https://memos.memtensor.cn/api/openmem/v1" headers = { "Content-Type": "application/json", "Authorization": f"Token {os.environ['MEMOS_API_KEY']}" } data = { "knowledgebase_id": "kb_xxx", # Replace with your knowledge base ID "file": [ { "type": "skill", "content": "https://cdn.memtensor.com.cn/file/SKILL.md" # Replace with your public file URL } ] } url = f"{os.environ['MEMOS_BASE_URL']}/add/knowledgebase-file" res = requests.post(url=url, headers=headers, data=json.dumps(data)) print(f"result: {res.json()}") ``` ```python [Base64 Upload] import os import json import base64 import requests os.environ["MEMOS_API_KEY"] = "YOUR_API_KEY" os.environ["MEMOS_BASE_URL"] = "https://memos.memtensor.cn/api/openmem/v1" skill_markdown = """--- name: Customer Return Processing description: Guide customer service to handle user return requests following standard procedures --- ## Procedure 1. Verify user identity and order number 2. Confirm return reason meets policy requirements 3. Guide user to select return method (pickup / self-ship) 4. Generate return tracking number and notify user 5. Track logistics status and notify user upon refund completion ## Experience - No-reason returns accepted within 7 days of receipt - Fresh products do not support returns; use after-sales compensation - High-value items (>$70) require supervisor approval ## User Preferences - Recommend pickup service first to reduce user effort - Default refund to original payment method ## Examples ### Example 1: Standard product return User: I want to return the headphones I bought three days ago. Assistant: Got it. I've confirmed your order is within the 7-day no-reason return window. Would you prefer pickup or self-shipping? """ encoded_skill = base64.b64encode(skill_markdown.encode("utf-8")).decode("utf-8") data = { "knowledgebase_id": "kb_xxx", # Replace with your knowledge base ID "file": [ { "type": "skill", "name": "customer-return-sop.md", "content": f"data:text/markdown;base64,{encoded_skill}" } ] } headers = { "Content-Type": "application/json", "Authorization": f"Token {os.environ['MEMOS_API_KEY']}" } url = f"{os.environ['MEMOS_BASE_URL']}/add/knowledgebase-file" res = requests.post(url=url, headers=headers, data=json.dumps(data)) print(f"result: {res.json()}") ``` #### 2. Upload Skill Files via Dashboard Go to [Dashboard - Knowledge Base](https://memos-dashboard.openmem.net/knowledgeBase/), select the target knowledge base, click "Upload Document", and drag in your `.md` or `.zip` file. Select "Skill file" as the upload type. ![image](https://cdn.memtensor.com.cn/img/1778148193764_flblvp_compressed.png) #### 3. Retrieve Skills After upload succeeds, pass `knowledgebase_ids` and enable `include_skill` during retrieval. MemOS will return skills relevant to the query. As shown below, the Agent can follow the "Customer Return Processing" flow to guide the user through the return. ```python data = { "query": "The user wants to return headphones bought three days ago", "user_id": "memos_user_123", "conversation_id": "session_001", "knowledgebase_ids": ["kb_xxx"], "include_skill": True } res = requests.post( url=f"{os.environ['MEMOS_BASE_URL']}/search/memory", headers=headers, data=json.dumps(data) ) print(f"result: {res.json()}") ``` ### Skill File Specification #### 1. `.md` Single File - The constraints are as follows: - Size limit: ≤ 100KB - File content: must include `name` and `description` - Recommended body structure: ```text --- name: (Skill name) description: (One-sentence description of purpose and scenario) --- ## Procedure 1. Step one 2. Step two 3. Step three ## Experience - Experience or note one - Experience or note two ## User Preferences - Preference setting one - Preference setting two ## Examples ### Example 1: (Scenario description) (Complete input/output example) ## Additional Information (Additional notes, such as reference links or special rules) ``` #### 2. `.zip` Skill Package - The constraints are as follows: | Constraint | Requirement | | --- | --- | | Format | Standard ZIP, no rar/7z | | Zip size | ≤ 20MB | | File count after extraction | ≤ 200 | | Single file after extraction | ≤ 10MB | | SKILL.md | ≤ 100KB, `name`/`description` required; must be at the first level of the archive | - Recommended structure: ```text refund-sop-v1.zip ├── SKILL.md ├── references/ │ └── return_policy_summary.md ├── scripts/ │ └── check_order.py └── assets/ └── flowchart.png ``` --- ## How to Use Retrieved Skills ### Returned Skill Details Regardless of whether the skill is auto-generated or uploaded to a knowledge base, each skill in `skill_detail_list` contains two fields: | Field | Description | | --- | --- | | `skill_value` | Structured skill content; can be converted to a string and injected into the Agent's prompt | | `skill_url` | Download link for the skill file; for ZIP packages, the Agent can download scripts, references, and other attachments | ### Usage Reference Choose the usage method based on whether your Agent can use Skill files. #### 1. The Agent Supports Skill Files Provide `skill_url` to the Agent so it can download the file. You can write it into the prompt: ```python skill_detail = result["skill_detail_list"][0] skill_url = skill_detail.get("skill_url") system_prompt = f"""You are a customer service assistant. Use the following Skill file when handling the task: {skill_url} """ ``` #### 2. The Agent Does Not Support Skill Files Convert `skill_value` to a string and add it to the prompt: ```python skill_detail = result["skill_detail_list"][0] skill = str(skill_detail["skill_value"]) system_prompt = f"""You are a customer service assistant. Refer to this skill when handling the task: {skill} """ ``` > **Tip**: During retrieval, MemOS searches both auto-generated personal skills and uploaded knowledge base skills, returning them in a unified ranked list. You do not need to distinguish the source. --- **Start exploring MemOS Self-Evolving capabilities now!** - Go to the [Dashboard - Skills page](https://memos-dashboard.openmem.net/skill/) to view auto-generated skills. - Don't have any skills yet? [Add messages](/memos_cloud/mem_operations/add_message) to trigger generation. - Want to upload custom skills? Go to [Dashboard - Knowledge Base](https://memos-dashboard.openmem.net/knowledgeBase/) to upload. --- # Group Chat (/memos_cloud/features/group_chat) ## 1. What is Group Chat? In group chat scenarios, multiple users and/or Agents converse in the same session, and MemOS extracts and maintains memory for each participant. Once you pass in each speaker's identifier and name, memory extraction distinguishes "who said what" and produces memories with the specific person's name as the subject — so each participant is remembered more accurately. > **Note**: Typical scenarios > > - Multi-person discussions such as project groups, weekly meetings, and proposal reviews; > - Shared family / team assistants: after one group-chat write, each member's memory keeps a record of that discussion; > - Multi-Agent participation: `agent_id` also accepts an array, so multiple AI roles can join the same session. ## 2. Key Concepts - **User ID (`user_id`)**: accepts a string (single user) or an array of strings (multiple users in a group chat). - **Agent ID (`agent_id`)**: also accepts a string or an array of strings; multiple Agents can participate in the same group chat. - **Speaker ID (`role_id`)**: recommended in group chats; identifies who sent each message. Recommended to match one of the values in the top-level `user_id` / `agent_id`. - **Speaker name (`role_name`)**: when passed together with `role_id`, memory text can include the person's name so speakers are easier to tell apart. - **Conversation ID (`conversation_id`)**: the unique identifier for the group chat session. ### Limits | Limit | Description | | --- | --- | | `user_id` / `agent_id` list size | Up to 20 IDs per request | | QPS conversion | Scaled by the number of participants; for example, passing 20 IDs applies a ×20 factor, i.e. at most 2 requests per second | For more general quota details, see [Quotas and Limits](/memos_cloud/support/limit). ## 3. Workflow ```mermaid sequenceDiagram autonumber participant UserA as User A participant UserB as User B participant App as AI product participant Mem as MemOS participant LLM as LLM used by the product UserA->>App: Speaks in the group chat UserB->>App: Speaks in the group chat App->>Mem: searchMemory (user_id=User A) Mem-->>App: Recall from User A's memory App->>LLM: Build context LLM->>UserA: Show reply App->>Mem: addMessage (user_id list + role_id + role_name) Mem->>Mem: Write the group chat record into User A's memory Mem->>Mem: Write the group chat record into User B's memory ``` 1. **Multi-person conversation**: multiple users speak in the same session; 2. **Retrieve per person**: call searchMemory with a given `user_id` to search that user's memory space; 3. **Write once**: pass `user_id` as a list, and tag each message with `role_id` / `role_name`; 4. **Extract for each participant**: each participant in the list gets memory extracted about this group chat. ## 4. Examples ### Add a group chat message For example, Alex and Jordan align on a proposal-review time with an assistant in the same session: ```python [Python (HTTP)] import requests API_KEY = "YOUR_API_KEY" BASE_URL = "https://memos.memtensor.cn/api/openmem/v1" data = { "user_id": ["memos_user_1", "memos_user_2"], "agent_id": "memos_agent", "conversation_id": "group_conv_001", "messages": [ {"role": "user", "role_id": "memos_user_1", "role_name": "Alex", "content": "Does next Tuesday work for everyone for the proposal review?"}, {"role": "user", "role_id": "memos_user_2", "role_name": "Jordan", "content": "Works for me. How about 2pm?"}, {"role": "assistant", "role_id": "memos_agent", "content": "Got it. Proposal review next Tuesday at 2pm. Want me to help prepare the agenda?"} ] } res = requests.post( f"{BASE_URL}/add/message", headers={"Authorization": f"Token {API_KEY}"}, json=data ) print(res.json()) ``` ```python [Python (SDK)] # Make sure MemOS is installed (pip install MemoryOS -U) from memos.api.client import MemOSClient client = MemOSClient(api_key="YOUR_API_KEY") res = client.add_message( user_id=["memos_user_1", "memos_user_2"], agent_id="memos_agent", conversation_id="group_conv_001", messages=[ {"role": "user", "role_id": "memos_user_1", "role_name": "Alex", "content": "Does next Tuesday work for everyone for the proposal review?"}, {"role": "user", "role_id": "memos_user_2", "role_name": "Jordan", "content": "Works for me. How about 2pm?"}, {"role": "assistant", "role_id": "memos_agent", "content": "Got it. Proposal review next Tuesday at 2pm. Want me to help prepare the agenda?"} ] ) print(res) ``` ```bash [Curl] curl --request POST \ --url https://memos.memtensor.cn/api/openmem/v1/add/message \ --header 'Authorization: Token YOUR_API_KEY' \ --header 'Content-Type: application/json' \ --data '{ "user_id": ["memos_user_1", "memos_user_2"], "agent_id": "memos_agent", "conversation_id": "group_conv_001", "messages": [ {"role": "user", "role_id": "memos_user_1", "role_name": "Alex", "content": "Does next Tuesday work for everyone for the proposal review?"}, {"role": "user", "role_id": "memos_user_2", "role_name": "Jordan", "content": "Works for me. How about 2pm?"}, {"role": "assistant", "role_id": "memos_agent", "content": "Got it. Proposal review next Tuesday at 2pm. Want me to help prepare the agenda?"} ] }' ``` After writing, speakers can be told apart in memory text via `role_name`. ### Search group-chat related memories When any participant continues the conversation later, search with that user's `user_id` to recall this group-chat context. For example, Alex asks about meeting plans: ```python [Python (HTTP)] import requests API_KEY = "YOUR_API_KEY" BASE_URL = "https://memos.memtensor.cn/api/openmem/v1" data = { "user_id": "memos_user_1", "query": "What meetings do I have coming up?" } res = requests.post( f"{BASE_URL}/search/memory", headers={"Authorization": f"Token {API_KEY}"}, json=data ) print(res.json()) ``` ```python [Python (SDK)] # Make sure MemOS is installed (pip install MemoryOS -U) from memos.api.client import MemOSClient client = MemOSClient(api_key="YOUR_API_KEY") res = client.search_memory( user_id="memos_user_1", query="What meetings do I have coming up?" ) print(res) ``` ```bash [Curl] curl --request POST \ --url https://memos.memtensor.cn/api/openmem/v1/search/memory \ --header 'Authorization: Token YOUR_API_KEY' \ --header 'Content-Type: application/json' \ --data '{ "user_id": "memos_user_1", "query": "What meetings do I have coming up?" }' ``` > **Note**: If you still need to narrow the search further, use conditions such as `related_id` in `filter`. See [Memory Filters](/memos_cloud/features/filters). ## 5. Related Features - [Multi-user / Multi-Agent Isolation](/memos_cloud/introduction/isolation_filters): How user_id, agent_id, and conversation isolation work - [Quotas and Limits](/memos_cloud/support/limit): Group chat list limits and QPS conversion details --- # Tool Calling (/memos_cloud/features/tool_calling) > **Warning**: Note > > > > **[You must first pass tool memory when calling addMessage (Click here for detailed API documentation)](/api_docs/core/add_message)** > > > **[Only then can you search for tool memory when calling searchMemory (Click here for detailed API documentation)](/api_docs/core/search_memory)** > > > > **This article focuses on functional description. For detailed API fields and limits, please click the text links above.** ## 1. When to Use This message structure is suitable when your Agent needs to obtain external information through tools (function / tool), and you want these "tool calling contexts and results" to be understood, associated, and precipitated as retrievable memories by MemOS. ## 2. How it Works Step 1: Add Tool Calling Information `assistant` message: `tool_calls` describes the model's decision to call a tool and its parameters. `tool` message: Carries the actual tool execution result and precisely associates with the corresponding `tool_calls` via `tool_call_id`. Step 2: MemOS Processes Tool-Related Memory * **Tool Schema**: MemOS supports structured management and dynamic updates of tool information, unifying the description of different tools. This enables the model to efficiently retrieve, understand, and discover tools without hardcoding tool details in prompts. * **Tool Trajectory Memory**: MemOS extracts and stores key trajectories during tool usage, including "what tool was called in what context, what parameters were used, and what result was returned". These trajectories can be retrieved and reused in subsequent conversations, helping the model reproduce tool usage patterns more stably and reducing repetitive trial-and-error and calling errors. ## 3. Usage Example For a complete list of API fields, formats, etc., please refer to the [Add Message API Documentation](/api_docs/core/add_message) to see how to add tool calling information. ### Add Tool Calling Information > **Note**:  Session A: User asks [How is the weather in Beijing] in the conversation. The assistant calls the [Weather Tool]. The weather tool returns the result [Beijing, Temperature 7°C, Cloudy]. ```python import os import requests import json # Replace with your MemOS API Key os.environ["MEMOS_API_KEY"] = "YOUR_API_KEY" os.environ["MEMOS_BASE_URL"] = "https://memos.memtensor.cn/api/openmem/v1" # Message sequence with tool_call tool_schema = [{ "name": "get_weather", "description": "Get current weather information for a given location", "parameters": { "type": "object", "properties": { "location": { "type": "string", "description": "City name, e.g. Beijing" } }, "required": [ "location" ] } }] data = { "user_id": "memos_user_123", "conversation_id": "demo-conv-id", "messages": [ { "role": "system", "content": f"""You are an assistant that can call tools. When a user's request can be fulfilled by a tool, you MUST call the appropriate tool. {json.dumps(tool_schema, indent=2, ensure_ascii=False)} """ }, {"role": "user", "content": "What's the weather like in Beijing right now?"}, { "role": "assistant", "tool_calls": [ { "id": "call_123", "type": "function", "function": { "name": "get_weather", "arguments": json.dumps({"location": "Beijing"}), }, } ], }, { "role": "tool", "tool_call_id": "call_123", "content": [ { "type": "text", "text": json.dumps( {"location": "Beijing", "temperature": "7°C", "condition": "Cloudy"} ), } ], }, ], } headers = { "Content-Type": "application/json", "Authorization": f"Token {os.environ['MEMOS_API_KEY']}" } url = f"{os.environ['MEMOS_BASE_URL']}/add/message" res = requests.post(url=url, headers=headers, data=json.dumps(data)) print(json.dumps(res.json(), indent=2, ensure_ascii=False)) ``` ### Retrieve Tool Memory > **Note**:  Session B: In a new session, the user asks [What clothes are suitable for Beijing]. MemOS can recall relevant tool memories from past [Weather Tool Calls]. The model can use tool memories in the future to improve the accuracy and effectiveness of tool usage. ```python import os import requests import json os.environ["MEMOS_API_KEY"] = "YOUR_API_KEY" os.environ["MEMOS_BASE_URL"] = "https://memos.memtensor.cn/api/openmem/v1" data = { "user_id": "memos_user_123", "conversation_id": "0928", "query": "What clothes are suitable for Beijing", "include_memory_view": ["tool_memory"], "memory_limit_number": 10 } headers = { "Content-Type": "application/json", "Authorization": f"Token {os.environ['MEMOS_API_KEY']}" } url = f"{os.environ['MEMOS_BASE_URL']}/search/memory" res = requests.post(url=url, headers=headers, data=json.dumps(data)) print(json.dumps(res.json(), indent=2, ensure_ascii=False)) ``` ### Output Result ```python "tool_memory_detail_list": [ { "id": "7ec50fd8-19ec-42a2-a7c7-ce3cebdb70cf", "tool_type": "ToolSchemaMemory", "tool_value": {"name": "get_weather", "description": "Get current weather information for a given location", "parameters": {"type": "object", "properties": {"location": {"type": "string", "description": "City name, e.g. Beijing"}}, "required": ["location"]}}, "create_time": 1766494806624, "conversation_id": "demo-conv-id", "status": "activated", "update_time": 1766494806625, "relativity": 0.44700349055540967 }, { "id": "4b208707-991a-481c-9dd6-c7f0577ff371", "tool_type": "ToolTrajectoryMemory", "tool_value": "User asked about the current weather in Beijing -> Tool 'get_weather' was called with the parameter 'location' set to 'Beijing' -> The tool returned the weather information: temperature is 7°C and condition is Cloudy.", "tool_used_status": [ { "used_tool": "get_weather", "error_type": "", "success_rate": 1.0, "tool_experience": "The 'get_weather' tool requires a valid location parameter and provides current weather information for that location." # New: Experience with this tool in the current trajectory. } ], "create_time": 1768390489180, "conversation_id": "demo-conv-id", "status": "activated", "update_time": 1768390489181, "relativity": 0.47883897395535013, "experience": "when encountering weather inquiry tasks, then ensure to call the 'get_weather' tool with the correct location parameter." # New: Procedural experience of the entire trajectory, serving as overall guidance for task completion. } ] ``` --- # Multimodal Messages (/memos_cloud/features/multimodal) > **Warning**: **[This article expands on how to add multimodal data in the [Add Memory - addMessage API], click here to view the detailed API documentation directly](/api_docs/core/add_message)** MemOS supports not only text but also multimodal data, including documents and images. Users can seamlessly integrate text, documents, and images into their interactions with MemOS, enabling the system to extract relevant information from multiple media types, enrich memory content, and enhance the capabilities of the memory system. ## 1. How to Add Multimodal Messages > **Note**: Note > When a message contains multimodal content, since file memory processing takes a long time, the `async_mode` field you pass becomes invalid, and "Async Mode" is used by default. You can query the processing progress of file memory via the `get/status` interface. When a user uploads a document or image, MemOS extracts text, visual information, and other relevant details, and processes them into user memory. > **Note**: **Multimodal Messages and Tool Memory** > > In addition to processing document and image content, MemOS also supports processing tool calling information. When you add tool calling information to a message, the system processes it into tool memory, including Tool Schema and Tool Trajectory Memory. See [Tool Calling](/memos_cloud/features/tool_calling) for details. ### Add Message ```python import os import requests import json # Replace with your MemOS API Key os.environ["MEMOS_API_KEY"] = "YOUR_API_KEY" os.environ["MEMOS_BASE_URL"] = "https://memos.memtensor.cn/api/openmem/v1" data = { "user_id": "memos_user_123", "conversation_id": "1211", "messages": [ { "role": "user", "content": [ { "type": "text", "text": "I am studying MemOS." }, { "type": "image_url", "image_url": { "url": "https://cdn.memtensor.com.cn/img/1758706201390_iluj1c_compressed.png" } } ] }, {"role": "assistant", "content": "Okay, do you need any help?"} ] } headers = { "Content-Type": "application/json", "Authorization": f"Token {os.environ['MEMOS_API_KEY']}" } url = f"{os.environ['MEMOS_BASE_URL']}/add/message" res = requests.post(url=url, headers=headers, data=json.dumps(data)) print(json.dumps(res.json(), indent=2, ensure_ascii=False)) ``` ### Search Memory ```python import os import requests import json # Replace with your MemOS API Key os.environ["MEMOS_API_KEY"] = "YOUR_API_KEY" os.environ["MEMOS_BASE_URL"] = "https://memos.memtensor.cn/api/openmem/v1" data = { "query": "Help me summarize this image", "user_id": "memos_user_123", "conversation_id": "1214" } headers = { "Content-Type": "application/json", "Authorization": f"Token {os.environ['MEMOS_API_KEY']}" } url = f"{os.environ['MEMOS_BASE_URL']}/search/memory" res = requests.post(url=url, headers=headers, data=json.dumps(data)) # Replace print part print("Result:") print(json.dumps(res.json(), indent=2, ensure_ascii=False)) ``` ### Output Result ```python { "code": 0, "data": { "memory_detail_list": [ { "id": "a5136287-de10-4df2-afc5-e412cdb8b649", "memory_key": "Studying MemOS", "memory_value": "The user is studying MemOS and shared a relevant image at 7:07 AM on December 18, 2025 (UTC).", "memory_type": "WorkingMemory", "create_time": 1766041646311, "conversation_id": "1211", "status": "activated", "confidence": 0.99, "tags": [ "Study", "MemOS", "Image Sharing" ], "update_time": 1766041689234, "relativity": 0.5170716 }, { "id": "4a1d42f4-c9fa-41bf-805d-2ea985bba984", "memory_key": "MemOS Feature Overview", "memory_value": "MemOS is an intelligent memory system capable of storing information by adding paths and retrieving information through query functions. The system supports various document formats, such as PDF and DOC, and utilizes AI for intelligent response and processing.", "memory_type": "WorkingMemory", "create_time": 1766041689091, "conversation_id": "1211", "status": "activated", "confidence": 0.99, "tags": [ "MemOS", "Intelligent Memory", "Information Storage", "Query Function", "image", "visual" ], "update_time": 1766041689234, "relativity": 0.38406307 } ], "preference_detail_list": [], "tool_memory_detail_list": [], "preference_note": "" }, "message": "ok" } ``` ## 2. Media Types MemOS currently supports the following media types: 1. **Images** - JPG, PNG, and other common image formats 2. **Documents** - PDF, DOCX, DOC, TXT, JSON, MD, XML ## 3. File Upload Limits 1. When adding messages, upload no more than 20 files per request, with a single file size not exceeding 100 MB and 200 pages. 2. When the number of files, single file size, or page count exceeds the above limits, the current task will be judged as "Processing Failed". You need to adjust according to the limit requirements and re-initiate the request. ## 4. Usage Examples ### Upload Image Message **Use Image URL** When adding a message, you can directly upload the image URL. ```python import os import requests import json # Replace with your MemOS API Key os.environ["MEMOS_API_KEY"] = "YOUR_API_KEY" os.environ["MEMOS_BASE_URL"] = "https://memos.memtensor.cn/api/openmem/v1" data = { "user_id": "memos_user_123", "conversation_id": "1211", "messages": [ { "role": "user", "content": [ { "type": "image_url", "image_url": { "url": "https://cdn.memtensor.com.cn/img/1758706201390_iluj1c_compressed.png" } } ] } ] } headers = { "Content-Type": "application/json", "Authorization": f"Token {os.environ['MEMOS_API_KEY']}" } url = f"{os.environ['MEMOS_BASE_URL']}/add/message" res = requests.post(url=url, headers=headers, data=json.dumps(data)) print(json.dumps(res.json(), indent=2, ensure_ascii=False)) ``` **Upload Local Image using Base64 Encoding** To upload a local image or embed an image directly, you can use Base64 image encoding. ```python import os import requests import json import base64 # Replace with your MemOS API Key os.environ["MEMOS_API_KEY"] = "YOUR_API_KEY" os.environ["MEMOS_BASE_URL"] = "https://memos.memtensor.cn/api/openmem/v1" # Path to the image file image_path = "path/to/your/image.jpg" # Encode image using Base64 with open(image_path, "rb") as image_file: base64_image = base64.b64encode(image_file.read()).decode("utf-8") data = { "user_id": "memos_user_123", "conversation_id": "1211", "messages": [ { "role": "user", "content": [ { "type": "image_url", "image_url": {"url": f"data:image/jpeg;base64,{base64_image}"} } ] } ] } headers = { "Content-Type": "application/json", "Authorization": f"Token {os.environ['MEMOS_API_KEY']}" } url = f"{os.environ['MEMOS_BASE_URL']}/add/message" res = requests.post(url=url, headers=headers, data=json.dumps(data)) print(json.dumps(res.json(), indent=2, ensure_ascii=False)) ``` ### Upload Document Message **Use Document URL** ```python import os import requests import json # Replace with your MemOS API Key os.environ["MEMOS_API_KEY"] = "YOUR_API_KEY" os.environ["MEMOS_BASE_URL"] = "https://memos.memtensor.cn/api/openmem/v1" data = { "user_id": "memos_user_123", "conversation_id": "1211", "messages": [ { "role": "user", "content": [ { "type": "file", "file": { "file_data": "https://cdn.memtensor.com.cn/file/MemOS 2.pdf" } } ] } ] } headers = { "Content-Type": "application/json", "Authorization": f"Token {os.environ['MEMOS_API_KEY']}" } url = f"{os.environ['MEMOS_BASE_URL']}/add/message" res = requests.post(url=url, headers=headers, data=json.dumps(data)) print(json.dumps(res.json(), indent=2, ensure_ascii=False)) ``` **Upload Local Document using Base64 Encoding** ```python import os import requests import json import base64 # Replace with your MemOS API Key os.environ["MEMOS_API_KEY"] = "YOUR_API_KEY" os.environ["MEMOS_BASE_URL"] = "https://memos.memtensor.cn/api/openmem/v1" # Path to the document file document_path = "path/to/your/document.pdf" # Function to convert file to Base64 string def file_to_base64(file_path): with open(file_path, "rb") as file: return base64.b64encode(file.read()).decode('utf-8') # Encode document using Base64 base64_document = file_to_base64(document_path) data = { "user_id": "memos_user_123", "conversation_id": "1211", "messages": [ { "role": "user", "content": [ { "type": "file", "file": {"file_data": base64_document} } ] } ] } headers = { "Content-Type": "application/json", "Authorization": f"Token {os.environ['MEMOS_API_KEY']}" } url = f"{os.environ['MEMOS_BASE_URL']}/add/message" res = requests.post(url=url, headers=headers, data=json.dumps(data)) print("Result:") print(json.dumps(res.json(), indent=2, ensure_ascii=False)) ``` ### Complete Example Here is a complete example showing how to add conversation messages containing different media types between a user and an assistant: ```python import os import json import requests # Replace with your MemOS API Key os.environ["MEMOS_API_KEY"] = "YOUR_API_KEY" os.environ["MEMOS_BASE_URL"] = "https://memos.memtensor.cn/api/openmem/v1" data = { "user_id": "memos_user_123", "conversation_id": "1211", "messages": [ { "role": "user", "content": [ { "type": "text", "text": "I am studying MemOS." } # Text message ] }, { "role": "user", "content": [ { "type": "image_url", "image_url": { "url": "https://cdn.memtensor.com.cn/img/1758706201390_iluj1c_compressed.png" } } # Upload image ] }, { "role": "user", "content": [ { "type": "file", "file": { "file_data": "https://cdn.memtensor.com.cn/file/MemOS 2.pdf" } } # Upload document ] } ] } headers = { "Content-Type": "application/json", "Authorization": f"Token {os.environ['MEMOS_API_KEY']}" } url = f"{os.environ['MEMOS_BASE_URL']}/add/message" res = requests.post(url=url, headers=headers, data=json.dumps(data)) print(json.dumps(res.json(), indent=2, ensure_ascii=False)) ``` --- # Cloud FAQs (/memos_cloud/support/faq) This page answers common questions about using MemOS Cloud. If you want to understand MemOS concepts such as RAG, open source deployment, private deployment, or memory scheduling, see [FAQ](/memos_cloud/introduction/faq). ## Which document should a new user read first? If you have not logged in to the console yet, choose the entry point based on how you plan to use MemOS Cloud: - If you want Agent tools such as Claude Code or Cursor to help with integration, start with [Use in Agents](/memos_cloud/getting_started/agent_usage). - If you want to call Cloud APIs from your own application, start with [Integrate into Your App](/memos_cloud/getting_started/quick_start). [Configuration](/api_docs/start/configuration) is more useful when you need to manage multiple projects, edit or delete projects, or understand how knowledge bases are bound to projects. ## What is the relationship between API Keys and projects? Each project has its own API Key. When you call an API with a specific API Key, you can only access memories, messages, knowledge bases, and configuration under that project. If data is visible in the console but not returned by the API, check: - Whether the console project matches the project that owns the API Key. - Whether the request uses the same `user_id`. - Whether the search request uses an overly narrow `filter`, `knowledgebase_ids`, or a high `relativity`. ## How do I troubleshoot authentication or permission errors? Start by checking the request header: ```text Authorization: Token YOUR_API_KEY ``` Common issues include: - Missing `Authorization`. - Missing the `Token` prefix. - Incomplete API Key copied from the console. - API Key belongs to another project. - API Key is invalid, expired, or has no permission for the current resource. If the response returns `40100`, `40130`, or `40132`, go back to [Configuration](/api_docs/start/configuration) and check the API Key and project. ## Why did Search Memory or Chat not recall knowledge base content? First confirm that the knowledge base is bound to the current project and that the files have finished processing. Also check the API request: - If `knowledgebase_ids` is not provided, knowledge bases are not searched by default. - If `knowledgebase_ids` is provided, make sure the IDs belong to knowledge bases accessible from the current project. - If `filter` is too narrow or `relativity` is too high, relevant content may be filtered out. For upload, binding, and processing status, see [Knowledge Base](/memos_cloud/features/knowledge_base). ## What should I do when I hit quota or rate limits? First identify which limit was reached: - Single input or output is too long: reduce the current input, history, or expected output. - API call quota is exhausted: wait for quota recovery or request more quota. - Too many requests in a short period: reduce request frequency and avoid repeated retries. For quota details, see [Quotas and Limits](/memos_cloud/support/limit). ## Why can I not search a memory immediately after writing it? After memory is written, it still needs to be extracted, processed, and indexed. If you search immediately after writing, processing may not be finished yet. Check: - The write and search requests use the same `user_id`. - The request is not restricted by an overly narrow `conversation_id`, `filter`, or `knowledgebase_ids`. - If asynchronous writing is used, wait for the task to finish before searching. ## What should I check when Delete Memory fails? When deleting individual memories, prefer `memory_ids`. Do not use `conversation_id`, `user_id`, or knowledge base IDs as `memory_id`. Only pass `user_id` when you need to delete all memories for that user under the current project. This is a high-risk operation, so confirm the API Key, project, and user ID before running it. ## Why are console and API data ranges different? Both the console and APIs isolate data by project. Inconsistent data ranges are usually caused by: - The selected console project is different from the project that owns the API Key. - The API request uses a different `user_id`. - Extra filters are applied in the API request. - The knowledge base is not authorized for the current project. If an API response returns a specific `code`, see [Error Codes](/api_docs/help/error_codes). --- # Limits (/memos_cloud/support/limit) ## 1. Quota ![image.png](https://cdn.memtensor.com.cn/img/1766630472243_emn5fx_compressed.png) MemOS Cloud Services currently provides multiple pricing plans, from the free tier to the enterprise tier, to meet the needs of teams of different sizes. All plans are currently free for a limited time. Visit [MemOS Pricing page](https://memos.openmem.net/en/pricing) to apply for the plan that fits your needs. Take action now and use MemOS Cloud Services to support the growth of your projects. > **Note**: **Note** > - The free quota is provided per **developer account** and is shared across all projects under that account. > - Failed requests (authentication failure, parameter error, exceeding limits, etc.) **do not consume quota**. ## 2. Resource Limits To ensure service stability and security, MemOS Cloud Services imposes the following limits on core API calls, calculated per account: | **API Name** | **Single Input Limit** | **Single Output Limit** | |-----------------|------------------------|-------------------------| | addMessage | 40,000 tokens | - | | searchMemory | 40,000 tokens | Factual Memory: 25 items Preference Memory: 25 items Tool Memory: 25 items Skills: 25 items | In addition, the document upload feature for the knowledge base currently has the following limits: - Supported document types: PDF, DOCX, DOC, TXT, JSON, MD, XML - Maximum single-file size: no more than 100 MB and 500 pages - Maximum number of files per upload: no more than 20 files > **Note**: **Note** > Knowledge bases now also support uploading Skill files. For detailed limits, see [Knowledge Base](/memos_cloud/features/knowledge_base). If you have higher-level or special requirements, please contact the project team for further discussion. > **Note**: **Note** > - Requests exceeding the per-call limit will return the corresponding error code without deducting quota. > - The total input tokens per minute must not exceed 400,000 tokens. Requests exceeding this limit will be rate-limited. > - Additionally, we recommend a maximum QPS ≤ 50 (i.e., up to 50 requests per second). This is not a strict limit, but high concurrency may be affected by platform capacity, so control request frequency according to actual needs. ## 3. Usage Monitoring You can view the remaining quota for each API through the **API Console**, with filters for project, API key, and date to facilitate tracking and managing usage. image --- # Search memories **POST** `/product/search` Search memories for a specific user. - operationId: `search_memories_product_search_post` ## Request Body ## Response Successful Response URL: /api-reference/search-memories --- # Add memories **POST** `/product/add` Add memories for a specific user. - operationId: `add_memories_product_add_post` ## Request Body ## Response Successful Response URL: /api-reference/add-memories --- # Get all memories for user **POST** `/product/get_all` Get all memories or subgraph for a specific user. If search_query is provided, returns a subgraph based on the query. Otherwise, returns all memories of the specified type. - operationId: `get_all_memories_product_get_all_post` ## Request Body ## Response Successful Response URL: /api-reference/get-all-memories-for-user --- # Get memories for user **POST** `/product/get_memory` Get memories for user with pagination support. - operationId: `get_memories_product_get_memory_post` ## Request Body | Parameter | Type | Required | Description | |---|---|---|---| | `user_id` | string | No | Unique identifier of the user whose memories are being retrieved. | | `agent_id` | string | No | Unique identifier of the Agent whose memories are being retrieved. Available only when independent Agent memory is enabled. Use either user_id or agent_id. | | `page` | integer | No | Page number for pagination when many results are returned. | | `size` | integer | No | Number of entries returned per memory category on the current page, up to 50. | | `filter` | object | No | Filter conditions, used to precisely limit the memory scope before retrieval. Available fields include: "agent_id", "app_id", "create_time", "update_time", and specific fields in "info". Supports logical operators (and, or) and comparison operators (gte, lte, gt, lt). For the "info" field, supports filtering by "business_type", "biz_id", "scene", and other custom fields. | | `include_memory_view` | array | No | Allowed memory types to retrieve. When omitted, all memory types are returned by default. See Memory Types for values. | ## Response Successful Response | Parameter | Type | Required | Description | |---|---|---|---| | `code` | number | Yes | API status code; refer to the error-code list for details. | | `data` | object | No | | | `message` | string | Yes | API message. | #### `data` object | Parameter | Type | Required | Description | |---|---|---|---| | `memory_detail_list` | array | No | List of factual memory fragment details returned. | | `preference_detail_list` | array | No | List of preference memory fragment details returned. | | `profile_detail_list` | array | No | List of profile memory fragment details returned. | | `event_detail_list` | array | No | List of event memory fragment details returned. | | `tool_memory_detail_list` | array | No | List of tool memory fragment details returned. | | `skill_detail_list` | array | No | List of Skill details returned. | | `total` | integer | No | Maximum count across memory types, used to check if another page exists. | | `size` | integer | No | Number of entries per memory type on the current page. | | `current` | integer | No | Index of the current page. | | `pages` | integer | No | Total number of pages. | #### `memory_detail_list` object | Parameter | Type | Required | Description | |---|---|---|---| | `id` | string | No | Unique identifier of the factual memory. | | `memory_key` | string | No | Title or keyword of the factual memory. | | `memory_value` | string | No | Detailed content of the factual memory. | | `memory_type` | string (enum: WorkingMemory, LongTermMemory, UserMemory) | No | Type of factual memory. | | `create_time` | string | No | Creation time in ISO 8601 format. | | `conversation_id` | string | No | Conversation identifier linked to this memory. | | `status` | string (enum: activated) | No | Factual memory status. Currently only activated is returned. | | `confidence` | number | No | Confidence score between 0 and 1. | | `tags` | array | No | Tag list associated with the factual memory. | | `update_time` | string | No | Last update time in ISO 8601 format. | | `relativity` | number | No | Relevance score between 0 and 1. | | `sources` | array | No | Source messages of the factual memory. | | `info` | object | No | Custom metadata provided when adding the message. | #### `preference_detail_list` object | Parameter | Type | Required | Description | |---|---|---|---| | `id` | string | No | Unique identifier of the preference memory. | | `preference_type` | string (enum: explicit_preference, implicit_preference) | No | Type of preference memory. | | `preference` | string | No | Detailed content of the preference memory. | | `reasoning` | string | No | Reason why the preference memory was extracted. | | `create_time` | string | No | Creation time in ISO 8601 format. | | `conversation_id` | string | No | Conversation identifier linked to this memory. | | `status` | string (enum: activated) | No | Preference memory status. Currently only activated is returned. | | `update_time` | string | No | Last update time in ISO 8601 format. | | `relativity` | number | No | Relevance score between 0 and 1. | | `sources` | array | No | Source messages of the preference memory. | | `info` | object | No | Custom metadata provided when adding the message. | #### `profile_detail_list` object | Parameter | Type | Required | Description | |---|---|---|---| | `id` | string | No | Unique identifier of the profile memory instance. | | `project_id` | string | No | Project ID. | | `profile_template_id` | string | No | Profile template ID. | | `properties` | object | No | Structured profile field tree. | | `status` | string (enum: activated) | No | Profile memory status. Currently only activated is returned. | | `created_at` | string | No | Profile memory creation time in ISO 8601 format. | | `updated_at` | string | No | Last update time of the profile memory in ISO 8601 format. | #### `event_detail_list` object | Parameter | Type | Required | Description | |---|---|---|---| | `id` | string | No | Unique identifier of the event memory. | | `event_key` | string | No | Title or keyword of the event memory. | | `event_value` | string | No | Detailed content of the event memory. | | `event_type` | string | No | Event memory type, usually EventMemory. | | `create_time` | string | No | Event memory creation time in ISO 8601 format. | | `conversation_id` | string | No | Unique identifier of the conversation associated with the event memory. | | `status` | string (enum: activated) | No | Event memory status. Currently only activated is returned. | | `update_time` | string | No | Last update time of the event memory in ISO 8601 format. | | `info` | object | No | Extended information of the event memory. | | `sources` | array | No | Source messages of the event memory. | | `event_time` | array | No | List of event times. | | `event_location` | array | No | List of event locations. | | `event_roles` | array | No | List of event participants. | #### `tool_memory_detail_list` object | Parameter | Type | Required | Description | |---|---|---|---| | `id` | string | No | Unique identifier of the tool memory fragment. | | `tool_type` | string (enum: ToolTrajectoryMemory, ToolSchema) | No | Tool memory type. ToolTrajectoryMemory means tool trajectory memory; ToolSchema means tool schema memory. | | `tool_value` | string | No | Detailed content of the tool memory. | | `tool_used_status` | array | No | Tool trajectory records, each containing the used tool and experience. | | `create_time` | string | No | Creation time in ISO 8601 format. | | `conversation_id` | string | No | Conversation identifier linked to this memory. | | `status` | string (enum: activated) | No | Tool memory status. Currently activated only. | | `update_time` | string | No | Last update time in ISO 8601 format. | | `relativity` | number | No | Relevance score between 0 and 1. | | `source` | string | No | Source information of the tool memory. | | `experience` | string | No | Procedural experience of the entire trajectory. | | `info` | object | No | Custom metadata provided when adding the message. | #### `skill_detail_list` object | Parameter | Type | Required | Description | |---|---|---|---| | `id` | string | No | The unique identifier of the Skill, used internally by the system to distinguish different memory entries. | | `skill_value` | object | No | Structured Skill content. You can convert it to a string and inject it into the Agent prompt. | | `skill_url` | string | No | Download link for the Skill. A Markdown Skill can be downloaded as SKILL.md; a ZIP Skill package can include SKILL.md, scripts, references, assets, and other attachments. | | `skill_type` | string | No | The type of the Skill. | | `create_time` | string | No | The creation time of the Skill content, usually in ISO 8601 format. | | `conversation_id` | string | No | The unique identifier of the conversation associated with the Skill. | | `status` | string (enum: activated) | No | The status of the Skill. Currently, all retrieved Skills are 'activated'. activated: Active status, the Skill is currently retrievable and usable. | | `confidence` | number | No | The confidence score of the Skill, ranging from 0 to 1. A value closer to 1 indicates the Skill is more accurate and reliable. The confidence score gradually decays as the model infers this Skill more times, reflecting the uncertainty that may arise over time or usage frequency. | | `tags` | array | No | A list of tags associated with the Skill, used for classification, retrieval, or topic marking. Each element in the array is a string, e.g., ["Person", "Event", "Work"]. | | `update_time` | string | No | The time when the Skill was last modified or updated, usually in ISO 8601 format. | | `relativity` | string | No | The relevance score between the query content and the Skill, ranging from 0 to 1. A value closer to 1 indicates higher relevance. | ### Response Example ```json { "data": { "memory_detail_list": [ { "memory_type": "WorkingMemory", "status": "activated" } ], "preference_detail_list": [ { "preference_type": "explicit_preference", "status": "activated" } ], "profile_detail_list": [ { "status": "activated" } ], "event_detail_list": [ { "status": "activated" } ], "tool_memory_detail_list": [ { "tool_type": "ToolTrajectoryMemory", "status": "activated" } ], "skill_detail_list": [ { "status": "activated" } ] } } ``` URL: /api-reference/get-memories-for-user --- # Get memory by id **GET** `/product/get_memory/{memory_id}` Get a specific memory by its ID. - operationId: `get_memory_by_id_product_get_memory__memory_id__get` ## Response Successful Response | Parameter | Type | Required | Description | |---|---|---|---| | `code` | number | Yes | API status code; refer to the error-code list for details. | | `data` | object | No | | | `message` | string | Yes | API message. | #### `data` object | Parameter | Type | Required | Description | |---|---|---|---| | `memory_detail_list` | array | No | List of factual memory fragment details returned. | | `preference_detail_list` | array | No | List of preference memory fragment details returned. | | `profile_detail_list` | array | No | List of profile memory fragment details returned. | | `event_detail_list` | array | No | List of event memory fragment details returned. | | `tool_memory_detail_list` | array | No | List of tool memory fragment details returned. | | `skill_detail_list` | array | No | List of Skill details returned. | | `total` | integer | No | Maximum count across memory types, used to check if another page exists. | | `size` | integer | No | Number of entries per memory type on the current page. | | `current` | integer | No | Index of the current page. | | `pages` | integer | No | Total number of pages. | #### `memory_detail_list` object | Parameter | Type | Required | Description | |---|---|---|---| | `id` | string | No | Unique identifier of the factual memory. | | `memory_key` | string | No | Title or keyword of the factual memory. | | `memory_value` | string | No | Detailed content of the factual memory. | | `memory_type` | string (enum: WorkingMemory, LongTermMemory, UserMemory) | No | Type of factual memory. | | `create_time` | string | No | Creation time in ISO 8601 format. | | `conversation_id` | string | No | Conversation identifier linked to this memory. | | `status` | string (enum: activated) | No | Factual memory status. Currently only activated is returned. | | `confidence` | number | No | Confidence score between 0 and 1. | | `tags` | array | No | Tag list associated with the factual memory. | | `update_time` | string | No | Last update time in ISO 8601 format. | | `relativity` | number | No | Relevance score between 0 and 1. | | `sources` | array | No | Source messages of the factual memory. | | `info` | object | No | Custom metadata provided when adding the message. | #### `preference_detail_list` object | Parameter | Type | Required | Description | |---|---|---|---| | `id` | string | No | Unique identifier of the preference memory. | | `preference_type` | string (enum: explicit_preference, implicit_preference) | No | Type of preference memory. | | `preference` | string | No | Detailed content of the preference memory. | | `reasoning` | string | No | Reason why the preference memory was extracted. | | `create_time` | string | No | Creation time in ISO 8601 format. | | `conversation_id` | string | No | Conversation identifier linked to this memory. | | `status` | string (enum: activated) | No | Preference memory status. Currently only activated is returned. | | `update_time` | string | No | Last update time in ISO 8601 format. | | `relativity` | number | No | Relevance score between 0 and 1. | | `sources` | array | No | Source messages of the preference memory. | | `info` | object | No | Custom metadata provided when adding the message. | #### `profile_detail_list` object | Parameter | Type | Required | Description | |---|---|---|---| | `id` | string | No | Unique identifier of the profile memory instance. | | `project_id` | string | No | Project ID. | | `profile_template_id` | string | No | Profile template ID. | | `properties` | object | No | Structured profile field tree. | | `status` | string (enum: activated) | No | Profile memory status. Currently only activated is returned. | | `created_at` | string | No | Profile memory creation time in ISO 8601 format. | | `updated_at` | string | No | Last update time of the profile memory in ISO 8601 format. | #### `event_detail_list` object | Parameter | Type | Required | Description | |---|---|---|---| | `id` | string | No | Unique identifier of the event memory. | | `event_key` | string | No | Title or keyword of the event memory. | | `event_value` | string | No | Detailed content of the event memory. | | `event_type` | string | No | Event memory type, usually EventMemory. | | `create_time` | string | No | Event memory creation time in ISO 8601 format. | | `conversation_id` | string | No | Unique identifier of the conversation associated with the event memory. | | `status` | string (enum: activated) | No | Event memory status. Currently only activated is returned. | | `update_time` | string | No | Last update time of the event memory in ISO 8601 format. | | `info` | object | No | Extended information of the event memory. | | `sources` | array | No | Source messages of the event memory. | | `event_time` | array | No | List of event times. | | `event_location` | array | No | List of event locations. | | `event_roles` | array | No | List of event participants. | #### `tool_memory_detail_list` object | Parameter | Type | Required | Description | |---|---|---|---| | `id` | string | No | Unique identifier of the tool memory fragment. | | `tool_type` | string (enum: ToolTrajectoryMemory, ToolSchema) | No | Tool memory type. ToolTrajectoryMemory means tool trajectory memory; ToolSchema means tool schema memory. | | `tool_value` | string | No | Detailed content of the tool memory. | | `tool_used_status` | array | No | Tool trajectory records, each containing the used tool and experience. | | `create_time` | string | No | Creation time in ISO 8601 format. | | `conversation_id` | string | No | Conversation identifier linked to this memory. | | `status` | string (enum: activated) | No | Tool memory status. Currently activated only. | | `update_time` | string | No | Last update time in ISO 8601 format. | | `relativity` | number | No | Relevance score between 0 and 1. | | `source` | string | No | Source information of the tool memory. | | `experience` | string | No | Procedural experience of the entire trajectory. | | `info` | object | No | Custom metadata provided when adding the message. | #### `skill_detail_list` object | Parameter | Type | Required | Description | |---|---|---|---| | `id` | string | No | The unique identifier of the Skill, used internally by the system to distinguish different memory entries. | | `skill_value` | object | No | Structured Skill content. You can convert it to a string and inject it into the Agent prompt. | | `skill_url` | string | No | Download link for the Skill. A Markdown Skill can be downloaded as SKILL.md; a ZIP Skill package can include SKILL.md, scripts, references, assets, and other attachments. | | `skill_type` | string | No | The type of the Skill. | | `create_time` | string | No | The creation time of the Skill content, usually in ISO 8601 format. | | `conversation_id` | string | No | The unique identifier of the conversation associated with the Skill. | | `status` | string (enum: activated) | No | The status of the Skill. Currently, all retrieved Skills are 'activated'. activated: Active status, the Skill is currently retrievable and usable. | | `confidence` | number | No | The confidence score of the Skill, ranging from 0 to 1. A value closer to 1 indicates the Skill is more accurate and reliable. The confidence score gradually decays as the model infers this Skill more times, reflecting the uncertainty that may arise over time or usage frequency. | | `tags` | array | No | A list of tags associated with the Skill, used for classification, retrieval, or topic marking. Each element in the array is a string, e.g., ["Person", "Event", "Work"]. | | `update_time` | string | No | The time when the Skill was last modified or updated, usually in ISO 8601 format. | | `relativity` | string | No | The relevance score between the query content and the Skill, ranging from 0 to 1. A value closer to 1 indicates higher relevance. | ### Response Example ```json { "data": { "memory_detail_list": [ { "memory_type": "WorkingMemory", "status": "activated" } ], "preference_detail_list": [ { "preference_type": "explicit_preference", "status": "activated" } ], "profile_detail_list": [ { "status": "activated" } ], "event_detail_list": [ { "status": "activated" } ], "tool_memory_detail_list": [ { "tool_type": "ToolTrajectoryMemory", "status": "activated" } ], "skill_detail_list": [ { "status": "activated" } ] } } ``` URL: /api-reference/get-memory-by-id --- # Delete memories for user **POST** `/product/delete_memory` Delete memories for a specific user. - operationId: `delete_memories_product_delete_memory_post` ## Request Body | Parameter | Type | Required | Description | |---|---|---|---| | `memory_ids` | array | No | List of memory IDs to delete. | | `user_id` | string | No | Delete all memories of this user in the current project. Mutually exclusive with memory_ids and agent_id. | | `agent_id` | string | No | Delete all memories of this Agent in the current project. Available only when independent Agent memory is enabled. Mutually exclusive with memory_ids and user_id. | ## Response Successful Response | Parameter | Type | Required | Description | |---|---|---|---| | `code` | integer | No | API status code. See Error Code for details. | | `data` | object | No | Returned deletion information | | `message` | string | No | API response message | #### `data` object | Parameter | Type | Required | Description | |---|---|---|---| | `success` | boolean | No | Whether deletion was successful. true for success, false for failure. | ### Response Example ```json { "data": { "success": true } } ``` URL: /api-reference/delete-memories-for-user --- # Chat with MemOS (Complete Response) **POST** `/product/chat/complete` Chat with MemOS for a specific user. Returns complete response (non-streaming). - operationId: `chat_complete_product_chat_complete_post` ## Request Body ## Response Successful Response URL: /api-reference/chat-with-memos-(complete-response) --- # Chat with MemOS **POST** `/product/chat/stream` Chat with MemOS for a specific user. Returns SSE stream. - operationId: `chat_stream_product_chat_stream_post` ## Request Body | Parameter | Type | Required | Description | |---|---|---|---| | `user_id` | string | Yes | Unique identifier of the user associated with the conversation. | | `conversation_id` | string | Yes | Unique identifier of the conversation. Providing this clarifies the current session, prioritizing its memory over historical sessions. If omitted, cross-session memory retrieval is performed for more relevant responses. | | `query` | string | Yes | User input content. | | `filter` | object | No | Filter conditions, used to precisely limit the memory scope before retrieval. Available fields include: "agent_id", "app_id", "create_time", "update_time", and specific fields in "info". Supports logical operators (and, or) and comparison operators (gte, lte, gt, lt). For the "info" field, supports filtering by "business_type", "biz_id", "scene", and other custom fields. | | `knowledgebase_ids` | array | No | Specifies the scope of Knowledge Bases accessible for the current search. Defaults to empty, meaning no Knowledge Bases are searched. Pass specific Knowledge Base IDs to search ordinary documents and uploaded Skills in those Knowledge Bases; pass "all" to search across all associated Knowledge Bases within the project. | | `memory_limit_number` | integer | No | Maximum number of memories that can be recalled: as long as the relevance threshold (relativity) is met, up to this many memories may be returned. Default is 9, maximum is 25. | | `include_preference` | boolean | No | Whether to recall preference memories. When enabled, the system intelligently recalls memories related to user preferences based on the query. Default = true. | | `preference_limit_number` | integer | No | Maximum number of preferred memories that can be recalled: as long as the relevance threshold (relativity) is met, up to this many preference memories may be returned. Default is 9, maximum is 25. | | `relativity` | number | No | Relevance threshold (0–1) for recalled memories. Filters out low-relevance memories and, together with the maximum counts for factual and preferred recalls, constrains the final results. When omitted, the system default threshold is used. A value of 0 disables relevance filtering. | | `model_name` | string (enum: qwen3-32b, deepseek-r1, qwen2.5-72b-instruct) | No | Specifies the concrete conversation model. | | `system_prompt` | string | No | Custom system instructions. | | `stream` | boolean | No | Whether to enable streaming response. | | `max_tokens` | integer | No | Indicates the maximum number of generated tokens. | | `temperature` | number | No | Controls generation randomness. Range: 0 ≤ x ≤ 2. | | `top_p` | number | No | Nucleus sampling parameter. Range: 0 ≤ x ≤ 1. | | `add_message_on_answer` | boolean | No | Whether to automatically write user and assistant conversation content into memory. When enabled, developers do not need to call the add/message API to add messages as memory. | | `app_id` | string | No | Unique identifier of the application associated with the conversation. | | `agent_id` | string | No | Unique identifier of the Agent associated with the conversation. | | `tags` | array | No | List of custom tags used to mark the topic or category of the conversation. | | `info` | object | No | Custom metadata field capable of storing any structured data related to the conversation, such as location, source, version, etc., primarily for precise filtering or source tracking during retrieval. | | `allow_public` | boolean | No | Whether to allow adding to public memory. | | `allow_knowledgebase_ids` | array | No | List of knowledgebases where memories generated from added messages are allowed to be written. | ## Response Successful Response URL: /api-reference/chat-with-memos --- # Chat with MemOS playground **POST** `/product/chat/stream/playground` Chat with MemOS for a specific user in playground. Returns SSE stream. - operationId: `chat_stream_playground_product_chat_stream_playground_post` ## Request Body ## Response Successful Response URL: /api-reference/chat-with-memos-playground --- # Get suggestion queries **POST** `/product/suggestions` Get suggestion queries for a specific user with language preference. - operationId: `get_suggestion_queries_product_suggestions_post` ## Request Body ## Response Successful Response URL: /api-reference/get-suggestion-queries --- # Feedback memories **POST** `/product/feedback` Feedback memories for a specific user. - operationId: `feedback_memories_product_feedback_post` ## Request Body ## Response Successful Response URL: /api-reference/feedback-memories --- # Get detailed scheduler status **GET** `/product/scheduler/allstatus` Get detailed scheduler status including running tasks and queue metrics. - operationId: `scheduler_allstatus_product_scheduler_allstatus_get` ## Response Successful Response URL: /api-reference/get-detailed-scheduler-status --- # Get scheduler running status **GET** `/product/scheduler/status` Get scheduler running status. - operationId: `scheduler_status_product_scheduler_status_get` ## Response Successful Response URL: /api-reference/get-scheduler-running-status --- # Get scheduler task queue status **GET** `/product/scheduler/task_queue_status` Get scheduler task queue backlog/pending status for a user. - operationId: `scheduler_task_queue_status_product_scheduler_task_queue_status_get` ## Response Successful Response URL: /api-reference/get-scheduler-task-queue-status --- # Wait until scheduler is idle for a specific user **POST** `/product/scheduler/wait` Wait until scheduler is idle for a specific user. - operationId: `scheduler_wait_product_scheduler_wait_post` ## Response Successful Response URL: /api-reference/wait-until-scheduler-is-idle-for-a-specific-user --- # Stream scheduler progress for a user **GET** `/product/scheduler/wait/stream` Stream scheduler progress via Server-Sent Events (SSE). - operationId: `scheduler_wait_stream_product_scheduler_wait_stream_get` ## Response Successful Response URL: /api-reference/stream-scheduler-progress-for-a-user --- # Get user names by memory ids **POST** `/product/get_user_names_by_memory_ids` Get user names by memory ids. - operationId: `get_user_names_by_memory_ids_product_get_user_names_by_memory_ids_post` ## Request Body ## Response Successful Response URL: /api-reference/get-user-names-by-memory-ids --- # Check if mem cube id exists **POST** `/product/exist_mem_cube_id` Check if mem cube id exists. - operationId: `exist_mem_cube_id_product_exist_mem_cube_id_post` ## Request Body ## Response Successful Response URL: /api-reference/check-if-mem-cube-id-exists --- # Installation Guide (/open_source/getting_started/installation) - [Install via Docker](/open_source/getting_started/installation#from-docker): Ideal for quick deployment: one-click startup for services and dependencies. - [Install from Source](/open_source/getting_started/installation#from-source): Ideal for development and contribution: editable installation, run tests, local debugging. - [Install via pip](/open_source/getting_started/installation#from-pip): The simplest installation method: get started with MemOS quickly. ## Install via Docker ```bash git clone https://github.com/MemTensor/MemOS.git cd MemOS ``` #### Create .env Configuration File > **Note**: **Please Note** > The .env file must be placed in the MemOS project root directory. #### 1. Create .env ```bash cd MemOS touch .env ``` #### 2. .env Contents Here is a quick .env configuration example: ```bash # OpenAI API Key (Required configuration) OPENAI_API_KEY=sk-xxx # OpenAI API Base URL OPENAI_API_BASE=http://xxx:3000/v1 # Default model name MOS_CHAT_MODEL=qwen3-max # Memory Reader LLM Model MEMRADER_MODEL=qwen3-max # Memory Reader API Key MEMRADER_API_KEY=sk-xxx # Memory Reader API Base URL MEMRADER_API_BASE=http://xxx:3000/v1 # Embedder Model Name MOS_EMBEDDER_MODEL=text-embedding-v4 # Configure embedding backend: ollama | universal_api MOS_EMBEDDER_BACKEND=universal_api # Embedder API Base URL MOS_EMBEDDER_API_BASE=http://xxx:8081/v1 # Embedder API Key MOS_EMBEDDER_API_KEY=xxx # Embedding Vector Dimension EMBEDDING_DIMENSION=1024 # Reranker Backend (http_bge | etc.) MOS_RERANKER_BACKEND=cosine_local # Neo4j Connection URI # Options: neo4j-community | neo4j | nebular | polardb NEO4J_BACKEND=neo4j-community # Required when backend=neo4j* NEO4J_URI=bolt://localhost:7687 NEO4J_USER=neo4j NEO4J_PASSWORD=12345678 NEO4J_DB_NAME=neo4j MOS_NEO4J_SHARED_DB=false # Whether to use redis scheduler DEFAULT_USE_REDIS_QUEUE=false # Enable Chat API ENABLE_CHAT_API=true # Chat model list, can be applied through Bailian. Models are customizable. CHAT_MODEL_LIST=[{"backend": "qwen", "api_base": "https://xxx/v1", "api_key": "sk-xxx", "model_name_or_path": "qwen3-max", "extra_body": {"enable_thinking": true} ,"support_models": ["qwen3-max"]}] ``` #### .env Configuration Example using Bailian ```bash # Can be applied through Bailian platform # https://bailian.console.aliyun.com/?spm=a2c4g.11186623.0.0.2f2165b08fRk4l&tab=api#/api # After successful application, get API_KEY and BASE_URL, configuration example as follows # OpenAI API Key (Use Bailian API_KEY) OPENAI_API_KEY=you_bailian_api_key # OpenAI API Base URL OPENAI_API_BASE=https://dashscope.aliyuncs.com/compatible-mode/v1 # Default model name MOS_CHAT_MODEL=qwen3-max # Memory Reader LLM Model MEMRADER_MODEL=qwen3-max # Memory Reader API Key (Use Bailian API_KEY) MEMRADER_API_KEY=you_bailian_api_key # Memory Reader API Base URL MEMRADER_API_BASE=https://dashscope.aliyuncs.com/compatible-mode/v1 # Embedder model name can refer to the link below # https://bailian.console.aliyun.com/?spm=a2c4g.11186623.0.0.2f2165b08fRk4l&tab=api#/api/?type=model&url=2846066 MOS_EMBEDDER_MODEL=text-embedding-v4 # Configure embedding backend: ollama | universal_api MOS_EMBEDDER_BACKEND=universal_api # Embedder API Base URL MOS_EMBEDDER_API_BASE=https://dashscope.aliyuncs.com/compatible-mode/v1 # Embedder API Key (Use Bailian API_KEY) MOS_EMBEDDER_API_KEY=you_bailian_api_key # Embedding Vector Dimension EMBEDDING_DIMENSION=1024 # Reranker Backend (http_bge | etc.) MOS_RERANKER_BACKEND=cosine_local # Neo4j Connection URI # Options: neo4j-community | neo4j | nebular | polardb NEO4J_BACKEND=neo4j-community # Required when backend=neo4j* NEO4J_URI=bolt://localhost:7687 NEO4J_USER=neo4j NEO4J_PASSWORD=12345678 NEO4J_DB_NAME=neo4j MOS_NEO4J_SHARED_DB=false # Whether to use redis scheduler DEFAULT_USE_REDIS_QUEUE=false # Enable Chat API ENABLE_CHAT_API=true CHAT_MODEL_LIST=[{"backend": "qwen", "api_base": "https://dashscope.aliyuncs.com/compatible-mode/v1", "api_key": "you_bailian_api_key", "model_name_or_path": "qwen3-max-preview", "extra_body": {"enable_thinking": true} ,"support_models": ["qwen3-max-preview"]}] ``` ![MemOS bailian](https://cdn.memtensor.com.cn/img/get_key_url_by_bailian_compressed.png)
Example of applying for API_KEY and BASE_URL in Bailian #### Configure Dockerfile > **Note**: **Please Note** > The Dockerfile is located in the docker directory. ```bash # Enter the docker directory cd docker ``` Includes quick mode and full mode. You can choose to use the lite package (distinguished by arm and x86) or the full package (distinguished by arm and x86). ```bash ● Lite Package: Simplifies large dependencies like nvidia-related ones, effectively making the image lightweight for faster local deployment. url: registry.cn-shanghai.aliyuncs.com/memtensor/memos-base:v1.0 url: registry.cn-shanghai.aliyuncs.com/memtensor/memos-base-arm:v1.0 ● Full Package: Packaged with all MemOS dependencies into the image, allowing for a full-feature experience. Can be built and started directly by configuring the Dockerfile. url: registry.cn-shanghai.aliyuncs.com/memtensor/memos-full-base:v1.0.0 url: registry.cn-shanghai.aliyuncs.com/memtensor/memos-full-base-arm:v1.0.0 ``` ```bash # This example uses the lite package url FROM registry.cn-shanghai.aliyuncs.com/memtensor/memos-base-arm:v1.0 WORKDIR /app ENV HF_ENDPOINT=https://hf-mirror.com ENV PYTHONPATH=/app/src COPY src/ ./src/ EXPOSE 8000 CMD ["uvicorn", "memos.api.server_api:app", "--host", "0.0.0.0", "--port", "8000", "--reload"] ``` #### Start Docker Client ```bash # If Docker is not installed, please install the corresponding version. Download address: https://www.docker.com/ #After installation, Docker can be started through the client or through the command line #Command line start sudo systemctl start docker # After installation, check docker status docker ps # Check docker images (optional) docker images ``` #### Build and Start Service: > **Note**: **Please Note** > The build command must also be executed in the docker directory. ```bash # In the docker directory docker compose up ``` ![MemOS buildComposeupSuccess](https://cdn.memtensor.com.cn/img/memos_build_composeup_success_compressed.png)
Example image, port according to custom docker configuration #### Access the API at [http://localhost:8000/docs](http://localhost:8000/docs). ![MemOS Architecture](https://cdn.memtensor.com.cn/img/memos_run_server_success_compressed.png) #### Search Memory ```bash curl --location --request POST 'http://127.0.0.1:8000/product/search' \ --header 'Content-Type: application/json' \ --data-raw '{ "query": "What do I like to eat", "user_id": "8736b16e-1d20-4163-980b-a5063c3facdc", "readable_cube_ids": ["b32d0977-435d-4828-a86f-4f47f8b55bca"], "top_k":20 }' # response { "code": 200, "message": "Search completed successfully", "data": { "text_mem": [ { "cube_id": "7231eda8-6c57-4f6e-97ce-98b699eebb98", "memories": [ { "id": "2f40be8f-736c-4a5f-aada-9489037769e0", "memory": "[user opinion] User likes strawberries.", "metadata": { "user_id": "de8215e3-3beb-4afc-9b64-ae594d62f1ea", "session_id": "root_session", "status": "activated", "type": "fact", "key": "User's preference for strawberries", "confidence": 0.99, "source": null, "tags": [ "preference", "strawberries" ], "visibility": null, "updated_at": "2025-09-18T08:23:44.625479000+00:00", "memory_type": "UserMemory", "sources": [], "embedding": [], "created_at": "2025-09-18T08:23:44.625511000+00:00", "usage": [ "{ "time": "2025-09-18T08:24:17.759748", "info": { "user_id": "de8215e3-3beb-4afc-9b64-ae594d62f1ea", "session_id": "root_session" } }" ], "background": "User expressed a preference for strawberries, indicating a tendency in dietary preferences.", "relativity": 0.6349761312470591, "vector_sync": "success", "ref_id": "[2f40be8f]", "id": "2f40be8f-736c-4a5f-aada-9489037769e0", "memory": "[user opinion] User likes strawberries." }, "ref_id": "[2f40be8f]" }, ... } } ], "act_mem": [], "para_mem": [] } } ``` ## Install from Source ```bash git clone https://github.com/MemTensor/MemOS.git cd MemOS ``` #### Create .env Configuration File The MemOS server_api relies on environment variables to start, so you need to create a .env file in the startup directory. 1. Create .env file ```bash cd MemOS touch .env ``` 2. .env contents Please refer to the Docker installation for quick configuration[env configuration](/open_source/getting_started/installation#from-docker) For detailed .env configuration, please refer to [env configuration](/open_source/getting_started/rest_api_server/#local-deployment) > **Note**: **Please Note** > The .env file must be placed in the MemOS project root directory. #### Install Dependencies ```bash # Execute the installation command pip install -e . pip install --no-cache-dir -r ./docker/requirements.txt # Configure PYTHONPATH to the absolute directory of the current project file src export PYTHONPATH=/******/MemOS/src ``` #### Neo4j Support > **Note**: **Neo4j Desktop Requirement** If you plan to use Neo4j for graph memory, please install Neo4j Desktop. > Additionally, you need to set **NEO4J_BACKEND=neo4j** in .env file #### Start MemOS Server ```bash # project root directory uvicorn memos.api.server_api:app --host 0.0.0.0 --port 8000 --workers 1 ``` #### Add Memory ```bash curl --location --request POST 'http://127.0.0.1:8000/product/add' \ --header 'Content-Type: application/json' \ --data-raw '{ "messages": [{ "role": "user", "content": "I like eating strawberries" }], "user_id": "8736b16e-1d20-4163-980b-a5063c3facdc", "writable_cube_ids":["b32d0977-435d-4828-a86f-4f47f8b55bca"] }' # response { "code": 200, "message": "Memory created successfully", "data": null } ``` #### Search Memory ```bash curl --location --request POST 'http://127.0.0.1:8000/product/search' \ --header 'Content-Type: application/json' \ --data-raw '{ "query": "What do I like to eat", "user_id": "8736b16e-1d20-4163-980b-a5063c3facdc", "readable_cube_ids": ["b32d0977-435d-4828-a86f-4f47f8b55bca"], "top_k":20 }' # response { "code": 200, "message": "Search completed successfully", "data": { "text_mem": [ { "cube_id": "7231eda8-6c57-4f6e-97ce-98b699eebb98", "memories": [ { "id": "2f40be8f-736c-4a5f-aada-9489037769e0", "memory": "[user opinion] User likes strawberries.", "metadata": { "user_id": "de8215e3-3beb-4afc-9b64-ae594d62f1ea", "session_id": "root_session", "status": "activated", "type": "fact", "key": "User's preference for strawberries", "confidence": 0.99, "source": null, "tags": [ "preference", "strawberries" ], "visibility": null, "updated_at": "2025-09-18T08:23:44.625479000+00:00", "memory_type": "UserMemory", "sources": [], "embedding": [], "created_at": "2025-09-18T08:23:44.625511000+00:00", "usage": [ "{ "time": "2025-09-18T08:24:17.759748", "info": { "user_id": "de8215e3-3beb-4afc-9b64-ae594d62f1ea", "session_id": "root_session" } }" ], "background": "User expressed a preference for strawberries, indicating a tendency in dietary preferences.", "relativity": 0.6349761312470591, "vector_sync": "success", "ref_id": "[2f40be8f]", "id": "2f40be8f-736c-4a5f-aada-9489037769e0", "memory": "[user opinion] User likes strawberries." }, "ref_id": "[2f40be8f]" }, ... } } ], "act_mem": [], "para_mem": [] } } ``` ## Install via pip The simplest way to install MemOS is using pip. #### Create and Activate Conda Environment (Recommended) To avoid dependency conflicts, it is strongly recommended to use a dedicated Conda environment. ```bash conda create -n memos python=3.11 conda activate memos ``` #### Install MemOS from PyPI Install MemOS with all optional components: ```bash pip install -U "MemoryOS[all]" ``` After installation, you can verify it was successful: ```bash python -c "import memos; print(memos.__version__)" ``` > **Note**: **Optional Dependencies** > > MemOS provides several optional dependency groups for different features. You can install them based on your needs. > > | Feature | Package Name | > | ---------------- | ------------------------- | > | Tree Memory | `MemoryOS[tree-mem]` | > | Memory Reader | `MemoryOS[mem-reader]` | > | Memory Scheduler | `MemoryOS[mem-scheduler]` | > > Example installation commands: > > ```bash > pip install MemoryOS[tree-mem] > pip install MemoryOS[tree-mem,mem-reader] > pip install MemoryOS[mem-scheduler] > pip install MemoryOS[tree-mem,mem-reader,mem-scheduler] > ``` #### Create .env Configuration File The MemOS server_api relies on environment variables to start, so you need to create a .env file in the startup directory. 1. Create .env file ```bash touch .env ``` 2. Example .env contents ```text # ========== Required Configuration ========== CHAT_MODEL_LIST='[ { "name": "default", "backend": "openai", "config": { "model": "gpt-4o-mini", "api_key": "YOUR_API_KEY" } } ]' # ========== Optional Configuration ========== MEMOS_LOG_LEVEL=INFO ``` > **Note**: **Please Note** > env notes For detailed development environment setup, workflow guidelines, and contribution best practices, please see our [Contribution Guide](/open_source/contribution/overview). #### Start MemOS Server MemOS does not automatically load .env files. Please use the python-dotenv method to start. ```bash python -m dotenv run -- \ uvicorn memos.api.server_api:app \ --host 0.0.0.0 \ --port 8000 ``` After successful startup, you will see output similar to: ```text INFO: Uvicorn running on http://0.0.0.0:8000 INFO: Application startup complete. ``` #### Verify Service is Running #### Ollama Support To use MemOS with [Ollama](https://ollama.com/), first install the Ollama CLI: ```bash curl -fsSL https://ollama.com/install.sh | sh ``` #### Transformers Support To use functionalities based on the `transformers` library, ensure you have [PyTorch](https://pytorch.org/get-started/locally/) installed (CUDA version recommended for GPU acceleration). #### Neo4j Support > **Note**: **Neo4j Desktop Requirement** If you plan to use Neo4j for graph memory, please install Neo4j Desktop. #### Download Examples To download example code, data, and configurations, run the following command: ```bash memos download_examples ``` --- # Your First Memory (/open_source/getting_started/your_first_memory) ## What You'll Learn By the end of this guide, you will: - Extract memories from plain text or chat messages. - Store them as semantic vectors. - Search and manage them using vector similarity. ## How It Works ### Memory Structure Every memory is stored as a `TextualMemoryItem`: - `memory`: the main text content (e.g., "The user loves tomatoes.") - `metadata`: extra details to make the memory searchable and manageable — type, time, source, confidence, entities, tags, visibility, and updated_at. These fields make each piece of memory queryable, filterable, and easy to govern. For each `TextualMemoryItem`: | Field | Example | What it means | | ------------- | ------------------------- | ------------------------------------------ | | `type` | `"opinion"` | Classify if it's a fact, event, or opinion | | `memory_time` | `"2025-07-02"` | When it happened | | `source` | `"conversation"` | Where it came from | | `confidence` | `100.0` | Certainty score (0–100) | | `entities` | `["tomatoes"]` | Key concepts | | `tags` | `["food", "preferences"]` | Extra labels for grouping | | `visibility` | `"private"` | Who can access it | | `updated_at` | `"2025-07-02T00:00:00Z"` | Last modified | > **Note**: **Best Practice** You can define any metadata fields that make sense for your use case! ### The Core Steps When you run this example: 1. **Extract:** Your messages go through an `extractor_llm`, which returns a JSON list of `TextualMemoryItem`s. 2. **Embed:** Each memory's `memory` field is turned into an embedding vector via `embedder`. 3. **Store:** The embeddings are saved into a local **Qdrant** collection. 4. **Search & Manage:** You can now `search` by semantic similarity, `update` by ID, or `delete` memories. > **Note**: **Hint** Make sure your embedder's output dimension matches your vector DB's `vector_dimension`. > Mismatch may cause search errors! > **Note**: **Hint** If your search results are too noisy or irrelevant, check whether your embedder config and vector DB are properly initialized. ### Example Flow **Input Messages:** ```json [ {"role": "user", "content": "I love tomatoes."}, {"role": "assistant", "content": "Great! Tomatoes are healthy."} ] ``` **Extracted Memory:** ```json { "memory": "The user loves tomatoes.", "metadata": { "type": "opinion", "memory_time": "2025-07-02", "source": "conversation", "confidence": 100.0, "entities": ["tomatoes"], "tags": ["food", "preferences"], "visibility": "private", "updated_at": "2025-07-02T00:00:00" } } ``` Here's a minimal script to create, extract, store, and search a memory: #### Create a Memory Config First, create your minimal GeneralTextMemory config. It contains three key parts: - extractor_llm: uses an LLM to extract plaintext memories from conversations. - embedder: turns each memory into a vector. - vector_db: stores vectors and supports similarity search. ```python from memos.configs.memory import MemoryConfigFactory from memos.memories.factory import MemoryFactory config = MemoryConfigFactory( backend="general_text", config={ "extractor_llm": { "backend": "ollama", "config": { "model_name_or_path": "qwen3:0.6b", "temperature": 0.0, "remove_think_prefix": True, "max_tokens": 8192, }, }, "vector_db": { "backend": "qdrant", "config": { "collection_name": "test_textual_memory", "distance_metric": "cosine", "vector_dimension": 768, }, }, "embedder": { "backend": "ollama", "config": { "model_name_or_path": "nomic-embed-text:latest", }, }, }, ) m = MemoryFactory.from_config(config) ``` #### Extract Memories from Messages Give your LLM a simple dialogue and see how it extracts structured plaintext memories. ```python memories = m.extract( [ {"role": "user", "content": "I love tomatoes."}, {"role": "assistant", "content": "Great! Tomatoes are delicious."}, ] ) print("Extracted:", memories) ``` You'll get a list of TextualMemoryItem, with each of them like: ```text TextualMemoryItem( id='...', memory='The user loves tomatoes.', metadata=... ) ``` #### Add Memories to Your Vector DB Save the extracted memories to your vector DB and demonstrate adding a custom plaintext memory manually (with a custom ID). ```python m.add(memories) m.add([ { "id": "a19b6caa-5d59-42ad-8c8a-e4f7118435b4", "memory": "User is Chinese.", "metadata": {"type": "opinion"}, } ]) ``` #### Search Memories Now test similarity search! Type any natural language query and find related memories. ```python results = m.search("Tell me more about the user", top_k=2) print("Search results:", results) ``` #### Get Memories by ID Fetch any memory directly by its ID: ```python print("Get one by ID:", m.get("a19b6caa-5d59-42ad-8c8a-e4f7118435b4")) ``` #### Update a Memory Need to fix or refine a memory? Update it by ID and re-embed the new version. ```python m.update( "a19b6caa-5d59-42ad-8c8a-e4f7118435b4", { "memory": "User is Canadian.", "metadata": { "type": "opinion", "confidence": 85, "memory_time": "2025-05-24", "source": "conversation", "entities": ["Canadian"], "tags": ["happy"], "visibility": "private", "updated_at": "2025-05-19T00:00:00", }, } ) print("Updated:", m.get("a19b6caa-5d59-42ad-8c8a-e4f7118435b4")) ``` #### Delete Memories Remove one or more memories cleanly ```python m.delete(["a19b6caa-5d59-42ad-8c8a-e4f7118435b4"]) print("Remaining:", m.get_all()) ``` #### Dump Memories to Disk Finally, dump all your memories to local storage: ```python m.dump("tmp/mem") print("Memory dumped to tmp/mem") ``` By default, your memories are saved to: ``` / ``` They can be reloaded anytime with `load()`. > **Note**: By default, your dumped memories are saved to the file path you set in your config. > Always check config.memory_filename if you want to customize it. Now your agent remembers — no more stateless chatbots! ## What's Next? Ready to level up? - **Try your own LLM backend:** Swap to OpenAI, HuggingFace, or Ollama. - **Explore [TreeTextMemory](/open_source/modules/memories/tree_textual_memory):** Build a graph-based, hierarchical memory. - **Add [Activation Memory](/open_source/modules/memories/kv_cache_memory):** Cache key-value states for faster inference. - **Dive deeper:** Check the [API Reference](/api-reference/search-memories) and [Examples](/open_source/getting_started/examples) for advanced workflows. > **Note**: **Try Graph Textual Memory** Try switching to > TreeTextMemory to add a graph-based, hierarchical structure to your memories. Perfect for scenarios that need explainability and long-term structured knowledge. --- # Core Concepts (/open_source/home/core_concepts) ## Overview * [MOS (Memory Operating System)](#mos-memory-operating-system) * [MemCube](#️memcube) * [Memory Types](#memory-types) * [Cross-Cutting Concepts](#cross-cutting-concepts) ## MOS (Memory Operating System) **What it is:** The orchestration layer that coordinates multiple MemCubes and memory operations. It connects your LLMs with structured, explainable memory for reasoning and planning. **When to use:** Use MOS whenever you need to bridge users, sessions, or agents with consistent, auditable memory workflows. ## MemCube **What it is:** A MemCube is like a flexible, swappable memory cartridge. Each user, session, or task can have its own MemCube, which can hold one or more memory types. **When to use:** Use different MemCubes to isolate, reuse, or scale your memory as your system grows. ## Memory Types MemOS treats memory like a living system — not just static data but evolving knowledge. Here's how the three core memory types work together: | Memory Type | Description | When to Use | |----------------|----------------------------------------------|---------------------------------------------| | **Parametric** | Knowledge distilled into model weights | Evergreen skills, stable domain expertise | | **Activation** | Short-term KV cache and hidden states | Fast reuse in dialogue, multi-turn sessions | | **Plaintext** | Text, docs, graph nodes, or vector chunks | Searchable, inspectable, evolving knowledge | ### Parametric Memory **What:** Knowledge embedded directly into the model's weights — think of this as the model's "cortex". It's always on, providing zero-latency reasoning. **When to use:** Perfect for stable domain knowledge, distilled FAQs, or skills that rarely change. ### Activation Memory **What:** Activation Memory is your model's reusable "working memory" — it includes precomputed key-value caches and hidden states that can be directly injected into the model's attention mechanism. Think of it as pre-cooked context that saves your LLM from repeatedly re-encoding static or frequently used information. **Why it matters:** By storing stable background content (like FAQs or known facts) in a KV-cache, your model can skip redundant computation during the prefill phase. This dramatically reduces Time To First Token (TTFT) and improves throughput for multi-turn conversations or retrieval-augmented generation. **When to use:** - Reuse background knowledge across many user queries. - Speed up chatbots that rely on the same domain context each turn. - Combine with MemScheduler to auto-promote stable plaintext memory to KV format. ### Explicit Memory **What:** Structured or unstructured knowledge units — user-visible, explainable. These can be documents, chat logs, graph nodes, or vector embeddings. **When to use:** Best for semantic search, user preferences, or traceable facts that evolve over time. Supports tags, provenance, and lifecycle states. ## How They Work Together MemOS lets you orchestrate all three memory types in a living loop: - Hot plaintext memories can be distilled into parametric weights. - High-frequency activation paths become reusable KV templates. - Stale parametric or activation units can be downgraded to plaintext nodes for traceability. With MemOS, your AI doesn't just store facts — it **remembers**, **understands**, and **grows**. > **Note**: **Insight** > Over time, frequently used plaintext memories can be distilled into parametric form. > Rarely used weights or caches can be demoted to plaintext storage for auditing and retraining. ## Cross-Cutting Concepts ### Hybrid Retrieval Combines vector similarity and graph traversal for robust, context-aware search. ### Governance & Lifecycle Every memory unit supports states (active, merged, archived), provenance tracking, and fine-grained access control — essential for auditing and compliance. > **Note**: **Compliance Reminder** > Always track provenance and state changes for each memory unit. > This helps meet audit and data governance requirements. ## Key Takeaway With MemOS, your LLM applications gain structured, evolving memory — empowering agents to plan, reason, and adapt like never before. --- # Architecture (/open_source/home/architecture) ## Core Modules ### MOS (Memory Operating System) The orchestration layer of MemOS — it manages predictive, asynchronous scheduling across multiple memory types (plaintext, activation, parametric) and orchestrates **multi-user, multi-session** memory workflows. MOS connects memory containers (**MemCubes**) with LLMs via a unified API for adding, searching, updating, transferring, or rolling back memories. It also supports cross-model, cross-device interoperability through a unified Memory Interchange Protocol (MIP). ### MemCube A modular, portable **memory container** — think of it like a flexible cartridge that can hold one or more memory types for a **user, agent, or session**. MemCubes can be dynamically registered, updated, or removed. They support containerized storage that is transferable across sessions, models, and devices. ### Memories MemOS supports several specialized memory types for different needs: #### 1. **Parametric Memory**(**Coming Soon**) Embedded in model weights; long-term, high-efficiency, but hard to edit. #### 2. **Activation Memory** Runtime hidden states & KV-cache; short-term, transient, steering dynamic behavior. #### 3. Plaintext Memory Structured or unstructured knowledge blocks; editable, traceable, suitable for fast updates, personalization & multi-agent sharing. - **GeneralTextMemory:** Flexible, vector-based storage for unstructured textual knowledge with semantic search and metadata filtering. - **TreeTextMemory:** Hierarchical, graph-style memory for structured knowledge — combining **tree-based hierarchy** and **cross-branch linking** for dynamic, evolving knowledge graphs. It supports long-term organization and multi-hop reasoning (often Neo4j-backed). > **Note**: **Best Practice** > Start simple with GeneralTextMemory — then scale to graph or KV-cache as your needs grow. #### Basic Modules Includes chunkers, embedders, LLM connectors, parsers, and interfaces for vector/graph databases. These provide the building blocks for memory extraction, semantic embedding, storage, and retrieval. ## Code Structure MemOS project is organized for clarity and plug-and-play: ``` src/memos/ api/ # API definitions chunkers/ # Text chunking utilities configs/ # Configuration schemas context/ # Log context embedders/ # Embedding models graph_dbs/ # Graph database backends (e.g., Neo4j) vec_dbs/ # Vector database backends (e.g., Qdrant) llms/ # LLM connectors mem_agent/ # Deep search mem_chat/ # Memory-augmented chat logic mem_cube/ # MemCube management mem_feedback # Memory feedback mem_os/ # MOS orchestration mem_reader/ # Memory readers mem_scheduler/ # Memory scheduling module memories/ # Memory type implementations multi_mem_cube/# Multi-view Cube parsers/ # Parsing utilities reranker/ # Reranker module templates/ # Prompt templates types/ # Type definitions ``` > **Note**: **Pro Tip** > Use examples/ for quick experimentation and docs/ for module deep dives. ## Extensibility MemOS is **modular by design**. Add your own memory types, storage backends, or LLM connectors with minimal changes — thanks to its **unified config and factory patterns**. > **Note**: **Pro Tip** > [Contribute](/open_source/contribution/overview) a new backend or share your custom memory > type — it’s easy to plug in. --- # REST API Server (/open_source/getting_started/rest_api_server) ![MemOS Architecture](https://cdn.memtensor.com.cn/img/memos_run_server_success_compressed.png)
APIs supported by MemOS REST API Server ### Features - Add new memory: Create a new memory for a specific user. - Search memories: Search for memory content for a specific user. - Get all user memories: Get all memory content for a specific user. - Memory feedback: Feedback memory content for a specific user. - Chat with MemOS: Chat with MemOS, returning SSE streaming response. ## Run Locally ### 1、Local Download ```bash # Download the code to the local folder git clone https://github.com/MemTensor/MemOS ``` ### 2、Configure Environment Variables ```bash # Enter the folder directory cd MemOS ``` #### Create a `.env` file in the root directory and set your environment variables. ##### .env The quick mode configuration is as follows, Complete Mode Reference [.env.example](https://github.com/MemTensor/MemOS/blob/main/docker/.env.example). ```bash # OpenAI API Key (Custom configuration required) OPENAI_API_KEY=sk-xxx # OpenAI API Base URL OPENAI_API_BASE=http://xxx:3000/v1 # Default model name MOS_CHAT_MODEL=qwen3-max # Memory Reader LLM model MEMRADER_MODEL=qwen3-max # Memory Reader API Key MEMRADER_API_KEY=sk-xxx # Memory Reader API Base URL MEMRADER_API_BASE=http://xxx:3000/v1 # Embedder model name MOS_EMBEDDER_MODEL=text-embedding-v4 # set default embedding backend default: ollama | universal_api MOS_EMBEDDER_BACKEND=universal_api # Embedder API Base URL MOS_EMBEDDER_API_BASE=http://xxx:8081/v1 # Embedder API Key MOS_EMBEDDER_API_KEY=xxx # Embedding vector dimension EMBEDDING_DIMENSION=1024 # Reranker backend (http_bge | etc.) MOS_RERANKER_BACKEND=cosine_local # Neo4j Connection URI # Optional values: neo4j-community | neo4j | nebular | polardb NEO4J_BACKEND=neo4j-community # required when backend=neo4j* NEO4J_URI=bolt://localhost:7687 NEO4J_USER=neo4j NEO4J_PASSWORD=12345678 NEO4J_DB_NAME=neo4j MOS_NEO4J_SHARED_DB=false # Whether to use Redis scheduler DEFAULT_USE_REDIS_QUEUE=false # Enable chat api ENABLE_CHAT_API=true # Chat Model List can apply through Bailian. Models are selectable. CHAT_MODEL_LIST=[{"backend": "qwen", "api_base": "https://xxx/v1", "api_key": "sk-xxx", "model_name_or_path": "qwen3-max", "extra_body": {"enable_thinking": true} ,"support_models": ["qwen3-max"]}] ``` ### 3、Taking Bailian as an example to customize configuration ```bash # You can apply through the Bailian platform # https://bailian.console.aliyun.com/?spm=a2c4g.11186623.0.0.2f2165b08fRk4l&tab=api#/api # After successful application, obtain API_KEY and BASE-URL. The example configuration is as follows # OpenAI API Key (Using the API_KEY of Bailian) OPENAI_API_KEY=you_bailian_api_key # OpenAI API Base URL OPENAI_API_BASE=https://dashscope.aliyuncs.com/compatible-mode/v1 # Default model name MOS_CHAT_MODEL=qwen3-max # Memory Reader LLM model MEMRADER_MODEL=qwen3-max # Memory Reader API Key (Using the API_KEY of Bailian) MEMRADER_API_KEY=you_bailian_api_key # Memory Reader API Base URL MEMRADER_API_BASE=https://dashscope.aliyuncs.com/compatible-mode/v1 # Embedder The model name can refer to the following link # https://bailian.console.aliyun.com/?spm=a2c4g.11186623.0.0.2f2165b08fRk4l&tab=api#/api/?type=model&url=2846066 MOS_EMBEDDER_MODEL=text-embedding-v4 # set default embedding backend default: ollama | universal_api MOS_EMBEDDER_BACKEND=universal_api # Embedder API Base URL MOS_EMBEDDER_API_BASE=https://dashscope.aliyuncs.com/compatible-mode/v1 # Embedder API Key (Using the API_KEY of Bailian) MOS_EMBEDDER_API_KEY=you_bailian_api_key # Embedding vector dimension EMBEDDING_DIMENSION=1024 # Reranker backend (http_bge | etc.) MOS_RERANKER_BACKEND=cosine_local # Neo4j Connection URI # Optional values: neo4j-community | neo4j | nebular | polardb NEO4J_BACKEND=neo4j-community # required when backend=neo4j* NEO4J_URI=bolt://localhost:7687 NEO4J_USER=neo4j NEO4J_PASSWORD=12345678 NEO4J_DB_NAME=neo4j MOS_NEO4J_SHARED_DB=false # Whether to use Redis scheduler DEFAULT_USE_REDIS_QUEUE=false # Enable chat api ENABLE_CHAT_API=true CHAT_MODEL_LIST=[{"backend": "qwen", "api_base": "https://dashscope.aliyuncs.com/compatible-mode/v1", "api_key": "you_bailian_api_key", "model_name_or_path": "qwen3-max-preview", "extra_body": {"enable_thinking": true} ,"support_models": ["qwen3-max-preview"]}] ``` ![MemOS bailian](https://cdn.memtensor.com.cn/img/get_key_url_by_bailian_compressed.png)
Bailian application API_KEY and BASE_URL example Configure dependency versions in docker/requirement.txt (negligible), Complete Mode Reference [requirements.txt](https://github.com/MemTensor/MemOS/blob/main/docker/requirements.txt). ### 4、Start Docker ```bash # If Docker is not installed, please install the corresponding version. The download link is as follows: https://www.docker.com/ #After installation, Docker can be started through the client or through the command line #Command line start sudo systemctl start docker # Check docker status docker ps # Check docker images (optional) docker images ``` ### Method 1: Docker use repository dependency package image/start (Recommended use) ```bash # Enter the Docker directory cd docker ``` #### Reference configuration environment variables above, .env file should be configured #### Configure Dockerfile(cd docker) Contains quick mode and full mode, distinguishing between using simplified packages (x86 and arm) and full packages (x86 and arm) ```bash ● Simplified package: Simplify dependencies related to Nvidia that are too large in size, achieve lightweight mirroring, and make local deployment lighter and faster. url: registry.cn-shanghai.aliyuncs.com/memtensor/memos-base:v1.0 url: registry.cn-shanghai.aliyuncs.com/memtensor/memos-base-arm:v1.0 ● Full package: Convert all MemOS dependencies into images, Experience complete functionality. By configuring Dockerfiles, you can directly build and start the package. url: registry.cn-shanghai.aliyuncs.com/memtensor/memos-full-base:v1.0.0 url: registry.cn-shanghai.aliyuncs.com/memtensor/memos-full-base-arm:v1.0.0 ``` #### Configure Dockerfile(cd docker) ```bash # The current example uses a simplified package url FROM registry.cn-shanghai.aliyuncs.com/memtensor/memos-base:v1.0 WORKDIR /app ENV HF_ENDPOINT=https://hf-mirror.com ENV PYTHONPATH=/app/src COPY src/ ./src/ EXPOSE 8000 CMD ["uvicorn", "memos.api.server_api:app", "--host", "0.0.0.0", "--port", "8000", "--reload"] ``` #### Build and start service using docker compose up: ```bash # Enter docker directory docker compose up ``` ![MemOS buildComposeupSuccess](https://cdn.memtensor.com.cn/img/memos_build_composeup_success_compressed.png)
Example image, port as per docker custom configuration #### Access API via [http://localhost:8000/docs](http://localhost:8000/docs). ![MemOS Architecture](https://cdn.memtensor.com.cn/img/memos_run_server_success_compressed.png) #### Test cases (Add user memory->Query user memory) Refer to Docker Compose up test cases ### Method 2:Client Install with Docker Compose up Development Docker Compose up comes pre-configured with qdrant, neo4j. Running the server requires the `OPENAI_API_KEY` environment variable. #### Enter docker folder ```bash # Enter docker folder from current directory cd docker ``` #### Install corresponding dependency modules ```bash pip install --upgrade pip && pip install --no-cache-dir -r requirements.txt # Install dependencies using Aliyun source # pip install --upgrade pip && pip install --no-cache-dir -r requirements.txt -i https://mirrors.aliyun.com/pypi/simple/ ``` #### Start container using Docker Compose Up in docker directory (ensure vpn connects normally): ```bash # Build required for first run docker compose up --build # Not required for subsequent runs docker compose up ``` #### Access API via [http://localhost:8000/docs](http://localhost:8000/docs). #### Example process ##### (Query user memory (stop if none) -> Add user memory -> Query user memory) ##### Add User Memory http://localhost:8000/product/add (POST) ```bash # Request params { "user_id": "8736b16e-1d20-4163-980b-a5063c3facdc", "mem_cube_id": "b32d0977-435d-4828-a86f-4f47f8b55bca", "messages": [ { "role": "user", "content": "I like strawberry" } ], "memory_content": "", "doc_path": "", "source": "", "user_profile": false } # Response { "code": 200, "message": "Memory created successfully", "data": null } ``` ##### Query User Memory http://localhost:8000/product/search (POST) ```bash # Request params { "query": "What do I like", "user_id": "8736b16e-1d20-4163-980b-a5063c3facdc", "mem_cube_id": "b32d0977-435d-4828-a86f-4f47f8b55bca" } # Response { "code": 200, "message": "Search completed successfully", "data": { "text_mem": [ { "cube_id": "7231eda8-6c57-4f6e-97ce-98b699eebb98", "memories": [ { "id": "2f40be8f-736c-4a5f-aada-9489037769e0", "memory": "[user viewpoint] User likes strawberries.", "metadata": { "user_id": "de8215e3-3beb-4afc-9b64-ae594d62f1ea", "session_id": "root_session", "status": "activated", "type": "fact", "key": "User preference for strawberries", "confidence": 0.99, "source": null, "tags": [ "preference", "strawberry" ], "visibility": null, "updated_at": "2025-09-18T08:23:44.625479000+00:00", "memory_type": "UserMemory", "sources": [], "embedding": [], "created_at": "2025-09-18T08:23:44.625511000+00:00", "usage": [ "{ "time": "2025-09-18T08:24:17.759748", "info": { "user_id": "de8215e3-3beb-4afc-9b64-ae594d62f1ea", "session_id": "root_session" } }" ], "background": "The user expressed a preference for strawberries, indicating their inclination towards dietary preferences.", "relativity": 0.6349761312470591, "vector_sync": "success", "ref_id": "[2f40be8f]", "id": "2f40be8f-736c-4a5f-aada-9489037769e0", "memory": "[user viewpoint] User likes strawberries." }, "ref_id": "[2f40be8f]" }, ... } } ], "act_mem": [], "para_mem": [] } } # Response failure, troubleshooting # src/memos/api/config.py # Check "neo4j_vec_db" and "EMBEDDING_DIMENSION" configured in get_neo4j_community_config method ``` #### Modifications to server code or library code will automatically reload the server. ### Method 3:Client Install using CLI commands #### Install dependencies ```bash # pip install --upgrade pip && pip install --no-cache-dir -r ./docker/requirements.txt # Install dependencies using Aliyun source pip install --no-cache-dir -r ./docker/requirements.txt -i https://mirrors.aliyun.com/pypi/simple/ ``` #### Open terminal and run the following command to install: ```bash # Packages that might need manual installation currently. Need to find resources for these two packages # neo4j.5.26.4.tar qdrant.v1.15.3.tar docker load -i neo4j.5.26.4.tar docker load -i qdrant.v1.15.3.tar # Check if installed successfully docker images # Check if running docker ps -a # Root directory uvicorn memos.api.server_api:app --host 0.0.0.0 --port 8000 --workers 1 # If ModuleNotFoundError: No module named 'memos' appears during startup, it is due to path matching problem, please execute export PYTHONPATH=/you-file-absolute-path/MemOS/src ``` #### Access API After startup is complete, access API via [http://localhost:8000/docs](http://localhost:8000/docs). ### Method 4: Without Docker #### Reference configuration environment variables above, .env file should be configured #### Install Poetry for dependency management: ```bash curl -sSL https://install.python-poetry.org | python3 - ``` #### Poetry environment variable configuration: ```bash # To start using, you need to find Poetry's bin directory in "PATH" (/Users/jinyunyuan/.local/bin) environment variable # Modern macOS systems default Shell is zsh. You can confirm via following command 1. Determine which Shell you are using echo $SHELL # If output is /bin/zsh or /usr/bin/env zsh, then you are zsh. # (If your system version is older, might still be using bash, output will be /bin/bash) 2. Open corresponding Shell config file # If using zsh (vast majority of cases): # Use nano editor (recommended for beginners) nano ~/.zshrc # Or use vim editor # vim ~/.zshrc # If using bash: nano ~/.bash_profile # Or nano ~/.bashrc 3. Add PATH environment variable # At the very end of opened file, start a new line, paste installation prompt command: export PATH="/you-path/.local/bin:$PATH" 4. Save and exit editor # If using nano: # Press Ctrl + O to write (save), press Enter to confirm filename. # Then press Ctrl + X to exit editor. # If using vim: # Press i to enter insert mode, paste code, then press ESC key to exit insert mode. # Input :wq, then press Enter to save and exit. 5. Make configuration take effect immediately # Newly modified config file won't automatically take effect in currently open terminal window, you need to run one of the following commands to reload it: # For zsh: source ~/.zshrc # For bash: source ~/.bash_profile 6. Verify if installation is successful # Now, you can execute test command in prompt to check if everything is ready: poetry --version # Success will show version number Poetry (version 2.2.0) ``` #### Install all project dependencies and development tools: ```bash make install ``` #### First start neo4j and qdrant in docker #### Start FastAPI server (In MomOS directory): ```bash uvicorn memos.api.product_api:app --host 0.0.0.0 --port 8000 --reload ``` #### After server runs, you can use OpenAPI docs to test API, URL is [http://localhost:8000/docs](http://localhost:8000/docs) or [http://127.0.0.1:8000/docs](http://127.0.0.1:8000/docs) #### Test cases (Register user->Add user memory->Query user memory) Refer to Docker Compose up test cases ### Method 5:Start using PyCharm #### Run server_api ```bash 1. Enter MemOS/docker/Dockerfile file, modify run configuration # Start the docker CMD ["uvicorn", "memos.api.server_api:app", "--host", "0.0.0.0", "--port", "8000", "--reload"] 2. Enter directory MemOS/src/memos/api directly run server_api.py ``` --- # MemOS Examples (/open_source/getting_started/examples) - [Minimal Pipeline](/open_source/getting_started/examples#example-1-minimal-pipeline): The smallest working pipeline — add, search, update and dump plaintext memories. - [Adding and retrieving multiple information sources](/open_source/getting_started/examples#example-2-multi-modal): Adding multi-source messages—including text, images, files, and tool calls—into memory and enabling their retrieval. - [Multi-Cube addition and retrieval](/open_source/getting_started/examples#example-3-multi-cube): Add different memories to different Cubes and retrieve them simultaneously during a search. - [KVCacheMemory Only](/open_source/getting_started/examples#example-4-kvcachememory-only): Speed up sessions with short-term KV cache for fast context injection. - [Hybrid TreeText + KVCache](/open_source/getting_started/examples#example-5-hybrid): Combine explainable graph memory with fast KV caching in a single MemCube. - [Multi-Memory Scheduling](/open_source/getting_started/examples#example-6-multi-memory-scheduling): Run dynamic memory orchestration for multi-user, multi-session agents. ## Example 1: Minimal Pipeline ### When to Use: - You want the smallest possible working example. - You only need simple plaintext memories stored in a vector DB and retrieve them. ### Key Points: - Supports basic personal memory integration and search. ### Full Example Code ```python import json from memos.api.routers.server_router import add_memories, search_memories from memos.api.product_models import APIADDRequest, APISearchRequest user_id = "test_user_1" add_req = APIADDRequest( user_id=user_id, writable_cube_ids=["cube_test_user_1"], messages = [ {"role": "user", "content": "I’ve planned to travel to Guangzhou during the summer vacation. What chain hotels are available for accommodation?"}, {"role": "assistant", "content": "You can consider [7 Days Inn, Ji Hotel, Hilton], etc."}, {"role": "user", "content": "I’ll choose 7 Days Inn."}, {"role": "assistant", "content": "Okay, feel free to ask me if you have any other questions."} ], async_mode="sync", mode="fine", ) add_rsp = add_memories(add_req) print("add_memories rsp: \n\n", add_rsp) search_req = APISearchRequest( user_id=user_id, readable_cube_ids=["cube_test_user_1"], query="Please recommend a hotel that I haven’t stayed at before.", include_preference=True, ) search_rsp = search_memories(search_req).data print("\n\nsearch_rsp: \n\n", json.dumps(search_rsp, indent=2, ensure_ascii=False)) ``` ## Example 2: Adding and retrieving multi-source memories ### When to Use: - In addition to plain text conversations, you need to add files, image content, or tool call history to memory. - At the same time, you want to retrieve memories from these multiple sources. ### Key Points: - Adding memories from multiple information sources. - Needs to include downloadable file and image URLs. - The added information must strictly follow the OpenAI Messages format. - The tool schema in the system prompt needs to be wrapped in . ### Full Example Code Adding text and files to memory ```python import json from memos.api.routers.server_router import add_memories, search_memories from memos.api.product_models import APIADDRequest, APISearchRequest user_id = "test_user_2" add_req = APIADDRequest( user_id=user_id, writable_cube_ids=["cube_test_user_2"], messages = [ { "role": "user", "content": [ { "type": "text", "text": "Please read this file, summarize the key points, and provide a final conclusion." }, { "type": "file", "file": { "file_id": "file_123", "filename": "report.md", "file_data": "@http://139.196.232.20:9090/graph-test/algorithm/2025_11_13/1763043889_1763043782_PM1%E8%BD%A6%E9%97%B4PMT%E9%9D%B4%E5%8E%8B%E8%BE%B9%E5%8E%8B%E5%8E%8B%E5%8A%9B%E6%97%A0%E6%B3%95%E5%BB%BA%E7%AB%8B%E6%95%85%E9%9A%9C%E6%8A%A5%E5%91%8A20240720.md" } }, ] }, { "role": "assistant", "content": [ { "type": "text", "text": "Final Summary: During the PMT boot-pressure startup test of the PM1 workshop on July 20, 2024, the drive could not run because the edge pressures on both sides failed to reach the 2.5-bar interlock requirement. After troubleshooting, the PLC output signals, hydraulic pipelines, and valves were all found to be normal. The root cause was ultimately identified as poor contact at the negative terminal of the proportional valve’s DC 24V power supply inside the PLC cabinet, caused by a short-jumpered terminal block. After re-connecting the negative incoming lines in parallel, the equipment returned to normal operation. It is recommended to replace terminal blocks in batches, inspect instruments with uncertain service life, and optimize the troubleshooting process by tracing common-mode issues from shared buses and power supply sources." } ] } ], async_mode="sync", mode="fine", ) add_rsp = add_memories(add_req) print("add_memories rsp: \n\n", add_rsp) search_req = APISearchRequest( user_id=user_id, readable_cube_ids=["cube_test_user_2"], query="Workshop PMT boot pressure startup test", include_preference=False, ) search_rsp = search_memories(search_req).data print("\n\nsearch_rsp: \n\n", json.dumps(search_rsp, indent=2, ensure_ascii=False)) ``` Adding messages from multiple mixed information sources to memory ```python import json from memos.api.routers.server_router import add_memories, search_memories from memos.api.product_models import APIADDRequest, APISearchRequest user_id = "test_user_2" add_req = APIADDRequest( user_id=user_id, writable_cube_ids=["cube_test_user_2"], messages = [ { "role": "system", "content": [ { "type": "text", "text": "You are a professional industrial fault analysis assistant. Please read the PDF, images, and instructions provided by the user and provide a professional technical summary.\n\n\n[\n {\n \"name\": \"file_reader\",\n \"description\": \"Used to read the content of files uploaded by the user and return the text data (in JSON string format).\",\n \"parameters\": [\n {\"name\": \"file_id\", \"type\": \"string\", \"required\": true, \"description\": \"The file ID to be read\"}\n ],\n \"returns\": {\"type\": \"text\", \"description\": \"Returns the extracted text content of the file\"}\n }\n]\n" } ] }, { "role": "user", "content": [ { "type": "text", "text": "Please read this file and image, summarize the key points, and provide a final conclusion." }, { "type": "file", "file": { "file_id": "file_123", "filename": "report.pdf", "file_data": "@http://139.196.232.20:9090/graph-test/algorithm/2025_11_13/1763043889_1763043782_PM1%E8%BD%A6%E9%97%B4PMT%E9%9D%B4%E5%8E%8B%E8%BE%B9%E5%8E%8B%E5%8E%8B%E5%8A%9B%E6%97%A0%E6%B3%95%E5%BB%BA%E7%AB%8B%E6%95%85%E9%9A%9C%E6%8A%A5%E5%91%8A20240720.md" } }, { "type": "image_url", "image_url": { "url": "https://play-groud-test-1.oss-cn-shanghai.aliyuncs.com/%E5%9B%BE%E7%89%871.jpeg" } } ] }, { "role": "assistant", "tool_calls": [ { "id": "call_file_reader_001", "type": "function", "function": { "name": "file_reader", "arguments": "{\"file_id\": \"file_123\"}" } } ] }, { "role": "tool", "tool_call_id": "call_file_reader_001", "content": [ { "type": "text", "text": "{\"file_id\":\"file_123\",\"extracted_text\":\"PM1 workshop PMT boot pressure startup test record… Final fault cause: poor contact at the negative terminal of the DC 24V power supply circuit due to a short-jumped terminal block.\"}" } ] }, { "role": "assistant", "content": [ { "type": "text", "text": "Final Summary: During the PMT boot-pressure startup test of the PM1 workshop on July 20, 2024, the drive could not run because the edge pressures on both sides failed to reach the 2.5-bar interlock requirement. After troubleshooting, the PLC output signals, hydraulic pipelines, and valves were all found to be normal. The root cause was ultimately identified as poor contact at the negative terminal of the proportional valve’s DC 24V power supply inside the PLC cabinet, caused by a short-jumpered terminal block. After re-connecting the negative incoming lines in parallel, the equipment returned to normal operation. It is recommended to replace terminal blocks in batches, inspect instruments with uncertain service life, and optimize the troubleshooting process by tracing common-mode issues from shared buses and power supply sources." } ] } ], async_mode="sync", mode="fine", ) add_rsp = add_memories(add_req) print("add_memories rsp: \n\n", add_rsp) search_req = APISearchRequest( user_id=user_id, readable_cube_ids=["cube_test_user_2"], query="Workshop PMT boot pressure startup test", include_preference=False, ) search_rsp = search_memories(search_req).data print("\n\nsearch_rsp: \n\n", json.dumps(search_rsp, indent=2, ensure_ascii=False)) ``` ## Example 3: Multi-Cube addition and retrieval ### When to Use: - Add memories to separate, isolated Cube spaces - You want to retrieve memories from different Cube spaces simultaneously ### Key Points: - Input a readable_cube_ids list containing multiple cube IDs during retrieval ### Full Example Code ```python import json from memos.api.routers.server_router import add_memories, search_memories from memos.api.product_models import APIADDRequest, APISearchRequest user_id = "test_user_3" add_req = APIADDRequest( user_id=user_id, writable_cube_ids=["cube_test_user_3_1"] , messages = [ {"role": "user", "content": "I’ve planned to travel to Guangzhou during the summer vacation. What chain hotels are available for accommodation?"}, {"role": "assistant", "content": "You can consider [7 Days Inn, Ji Hotel, Hilton], etc."}, {"role": "user", "content": "I’ll choose 7 Days Inn."}, {"role": "assistant", "content": "Okay, feel free to ask me if you have any other questions."} ], async_mode="sync", mode="fine", ) add_rsp = add_memories(add_req) print("add_memories rsp: \n\n", add_rsp) add_req = APIADDRequest( user_id=user_id, writable_cube_ids=["cube_test_user_3_2"] , messages = [ {"role": "user", "content": "I love you, I need you."}, {"role": "assistant", "content": "Wow, I love you too"}, ], async_mode="sync", mode="fine", ) add_rsp = add_memories(add_req) print("add_memories rsp: \n\n", add_rsp) search_req = APISearchRequest( user_id=user_id, readable_cube_ids=["cube_test_user_3_1", "cube_test_user_3_2"], query="Please recommend a hotel, Love u u", include_preference=True, ) search_rsp = search_memories(search_req).data print("\n\nsearch_rsp: \n\n", json.dumps(search_rsp, indent=2, ensure_ascii=False)) ``` ## Example 4: KVCacheMemory Only ### When to Use: - You want short-term working memory for faster multi-turn conversation. - Useful for chatbot session acceleration or prompt reuse. - Best for caching hidden states / KV pairs. ### Key Points: - Uses KVCacheMemory with no explicit text memory. - Demonstrates extract → add → merge → get → delete. - Shows how to dump/load KV caches. ### Full Example Code ```python from memos.configs.memory import MemoryConfigFactory from memos.memories.factory import MemoryFactory # Create config for KVCacheMemory (HuggingFace backend) config = MemoryConfigFactory( backend="kv_cache", config={ "extractor_llm": { "backend": "huggingface", "config": { "model_name_or_path": "Qwen/Qwen3-0.6B", "max_tokens": 32, "add_generation_prompt": True, "remove_think_prefix": True, }, }, }, ) # Instantiate KVCacheMemory kv_mem = MemoryFactory.from_config(config) # Extract a KVCacheItem (DynamicCache) prompt = [ {"role": "user", "content": "What is MemOS?"}, {"role": "assistant", "content": "MemOS is a memory operating system for LLMs."}, ] print("===== Extract KVCacheItem =====") cache_item = kv_mem.extract(prompt) print(cache_item) # Add the cache to memory kv_mem.add([cache_item]) print("All caches:", kv_mem.get_all()) # Get by ID retrieved = kv_mem.get(cache_item.id) print("Retrieved:", retrieved) # Merge caches (simulate multi-turn) item2 = kv_mem.extract([{"role": "user", "content": "Tell me a joke."}]) kv_mem.add([item2]) merged = kv_mem.get_cache([cache_item.id, item2.id]) print("Merged cache:", merged) # Delete one kv_mem.delete([cache_item.id]) print("After delete:", kv_mem.get_all()) # Dump & load caches kv_mem.dump("tmp/kv_mem") print("Dumped to tmp/kv_mem") kv_mem.delete_all() kv_mem.load("tmp/kv_mem") print("Loaded caches:", kv_mem.get_all()) ``` ## Example 5: Hybrid ### When to Use: - You want long-term explainable memory and short-term fast context together. - Ideal for complex agents that plan, remember facts, and keep chat context. - Demonstrates multi-memory orchestration. ### How It Works: - **TreeTextMemory** stores your long-term knowledge in a graph DB (Neo4j). - **KVCacheMemory** stores recent or stable context as activation caches. - Both work together in a single **MemCube**, managed by your `MOS` pipeline. ### Full Example Code ```python import os from memos.configs.mem_cube import GeneralMemCubeConfig from memos.configs.mem_os import MOSConfig from memos.mem_cube.general import GeneralMemCube from memos.mem_os.main import MOS # 1. Setup CUDA (if needed) — for local GPU inference os.environ["CUDA_VISIBLE_DEVICES"] = "1" # 2. Define user & paths user_id = "root" cube_id = "root/mem_cube_kv_cache" tmp_cube_path = "/tmp/default/mem_cube_5" # 3. Initialize MOSConfig mos_config = MOSConfig.from_json_file("examples/data/config/simple_treekvcache_memos_config.json") mos = MOS(mos_config) # 4. Initialize the MemCube (TreeTextMemory + KVCacheMemory) cube_config = GeneralMemCubeConfig.from_json_file( "examples/data/config/simple_treekvcache_cube_config.json" ) mem_cube = GeneralMemCube(cube_config) # 5. Dump the MemCube to disk try: mem_cube.dump(tmp_cube_path) except Exception as e: print(e) # 6. Register the MemCube explicitly mos.register_mem_cube(tmp_cube_path, mem_cube_id=cube_id, user_id=user_id) # 7. Extract and add a KVCache memory (simulate stable context) extract_kvmem = mos.mem_cubes[cube_id].act_mem.extract("I like football") mos.mem_cubes[cube_id].act_mem.add([extract_kvmem]) # 8. Start chatting — now your chat uses: # - TreeTextMemory: for structured multi-hop retrieval # - KVCacheMemory: for fast context injection while True: user_input = input("👤 [You] ").strip() print() response = mos.chat(user_input) print(f"🤖 [Assistant] {response}\n") print("📢 [System] MemChat has stopped.") ``` ## Example 6: Multi-Memory Scheduling ### When to Use: - You want to manage multiple users, multiple MemCubes, or dynamic memory flows. - Good for SaaS agents or multi-session LLMs. - Demonstrates MemScheduler + config YAMLs. ### Key Points: - Uses parse_yaml to load MOSConfig and MemCubeConfig. - Dynamic user and cube creation. - Shows runtime scheduling of memories. ### Full Example Code ```python import shutil import uuid from pathlib import Path from memos.configs.mem_cube import GeneralMemCubeConfig from memos.configs.mem_os import MOSConfig from memos.mem_cube.general import GeneralMemCube from memos.mem_os.main import MOS from memos.mem_scheduler.utils import parse_yaml # Load main MOS config with MemScheduler config = parse_yaml("./examples/data/config/mem_scheduler/memos_config_w_scheduler.yaml") mos_config = MOSConfig(**config) mos = MOS(mos_config) # Create user with dynamic ID user_id = str(uuid.uuid4()) mos.create_user(user_id=user_id) # Create MemCube config and dump it config = GeneralMemCubeConfig.from_yaml_file( "./examples/data/config/mem_scheduler/mem_cube_config.yaml" ) mem_cube_id = "mem_cube_5" mem_cube_name_or_path = f"./outputs/mem_scheduler/{user_id}/{mem_cube_id}" # Remove old folder if exists if Path(mem_cube_name_or_path).exists(): shutil.rmtree(mem_cube_name_or_path) print(f"{mem_cube_name_or_path} is not empty, and has been removed.") # Dump new cube mem_cube = GeneralMemCube(config) mem_cube.dump(mem_cube_name_or_path) # Register MemCube for this user mos.register_mem_cube( mem_cube_name_or_path=mem_cube_name_or_path, mem_cube_id=mem_cube_id, user_id=user_id ) # Add messages messages = [ { "role": "user", "content": "I like playing football." }, { "role": "assistant", "content": "I like playing football too." }, ] mos.add(messages, user_id=user_id, mem_cube_id=mem_cube_id) # Chat loop: show TreeTextMemory nodes + KVCache while True: user_input = input("👤 [You] ").strip() print() response = mos.chat(user_input, user_id=user_id) retrieved_memories = mos.get_all(mem_cube_id=mem_cube_id, user_id=user_id) print(f"🤖 [Assistant] {response}") # Show WorkingMemory nodes in TreeTextMemory for node in retrieved_memories["text_mem"][0]["memories"]["nodes"]: if node["metadata"]["memory_type"] == "WorkingMemory": print(f"[WorkingMemory] {node['memory']}") # Show Activation Memory if retrieved_memories["act_mem"][0]["memories"]: for act_mem in retrieved_memories["act_mem"][0]["memories"]: print(f"⚡ [KVCache] {act_mem['memory']}") else: print("⚡ [KVCache] None\n") ``` > **Note**: **Keep in Mind** > Use dump() and load() to persist your memory cubes. > > Always check your vector DB dimension matches your embedder. > > For graph memory, you'll need Neo4j Desktop (community version support coming soon). ## Next Steps You're just getting started!Next, try: - Pick the example that matches your use case. - Combine modules to build smarter, more persistent agents! Need more? See the API Reference or contribute your own example! --- # MemOS API Development Guide (Components & Handlers Architecture) (/open_source/modules/mos/overview) This architecture separates "system components" (Components) from "business logic execution" (Handlers), making the system easier to extend, test, and maintain. ## 1. Core Concepts ### 1.1 Components (Core Components) Components are the "organs" of MemOS. They are initialized when the server starts (via `init_server()`) and reused throughout the system lifecycle. Core components include: #### Core Memory Components 1. **MemCube**: A memory container that isolates memories across different users and application scenarios, managing multiple memory modules in a unified way. 2. **MemReader**: A memory processor that parses user inputs (chat, documents, images) into standardized memory items that the system can persist. 3. **MemScheduler**: A background scheduler that handles asynchronous processing of memory operations—storage, indexing, and organization—supporting concurrent task execution. 4. **MemChat**: A conversation controller responsible for orchestrating the memory-augmented dialogue loop: "retrieve memory → generate response → store new memory". 5. **MemFeedback**: A memory correction engine that understands users' natural-language feedback and performs atomic-level updates to memories (correction, addition, replacement). ### 1.2 Handlers (Business Processors) Handlers are the "brain" of MemOS. They encapsulate concrete business logic by coordinating and calling the capabilities of Components to complete user-facing tasks. #### Core Handlers Overview | Handler | Purpose | Key Methods | | :--- | :--- | :--- | | **AddHandler** | Add memories (chat / documents / text) | `handle_add_memories` | | **SearchHandler** | Search memories (semantic retrieval) | `handle_search_memories` | | **ChatHandler** | Chat (with memory augmentation) | `handle_chat_complete`, `handle_chat_stream` | | **FeedbackHandler** | Feedback (correct memories / human feedback) | `handle_feedback_memories` | | **MemoryHandler** | Manage (get details / delete) | `handle_get_memory`, `handle_delete_memories` | | **SchedulerHandler** | Scheduling (query async task status) | `handle_scheduler_status`, `handle_scheduler_wait` | | **SuggestionHandler** | Suggestions (generate recommended questions) | `handle_get_suggestion_queries` | ## 2. API Details ### 2.1 Initialization Initialization is the foundation of system startup. All Handlers rely on a unified component registry and dependency-injection mechanism. - Component loading (`init_server`): When the system starts, it initializes all core components, including the LLM, storage layers (vector DB, graph DB), scheduler, and various Memory Cubes. - Dependency injection (`HandlerDependencies`): To ensure loose coupling and testability, all components are wrapped into a `HandlerDependencies` container. When a Handler is instantiated, it receives this container and can access needed resources—such as `naive_mem_cube`, `mem_reader`, or `feedback_server`—without duplicating initialization logic. ### 2.2 Add Memories (AddHandler) AddHandler is the brain's "memory intake instruction", responsible for converting external information into system memories. It handles not only intake and conversion of various information types, but also automatically recognizes feedback and routes it to dedicated feedback processing. - Core capabilities: - Multimodal support: Processes user conversations, documents, images, and other input types, converting them into standardized memory objects. - Sync and async modes: Controlled via `async_mode`. **Sync mode** ("sync"): processes immediately and blocks until completion, suitable for debugging. **Async mode** ("async"): pushes tasks to a background queue for concurrent processing by MemScheduler, returns a task ID immediately, suitable for production to improve response speed. - Automatic feedback routing: If the request sets `is_feedback=True`, the Handler automatically extracts the last user message as feedback content and routes it to MemFeedback processing, instead of adding it as a normal memory. - Multi-target writes: Supports writing to multiple MemCubes simultaneously. When multiple targets are specified, the system processes all write tasks in parallel; when only one target is specified, it uses a lightweight approach. ### 2.3 Search Memories (SearchHandler) SearchHandler is the brain's "memory retrieval instruction", providing semantic-based intelligent memory query capabilities and serving as a key component for RAG (Retrieval-Augmented Generation). - Core capabilities: - Semantic retrieval: Uses embedding technology to recall relevant memories based on semantic similarity, understanding user intent more accurately than simple keyword matching. - Flexible search scope: Supports specifying the target data range for retrieval. For example, you can search only within a specific user's memory, or search across multiple users' shared public memories, meeting different privacy and business needs. - Multiple retrieval modes: Flexibly choose between speed and accuracy based on application scenarios. **Fast mode** suits scenarios requiring high real-time performance, **fine mode** suits scenarios pursuing high retrieval accuracy, and **mixed mode** balances both. - Multi-step reasoning retrieval: For complex questions, supports deep reasoning capability to progressively approach the most relevant memories through multiple rounds of understanding and retrieval. ### 2.4 Chat (ChatHandler) ChatHandler is the brain's "dialogue coordination instruction", responsible for converting user dialogue requirements into a complete business process. It does not directly operate on memories; instead, it coordinates other Handlers to complete end-to-end dialogue tasks. - Core capabilities: - Orchestration: Automatically executes the complete dialogue loop of "retrieve memory → generate response → store memory". Each user query benefits from historical memories for smarter responses, and each dialogue is crystallized as new memory, achieving "chat-as-learning". - Context management: Handles the assembly of `history` (past conversation) and `query` (current question) to ensure the LLM understands the complete dialogue context and avoids information loss. - Multiple interaction modes: Supports standard request-response mode and streaming response mode. Standard mode suits simple questions, streaming mode suits long-text replies, meeting different frontend interaction needs. - Message push (optional): Supports automatically pushing results to third-party platforms (such as DingTalk) after generating responses, enabling multi-channel integration. ### 2.5 Feedback and Correction (FeedbackHandler) FeedbackHandler is the brain's "feedback correction instruction", responsible for understanding users' natural-language feedback about AI performance and automatically locating and correcting relevant memory content. - Core capabilities: - Memory correction: When users point out AI errors (such as "the meeting location is Shanghai, not Beijing"), the Handler automatically updates or marks old memories. The system uses version management rather than direct deletion, maintaining traceability of modification history. - Positive and negative feedback: Supports users marking specific memory quality through upvote or downvote. The system adjusts the memory's weight and credibility accordingly, making subsequent retrieval more accurate. - Precise targeting: Supports two feedback modes. One is automatic conflict detection based on dialogue history, the other allows users to directly specify memories to correct, improving feedback effectiveness and accuracy. ### 2.6 Memory Management (MemoryHandler) MemoryHandler is the brain's "memory management instruction", providing low-level CRUD capabilities for memory data, primarily for system admin backends or data cleanup scenarios. - Core capabilities: - Fine-grained management: Unlike AddHandler's business-level writes, this Handler allows fetching detailed information of a single memory or performing physical deletion by memory ID. This direct operation bypasses business logic packaging, primarily for debugging, auditing, or system cleanup. - Direct backend access: Some management operations need to interact directly with the underlying memory component (naive_mem_cube) to provide the most efficient and lowest-latency data operations, meeting system operations needs. ### 2.7 Scheduler Status (SchedulerHandler) SchedulerHandler is the brain's "task monitoring instruction", responsible for tracking the real-time execution status of all async tasks in the system, allowing users to understand background task progress and results. - Core capabilities: - Status tracking: Tracks real-time task status in real-time (queued, running, completed, failed). This is important for users in async mode who need to understand when tasks complete. - Result fetching: Provides a task result query interface. When async tasks complete, users can fetch the final execution result or error information through this interface, understanding whether operations succeeded and the reasons for failure. - Sync wait (debugging tool): During testing and integration testing, provides a tool to force async tasks into synchronous waits, allowing developers to debug async flows like debugging synchronous code, improving development efficiency. ### 2.8 Suggested Questions (SuggestionHandler) SuggestionHandler is the brain's "suggestion generation instruction", predicting users' potential needs and proactively recommending related questions to help users explore system capabilities and discover topics of interest. - Core capabilities: - Dual-mode generation: - Conversation-based suggestions: When users provide recent conversation records, the system analyzes dialogue context and infers potential follow-up topics of interest, generating 3 related recommended questions. - Memory-based suggestions: When there is no conversation context, the system infers user interests and status from recent memories, generating recommended questions related to the user's recent life or work. This suits dialogue initiation or topic transitions. - Multi-language support: Recommended questions automatically adapt to user language settings, supporting Chinese, English, and other languages, improving experience for different users. --- # MemCube (/open_source/modules/mem_cube) ## What is MemCube? **MemCube** contains three major types of memory: - **Textual Memory**: Stores text knowledge, supporting semantic search and knowledge management. - **Activation Memory**: Stores intermediate reasoning results, accelerating LLM responses. - **Parametric Memory**: Stores model adaptation weights, used for personalization. Each memory type can be independently configured and flexibly combined based on application needs. ## Structure MemCube is defined by a configuration (see `GeneralMemCubeConfig`), which specifies the backend and settings for each memory type. The typical structure is: ``` MemCube ├── user_id ├── cube_id ├── text_mem: TextualMemory ├── act_mem: ActivationMemory └── para_mem: ParametricMemory ``` All memory modules are accessible via the MemCube interface: - `mem_cube.text_mem` - `mem_cube.act_mem` - `mem_cube.para_mem` ## View Architecture Starting from MemOS 2.0, runtime operations (add/search) should go through the **View architecture**: ### SingleCubeView Use this to manage a single MemCube. When you only need one memory space. ```python from memos.multi_mem_cube.single_cube import SingleCubeView view = SingleCubeView( cube_id="my_cube", naive_mem_cube=naive_mem_cube, mem_reader=mem_reader, mem_scheduler=mem_scheduler, logger=logger, searcher=searcher, feedback_server=feedback_server, # Optional ) # Add memories view.add_memories(add_request) # Search memories view.search_memories(search_request) ``` ### CompositeCubeView Use this to manage multiple MemCubes. When you need unified operations across multiple memory spaces. ```python from memos.multi_mem_cube.composite_cube import CompositeCubeView # Create multiple SingleCubeViews view1 = SingleCubeView(cube_id="cube_1", ...) view2 = SingleCubeView(cube_id="cube_2", ...) # Composite view for multi-cube operations composite = CompositeCubeView(cube_views=[view1, view2], logger=logger) # Search across all cubes results = composite.search_memories(search_request) # Results contain cube_id field to identify source ``` ## API Request Fields When using the View architecture for add/search operations, specify these parameters: | Field | Type | Description | | :--- | :--- | :--- | | `writable_cube_ids` | `list[str]` | Target cubes for add operations. Can specify multiple; the system will write to all targets in parallel. | | `readable_cube_ids` | `list[str]` | Target cubes for search operations. Can search across multiple cubes; results include source information. | | `async_mode` | `str` | Execution mode: `"sync"` for synchronous processing (wait for results), `"async"` for asynchronous processing (push to background queue, return task ID immediately). | ## Core Methods (`GeneralMemCube`) **GeneralMemCube** is the standard implementation of MemCube, managing all system memories through a unified interface. Here are the main methods to complete memory lifecycle management. ### Initialization ```python from memos.mem_cube.general import GeneralMemCube mem_cube = GeneralMemCube(config) ``` ### Static Data Operations | Method | Description | | :--- | :--- | | `init_from_dir(dir)` | Load a MemCube from a local directory | | `init_from_remote_repo(repo, base_url)` | Load a MemCube from a remote repository (e.g., Hugging Face) | | `load(dir)` | Load all memories from a directory into the existing instance | | `dump(dir)` | Save all memories to a directory for persistence | ## File Structure A MemCube directory contains the following files, with each file corresponding to a memory type: - `config.json` (MemCube configuration) - `textual_memory.json` (textual memory) - `activation_memory.pickle` (activation memory) - `parametric_memory.adapter` (parametric memory) ## Usage Examples ### Export Example (dump_cube.py) ```python import json import os import shutil from memos.api.handlers import init_server from memos.api.product_models import APIADDRequest from memos.log import get_logger from memos.multi_mem_cube.single_cube import SingleCubeView logger = get_logger(__name__) EXAMPLE_CUBE_ID = "example_dump_cube" EXAMPLE_USER_ID = "example_user" # 1. Initialize server components = init_server() naive = components["naive_mem_cube"] # 2. Create SingleCubeView view = SingleCubeView( cube_id=EXAMPLE_CUBE_ID, naive_mem_cube=naive, mem_reader=components["mem_reader"], mem_scheduler=components["mem_scheduler"], logger=logger, searcher=components["searcher"], feedback_server=components["feedback_server"], ) # 3. Add memories via View result = view.add_memories(APIADDRequest( user_id=EXAMPLE_USER_ID, writable_cube_ids=[EXAMPLE_CUBE_ID], messages=[ {"role": "user", "content": "This is a test memory"}, {"role": "user", "content": "Another memory to persist"}, ], async_mode="sync", # Use sync mode to ensure immediate completion )) print(f"✓ Added {len(result)} memories") # 4. Export data for the specific cube_id output_dir = "tmp/mem_cube_dump" if os.path.exists(output_dir): shutil.rmtree(output_dir) os.makedirs(output_dir, exist_ok=True) # Export graph data (only data for the current cube_id) json_data = naive.text_mem.graph_store.export_graph( include_embedding=True, # Include embeddings to support semantic search user_name=EXAMPLE_CUBE_ID, # Filter by cube_id ) # Fix embedding format: parse string to list for import compatibility import contextlib for node in json_data.get("nodes", []): metadata = node.get("metadata", {}) if "embedding" in metadata and isinstance(metadata["embedding"], str): with contextlib.suppress(json.JSONDecodeError): metadata["embedding"] = json.loads(metadata["embedding"]) print(f"✓ Exported {len(json_data.get('nodes', []))} nodes") # Save to file memory_file = os.path.join(output_dir, "textual_memory.json") with open(memory_file, "w", encoding="utf-8") as f: json.dump(json_data, f, indent=2, ensure_ascii=False) print(f"✓ Saved to: {memory_file}") ``` ### Import and Search Example (load_cube.py) > **Embedding Compatibility Note**: The sample data uses the **bge-m3** model with **1024 dimensions**. If your environment uses a different embedding model or dimension, semantic search after import may be inaccurate or fail. Ensure your `.env` configuration matches the embedding settings used during export. ```python import json import os from memos.api.handlers import init_server from memos.api.product_models import APISearchRequest from memos.log import get_logger from memos.multi_mem_cube.single_cube import SingleCubeView logger = get_logger(__name__) EXAMPLE_CUBE_ID = "example_dump_cube" EXAMPLE_USER_ID = "example_user" # 1. Initialize server components = init_server() naive = components["naive_mem_cube"] # 2. Create SingleCubeView view = SingleCubeView( cube_id=EXAMPLE_CUBE_ID, naive_mem_cube=naive, mem_reader=components["mem_reader"], mem_scheduler=components["mem_scheduler"], logger=logger, searcher=components["searcher"], feedback_server=components["feedback_server"], ) # 3. Load data from file into graph_store load_dir = "examples/data/mem_cube_tree" memory_file = os.path.join(load_dir, "textual_memory.json") with open(memory_file, encoding="utf-8") as f: json_data = json.load(f) naive.text_mem.graph_store.import_graph(json_data, user_name=EXAMPLE_CUBE_ID) nodes = json_data.get("nodes", []) print(f"✓ Imported {len(nodes)} nodes") # 4. Display loaded data print(f"\nLoaded {len(nodes)} memories:") for i, node in enumerate(nodes[:3], 1): # Show first 3 metadata = node.get("metadata", {}) memory_text = node.get("memory", "N/A") mem_type = metadata.get("memory_type", "unknown") print(f" [{i}] Type: {mem_type}") print(f" Content: {memory_text[:60]}...") # 5. Semantic search verification query = "test memory dump persistence demonstration" print(f'\nSearching: "{query}"') search_result = view.search_memories( APISearchRequest( user_id=EXAMPLE_USER_ID, readable_cube_ids=[EXAMPLE_CUBE_ID], query=query, ) ) text_mem_results = search_result.get("text_mem", []) memories = [] for group in text_mem_results: memories.extend(group.get("memories", [])) print(f"✓ Found {len(memories)} relevant memories") for i, mem in enumerate(memories[:2], 1): # Show first 2 print(f" [{i}] {mem.get('memory', 'N/A')[:60]}...") ``` ### Complete Examples See examples in the code repository: - `MemOS/examples/mem_cube/dump_cube.py` - Export MemCube data (add + export) - `MemOS/examples/mem_cube/load_cube.py` - Import MemCube data and perform semantic search (import + search) ### Legacy API Notes The old approach of directly calling `mem_cube.text_mem.get_all()` is deprecated. Please use the View architecture. Legacy examples have been moved to `MemOS/examples/mem_cube/_deprecated/`. ## Developer Notes * MemCube enforces schema consistency to ensure safe loading and dumping * Each memory type can be independently configured, tested, and extended * See `/tests/mem_cube/` for integration tests and usage examples --- # MemReader (/open_source/modules/mem_reader) ## 1. Overview When building AI applications, we often run into this problem: users send all kinds of things—casual chat messages, PDF documents, and images. **MemReader** turns these raw inputs (Raw Data) into standard memory blocks (Memory Items) with embeddings and metadata by "chewing" and "digesting" them. In short, it does three things: 1. **Normalization**: Whether you send a string or JSON, it first converts everything into a standard format. 2. **Chunking**: It splits long conversations or documents into appropriately sized chunks for downstream processing. 3. **Extraction**: It calls an LLM to extract unstructured information into structured knowledge points (Fine mode), or directly generates snapshots (Fast mode). --- ## 2. Core Modes MemReader provides two modes, corresponding to the needs for "speed" and "accuracy": ### ⚡ Fast Mode (speed first) * **Characteristics**: **Does not call an LLM**, only performs chunking and embeddings. * **Use cases**: * Users are sending messages quickly and the system needs millisecond-level responses. * You only need to keep "snapshots" of the conversation, without deep understanding. * **Output**: raw text chunks + vector index + provenance tracking (Sources). ### 🧠 Fine Mode (carefully crafted) * **Characteristics**: **Calls an LLM** for deeper analysis. * **Use cases**: * Long-term memory writing (needs key facts extracted). * Document analysis (needs core ideas summarized). * Multimodal understanding (needs to understand what's in an image). * **Output**: structured facts + key information extraction (Key) + background (Background) + vector index + provenance tracking (Sources) + multimodal details. --- ## 3. Code Structure MemReader's code structure is straightforward and mainly includes: * **`base.py`**: defines the interface contract that all Readers must follow. * **`simple_struct.py`**: **the most commonly used implementation**. Focuses on pure-text conversations and local documents; lightweight and efficient. * **`multi_modal_struct.py`**: **an all-rounder**. Handles images, file URLs, tool calls, and other complex inputs. * **`read_multi_modal/`**: contains various parsers, such as `ImageParser` for images and `FileParser` for files. --- ## 4. How to Choose? | Your need | Recommended choice | Why | | :--- | :--- | :--- | | **Only process plain text chats** | `SimpleStructMemReader` | Simple, direct, and performant. | | **Need to handle images and file links** | `MultiModalStructMemReader` | Built-in multimodal parsing. | | **Upgrade from Fast to Fine** | Any Reader's `fine_transfer` method | Supports a progressive "store first, refine later" strategy. | --- ## 5. API Overview ### Unified Factory: `MemReaderFactory` Don't instantiate readers directly; using the factory pattern is best practice: ```python from memos.configs.mem_reader import MemReaderConfigFactory from memos.mem_reader.factory import MemReaderFactory # Create a Reader from configuration cfg = MemReaderConfigFactory.model_validate({...}) reader = MemReaderFactory.from_config(cfg) ``` ### Core Method: `get_memory()` This is the method you will call most often. ```python memories = reader.get_memory( scene_data, # your input data type="chat", # type: chat or doc info=user_info, # user info (user_id, session_id) mode="fine" # mode: fast or fine (highly recommended to specify explicitly!) ) ``` **Return value**: `list[list[TextualMemoryItem]]` > **Note**: Why a nested list? > Because a long conversation may be split into multiple windows (Window). The outer list represents windows, and the inner list represents memory items extracted from that window. --- ## 6. Practical Development ### Scenario 1: Processing simple chat logs This is the most basic usage, with `SimpleStructMemReader`. ```python # 1. Prepare input: standard OpenAI-style conversation format conversation = [ [ {"role": "user", "content": "I have a meeting tomorrow at 3pm"}, {"role": "assistant", "content": "What is the meeting about?"}, {"role": "user", "content": "Discussing the Q4 project deadline"}, ] ] # 2. Extract memory (Fine mode) memories = reader.get_memory( conversation, type="chat", mode="fine", info={"user_id": "u1", "session_id": "s1"} ) # 3. Result # memories will include extracted facts, e.g., "User has a meeting tomorrow at 3pm about the Q4 project deadline" ``` ### Scenario 2: Processing multimodal inputs When users send images or file links, switch to `MultiModalStructMemReader`. ```python # 1. Prepare input: a complex message containing files and images scene_data = [ [ { "role": "user", "content": [ {"type": "text", "text": "Check this file and image"}, # Files support automatic download and parsing via URL {"type": "file", "file": {"file_data": "https://example.com/readme.md"}}, # Images support URL {"type": "image_url", "image_url": {"url": "https://example.com/chart.png"}}, ] } ] ] # 2. Extract memory memories = multimodal_reader.get_memory( scene_data, type="chat", mode="fine", # Only Fine mode invokes the vision model to parse images info={"user_id": "u1", "session_id": "s1"} ) ``` ### Scenario 3: Progressive optimization (Fine Transfer) For better UX, you can first store the conversation quickly in Fast mode, then "refine" it into Fine memories when the system is idle. ```python # 1. Store quickly first (millisecond-level) fast_memories = reader.get_memory(conversation, mode="fast", ...) # ... store into the database ... # 2. Refine asynchronously in the background refined_memories = reader.fine_transfer_simple_mem( fast_memories_flat_list, # Note: pass a flattened list of Items here type="chat" ) # 3. Replace the original fast_memories with refined_memories ``` --- ## 7. Configuration Notes In `.env` or configuration files, you can adjust these key parameters: * **`chat_window_max_tokens`**: **sliding window size**. Default is 1024. It determines how much context is packed together for processing. Too small may lose context; too large may exceed the LLM token limit. * **`remove_prompt_example`**: **whether to remove examples from the prompt**. True = save tokens but may reduce extraction quality; False = keep few-shot examples for better accuracy but consume more tokens. * **`direct_markdown_hostnames`** (multimodal only): **hostname allowlist**. If a file URL's hostname is in this list (e.g., `raw.githubusercontent.com`), the Reader treats it as Markdown text directly instead of trying OCR or conversion, which is more efficient. --- # MemScheduler (/open_source/modules/mem_scheduler) ## Key Features - 🚀 **Concurrent operation with MemOS system**: Runs in independent threads/processes without blocking main business logic. - 🧠 **Multi-memory coordination**: Intelligently manages the flow of working memory, long-term memory, and user-personalized memory. - ⚡ **Event-driven scheduling**: Asynchronous task distribution based on message queues (Redis/Local). - 🔍 **Efficient retrieval**: Integrated vector and graph retrieval for quick location of relevant memories. - 📊 **Comprehensive monitoring**: Real-time monitoring of memory utilization, task queue status, and scheduling latency. - 📝 **Detailed logging**: Full-chain tracing of memory operations for debugging and system analysis. ## MemScheduler Architecture `MemScheduler` adopts a three-layer modular architecture: ### Scheduling Layer (Core) 1. **Scheduler (Router)**: Intelligent message router that dispatches tasks to corresponding handlers based on message types (e.g., `QUERY`, `ANSWER`, `MEM_UPDATE`). 2. **Message Processing**: Event-driven business logic through messages with specific labels, defining message formats and processing rules. ### Execution Layer (Guarantee) 3. **Task Queue**: Supports both Redis Stream (production) and Local Queue (development/testing) modes, providing asynchronous task buffering and persistence. 4. **Memory Management**: Executes read/write, compression, forgetting, and type conversion operations on three-layer memory (Working/Long-term/User). 5. **Retrieval System**: Hybrid retrieval module combining user intent, scenario management, and keyword matching for quick memory location. ### Support Layer (Auxiliary) 6. **Monitoring**: Tracks task accumulation, processing latency, and memory health status. 7. **Logging**: Maintains full-chain memory operation logs for debugging and analysis. ## MemScheduler Initialization In the MemOS architecture, `MemScheduler` is initialized as part of the server components during startup. ### Initialization in Server Router In `src/memos/api/routers/server_router.py`, the scheduler is automatically loaded through the `init_server()` function: ```python from memos.api import handlers from memos.api.handlers.base_handler import HandlerDependencies from memos.mem_scheduler.base_scheduler import BaseScheduler from memos.mem_scheduler.utils.status_tracker import TaskStatusTracker # ... other imports ... # 1. Initialize all server components (including DB, LLM, Memory, Scheduler) # init_server() reads environment variables and initializes global singleton components components = handlers.init_server() # Create dependency container for handlers dependencies = HandlerDependencies.from_init_server(components) # Initialize handlers... # search_handler = SearchHandler(dependencies) # ... # 2. Get the scheduler instance from the components dictionary # The scheduler is already initialized and started inside init_server (if enabled) mem_scheduler: BaseScheduler = components["mem_scheduler"] # 3. Users can also get other scheduling-related components from components (optional, for custom task handling) # redis_client is used for direct Redis operations or monitoring task status redis_client = components["redis_client"] # ... ``` ## Scheduling Tasks and Data Models The scheduler distributes and executes tasks through a message-driven approach. This section introduces supported task types, message structures, and execution logs. ### Message Types and Handlers The scheduler dispatches and executes tasks by registering specific task labels (Label) with handlers (Handler). The following are the default supported scheduling tasks in the current version (based on `GeneralScheduler` and `OptimizedScheduler`): | Message Label | Constant | Handler Method | Description | | :--- | :--- | :--- | :--- | | `query` | `QUERY_TASK_LABEL` | `_query_message_consumer` | Processes user queries, triggers intent recognition, memory retrieval, and converts them to memory update tasks. | | `answer` | `ANSWER_TASK_LABEL` | `_answer_message_consumer` | Processes AI responses and logs conversations. | | `mem_update` | `MEM_UPDATE_TASK_LABEL` | `_memory_update_consumer` | Core task. Executes the long-term memory update process, including extracting Query Keywords, updating Monitor, retrieving relevant memories, and replacing Working Memory. | | `add` | `ADD_TASK_LABEL` | `_add_message_consumer` | Handles logging of new memory additions (supports local and cloud logs). | | `mem_read` | `MEM_READ_TASK_LABEL` | `_mem_read_message_consumer` | Deep processing and importing external memory content using `MemReader`. | | `mem_organize` | `MEM_ORGANIZE_TASK_LABEL` | `_mem_reorganize_message_consumer` | Triggers memory reorganization and merge operations. | | `pref_add` | `PREF_ADD_TASK_LABEL` | `_pref_add_message_consumer` | Handles extraction and addition of user preference memory (Preference Memory). | | `mem_feedback` | `MEM_FEEDBACK_TASK_LABEL` | `_mem_feedback_message_consumer` | Processes user feedback for correcting or reinforcing preferences. | | `api_mix_search` | `API_MIX_SEARCH_TASK_LABEL` | `_api_mix_search_message_consumer` | (OptimizedScheduler only) Executes asynchronous hybrid search tasks combining fast and fine retrieval. | ### Message Data Structure (ScheduleMessageItem) The scheduler uses a unified `ScheduleMessageItem` structure to pass messages in the queue. > **Note**: The `mem_cube` object itself is not directly included in the message model; instead, it is resolved by the scheduler at runtime through `mem_cube_id`. | Field | Type | Description | Default/Remarks | | :--- | :--- | :--- | :--- | | `item_id` | `str` | Unique message identifier (UUID) | Auto-generated | | `user_id` | `str` | Associated user ID | (Required) | | `mem_cube_id` | `str` | Associated Memory Cube ID | (Required) | | `label` | `str` | Task label (e.g., `query`, `mem_update`) | (Required) | | `content` | `str` | Message payload (typically JSON string or text) | (Required) | | `timestamp` | `datetime` | Message submission time | Auto-generated (UTC now) | | `session_id` | `str` | Session ID for context isolation | `""` | | `trace_id` | `str` | Trace ID for full-chain log association | Auto-generated | | `user_name` | `str` | User display name | `""` | | `task_id` | `str` | Business-level task ID (for associating multiple messages) | `None` | | `info` | `dict` | Additional custom context information | `None` | | `stream_key` | `str` | (Internal use) Redis Stream key name | `""` | ### Execution Log Structure (ScheduleLogForWebItem) The scheduler generates structured log messages for frontend display or persistent storage. | Field | Type | Description | Remarks | | :--- | :--- | :--- | :--- | | `item_id` | `str` | Unique log entry identifier | Auto-generated | | `task_id` | `str` | Associated parent task ID | Optional | | `user_id` | `str` | User ID | (Required) | | `mem_cube_id` | `str` | Memory Cube ID | (Required) | | `label` | `str` | Log category (e.g., `addMessage`, `addMemory`) | (Required) | | `log_content` | `str` | Brief log description text | (Required) | | `from_memory_type` | `str` | Source memory area | e.g., `UserInput`, `LongTermMemory` | | `to_memory_type` | `str` | Destination memory area | e.g., `WorkingMemory` | | `memcube_log_content` | `list[dict]` | Structured detailed content | Contains specific memory text, reference IDs, etc. | | `metadata` | `list[dict]` | Memory item metadata | Contains confidence, status, tags, etc. | | `status` | `str` | Task status | e.g., `completed`, `failed` | | `timestamp` | `datetime` | Log creation time | Auto-generated | | `current_memory_sizes` | `MemorySizes` | Current memory quantity snapshot for each area | For monitoring dashboard display | | `memory_capacities` | `MemoryCapacities` | Memory capacity limits for each area | For monitoring dashboard display | ## Scheduling Function Examples ### 1. Message Processing and Custom Handlers The scheduler's most powerful feature is support for registering custom message handlers. You can define specific message types (e.g., `MY_CUSTOM_TASK`) and write functions to handle them. ```python import uuid from datetime import datetime # 1. Import necessary type definitions and scheduler instance # Note: mem_scheduler needs to be imported from server_router as it's a global singleton from memos.api.routers.server_router import mem_scheduler from memos.mem_scheduler.schemas.message_schemas import ScheduleMessageItem # Define a custom task label MY_TASK_LABEL = "MY_CUSTOM_TASK" # Define a handler function def my_task_handler(messages: list[ScheduleMessageItem]): """ Function to handle custom tasks """ for msg in messages: print(f"⚡️ [Handler] Received task: {msg.item_id}") print(f"📦 Content: {msg.content}") # Execute your business logic here, e.g., call LLM, write to database, trigger other tasks, etc. # 2. Register the handler to the scheduler # This step mounts your custom logic to the scheduling system mem_scheduler.register_handlers({ MY_TASK_LABEL: my_task_handler }) # 3. Submit a task task = ScheduleMessageItem( item_id=str(uuid.uuid4()), user_id="user_123", mem_cube_id="cube_001", label=MY_TASK_LABEL, content="This is a test message", timestamp=datetime.now() ) # If the scheduler is not started, the task will be queued for processing # or in local queue mode may require calling mem_scheduler.start() first mem_scheduler.submit_messages([task]) print(f"Task submitted: {task.item_id}") # Prevent scheduler main process from exiting prematurely time.sleep(10) ``` ### 2. Redis Queue vs Local Queue - **Local Queue**: - **Use case**: Unit tests, simple single-machine scripts. - **Characteristics**: Fast, but data is lost after process restart; does not support multi-process/multi-instance sharing. - **Configuration**: `MOS_SCHEDULER_USE_REDIS_QUEUE=false` - **Redis Queue (Redis Stream)**: - **Use case**: Production environment, distributed deployment. - **Characteristics**: Data persistence, supports consumer groups allowing multiple scheduler instances to handle tasks together (load balancing). - **Configuration**: `MOS_SCHEDULER_USE_REDIS_QUEUE=true` - **Debugging**: Use the `show_redis_status.py` script to check queue accumulation. ## Comprehensive Application Scenarios ### Scenario 1: Basic Conversation Flow and Memory Update The following is a complete example demonstrating how to initialize the environment, register custom logic, simulate conversation flow, and trigger memory updates. ```python import asyncio import json import os import sys import time from pathlib import Path # --- Environment Setup --- # 1. Add project root to sys.path to ensure memos module can be imported FILE_PATH = Path(__file__).absolute() BASE_DIR = FILE_PATH.parent.parent.parent sys.path.insert(0, str(BASE_DIR)) # 2. Set necessary environment variables (simulating .env configuration) os.environ["ENABLE_CHAT_API"] = "true" os.environ["MOS_ENABLE_SCHEDULER"] = "true" # Choose between Redis or Local queue os.environ["MOS_SCHEDULER_USE_REDIS_QUEUE"] = "false" # --- Import Components --- # Note: Importing server_router triggers component initialization, # ensure environment variables are set before this import from memos.api.product_models import APIADDRequest, ChatPlaygroundRequest from memos.api.routers.server_router import ( add_handler, chat_stream_playground, mem_scheduler, # mem_scheduler here is already an initialized singleton ) from memos.log import get_logger from memos.mem_scheduler.schemas.message_schemas import ScheduleMessageItem from memos.mem_scheduler.schemas.task_schemas import ( MEM_UPDATE_TASK_LABEL, QUERY_TASK_LABEL, ) logger = get_logger(__name__) # Global variable for demonstrating memory retrieval results working_memories = [] # --- Custom Handlers --- def custom_query_handler(messages: list[ScheduleMessageItem]): """ Handle user query messages: 1. Print query content 2. Convert message to MEM_UPDATE task, triggering memory retrieval/update process """ for msg in messages: print(f"\n[Scheduler 🟢] Received user query: {msg.content}") # Copy message and change label to MEM_UPDATE, a common "task chaining" pattern new_msg = msg.model_copy(update={"label": MEM_UPDATE_TASK_LABEL}) # Submit new task back to scheduler mem_scheduler.submit_messages([new_msg]) def custom_mem_update_handler(messages: list[ScheduleMessageItem]): """ Handle memory update tasks: 1. Use retriever to find relevant memories 2. Update global working memory list """ global working_memories search_args = {} top_k = 2 for msg in messages: print(f"[Scheduler 🔵] Retrieving memories for query...") # Call core retrieval functionality results = mem_scheduler.retriever.search( query=msg.content, user_id=msg.user_id, mem_cube_id=msg.mem_cube_id, mem_cube=mem_scheduler.current_mem_cube, top_k=top_k, method=mem_scheduler.search_method, search_args=search_args, ) # Simulate working memory update working_memories.extend(results) working_memories = working_memories[-5:] # Keep the latest 5 for mem in results: # Print retrieved memory fragments print(f" ↳ [Memory Found]: {mem.memory[:50]}...") # --- Mock Business Data --- def get_mock_data(): """Generate mock conversation data""" conversations = [ {"role": "user", "content": "I just adopted a golden retriever puppy named Max."}, {"role": "assistant", "content": "That's exciting! Max is a great name."}, {"role": "user", "content": "He loves peanut butter treats but I am allergic to nuts."}, {"role": "assistant", "content": "Noted. Peanut butter for Max, no nuts for you."}, ] questions = [ {"question": "What is my dog's name?", "category": "Pet"}, {"question": "What am I allergic to?", "category": "Allergy"}, ] return conversations, questions # --- Main Flow --- async def run_demo(): print("==== MemScheduler Demo Start ====") conversations, questions = get_mock_data() user_id = "demo_user_001" mem_cube_id = "cube_demo_001" print(f"1. Initialize user memory library ({user_id})...") # Use API Handler to add initial memories (synchronous mode) add_req = APIADDRequest( user_id=user_id, writable_cube_ids=[mem_cube_id], messages=conversations, async_mode="sync", ) add_handler.handle_add_memories(add_req) print(" Memory addition completed.") print("\n2. Start conversation testing (triggering background scheduling tasks)...") for item in questions: query = item["question"] print(f"\n>> User: {query}") # Initiate chat request chat_req = ChatPlaygroundRequest( user_id=user_id, query=query, readable_cube_ids=[mem_cube_id], writable_cube_ids=[mem_cube_id], ) # Get streaming response response = chat_stream_playground(chat_req) # Handle streaming output (simplified) full_answer = "" buffer = "" async for chunk in response.body_iterator: if isinstance(chunk, bytes): chunk = chunk.decode("utf-8") buffer += chunk while "\n\n" in buffer: msg, buffer = buffer.split("\n\n", 1) for line in msg.split("\n"): if line.startswith("data: "): try: data = json.loads(line[6:]) if data.get("type") == "text": full_answer += data["data"] except: pass print(f">> AI: {full_answer}") # Wait a moment for background scheduler to process tasks and print logs await asyncio.sleep(1) if __name__ == "__main__": # 1. Register our custom handlers # This will override or add to the default scheduling logic mem_scheduler.register_handlers( { QUERY_TASK_LABEL: custom_query_handler, MEM_UPDATE_TASK_LABEL: custom_mem_update_handler, } ) # 2. Ensure scheduler is started if not mem_scheduler._running: mem_scheduler.start() try: asyncio.run(run_demo()) except KeyboardInterrupt: pass finally: # Prevent scheduler main process from exiting prematurely time.sleep(10) print("\n==== Stopping scheduler ====") mem_scheduler.stop() ``` ### Scenario 2: Concurrent Asynchronous Tasks and Checkpoint Restart (Redis) This example demonstrates how to use Redis queues to achieve concurrent asynchronous task processing and checkpoint restart functionality. Running this example requires Redis environment configuration. ```python from pathlib import Path from time import sleep from memos.api.routers.server_router import mem_scheduler from memos.mem_scheduler.schemas.message_schemas import ScheduleMessageItem # Debug: Print scheduler configuration print("=== Scheduler Configuration Debug ===") print(f"Scheduler type: {type(mem_scheduler).__name__}") print(f"Config: {mem_scheduler.config}") print(f"use_redis_queue: {mem_scheduler.use_redis_queue}") print(f"Queue type: {type(mem_scheduler.memos_message_queue).__name__}") print(f"Queue maxsize: {getattr(mem_scheduler.memos_message_queue, 'maxsize', 'N/A')}") print("=====================================\n") queue = mem_scheduler.memos_message_queue # Define handler function def my_test_handler(messages: list[ScheduleMessageItem]): print(f"My test handler received {len(messages)} messages: {[one.item_id for one in messages]}") for msg in messages: # Create file based on task_id (use item_id as numeric ID 0..99) task_id = str(msg.item_id) file_path = tmp_dir / f"{task_id}.txt" try: sleep(5) file_path.write_text(f"Task {task_id} processed.\n") print(f"writing {file_path} done") except Exception as e: print(f"Failed to write {file_path}: {e}") def submit_tasks(): mem_scheduler.memos_message_queue.clear() # Create 100 messages (task_id 0..99) users = ["user_A", "user_B"] messages_to_send = [ ScheduleMessageItem( item_id=str(i), user_id=users[i % 2], mem_cube_id="test_mem_cube", label=TEST_HANDLER_LABEL, content=f"Create file for task {i}", ) for i in range(100) ] # Batch submit messages and print completion info print(f"Submitting {len(messages_to_send)} messages to the scheduler...") mem_scheduler.memos_message_queue.submit_messages(messages_to_send) print(f"Task submission done! tasks in queue: {mem_scheduler.get_tasks_status()}") # Register handler function TEST_HANDLER_LABEL = "test_handler" mem_scheduler.register_handlers({TEST_HANDLER_LABEL: my_test_handler}) # 5 second restart mem_scheduler.orchestrator.tasks_min_idle_ms[TEST_HANDLER_LABEL] = 5_000 tmp_dir = Path("./tmp") tmp_dir.mkdir(exist_ok=True) # Test stop and restart: if tmp has >1 files, skip submission and print info existing_count = len(list(Path("tmp").glob("*.txt"))) if Path("tmp").exists() else 0 if existing_count > 1: print(f"Skip submission: found {existing_count} files in tmp (>1), continue processing") else: submit_tasks() # Wait until tmp has 100 files or timeout poll_interval = 1 expected = 100 tmp_dir = Path("tmp") tasks_status = mem_scheduler.get_tasks_status() mem_scheduler.print_tasks_status(tasks_status=tasks_status) while ( mem_scheduler.get_tasks_status()["remaining"] != 0 or mem_scheduler.get_tasks_status()["running"] != 0 ): count = len(list(tmp_dir.glob("*.txt"))) if tmp_dir.exists() else 0 tasks_status = mem_scheduler.get_tasks_status() mem_scheduler.print_tasks_status(tasks_status=tasks_status) print(f"[Monitor] Files in tmp: {count}/{expected}") sleep(poll_interval) print(f"[Result] Final files in tmp: {len(list(tmp_dir.glob('*.txt')))})") # Stop scheduler sleep(20) print("Stopping the scheduler...") mem_scheduler.stop() ``` --- # MemChat (/open_source/modules/mem_chat) ## 1. Introduction **MemChat** is the conversation control center of MemOS. It is not just a chat interface, but a bridge connecting "instant conversation" and "long-term memory". During interactions with users, MemChat is responsible for real-time retrieval of relevant background information from MemCube (Memory Cube), building context, and crystallizing new conversation content into new memories. With it, your Agent is no longer "goldfish memory", but a truly intelligent companion that can understand the past and continuously grow. --- ## 2. Core Capabilities ### Memory-Augmented Chat Before answering user questions, MemChat automatically retrieves relevant Textual Memory from MemCube and injects it into the Prompt. This enables the Agent to answer questions based on past interaction history or knowledge bases, rather than relying solely on the LLM's pre-trained knowledge. ### Auto-Memorization After conversation, MemChat uses Extractor LLM to automatically extract valuable information from the conversation flow (such as user preferences, factual knowledge) and store it in MemCube. The entire process is fully automated without manual user intervention. ### Context Management Automatically manages conversation history window (`max_turns_window`). When conversations become too long, it intelligently trims old context while relying on retrieved long-term memory to maintain conversation coherence, effectively solving the LLM Context Window limitation problem. ### Flexible Configuration Supports configurable toggles for different types of memory (textual memory, activation memory, etc.) to adapt to different application scenarios. --- ## 3. Code Structure Core logic is located under `memos/src/memos/mem_chat/`. * **`simple.py`**: **Default implementation (SimpleMemChat)**. This is an out-of-the-box REPL (Read-Eval-Print Loop) implementation containing complete "retrieve -> generate -> store" loop logic. * **`base.py`**: **Interface definition (BaseMemChat)**. Defines the basic behavior of MemChat, such as `run()` and `mem_cube` properties. * **`factory.py`**: **Factory class**. Responsible for instantiating concrete MemChat objects based on configuration (`MemChatConfig`). --- ## 4. Key Interface The main interaction entry point is the `MemChat` class (typically created by `MemChatFactory`). ### 4.1 Initialization You need to first create a configuration object, then create an instance through the factory method. After creation, you must mount the `MemCube` instance to `mem_chat.mem_cube`. ### 4.2 `run()` Starts an interactive command-line conversation loop. Suitable for development and debugging, it handles user input, calls memory retrieval, generates replies, and prints output. ### 4.3 Properties * **`mem_cube`**: Associated MemCube object. MemChat reads and writes memories through it. * **`chat_llm`**: LLM instance used to generate replies. --- ## 5. Workflow A typical conversation round in MemChat includes the following steps: 1. **Receive Input**: Get user text input. 2. **Memory Recall**: (If `enable_textual_memory` is enabled) Use user input as Query to retrieve Top-K relevant memories from `mem_cube.text_mem`. 3. **Prompt Construction**: Concatenate system prompt, retrieved memories, and recent conversation history into a complete Prompt. 4. **Generate Response**: Call `chat_llm` to generate a reply. 5. **Memorization**: (If `enable_textual_memory` is enabled) Send this round's conversation (User + Assistant) to `mem_cube`'s extractor, extract new memories and store them in the database. --- ## 6. Development Example Below is a complete code example showing how to configure MemChat and mount a MemCube based on Qdrant and OpenAI. ### 6.1 Code Implementation ```python import os import sys # Ensure src module can be imported sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "../../../src"))) from memos.configs.mem_chat import MemChatConfigFactory from memos.configs.mem_cube import GeneralMemCubeConfig from memos.mem_chat.factory import MemChatFactory from memos.mem_cube.general import GeneralMemCube def get_mem_chat_config() -> MemChatConfigFactory: """Generate MemChat configuration""" return MemChatConfigFactory.model_validate( { "backend": "simple", "config": { "user_id": "user_123", "chat_llm": { "backend": "openai", "config": { "model_name_or_path": os.getenv("MOS_CHAT_MODEL", "gpt-4o"), "temperature": 0.8, "max_tokens": 1024, "api_key": os.getenv("OPENAI_API_KEY"), "api_base": os.getenv("OPENAI_API_BASE"), }, }, "max_turns_window": 20, "top_k": 5, "enable_textual_memory": True, # Enable explicit memory }, } ) def get_mem_cube_config() -> GeneralMemCubeConfig: """Generate MemCube configuration""" return GeneralMemCubeConfig.model_validate( { "user_id": "user03alice", "cube_id": "user03alice/mem_cube_tree", "text_mem": { "backend": "general_text", "config": { "cube_id": "user03alice/mem_cube_general", "extractor_llm": { "backend": "openai", "config": { "model_name_or_path": os.getenv("MOS_CHAT_MODEL", "gpt-4o"), "api_key": os.getenv("OPENAI_API_KEY"), "api_base": os.getenv("OPENAI_API_BASE"), }, }, "vector_db": { "backend": "qdrant", "config": { "collection_name": "user03alice_mem_cube_general", "vector_dimension": 1024, }, }, "embedder": { "backend": os.getenv("MOS_EMBEDDER_BACKEND", "universal_api"), "config": { "provider": "openai", "api_key": os.getenv("MOS_EMBEDDER_API_KEY", "EMPTY"), "model_name_or_path": os.getenv("MOS_EMBEDDER_MODEL", "bge-m3"), "base_url": os.getenv("MOS_EMBEDDER_API_BASE"), }, }, }, }, } ) def main(): print("Initializing MemChat...") mem_chat = MemChatFactory.from_config(get_mem_chat_config()) print("Initializing MemCube...") mem_cube = GeneralMemCube(get_mem_cube_config()) # Critical step: mount the memory cube mem_chat.mem_cube = mem_cube print("Starting Chat Session...") try: mem_chat.run() finally: print("Saving memory cube...") mem_chat.mem_cube.dump("new_cube_path") if __name__ == "__main__": main() ``` --- ## 7. Configuration Description When configuring `MemChatConfigFactory`, the following parameters are crucial: * **`user_id`**: Required. Used to identify the current user in the conversation, ensuring memory isolation. * **`chat_llm`**: Chat model configuration. Recommend using a capable model (such as GPT-4o) for better reply quality and instruction-following ability. * **`enable_textual_memory`**: `True` / `False`. Whether to enable textual memory. If enabled, the system will perform retrieval before conversation and storage after conversation. * **`max_turns_window`**: Integer. Number of conversation turns to retain in history. History beyond this limit will be truncated, relying on long-term memory to supplement context. * **`top_k`**: Integer. How many most relevant memory fragments to retrieve from the memory library and inject into the Prompt each time. --- # MemFeedback (/open_source/modules/mem_feedback) ## 1. Introduction **MemFeedback** is the "regret medicine" for MemOS. In long-term memory systems, the biggest headache is often not "forgetting," but "remembering wrong and unable to change." When a user says, "No, my birthday is tomorrow" or "Change the project code to X," simple RAG systems are usually helpless. MemFeedback can understand these natural language instructions, automatically locate conflicting memories in the database, and execute atomic correction operations (such as archiving old memories and writing new ones). With it, your Agent can correct errors and learn continuously during interactions, just like a human. --- ## 2. Core Capabilities It can handle four common feedback scenarios: ### Correction When the user points out a factual error. The system will not brutally delete the old data but **Archive** it and write new data. This corrects the error while preserving version history (Traceability). If it is an ongoing conversation (WorkingMemory), it updates in place to ensure context continuity. ### Addition If the user just supplements new information that does not conflict with old memories, it is simple—directly save it as a new node in the memory database. ### Keyword Replacement (Global Refactor) Similar to "Global Refactor" in an IDE. For example, if the user says, "Change 'Zhang San' to 'Li Si' in all documents," the system will combine the Reranker to automatically determine the scope of affected documents and update all relevant memories in batches. ### Preference Evolution Specifically handles preferences like "I don't eat cilantro" or "I like Python." The system records the context in which this preference arose, constantly enriching the user profile to make the Agent more tailored to use. --- ## 3. Code Structure The core logic is located under `memos/src/memos/mem_feedback/`. * **`simple_feedback.py`**: **Recommended entry point**. It is the official encapsulated version that assembles LLM, vector database, and searcher, ready to use out of the box. * **`feedback.py`**: Core implementation class `MemFeedback`. The heavy lifting is done here: intent recognition, conflict comparison, and security risk control. * **`base.py`**: Interface definition. * **`utils.py`**: Utility box. --- ## 4. Key Interface There is only one main entry point: `process_feedback()`. It is usually called asynchronously after the RAG process ends and the user gives feedback. ### 4.1 Input Parameters | Parameter | Description | | :--- | :--- | | `user_id` / `user_name` | User identification and Cube ID. | | `chat_history` | Conversation history, letting LLM know what you talked about. | | `feedback_content` | The feedback sentence from the user (e.g., "No, it's 5 o'clock"). | | **`retrieved_memory_ids`** | **Required (Strongly Recommended)**. Pass in the memory IDs retrieved in the previous RAG round. This gives the system a "target," telling it which memory to correct. If not passed, the system has to search again in the massive memory, which is slow and prone to errors. | | `corrected_answer` | Whether to generate a corrected response along the way. | ### 4.2 Output Result Returns a dictionary telling you what changed in this operation: * **`record`**: Database change details (e.g., `{ "add": [...], "update": [...] }`). * **`answer`**: Natural language response to the user. --- ## 5. Workflow The workflow of MemFeedback is like a rigorous editorial office: 1. **Review (Intent Recognition)**: First, see if the user is correcting errors, adding information, or renaming. 2. **Locate (Recall)**: Find the memory to be modified (if you passed the ID, this step is skipped). 3. **Proofread (Comparison)**: Let LLM carefully compare new and old information to determine if it is completely new (ADD) or needs an update (UPDATE). 4. **Risk Control (Security Check)**: Prevent LLM from making random changes. For example, is the ID correct? Is it trying to delete an entire long document? (Threshold interception applies). 5. **Publish (Write)**: Finally, execute graph database operations, archive the old, and write the new. --- ## 6. Development Example Here is a runnable code snippet showing how to initialize the service, preset an "incorrect memory," and then correct it through user feedback. ### 6.1 Preparation First, we need to initialize the `SimpleMemFeedback` service. ```python # Assuming components like llm, embedder, graph_db are initialized via Factory # For complete initialization code, please refer to examples/mem_feedback/example_feedback.py from memos.mem_feedback.simple_feedback import SimpleMemFeedback feedback_server = SimpleMemFeedback( llm=llm, embedder=embedder, graph_store=graph_db, memory_manager=memory_manager, mem_reader=mem_reader, searcher=searcher, reranker=mem_reranker, pref_mem=None, ) ``` ### 6.2 Simulate Scenario and Execute Feedback Scenario: The system incorrectly remembers "You like apples, dislike bananas," and now we want to correct it. ```python import json from memos.mem_feedback.utils import make_mem_item # 1. Simulate Chat History # User asks for preference, assistant answers wrongly history = [ {"role": "user", "content": "What fruits do I like and dislike?"}, {"role": "assistant", "content": "You like apples, dislike bananas."}, ] # 2. Preset "Incorrect Memory" # We manually insert an incorrect fact into the database mem_text = "You like apples, dislike bananas" # ... (Omitted detailed parameters of make_mem_item, see source code) ... memory_manager.add([make_mem_item(mem_text, ...)], ...) # 3. User Feedback feedback_content = "Wrong, actually I like mangosteens." print(f"Feedback Input: {feedback_content}") # 4. Execute Correction # MemFeedback will detect conflict, archive old memory, and write new memory "like mangosteens" res = feedback_server.process_feedback( ..., chat_history=history, feedback_content=feedback_content, ... ) # 5. View Result print(json.dumps(res, indent=4)) ``` --- ## 7. Configuration Description To make MemFeedback work, you need to prepare the configuration of the following components (usually in `.env` or YAML): * **LLM (`extractor_llm`)**: Needs a smart brain, recommend GPT-4o level models. Set Temperature low (e.g., 0) because it performs logical analysis and shouldn't be too divergent. * **Embedder (`embedder`)**: Used to convert new memories into vectors. * **GraphDB (`graph_db`)**: Where memories are stored and how, handled by these two. * **MemReader (`mem_reader`)**: Used to parse purely new memories. --- # Memory Modules Overview (/open_source/modules/memories/overview) The Memory Module provides Agents with essential long-term memory capabilities. Instead of acting as a static database, it mimics human cognitive processes by automatically extracting, organizing, and linking information. Choosing different memory modules allows you to customize and enhance your Agent's skills. ## 🎯 Quick Selection Guide > **Alert**: **Not sure which to choose?** Follow this decision tree: > - 🚀 **Quick testing/demo**: Get started easily with no additional software → [NaiveTextMemory](#naivetextmemory-simple-textual-memory) > - 📝 **General text memory**: Retain chat history or massive documents with semantic search capabilities → [GeneralTextMemory](#generaltextmemory-general-purpose-textual-memory) > - 👤 **User preference management**:Specifically designed for building and managing user profiles → [PreferenceTextMemory](#preferencetextmemory-preference-memory) > - 🌳 **Structured knowledge graph**: Ideal for data with complex logical relationships and interconnections → [TreeTextMemory](#treetextmemory-hierarchical-structured-memory) > - ⚡ **Inference acceleration**: Optimized for high-traffic scenarios to ensure stable and rapid responses → [KVCacheMemory](#kvcachememory-activation-memory) --- ## 📚 Memory Module Categories ### I. Textual Memory Series Focused on storing and retrieving text-based memories, suitable for most application scenarios. #### NaiveTextMemory: Simple Textual Memory **Use Cases:** Rapid prototyping, demos, teaching, small-scale applications **Core Features:** - ✅ Zero dependencies, pure in-memory storage - ✅ Keyword-based retrieval - ✅ Minimal API, get started in 5 minutes - ✅ File persistence support **Limitations:** - ❌ No vector semantic search - ❌ Not suitable for large-scale data - ❌ Limited retrieval precision 📖 [View Documentation](./naive_textual_memory) #### GeneralTextMemory: General-Purpose Textual Memory **Use Cases:** Conversational agents, personal assistants, knowledge management systems **Core Features:** - ✅ Vector-based semantic search - ✅ Rich metadata support (type, time, source, etc.) - ✅ Flexible filtering and querying - ✅ Suitable for medium to large-scale applications **Technical Requirements:** - Requires vector database (Qdrant, etc.) - Requires embedding model 📖 [View Documentation](./general_textual_memory) #### PreferenceTextMemory: Preference Memory **Use Cases:** Personalized recommendations, user profiling, intelligent assistants **Core Features:** - ✅ Automatic detection of explicit and implicit preferences - ✅ Preference deduplication and conflict detection - ✅ Filter by preference type and strength - ✅ Vector semantic retrieval **Specialized Functions:** - Dual preference extraction (explicit/implicit) - Preference strength scoring - Temporal decay support 📖 [View Documentation](./preference_textual_memory) #### TreeTextMemory: Hierarchical Structured Memory **Use Cases:** Knowledge graphs, complex relationship reasoning, multi-hop queries **Core Features:** - ✅ Graph database-based structured storage - ✅ Support for hierarchical relationships and causal chains - ✅ Multi-hop reasoning capabilities - ✅ Deduplication, conflict detection, memory scheduling **Advanced Features:** - Supports MultiModal Reader (images, URLs, files) - Supports Internet Retrieval (BochaAI, Google, Bing) - Working memory replacement mechanism **Technical Requirements:** - Requires graph database (Neo4j, etc.) - Requires vector database and embedding model 📖 [View Documentation](./tree_textual_memory) --- ### II. Specialized Memory Modules Memory systems optimized for specific scenarios. #### KVCacheMemory: Activation Memory **Use Cases:** LLM inference acceleration, high-frequency background knowledge reuse **Core Features:** - ⚡ Pre-computed KV Cache, skip repeated encoding - ⚡ Significantly reduce prefill phase computation - ⚡ Suitable for high-throughput scenarios **Typical Use Cases:** - FAQ caching - Conversation history reuse - Domain knowledge preloading **How It Works:** Stable text memory → Pre-convert to KV Cache → Direct injection during inference 📖 [View Documentation](./kv_cache_memory) #### ParametricMemory: Parametric Memory **Status:** 🚧 Under Development **Design Goals:** - Encode knowledge into model weights (LoRA, expert modules) - Dynamically load/unload capability modules - Support multi-task, multi-role architecture **Future Features:** - Parameter module generation and compression - Version control and rollback - Hot-swappable capability modules 📖 [View Documentation](./parametric_memory) --- ### III. Graph Database Backends Provide graph storage capabilities for TreeTextMemory. #### Neo4j Graph DB **Recommendation:** ⭐⭐⭐⭐⭐ **Features:** - Complete graph database functionality - Support for vector-enhanced retrieval - Multi-tenant architecture (v0.2.1+) - Compatible with Community Edition 📖 [View Documentation](./neo4j_graph_db) #### Nebula Graph DB **Features:** - Distributed graph database - High availability - Suitable for large-scale deployment 📖 [View Documentation](./nebula_graph_db) #### PolarDB Graph DB **Features:** - Alibaba Cloud PolarDB graph computing - Cloud-native architecture - Enterprise-grade reliability 📖 [View Documentation](./polardb_graph_db) --- ## 📊 Feature Comparison Table | Feature | Naive | General | Preference | Tree | KVCache | |---------|-------|---------|------------|------|---------| | **Search Method** | Keyword | Vector Semantic | Vector Semantic | Vector+Graph | N/A | | **Metadata Support** | ⭐ | ⭐⭐⭐ | ⭐⭐⭐ | ⭐⭐⭐⭐ | - | | **Relationship Reasoning** | ❌ | ❌ | ❌ | ✅ | - | | **Deduplication** | ❌ | ⭐ | ⭐⭐⭐ | ⭐⭐⭐⭐ | - | | **Scalability** | Small | Medium-Large | Medium-Large | Large | - | | **Deployment Complexity** | Minimal | Medium | Medium | Higher | Medium | | **Inference Acceleration** | - | - | - | - | ⭐⭐⭐⭐⭐ | --- ## 🛠️ Usage Scenario Recommendations ### Scenario 1: Rapid Prototyping **Recommended:** [NaiveTextMemory](./naive_textual_memory) ```python from memos.memories import NaiveTextMemory memory = NaiveTextMemory() memory.add("User likes coffee") results = memory.search("coffee") ``` ### Scenario 2: Chatbot Memory **Recommended:** [GeneralTextMemory](./general_textual_memory) - Supports semantic search - Filter by time, type, source - Suitable for conversation history management ### Scenario 3: Personalized Recommendation System **Recommended:** [PreferenceTextMemory](./preference_textual_memory) - Automatic user preference extraction - Preference conflict detection - Strength scoring and filtering ### Scenario 4: Knowledge Graph Applications **Recommended:** [TreeTextMemory](./tree_textual_memory) - Multi-hop relationship queries - Hierarchical structure management - Complex reasoning scenarios ### Scenario 5: High-Performance LLM Services **Recommended:** [KVCacheMemory](./kv_cache_memory) - FAQ systems - Customer service bots - High-volume request processing --- ## 🔗 Advanced Features ### MultiModal Reader (Multimodal Reading) Supported in TreeTextMemory for processing: - 📷 Images in conversations - 🌐 Web URLs - 📄 Local files (PDF, DOCX, TXT, Markdown) - 🔀 Mixed mode (text+images+URLs) 👉 [View Examples](./tree_textual_memory#using-multimodalstructmemreader-advanced) ### Internet Retrieval Fetch real-time information from the web and add to memory: - 🔍 BochaAI search - 🌍 Google search - 🔎 Bing search 👉 [View Examples](./tree_textual_memory#retrieve-memories-from-the-internet-optional) --- ## 🚀 Quick Start 1. **Choose Memory Module** - Select the appropriate module based on the guide above 2. **Read Documentation** - Click the corresponding link to view detailed documentation 3. **Hands-On Practice** - Each module has complete code examples 4. **Production Deployment** - Refer to the best practices section --- ## 📖 Related Resources - [API Reference](/api) - [Best Practices Guide](/best-practices) - [Example Code Repository](https://github.com/MemOS/examples) - [FAQ](/faq) --- > **Alert**: **Beginner Suggestion:** Start with NaiveTextMemory, understand the basic concepts, then explore GeneralTextMemory and TreeTextMemory. --- # KVCacheMemory: Key-Value Cache for Activation Memory (/open_source/modules/memories/kv_cache_memory) ## KV-cache Memory Use Cases In MemOS, KV-cache memory is best suited for storing **semantically stable and frequently reused background content** such as: - Frequently asked questions (FAQs) or domain-specific knowledge - Prior conversation history These stable **plaintext memory items** are automatically identified and managed by the `MemScheduler` module. Once selected, they are converted into KV-format representations (`KVCacheItem`) ahead of time. This precomputation step stores the activation states (Key/Value tensors) of the memory in a reusable format, allowing them to be injected into the model’s attention cache during inference. Once converted, these KV memories can be **reused across queries without requiring re-encoding** of the original content. This reduces the computational overhead of processing and storing large amounts of text, making it ideal for applications that require **rapid response times** and **high throughput**. ## Why KV-cache Memory Integrating `MemScheduler` with KV-cache memory enables significant performance optimization, particularly in the **prefill phase** of LLM inference. ### Without KVCacheMemory - Each new query is appended to the full prompt, including the background memory. - The model must **recompute token embeddings and attention** over the full sequence — even for unchanged memory. ### With KVCacheMemory - The background content is **cached once** as Key/Value tensors. - For each query, only the new user input (query tokens) is encoded. - The previously cached KV is injected directly into the attention mechanism. ### Benefits This separation reduces redundant computation in the prefill phase and leads to: - Skipping repeated encoding of background content - Faster attention computation between query tokens and cached memory - **Lower Time To First Token (TTFT)** latency during generation This optimization is especially valuable in: - Multi-turn chatbot interactions - Retrieval-augmented or context-augmented generation (RAG, CAG) - Assistants operating over fixed documentation or FAQ-style memory ### KVCacheMemory Acceleration Evaluation To validate the performance impact of KV-based memory injection, we conducted a set of controlled experiments simulating real memory reuse in MemOS. #### Experiment Setup During typical usage, the `MemScheduler` module continuously tracks interaction patterns and promotes high-frequency, stable plaintext memory into KV format. These KV memories are loaded into GPU memory as activation caches and reused during inference. The evaluation compares two memory injection strategies: 1. **Prompt-based injection**: background memory is prepended as raw text. 2. **KV-cache injection**: memory is injected directly into the model’s attention cache. We test these strategies across: - **Three context sizes**: short, medium, and long - **Three query types**: short-form, medium-form, and long-form The primary metric is **Time To First Token (TTFT)**, a key latency indicator for responsive generation. #### Results The following table shows results across three models (Qwen3-8B, Qwen3-32B, Qwen2.5-72B). TTFT under KV-cache injection is consistently lower than prompt-based injection, while the output tokens remain identical across both strategies. > **Note**: `Build (s)` refers to the one-time preprocessing cost of converting the memory to KV format, amortized across multiple queries. | Model | Ctx | CtxTok | Qry | QryTok | Build (s) | KV TTFT (s) | Dir TTFT (s) | Speedup (%) | | ----------- | ------ | ------ | ------ | ------ | --------- | ----------- | ------------ | ----------- | | Qwen3-8B | long | 6064 | long | 952.7 | 0.92 | 0.50 | 2.37 | 79.1 | | | | | medium | 302.7 | 0.93 | 0.19 | 2.16 | 91.1 | | | | | short | 167 | 0.93 | 0.12 | 2.04 | 94.2 | | | medium | 2773 | long | 952.7 | 0.41 | 0.43 | 1.22 | 64.6 | | | | | medium | 302.7 | 0.41 | 0.16 | 1.08 | 85.1 | | | | | short | 167 | 0.43 | 0.10 | 0.95 | 89.7 | | | short | 583 | long | 952.7 | 0.12 | 0.39 | 0.51 | 23.0 | | | | | medium | 302.7 | 0.12 | 0.14 | 0.32 | 55.6 | | | | | short | 167 | 0.12 | 0.08 | 0.29 | 71.3 | | Qwen3-32B | long | 6064 | long | 952.7 | 0.71 | 0.31 | 1.09 | 71.4 | | | | | medium | 302.7 | 0.71 | 0.15 | 0.98 | 84.3 | | | | | short | 167 | 0.71 | 0.11 | 0.96 | 88.8 | | | medium | 2773 | long | 952.7 | 0.31 | 0.24 | 0.56 | 56.9 | | | | | medium | 302.7 | 0.31 | 0.12 | 0.47 | 75.1 | | | | | short | 167 | 0.31 | 0.08 | 0.44 | 81.2 | | | short | 583 | long | 952.7 | 0.09 | 0.20 | 0.24 | 18.6 | | | | | medium | 302.7 | 0.09 | 0.09 | 0.15 | 39.6 | | | | | short | 167 | 0.09 | 0.07 | 0.14 | 53.5 | | Qwen2.5-72B | long | 6064 | long | 952.7 | 1.26 | 0.48 | 2.04 | 76.4 | | | | | medium | 302.7 | 1.26 | 0.23 | 1.82 | 87.2 | | | | | short | 167 | 1.27 | 0.15 | 1.79 | 91.4 | | | medium | 2773 | long | 952.7 | 0.58 | 0.39 | 1.05 | 62.7 | | | | | medium | 302.7 | 0.58 | 0.18 | 0.89 | 79.2 | | | | | short | 167 | 0.71 | 0.23 | 0.82 | 71.6 | | | short | 583 | long | 952.7 | 0.16 | 0.33 | 0.43 | 23.8 | | | | | medium | 302.7 | 0.16 | 0.15 | 0.27 | 43.2 | | | | | short | 167 | 0.16 | 0.10 | 0.25 | 60.5 | #### vLLM-based Performance MemOS now supports using vLLM to manage activation memory. To evaluate the impact of KV Cache prefilling for different prefix text lengths, we conducted performance tests on a system equipped with 8x `H800 80GB GPUs (112 vCPUs, 1920 GiB Memory)` and a system equipped with 8x `RTX4090-24G-PCIe (112 vCPUs, 960 GiB Memory)`. The evaluation covered two core models: Qwen3-32B and Qwen2.5-72B. The benchmarks were run across a range of memory and context length combinations to simulate various activation memory scenarios: - **Memory Text Lengths (tokens)**: 500, 1000, 2000 - **Context Text Lengths (tokens)**: 500, 1000, 2000, 4000 The following table summarizes the benchmark results. **Qwen2.5-72B** - On 4090 (2 Nodes 16 GPUs) | mem tks | prompt tks | TTFT (without cache, ms) | TTFT (With cache, ms) | TTFT Speedup (%) | Abs Dis(ms) | | --- | --- | --- | --- | --- | --- | | 0.5k | 0.5k | 1787.21 | 851.47 | 52.358% | 935.74 | | 0.5k | 1k | 2506.26 | 1290.68 | 48.502% | 1215.58 | | 0.5k | 2k | 3843.48 | 2897.97 | 24.600% | 945.51 | | 0.5k | 4k | 6078.01 | 5200.86 | 14.432% | 877.15 | | 1k | 0.5k | 2274.61 | 920.16 | 59.546% | 1354.45 | | 1k | 1k | 2907.17 | 1407.65 | 51.580% | 1499.52 | | 1k | 2k | 4278.53 | 2916.47 | 31.835% | 1362.06 | | 1k | 4k | 6897.99 | 5218.94 | 24.341% | 1679.05 | | 2k | 0.5k | 3460.12 | 782.73 | 77.379% | 2677.39 | | 2k | 1k | 4443.34 | 1491.24 | 66.439% | 2952.10 | | 2k | 2k | 5733.14 | 2758.48 | 51.885% | 2974.66 | | 2k | 4k | 8152.76 | 5627.41 | 30.975% | 2525.35 | - On H800 (4 GPUs) | mem tks | prompt tks | TTFT (without cache, ms) | TTFT (With cache, ms) | TTFT Speedup (%) | Abs Dis(ms) | | --- | --- | --- | --- | --- | --- | | 0.5k | 0.5k | 51.65 | 52.17 | \-1.007% | \-0.52 | | 0.5k | 1k | 55.70 | 57.03 | \-2.388% | \-1.33 | | 0.5k | 2k | 74.23 | 78.56 | \-5.833% | \-4.33 | | 0.5k | 4k | 77.56 | 77.45 | 0.142% | 0.11 | | 1k | 0.5k | 55.90 | 55.73 | 0.304% | 0.17 | | 1k | 1k | 55.35 | 52.89 | 4.444% | 2.46 | | 1k | 2k | 80.14 | 73.82 | 7.886% | 6.32 | | 1k | 4k | 82.83 | 73.51 | 11.252% | 9.32 | | 2k | 0.5k | 75.82 | 71.31 | 5.948% | 4.51 | | 2k | 1k | 80.60 | 78.71 | 2.345% | 1.89 | | 2k | 2k | 83.91 | 78.60 | 6.328% | 5.31 | | 2k | 4k | 99.15 | 80.12 | 19.193% | 19.03 | **Qwen3-32B** - On 4090 (1 Nodes 8 GPUs) | mem tks | prompt tks | TTFT (without cache, ms) | TTFT (With cache, ms) | TTFT Speedup (%) | Abs Dis(ms) | | --- | --- | --- | --- | --- | --- | | 0.5k | 0.5k | 288.72 | 139.29 | 51.756% | 149.43 | | 0.5k | 1k | 428.72 | 245.85 | 42.655% | 182.87 | | 0.5k | 2k | 683.65 | 538.59 | 21.218% | 145.06 | | 0.5k | 4k | 1170.48 | 986.94 | 15.681% | 183.54 | | 1k | 0.5k | 409.83 | 137.96 | 66.337% | 271.87 | | 1k | 1k | 507.95 | 262.21 | 48.379% | 245.74 | | 1k | 2k | 743.48 | 539.71 | 27.408% | 203.77 | | 1k | 4k | 1325.34 | 1038.59 | 21.636% | 286.75 | | 2k | 0.5k | 686.01 | 147.34 | 78.522% | 538.67 | | 2k | 1k | 762.96 | 246.22 | 67.728% | 516.74 | | 2k | 2k | 1083.93 | 498.05 | 54.051% | 585.88 | | 2k | 4k | 1435.39 | 1053.31 | 26.619% | 382.08 | - On H800 (2 GPUs) | mem tks | prompt tks | TTFT (without cache, ms) | TTFT (With cache, ms) | TTFT Speedup (%) | Abs Dis(ms) | | --- | --- | --- | --- | --- | --- | | 0.5k | 0.5k | 161.18 | 97.61 | 39.440% | 63.57 | | 0.5k | 1k | 164.00 | 121.39 | 25.982% | 42.61 | | 0.5k | 2k | 257.34 | 215.20 | 16.375% | 42.14 | | 0.5k | 4k | 365.14 | 317.95 | 12.924% | 47.19 | | 1k | 0.5k | 169.45 | 100.52 | 40.679% | 68.93 | | 1k | 1k | 180.91 | 128.25 | 29.108% | 52.66 | | 1k | 2k | 271.69 | 210.00 | 22.706% | 61.69 | | 1k | 4k | 389.30 | 314.64 | 19.178% | 74.66 | | 2k | 0.5k | 251.43 | 130.92 | 47.930% | 120.51 | | 2k | 1k | 275.81 | 159.60 | 42.134% | 116.21 | | 2k | 2k | 331.11 | 218.17 | 34.110% | 112.94 | | 2k | 4k | 451.06 | 334.80 | 25.775% | 116.26 | The results clearly demonstrate that integrating vLLM's KV Cache reuse provides a transformative performance improvement for MemOS. ## KV-cache Memory Structure KV-based memory reuse via `KVCacheMemory` offers substantial latency reduction across model sizes and query types, while maintaining identical output. By shifting reusable memory from plaintext prompts into precomputed KV caches, MemOS eliminates redundant context encoding and achieves faster response times—especially beneficial in real-time, memory-augmented LLM applications. Each cache is stored as a `KVCacheItem`: | Field | Type | Description | | ------------- | -------------- | ------------------------------------------- | | `kv_cache_id` | `str` | Unique ID for the cache (UUID) | | `kv_cache` | `DynamicCache` | The actual key-value cache (transformers) | | `metadata` | `dict` | Metadata (source, extraction time, etc.) | ## API Summary (`KVCacheMemory`) ### Initialization ```python KVCacheMemory(config: KVCacheMemoryConfig) ``` ### Core Methods | Method | Description | | ------------------------ | -------------------------------------------------------- | | `extract(text)` | Extracts a KV cache from input text using the LLM | | `add(memories)` | Adds one or more `KVCacheItem` to memory | | `get(memory_id)` | Fetch a single cache by ID | | `get_by_ids(ids)` | Fetch multiple caches by IDs | | `get_all()` | Returns all stored caches | | `get_cache(cache_ids)` | Merge and return a combined cache from multiple IDs | | `delete(ids)` | Delete caches by IDs | | `delete_all()` | Delete all caches | | `dump(dir)` | Serialize all caches to a pickle file in directory | | `load(dir)` | Load caches from a pickle file in directory | | `from_textual_memory(mem)` | Convert a `TextualMemoryItem` to a `KVCacheItem` | | `build_vllm_kv_cache( messages)` | Build a vLLM KV cache from a list of messages | When calling `dump(dir)`, the system writes to: ``` / ``` This file contains a pickled dictionary of all KV caches, which can be reloaded using `load(dir)`. ## How to Use ```python from memos.configs.memory import KVCacheMemoryConfig from memos.memories.activation.kv import KVCacheMemory config = KVCacheMemoryConfig( extractor_llm={ "backend": "huggingface", "config": {"model_name_or_path": "Qwen/Qwen3-1.7B"} } ) mem = KVCacheMemory(config) # Extract and add a cache cache_item = mem.extract("The capital of France is Paris.") mem.add([cache_item]) # Retrieve and merge caches merged_cache = mem.get_cache([cache_item.kv_cache_id]) # Save/load mem.dump("tmp/act_mem") mem.load("tmp/act_mem") ``` ## Developer Notes * Uses HuggingFace `DynamicCache` for efficient key-value storage * Pickle-based serialization for fast load/save * All methods are covered by integration tests in `/tests` --- # Parametric Memory *(Coming Soon)* (/open_source/modules/memories/parametric_memory) > **Note**: **Coming Soon** > This feature is still under active development. Stay tuned for updates! `Parametric Memory` is the core **long-term knowledge and capability store** inside MemOS. Unlike plaintext or activation memories, parametric memory is embedded directly within a model’s weights — encoding deep representations of language structure, world knowledge, and general reasoning abilities. In the MemOS architecture, parametric memory does not just refer to static pre-trained weights. It also includes modular weight components such as **LoRA adapters** and plug-in expert modules. These allow you to incrementally expand or specialize your LLM’s capabilities without retraining the entire model. For example, you could distill structured or stable knowledge into parametric form, save it as a **capability block**, and dynamically load or unload it during inference. This makes it easy to create “expert sub-models” for tasks like legal reasoning, financial analysis, or domain-specific summarization — all managed by MemOS. ## Design Goals - **Controllability** — Generate, load, swap, or compose parametric modules on demand. - **Plasticity** — Evolve alongside plaintext and activation memories; support knowledge distillation and rollback. - **Traceability** *(Coming Soon)* — Versioning and governance for parametric blocks. ## Current Status `Parametric Memory` is currently under design and prototyping. APIs for generating, compressing, and hot-swapping parametric modules will be released in future versions — supporting multi-task, multi-role, and multi-agent architectures. Stay tuned! ## Related Modules While parametric memory is under development, try out these today: - **[GeneralTextMemory](/open_source/modules/memories/general_textual_memory)**: Flexible vector-based semantic storage. - **[TreeTextMemory](/open_source/modules/memories/tree_textual_memory)**: Structured, hierarchical knowledge graphs. - **[Activation Memory](/open_source/modules/memories/kv_cache_memory)**: Efficient runtime state caching. ## Developer Note Parametric Memory will complete MemOS’s vision of a unified **Memory³** architecture: - **Parametric**: Embedded knowledge - **Activation**: Ephemeral runtime states - **Plaintext**: Structured, traceable external memories Bringing all three together enables adaptable, evolvable, and explainable intelligent systems. --- # NaiveTextMemory: Simple Plain Text Memory (/open_source/modules/memories/naive_textual_memory) Let's get started with the MemOS memory system in the simplest way possible! NaiveTextMemory is a lightweight, memory-based, plain-text memory module. It stores memories in an in-memory list and retrieves them using keyword matching. It is the perfect starting point for learning MemOS, as well as an ideal choice for demos, testing, and small-scale applications. ## Table of Contents - [What You'll Learn](#what-youll-learn) - [Why Choose NaiveTextMemory](#why-choose-naivetextmemory) - [Core Concepts](#core-concepts) - [Memory Structure](#memory-structure) - [Metadata Fields](#metadata-fields-textualmemorymetadata) - [Search Mechanism](#search-mechanism) - [API Reference](#api-reference) - [Initialization](#initialization) - [Core Methods](#core-methods) - [Configuration Parameters](#configuration-parameters) - [Hands-On Practice](#hands-on-practice) - [Quick Start](#quick-start) - [Complete Example](#complete-example) - [File Storage](#file-storage) - [Use Case Guide](#use-case-guide) - [Comparison with Other Memory Modules](#comparison-with-other-memory-modules) - [Best Practices](#best-practices) - [Next Steps](#next-steps) ## What You'll Learn By the end of this guide, you will be able to: - Automatically extract structured memories from conversations using LLM - Store and manage memories in memory (no database required) - Search memories using keyword matching - Persist and restore memory data - Understand when to use NaiveTextMemory and when to upgrade to other modules ## Why Choose NaiveTextMemory ### Key Advantages - **Zero Dependencies**: No vector database or embedding model required - **Fast Startup**: Up and running in just a few lines of code - **Lightweight & Efficient**: Low resource footprint, fast execution - **Simple & Intuitive**: Keyword matching with predictable results - **Easy to Debug**: All memories in memory, easy to inspect - **Perfect Starting Point**: The best entry point for learning MemOS ### Suitable Scenarios - Rapid prototyping and proof of concept - Simple conversational agents (< 1000 memories) - Testing and demo scenarios - Resource-constrained environments (cannot run embedding models) - Keyword search scenarios (queries directly match memories) > **Note**: **Performance Tip** > When memory count exceeds 1000, it's recommended to upgrade to [GeneralTextMemory](/open_source/modules/memories/general_textual_memory), which uses vector search for better performance. ## Core Concepts ### Memory Structure Each memory is represented as a `TextualMemoryItem` object with the following fields: | Field | Type | Required | Description | | ---------- | --------------------------- | -------- | ------------------------------------ | | `id` | `str` | ✗ | Unique identifier (auto-generated UUID) | | `memory` | `str` | ✓ | Main text content of the memory | | `metadata` | `TextualMemoryMetadata` | ✗ | Metadata (for categorization, filtering, and retrieval) | ### Metadata Fields (`TextualMemoryMetadata`) Metadata provides rich contextual information for categorization, filtering, and organizing memories: | Field | Type | Default | Description | | ------------- | -------------------------------------------------- | ---------- | ---------------------------------- | | `type` | `"procedure"` / `"fact"` / `"event"` / `"opinion"` | `"fact"` | Memory type classification | | `memory_time` | `str (YYYY-MM-DD)` | Current date | Time associated with the memory | | `source` | `"conversation"` / `"retrieved"` / `"web"` / `"file"` | - | Source of the memory | | `confidence` | `float (0-100)` | 80.0 | Certainty/confidence score | | `entities` | `list[str]` | `[]` | Mentioned entities or concepts | | `tags` | `list[str]` | `[]` | Topic tags | | `visibility` | `"private"` / `"public"` / `"session"` | `"private"` | Access control scope | | `updated_at` | `str` | Auto-generated | Last update timestamp (ISO 8601) | ## API Reference ### Initialization ```python from memos.memories.textual.naive import NaiveTextMemory from memos.configs.memory import NaiveTextMemoryConfig memory = NaiveTextMemory(config: NaiveTextMemoryConfig) ``` ### Core Methods | Method | Parameters | Returns | Description | | ------------------------ | ------------------------------------- | ----------------------------- | --------------------------------------------- | | `extract(messages)` | `messages: list[dict]` | `list[TextualMemoryItem]` | Extract structured memories from conversation using LLM | | `add(memories)` | `memories: list / dict / Item` | `None` | Add one or more memories | | `search(query, top_k)` | `query: str, top_k: int` | `list[TextualMemoryItem]` | Retrieve top-k memories using keyword matching | | `get(memory_id)` | `memory_id: str` | `TextualMemoryItem` | Get a single memory by ID | | `get_by_ids(ids)` | `ids: list[str]` | `list[TextualMemoryItem]` | Batch retrieve memories by ID list | | `get_all()` | - | `list[TextualMemoryItem]` | Return all memories | | `update(memory_id, new)` | `memory_id: str, new: dict` | `None` | Update content or metadata of specified memory | | `delete(ids)` | `ids: list[str]` | `None` | Delete one or more memories | | `delete_all()` | - | `None` | Clear all memories | | `dump(dir)` | `dir: str` | `None` | Serialize memories to JSON file | | `load(dir)` | `dir: str` | `None` | Load memories from JSON file | ### Search Mechanism Unlike `GeneralTextMemory`'s vector semantic search, `NaiveTextMemory` uses a **keyword matching algorithm**: #### Step 1: Tokenization Break down the query and each memory content into lists of tokens #### Step 2: Calculate Match Score Count the number of overlapping tokens between query and memory #### Step 3: Sort Sort all memories by match count in descending order #### Step 4: Return Results Return the top-k memories as search results > **Note**: **Example Comparison** > Query: "cat" > - **Keyword Matching**: Only matches memories containing "cat" > - **Semantic Search**: Also matches memories about "pet", "kitten", "feline", etc. ### Configuration Parameters **NaiveTextMemoryConfig** | Parameter | Type | Required | Default | Description | | ------------------ | ---------------------- | -------- | ---------------------- | ---------------------------------------------- | | `extractor_llm` | `LLMConfigFactory` | ✓ | - | LLM configuration for extracting memories from conversations | | `memory_filename` | `str` | ✗ | `textual_memory.json` | Filename for persistent storage | **Configuration Example** ```json { "backend": "naive_text", "config": { "extractor_llm": { "backend": "openai", "config": { "model_name_or_path": "gpt-4o-mini", "temperature": 0.8, "max_tokens": 1024, "api_base": "xxx", "api_key": "sk-xxx" } }, "memory_filename": "my_memories.json" } } ``` ## Hands-On Practice ### Quick Start Get started with NaiveTextMemory in just 3 steps: #### Step 1: Create Configuration ```python from memos.configs.memory import MemoryConfigFactory config = MemoryConfigFactory( backend="naive_text", config={ "extractor_llm": { "backend": "openai", "config": { "model_name_or_path": "gpt-4o-mini", "api_key": "your-api-key", "api_base": "your-api-base" }, }, }, ) ``` #### Step 2: Initialize Memory Module ```python from memos.memories.factory import MemoryFactory memory = MemoryFactory.from_config(config) ``` #### Step 3: Extract and Add Memories ```python # Automatically extract memories from conversation memories = memory.extract([ {"role": "user", "content": "I love tomatoes."}, {"role": "assistant", "content": "Great! Tomatoes are delicious."}, ]) # Add to memory store memory.add(memories) print(f"✓ Added {len(memories)} memories") ``` > **Note**: **Advanced: Using MultiModal Reader** > If you need to process multimodal content such as images, URLs, or files, use `MultiModalStructMemReader`. > View complete example: [Using MultiModalStructMemReader (Advanced)](./tree_textual_memory#using-multimodalstructmemreader-advanced) ### Complete Example Here's a complete end-to-end example demonstrating all core functionality: ```python from memos.configs.memory import MemoryConfigFactory from memos.memories.factory import MemoryFactory # ======================================== # 1. Initialization # ======================================== config = MemoryConfigFactory( backend="naive_text", config={ "extractor_llm": { "backend": "openai", "config": { "model_name_or_path": "gpt-4o-mini", "api_key": "your-api-key", }, }, }, ) memory = MemoryFactory.from_config(config) # ======================================== # 2. Extract and Add Memories # ======================================== memories = memory.extract([ {"role": "user", "content": "I love tomatoes."}, {"role": "assistant", "content": "Great! Tomatoes are delicious."}, ]) memory.add(memories) print(f"✓ Added {len(memories)} memories") # ======================================== # 3. Search Memories # ======================================== results = memory.search("tomatoes", top_k=2) print(f"\n🔍 Found {len(results)} relevant memories:") for i, item in enumerate(results, 1): print(f" {i}. {item.memory}") # ======================================== # 4. Get All Memories # ======================================== all_memories = memory.get_all() print(f"\n📊 Total {len(all_memories)} memories") # ======================================== # 5. Update Memory # ======================================== if memories: memory_id = memories[0].id memory.update( memory_id, { "memory": "User loves tomatoes.", "metadata": {"type": "opinion", "confidence": 95.0} } ) print(f"\n✓ Updated memory: {memory_id}") # ======================================== # 6. Persist to Storage # ======================================== memory.dump("tmp/mem") print("\n💾 Memories saved to tmp/mem/textual_memory.json") # ======================================== # 7. Load Memories # ======================================== memory.load("tmp/mem") print("✓ Memories loaded from file") # ======================================== # 8. Delete Memories # ======================================== if memories: memory.delete([memories[0].id]) print(f"\n🗑️ Deleted 1 memory") # Delete all memories # memory.delete_all() ``` > **Note**: **Extension: Internet Retrieval** > NaiveTextMemory focuses on local memory management. For retrieving information from the internet and adding it to your memory store, see: > [Retrieve Memories from the Internet (Optional)](./tree_textual_memory#retrieve-memories-from-the-internet-optional) ### File Storage When calling `dump(dir)`, the system saves memories to: ``` / ``` **Default File Structure** ```json [ { "id": "550e8400-e29b-41d4-a716-446655440000", "memory": "User loves tomatoes.", "metadata": { "type": "opinion", "confidence": 95.0, "entities": ["user", "tomatoes"], "tags": ["food", "preference"], "updated_at": "2026-01-14T10:30:00Z" } }, ... ] ``` Use `load(dir)` to fully restore all memory data. > **Note**: **Important Note** > Memories are stored in memory and will be lost after process restart. Remember to call `dump()` regularly to save data! ## Use Case Guide ### Best Suited For - **Rapid Prototyping**: No need to configure vector databases, get started in minutes - **Simple Conversational Agents**: Small-scale applications with < 1000 memories - **Testing and Demos**: Quickly validate memory extraction and retrieval logic - **Resource-Constrained Environments**: Scenarios where embedding models or vector databases cannot run - **Keyword Search**: Scenarios where query content directly matches memory text - **Learning and Teaching**: The best starting point for understanding MemOS memory system ### Not Recommended For - **Large-Scale Applications**: More than 10,000 memories (search performance degrades) - **Semantic Search Needs**: Need to understand synonyms (e.g., "cat" and "pet") - **Production Environments**: Strict performance and accuracy requirements - **Multilingual Scenarios**: Need cross-language semantic understanding - **Complex Relationship Reasoning**: Need to understand relationships between memories > **Alert**: **Upgrade Path** > For the scenarios not recommended above, consider upgrading to: > - [GeneralTextMemory](/open_source/modules/memories/general_textual_memory) - Vector semantic search, suitable for 10K-100K memories > - [TreeTextMemory](/open_source/modules/memories/tree_textual_memory) - Graph structure storage, supports relationship reasoning and multi-hop queries ## Comparison with Other Memory Modules Choosing the right memory module is crucial for project success. This comparison helps you make the decision: | Feature | **NaiveTextMemory** | **GeneralTextMemory** | **TreeTextMemory** | | ------------------ | --------------------- | -------------------------- | --------------------------- | | **Search Method** | Keyword matching | Vector semantic search | Graph structure + vector search | | **Dependencies** | LLM only | LLM + Embedder + Vector DB | LLM + Embedder + Graph DB | | **Suitable Scale** | < 1K | 1K - 100K | 10K - 1M | | **Query Complexity** | O(n) linear scan | O(log n) approximate NN | O(log n) + graph traversal | | **Semantic Understanding** | ❌ | ✅ | ✅ | | **Relationship Reasoning** | ❌ | ❌ | ✅ | | **Multi-Hop Queries** | ❌ | ❌ | ✅ | | **Storage Backend** | In-memory list | Vector DB (Qdrant, etc.) | Graph DB (Neo4j/PolarDB) | | **Configuration Complexity** | Low ⭐ | Medium ⭐⭐ | High ⭐⭐⭐ | | **Learning Curve** | Minimal | Moderate | Steep | | **Production Ready** | ❌ Prototype/demo only | ✅ Suitable for most cases | ✅ Suitable for complex apps | > **Alert**: **Selection Guide** > - **Just getting started?** → Start with NaiveTextMemory > - **Need semantic search?** → Use GeneralTextMemory > - **Need relationship reasoning?** → Choose TreeTextMemory ## Best Practices Follow these recommendations to make the most of NaiveTextMemory: ### 1. Persist Data Regularly ```python # Save immediately after critical operations memory.add(new_memories) memory.dump("tmp/mem") # ✓ Persist immediately # Regular automatic backups import schedule schedule.every(10).minutes.do(lambda: memory.dump("tmp/mem")) ``` ### 2. Control Memory Scale ```python # Regularly clean old memories if len(memory.get_all()) > 1000: old_memories = sorted( memory.get_all(), key=lambda m: m.metadata.updated_at )[:100] # Oldest 100 memory.delete([m.id for m in old_memories]) print("✓ Cleaned 100 old memories") ``` ### 3. Optimize Search Queries ```python # ❌ Poor: Vague query results = memory.search("thing", top_k=5) # ✅ Good: Use specific keywords results = memory.search("tomato", top_k=5) ``` ### 4. Use Metadata Wisely ```python # Set clear metadata when adding memories memory.add({ "memory": "User prefers dark mode", "metadata": { "type": "opinion", # ✓ Clear classification "tags": ["UI", "preference"], # ✓ Easy filtering "confidence": 90.0, # ✓ Mark confidence "entities": ["user", "dark mode"] # ✓ Entity annotation } }) ``` ### 5. Plan Upgrade Path ```python # Monitor memory count and upgrade timely memory_count = len(memory.get_all()) if memory_count > 800: print("⚠️ Memory count approaching limit, consider upgrading to GeneralTextMemory") # Migration code reference: # 1. Export existing memories: memory.dump("backup") # 2. Create GeneralTextMemory configuration # 3. Import memories to new module ``` ## Next Steps Congratulations! You've mastered the core usage of NaiveTextMemory. Next, you can: - **Upgrade to Vector Search**: Learn about [GeneralTextMemory](/open_source/modules/memories/general_textual_memory)'s semantic retrieval capabilities - **Explore Graph Structure**: Understand [TreeTextMemory](/open_source/modules/memories/tree_textual_memory)'s relationship reasoning features - **Integrate into Applications**: Check [Complete API Documentation](/api-reference/search-memories) to build production-grade applications - **Run Example Code**: Browse the `/examples/` directory for more practical cases - **Learn Graph Databases**: If you need advanced features, learn about [Neo4j](/open_source/modules/memories/neo4j_graph_db) or [PolarDB](/open_source/modules/memories/polardb_graph_db) > **Alert**: **Tip** > NaiveTextMemory is the perfect starting point for learning MemOS. When your application needs more powerful features, you can seamlessly migrate to other memory modules! --- # GeneralTextMemory: General-Purpose Textual Memory (/open_source/modules/memories/general_textual_memory) ## Table of Contents - [Memory Structure](#memory-structure) - [Metadata Fields (`TextualMemoryMetadata`)](#metadata-fields-textualmemorymetadata) - [API Summary (`GeneralTextMemory`)](#api-summary-generaltextmemory) - [Initialization](#initialization) - [Core Methods](#core-methods) - [File Storage](#file-storage) - [Example Usage](#example-usage) - [Extension: Internet Retrieval](#extension-internet-retrieval) - [Advanced: Using MultiModal Reader](#advanced-using-multimodal-reader) - [Developer Notes](#developer-notes) ## Memory Structure Each memory is represented as a `TextualMemoryItem`: | Field | Type | Description | | ---------- | --------------------------- | ---------------------------------- | | `id` | `str` | UUID (auto-generated if omitted) | | `memory` | `str` | The main memory content (required) | | `metadata` | `TextualMemoryMetadata` | Metadata for search/filtering | ### Metadata Fields (`TextualMemoryMetadata`) | Field | Type | Description | | ------------- | -------------------------------------------------- | ----------------------------------- | | `type` | `"procedure"`, `"fact"`, `"event"`, `"opinion"` | Memory type | | `memory_time` | `str (YYYY-MM-DD)` | Date/time the memory refers to | | `source` | `"conversation"`, `"retrieved"`, `"web"`, `"file"` | Source of the memory | | `confidence` | `float (0-100)` | Certainty/confidence score | | `entities` | `list[str]` | Key entities/concepts | | `tags` | `list[str]` | Thematic tags | | `visibility` | `"private"`, `"public"`, `"session"` | Access scope | | `updated_at` | `str` | Last update timestamp (ISO 8601) | All values are validated. Invalid values will raise errors. ### Search Mechanism Unlike NaiveTextMemory, which relies on keyword matching, GeneralTextMemory utilizes vector-based semantic search. ## Algorithm Comparison | Feature | Keyword Matching | Vector Semantic Search | | ------------------ | ---------------------------------- | ------------------------------------------ | | **Semantic Understanding** | ❌ Doesn't understand synonyms | ✅ Understands similar concepts | | **Resource Usage** | ✅ Extremely low | ⚠️ Requires embedding model and vector DB | | **Execution Speed** | ✅ Fast (O(n)) | ⚠️ Slower (indexing + querying) | | **Suitable Scale** | < 1K memories | 10K - 100K memories | | **Predictability** | ✅ Intuitive results | ⚠️ Black box model ## API Summary (`GeneralTextMemory`) ### Initialization ```python GeneralTextMemory(config: GeneralTextMemoryConfig) ``` ### Core Methods | Method | Description | | ------------------------ | --------------------------------------------------- | | `extract(messages)` | Extracts memories from message list (LLM-based) | | `add(memories)` | Adds one or more memories (items or dicts) | | `search(query, top_k)` | Retrieves top-k memories using vector similarity | | `get(memory_id)` | Fetch single memory by ID | | `get_by_ids(ids)` | Fetch multiple memories by IDs | | `get_all()` | Returns all memories | | `update(memory_id, new)` | Update a memory by ID | | `delete(ids)` | Delete memories by IDs | | `delete_all()` | Delete all memories | | `dump(dir)` | Serialize all memories to JSON file in directory | | `load(dir)` | Load memories from saved file | ## File Storage When calling `dump(dir)`, the system stores the memories to: ``` / ``` This file contains a JSON list of all memory items, which can be reloaded using `load(dir)`. ## Example Usage ```python import os from memos.configs.memory import MemoryConfigFactory from memos.memories.factory import MemoryFactory config = MemoryConfigFactory( backend="general_text", config={ "extractor_llm": { ... }, "vector_db": { ... }, "embedder": { ... }, }, ) m = MemoryFactory.from_config(config) # Extract and add memories memories = m.extract([ {"role": "user", "content": "I love tomatoes."}, {"role": "assistant", "content": "Great! Tomatoes are delicious."}, ]) m.add(memories) # Search results = m.search("Tell me more about the user", top_k=2) # Update m.update(memory_id, {"memory": "User is Canadian.", ...}) # Delete m.delete([memory_id]) # Dump/load m.dump("tmp/mem") m.load("tmp/mem") ``` > **Note**: **Extension: Internet Retrieval** > GeneralTextMemory can be combined with Internet Retrieval to extract content from web pages and add to memory. > View example: [Retrieve Memories from the Internet](./tree_textual_memory#retrieve-memories-from-the-internet-optional) > **Note**: **Advanced: Using MultiModal Reader** > For processing images, URLs, or files within conversations, see the comprehensive MultiModal Reader examples. > View documentation: [Using MultiModalStructMemReader](./tree_textual_memory#using-multimodalstructmemreader-advanced) ## Developer Notes * Uses Qdrant (or compatible) vector DB for fast similarity search * Embedding and extraction models are configurable (Ollama/OpenAI supported) * All methods are covered by integration tests in `/tests` --- # PreferenceTextMemory: Textual Memory for User Preferences (/open_source/modules/memories/preference_textual_memory) ## Table of Contents - [Why Preference Memory is Needed](#why-preference-memory-is-needed) - [Key Features](#key-features) - [Application Scenarios](#application-scenarios) - [Core Concepts and Workflow](#core-concepts-and-workflow) - [Memory Structure](#memory-structure) - [Metadata Fields (`PreferenceTextualMemoryMetadata`)](#metadata-fields-preferencetextualmemorymetadata) - [Core Workflow](#core-workflow) - [API Reference](#api-reference) - [Initialization](#initialization) - [Core Methods](#core-methods) - [File Storage](#file-storage) - [Hands-on Practice: From Zero to One](#hands-on-practice-from-zero-to-one) - [Create PreferenceTextMemory Configuration](#create-preferencetextmemory-configuration) - [Initialize PreferenceTextMemory](#initialize-preferencetextmemory) - [Extract Structured Memory](#extract-structured-memory) - [Search Memory](#search-memory) - [Backup and Restore](#backup-and-restore) - [Complete Code Example](#complete-code-example) ## Why Preference Memory is Needed ### Key Features - **Dual Preference Extraction**: Automatically identifies explicit and implicit preferences - **Semantic Understanding**: Uses vector embeddings to understand the deep meaning of preferences - **Smart Deduplication**: Automatically detects and merges duplicate or conflicting preferences - **Precise Retrieval**: Semantic search based on vector similarity - **Persistent Storage**: Supports vector databases (Qdrant/Milvus) - **Scalability**: Supports large-scale preference data management - **Personalization Enhancement**: Maintains independent preference profiles for each user ### Application Scenarios - Personalized conversational agents (remembering user likes/dislikes) - Intelligent recommendation systems (recommendations based on preferences) - Customer service systems (providing customized services) - Content filtering systems (filtering content based on preferences) - Learning assistance systems (adapting to learning styles) In conclusion, when you need to build systems that can "remember" user preferences and provide personalized services accordingly, `PreferenceTextMemory` is the best choice. ## Core Concepts and Workflow ### Memory Structure In MemOS, preference memory is represented by `PreferenceTextMemory`, where each memory item is a `TextualMemoryItem` stored in Milvus database. - `id`: Unique memory ID (automatically generated if omitted) - `memory`: Main text content - `metadata`: Includes hierarchical structure information, embeddings, tags, entities, sources, and status Preference memory can be divided into explicit preference memory and implicit preference memory: - **Explicit Preference Memory**: Preferences that users explicitly express. **Examples**: - "I like dark mode" - "I don't eat spicy food" - "Please use short answers" - "I prefer technical documentation over video tutorials" - **Implicit Preference Memory**: Preferences inferred from user behavior and conversation patterns. **Examples**: - User always asks for code examples → prefers practice-oriented learning - User frequently requests detailed explanations → prefers in-depth understanding - User mentions environmental topics multiple times → concerned about sustainable development > **Note**: **Intelligent Extraction** > `PreferenceTextMemory` automatically extracts both explicit and implicit preferences from conversations using LLM, no manual annotation required! ### Metadata Fields (`PreferenceTextualMemoryMetadata`) | Field | Type | Description | | ------------- | -------------------------------------------------- | ----------------------------------- | | `preference_type` | `"explicit_preference"`, `"implicit_preference"` | Preference memory type, divided into explicit and implicit preference memory | | `dialog_id` | `str` | Dialog ID, used to associate preference memory with specific dialogs | | `original_text` | `str` | Original text containing user preference information | | `embedding` | `str` | Embedding vector for semantic search and retrieval | | `preference` | `str` | User preference information | | `create_at` | `str` | Creation timestamp (ISO 8601) | | `mem_cube_id` | `str` | Memory cube ID, used to associate preference memory with specific memory cubes | | `score` | `float ` | Similarity score between preference memory and query in search results | ### Core Workflow When you run this example, your workflow will: 1. **Extraction:** Use LLM to extract structured memory from raw text. 2. **Embedding:** Generate vector embeddings for similarity search. 3. **Storage:** Store preference memory in Milvus database while updating metadata fields. 4. **Search:** Return the most relevant preference memories through vector similarity queries. ## API Reference ### Initialization ```python PreferenceTextMemory(config: PreferenceTextMemoryConfig) ``` ### Core Methods | Method | Description | | --------------------------- | ----------------------------------------------------- | | `get_memory(messages)` | Extract preference memories from original dialogues. | | `search(query, top_k)` | Retrieve top-k preference memories using vector similarity. | | `load(dir)` | Load preference memories from stored files. | | `dump(dir)` | Serialize all preference memories to JSON files in the directory. | | `add(memories)` | Batch add preference memories to Milvus database. | | `get_with_collection_name(collection_name, memory_id)` | Get specific type of preference memory by collection name and memory ID. | | `get_by_ids_with_collection_name(collection_name, memory_ids)` | Batch get specific type of preference memory by collection name and memory IDs. | | `get_all()` | Get all preference memories. | | `get_memory_by_filter(filter)` | Get preference memories based on filter conditions. | | `delete(memory_ids)` | Delete preference memories by specified IDs. | | `delete_by_filter(filter)` | Delete preference memories based on filter conditions. | | `delete_with_collection_name(collection_name, memory_ids)` | Delete all preference memories with specified collection name and IDs. | | `delete_all()` | Delete all preference memories. | ### File Storage When calling `dump(dir)`, MemOS will serialize all preference memories to JSON files in the directory: ``` / ``` --- ## Hands-on Practice: From Zero to One ### Create PreferenceTextMemory Configuration Define: - Your embedding model (e.g., nomic-embed-text:latest), - Your Milvus database backend, - Memory extractor (based on LLM) (optional). ```python from memos.configs.memory import PreferenceTextMemoryConfig config = PreferenceTextMemoryConfig.from_json_file("examples/data/config/preference_config.json") ``` ### Initialize PreferenceTextMemory ```python from memos.memories.textual.preference import PreferenceTextMemory preference_memory = PreferenceTextMemory(config) ``` ### Extract Structured Memory Use the memory extractor to parse dialogues, files, or documents into multiple `TextualMemoryItem`. ```python scene_data = [[ {"role": "user", "content": "Tell me about your childhood."}, {"role": "assistant", "content": "I loved playing in the garden with my dog."} ]] memories = preference_memory.get_memory(scene_data, type="chat", info={"user_id": "1234"}) preference_memory.add(memories) ``` ### Search Memory ```python results = preference_memory.search("Tell me more about the user", top_k=2) ``` ### Backup and Restore Support persistent storage and on-demand reloading of preference memories: ```python preference_memory.dump("tmp/pref_memories") preference_memory.load("tmp/pref_memories") ``` ### Complete Code Example This example integrates all the above steps, providing an end-to-end complete workflow — copy and run! ```python from memos.configs.memory import PreferenceTextMemoryConfig from memos.memories.textual.preference import PreferenceTextMemory # Create PreferenceTextMemory config = PreferenceTextMemoryConfig.from_json_file("examples/data/config/preference_config.json") preference_memory = PreferenceTextMemory(config) preference_memory.delete_all() scene_data = [[ {"role": "user", "content": "Tell me about your childhood."}, {"role": "assistant", "content": "I loved playing in the garden with my dog."} ]] # Extract preference memories from original dialogues and add to Milvus database memories = preference_memory.get_memory(scene_data, type="chat", info={"user_id": "1234"}) preference_memory.add(memories) # Search memory results = preference_memory.search("Tell me more about the user", top_k=2) # Persist preference memories preference_memory.dump("tmp/pref_memories") ``` --- # TreeTextMemory: Structured Hierarchical Textual Memory (/open_source/modules/memories/tree_textual_memory) ## Table of Contents - [What You’ll Learn](#what-youll-learn) - [Core Concepts and Workflow](#core-concepts-and-workflow) - [Memory Structure](#memory-structure) - [Metadata Fields](#metadata-fields-treenodetextualmemorymetadata) - [Core Workflow](#core-workflow) - [API Reference](#api-reference) - [Hands-on: From 0 to 1](#hands-on-from-0-to-1) - [Create TreeTextMemory Config](#create-treetextmemory-config) - [Initialize TreeTextMemory](#initialize-treetextmemory) - [Extract Structured Memories](#extract-structured-memories) - [Search Memories](#search-memories) - [Retrieve Memories from the Internet (Optional)](#retrieve-memories-from-the-internet-optional) - [Replace Working Memory](#replace-working-memory) - [Backup & Restore](#backup--restore) - [Full Code Example](#full-code-example) - [Why Choose TreeTextMemory](#why-choose-treetextmemory) - [What’s Next](#whats-next) ## What You’ll Learn By the end of this guide, you will: - Extract structured memories from raw text or conversations. - Store them as **nodes** in a graph database. - Link memories into **hierarchies** and semantic graphs. - Search them using **vector similarity + graph traversal**. ## Core Concepts and Workflow ### Memory Structure Every node in your `TreeTextMemory` is a `TextualMemoryItem`: - `id`: Unique memory ID (auto-generated if omitted). - `memory`: the main text. - `metadata`: includes hierarchy info, embeddings, tags, entities, source, and status. ### Metadata Fields (`TreeNodeTextualMemoryMetadata`) | Field | Type | Description | | --------------- |-------------------------------------------------------| ------------------------------------------ | | `memory_type` | `"WorkingMemory"`, `"LongTermMemory"`, `"UserMemory"` | Lifecycle category | | `status` | `"activated"`, `"archived"`, `"deleted"` | Node status | | `visibility` | `"private"`, `"public"`, `"session"` | Access scope | | `sources` | `list[str]` | List of sources (e.g. files, URLs) | | `source` | `"conversation"`, `"retrieved"`, `"web"`, `"file"` | Original source type | | `confidence` | `float (0-100)` | Certainty score | | `entities` | `list[str]` | Mentioned entities or concepts | | `tags` | `list[str]` | Thematic tags | | `embedding` | `list[float]` | Vector embedding for similarity search | | `created_at` | `str` | Creation timestamp (ISO 8601) | | `updated_at` | `str` | Last update timestamp (ISO 8601) | | `usage` | `list[str]` | Usage history | | `background` | `str` | Additional context | > **Note**: **Best Practice** > Use meaningful tags and background — they help organize your graph for > multi-hop reasoning. ### Core Workflow When you run this example, your workflow will: 1. **Extract:** Use an LLM to pull structured memories from raw text. 2. **Embed:** Generate vector embeddings for similarity search. 3. **Store & Link:** Add nodes to your graph database (Neo4j) with relationships. 4. **Search:** Query by vector similarity, then expand results by graph hops. > **Note**: **Hint** Graph links help retrieve context that pure vector search might miss! ## API Reference ### Initialization ```python TreeTextMemory(config: TreeTextMemoryConfig) ``` ### Core Methods | Method | Description | | --------------------------- | ----------------------------------------------------- | | `add(memories)` | Add one or more memories (items or dicts) | | `replace_working_memory()` | Replace all WorkingMemory nodes | | `get_working_memory()` | Get all WorkingMemory nodes | | `search(query, top_k)` | Retrieve top-k memories using vector + graph search | | `get(memory_id)` | Fetch single memory by ID | | `get_by_ids(ids)` | Fetch multiple memories by IDs | | `get_all()` | Export the full memory graph as dictionary | | `update(memory_id, new)` | Update a memory by ID | | `delete(ids)` | Delete memories by IDs | | `delete_all()` | Delete all memories and relationships | | `dump(dir)` | Serialize the graph to JSON in directory | | `load(dir)` | Load graph from saved JSON file | | `drop(keep_last_n)` | Backup graph & drop database, keeping N backups | ### File Storage When calling `dump(dir)`, the system writes to: ``` / ``` This file contains a JSON structure with `nodes` and `edges`. It can be reloaded using `load(dir)`. --- ## Hands-on: From 0 to 1 ### Create TreeTextMemory Config Define: - your embedder (to create vectors), - your graph DB backend (Neo4j), - and your extractor LLM (optional). ```python from memos.configs.memory import TreeTextMemoryConfig config = TreeTextMemoryConfig.from_json_file("examples/data/config/tree_config.json") ``` ### Initialize TreeTextMemory ```python from memos.memories.textual.tree import TreeTextMemory tree_memory = TreeTextMemory(config) ``` ### Extract Structured Memories Use your extractor to parse conversations, files, or docs into `TextualMemoryItem`s. ```python from memos.mem_reader.simple_struct import SimpleStructMemReader reader = SimpleStructMemReader.from_json_file("examples/data/config/simple_struct_reader_config.json") scene_data = [[ {"role": "user", "content": "Tell me about your childhood."}, {"role": "assistant", "content": "I loved playing in the garden with my dog."} ]] memories = reader.get_memory(scene_data, type="chat", info={"user_id": "1234"}) for m_list in memories: tree_memory.add(m_list) ``` #### Using MultiModalStructMemReader (Advanced) `MultiModalStructMemReader` supports processing multimodal content (text, images, URLs, files, etc.) and intelligently routes to different parsers: ```python from memos.configs.mem_reader import MultiModalStructMemReaderConfig from memos.mem_reader.multi_modal_struct import MultiModalStructMemReader # Create MultiModal Reader configuration multimodal_config = MultiModalStructMemReaderConfig( llm={ "backend": "openai", "config": { "model_name_or_path": "gpt-4o-mini", "api_key": "your-api-key" } }, embedder={ "backend": "openai", "config": { "model_name_or_path": "text-embedding-3-small", "api_key": "your-api-key" } }, chunker={ "backend": "text_splitter", "config": { "chunk_size": 1000, "chunk_overlap": 200 } }, extractor_llm={ "backend": "openai", "config": { "model_name_or_path": "gpt-4o-mini", "api_key": "your-api-key" } }, # Optional: specify which domains should return Markdown directly direct_markdown_hostnames=["github.com", "docs.python.org"] ) # Initialize MultiModal Reader multimodal_reader = MultiModalStructMemReader(multimodal_config) # ======================================== # Example 1: Process conversations with images # ======================================== scene_with_image = [[ { "role": "user", "content": [ {"type": "text", "text": "This is my garden"}, {"type": "image_url", "image_url": {"url": "https://example.com/garden.jpg"}} ] }, { "role": "assistant", "content": "Your garden looks beautiful!" } ]] memories = multimodal_reader.get_memory( scene_with_image, type="chat", info={"user_id": "1234", "session_id": "session_001"} ) for m_list in memories: tree_memory.add(m_list) print(f"✓ Added {len(memories)} multimodal memories") # ======================================== # Example 2: Process web URLs # ======================================== scene_with_url = [[ { "role": "user", "content": "Please analyze this article: https://example.com/article.html" }, { "role": "assistant", "content": "I'll help you analyze this article" } ]] url_memories = multimodal_reader.get_memory( scene_with_url, type="chat", info={"user_id": "1234", "session_id": "session_002"} ) for m_list in url_memories: tree_memory.add(m_list) print(f"✓ Extracted and added {len(url_memories)} memories from URL") # ======================================== # Example 3: Process local files # ======================================== # Supported file types: PDF, DOCX, TXT, Markdown, HTML, etc. file_paths = [ "./documents/report.pdf", "./documents/notes.md", "./documents/data.txt" ] file_memories = multimodal_reader.get_memory( file_paths, type="doc", info={"user_id": "1234", "session_id": "session_003"} ) for m_list in file_memories: tree_memory.add(m_list) print(f"✓ Extracted and added {len(file_memories)} memories from files") # ======================================== # Example 4: Mixed mode (text + images + URLs) # ======================================== mixed_scene = [[ { "role": "user", "content": [ {"type": "text", "text": "Here's my project documentation:"}, {"type": "text", "text": "https://github.com/user/project/README.md"}, {"type": "image_url", "image_url": {"url": "https://example.com/diagram.png"}} ] } ]] mixed_memories = multimodal_reader.get_memory( mixed_scene, type="chat", info={"user_id": "1234", "session_id": "session_004"} ) for m_list in mixed_memories: tree_memory.add(m_list) print(f"✓ Extracted and added {len(mixed_memories)} memories from mixed content") ``` > **Note**: **MultiModal Reader Advantages** > - **Smart Routing**: Automatically identifies content type (image/URL/file) and selects appropriate parser > - **Format Support**: Supports PDF, DOCX, Markdown, HTML, images, and more > - **URL Parsing**: Automatically extracts web content (including GitHub, documentation sites, etc.) > - **Large File Handling**: Automatically chunks oversized files to avoid token limits > - **Context Preservation**: Uses sliding window to maintain context continuity between chunks > **Note**: **Configuration Tips** > - Use the `direct_markdown_hostnames` parameter to specify which domains should return Markdown format > - Supports both `mode="fast"` and `mode="fine"` extraction modes; fine mode extracts more details > - See complete examples: `/examples/mem_reader/multimodal_struct_reader.py` ### Search Memories Try a vector + graph search: ```python results = tree_memory.search("Talk about the garden", top_k=5) for i, node in enumerate(results): print(f"{i}: {node.memory}") ``` ### Retrieve Memories from the Internet (Optional) You can also fetch real-time web content using search engines such as Google, Bing, or Bocha, and automatically extract them into structured memory nodes. MemOS provides a unified interface for this purpose. The following example demonstrates how to retrieve web content related to **“Alibaba 2024 ESG report”** and convert it into structured memories: ```python # Create the embedder embedder = EmbedderFactory.from_config( EmbedderConfigFactory.model_validate({ "backend": "ollama", "config": {"model_name_or_path": "nomic-embed-text:latest"}, }) ) # Configure the retriever (using BochaAI as an example) retriever_config = InternetRetrieverConfigFactory.model_validate({ "backend": "bocha", "config": { "api_key": "sk-xxx", # Replace with your BochaAI API Key "max_results": 5, "reader": { # Reader config for automatic chunking "backend": "simple_struct", "config": ..., # Your mem-reader config }, } }) # Instantiate the retriever retriever = InternetRetrieverFactory.from_config(retriever_config, embedder) # Perform internet search results = retriever.retrieve_from_internet("Alibaba 2024 ESG report") # Add results to the memory graph for m in results: tree_memory.add(m) ``` Alternatively, you can configure the `internet_retriever` field directly in the `TreeTextMemoryConfig`. For example: ```json { "internet_retriever": { "backend": "bocha", "config": { "api_key": "sk-xxx", "max_results": 5, "reader": { "backend": "simple_struct", "config": ... } } } } ``` With this setup, when you call `tree_memory.search(query)`, the system will automatically trigger an internet search (via BochaAI, Google, or Bing), and merge the results with local memory nodes in a unified ranked list — no need to manually call `retriever.retrieve_from_internet`. ### Replace Working Memory Replace your current `WorkingMemory` nodes with new ones: ```python tree_memory.replace_working_memory( [{ "memory": "User is discussing gardening tips.", "metadata": {"memory_type": "WorkingMemory"} }] ) ``` ### Backup & Restore Dump your entire tree structure to disk and reload anytime: ```python tree_memory.dump("tmp/tree_memories") tree_memory.load("tmp/tree_memories") ``` ### Full Code Example This combines all the steps above into one end-to-end example — copy & run! ```python from memos.configs.embedder import EmbedderConfigFactory from memos.configs.memory import TreeTextMemoryConfig from memos.configs.mem_reader import SimpleStructMemReaderConfig from memos.embedders.factory import EmbedderFactory from memos.mem_reader.simple_struct import SimpleStructMemReader from memos.memories.textual.tree import TreeTextMemory # Setup Embedder embedder_config = EmbedderConfigFactory.model_validate({ "backend": "ollama", "config": {"model_name_or_path": "nomic-embed-text:latest"} }) embedder = EmbedderFactory.from_config(embedder_config) # Create TreeTextMemory tree_config = TreeTextMemoryConfig.from_json_file("examples/data/config/tree_config.json") my_tree_textual_memory = TreeTextMemory(tree_config) my_tree_textual_memory.delete_all() # Setup Reader reader_config = SimpleStructMemReaderConfig.from_json_file( "examples/data/config/simple_struct_reader_config.json" ) reader = SimpleStructMemReader(reader_config) # Extract from conversation scene_data = [[ { "role": "user", "content": "Tell me about your childhood." }, { "role": "assistant", "content": "I loved playing in the garden with my dog." }, ]] memory = reader.get_memory(scene_data, type="chat", info={"user_id": "1234", "session_id": "2222"}) for m_list in memory: my_tree_textual_memory.add(m_list) # Search results = my_tree_textual_memory.search( "Talk about the user's childhood story?", top_k=10 ) for i, r in enumerate(results): print(f"{i}'th result: {r.memory}") # [Optional] Add from documents doc_paths = ["./text1.txt", "./text2.txt"] doc_memory = reader.get_memory( doc_paths, "doc", info={ "user_id": "your_user_id", "session_id": "your_session_id", } ) for m_list in doc_memory: my_tree_textual_memory.add(m_list) # [Optional] Dump & Drop my_tree_textual_memory.dump("tmp/my_tree_textual_memory") my_tree_textual_memory.drop() ``` ## Why Choose TreeTextMemory - **Structured Hierarchy:** Organize memories like a mind map — nodes can have parents, children, and cross-links. - **Graph-Style Linking:** Beyond pure hierarchy — build multi-hop reasoning chains. - **Semantic Search + Graph Expansion:** Combine the best of vectors and graphs. - **Explainability:** Trace how memories connect, merge, or evolve over time. > **Note**: **Try This** Add memory nodes from documents or web content. Link them > manually or auto-merge similar nodes! ## What’s Next - **Know more about [Neo4j](/open_source/modules/memories/neo4j_graph_db):** TreeTextMemory is powered by a graph database backend. Understanding how Neo4j handles nodes, edges, and traversal will help you design more efficient memory hierarchies, multi-hop reasoning, and context linking strategies. - **Add [Activation Memory](/open_source/modules/memories/kv_cache_memory):** Experiment with runtime KV-cache for session state. - **Explore Graph Reasoning:** Build workflows for multi-hop retrieval and answer synthesis. - **Go Deep:** Check the [API Reference](/api-reference/search-memories) for advanced usage, or run more examples in `examples/`. Now your agent remembers not just facts — but the connections between them! --- # Neo4j Graph Database (/open_source/modules/memories/neo4j_graph_db) ## Why Graph for Memory? Unlike flat vector stores, a graph database allows: - Structuring memory into **chains, hierarchies, and causal links** - Performing **multi-hop reasoning** and **subgraph traversal** - Supporting memory **deduplication, conflict detection, and scheduling** - Dynamically evolving a memory graph over time This forms the backbone of long-term, explainable, and compositional memory reasoning. ## Features - Unified interface across different graph databases - Built-in support for Neo4j - Support for vector-enhanced retrieval (`search_by_embedding`) - Modular, pluggable, and testable - [v0.2.1 New! ] Supports **multi-tenant graph memory architecture** (shared DB, per-user logic) - [v0.2.1 New! ] Compatible with **Neo4j Community Edition** environments ## Directory Structure ``` src/memos/graph_dbs/ ├── base.py # Abstract interface: BaseGraphDB ├── factory.py # Factory to instantiate GraphDB from config ├── neo4j.py # Neo4jGraphDB: production implementation ```` ## How to Use ```python from memos.graph_dbs.factory import GraphStoreFactory from memos.configs.graph_db import GraphDBConfigFactory # Step 1: Build factory config config = GraphDBConfigFactory( backend="neo4j", config={ "uri": "bolt://localhost:7687", "user": "your_neo4j_user_name", "password": "your_password", "db_name": "memory_user1", "auto_create": True, "embedding_dimension": 768 } ) # Step 2: Instantiate the graph store graph = GraphStoreFactory.from_config(config) # Step 3: Add memory graph.add_node( id="node-001", memory="Today I learned about retrieval-augmented generation.", metadata={"type": "WorkingMemory", "tags": ["RAG", "AI"], "timestamp": "2025-06-05", "sources": []} ) ```` ## Pluggable Design ### Interface: `BaseGraphDB` ```` Function Introduction: 1. Node Operations: Insert: add_node (Adds a single node) add_nodes_batch (Adds multiple nodes in batch) Query: get_node (Retrieves a single node) get_nodes (Retrieves multiple nodes) get_memory_count (Retrieves the count of nodes) node_not_exist (Checks if a node exists) search_by_embedding (Vector search supports adding filter conditions for filtering. For usage of the filter, refer to the function neo4j_example.example_complex_shared_db_search_filter for the complete method documentation.) Update: update_node (Updates a single node) Delete: delete_node (Deletes a single node) clear(deletes all associated nodes by the user_name attribute.) See neo4j_example.example_complex_shared_db_delete_memory for full method docs 2. Edge Operations: Insert: add_edge (Adds a triple/relation as a memory element) Query: get_edges (Retrieves multiple relations/edges) edge_exists (Checks if a relation/edge exists) get_children_with_embeddings (Retrieves a list of child nodes for the PARENT relation type) get_subgraph (Queries multi-hop nodes/retrieves a subgraph) Delete: delete_edge (Deletes a relation/edge) 3. Import/Export Operations: import_graph (Imports an entire graph from a serialized dictionary. Parameters: A dictionary containing all nodes and edges to load, format: {'nodes': [], 'edges': []}) export_graph (Exports all graph nodes and edges in a structured format, with pagination support) See src/memos/graph_dbs/base.py for full method docs. ```` ### Current Backend: | Backend | Status | File | | ------- | ------ | ---------- | | Neo4j | Stable | `neo4j.py` | ## Shared DB, Multi-Tenant Support By specifying the `user_name` field, MemOS can isolate memory graphs for multiple users in a single Neo4j database. Ideal for collaborative systems or multi-agent applications: ```python config = GraphDBConfigFactory( backend="neo4j", config={ "uri": "bolt://localhost:7687", "user": "neo4j", "password": "your_password", "db_name": "shared-graph", "user_name": "alice", "use_multi_db": False, "embedding_dimension": 768, }, ) ``` User data is logically isolated via the `user_name` field. Filtering is handled automatically during reads, writes, and searches. > **Note**: **Example? You bet.** > No blah blah, just go check the code: > `examples/basic_modules/neo4j_example.example_complex_shared_db(db_name="shared-traval-group-complex-new")` ## Neo4j Community Edition Support New backend identifier: `neo4j-community` Usage is similar to standard Neo4j, but disables Enterprise-only features: - ❌ No support for `auto_create` databases - ❌ No native vector indexes (External vector library must be used, currently only Qdrant is supported) - ✅ Enforces `user_name` logic-based isolation(Community version or username belong to the same business and do not require strong isolation) Example configuration: ```python config = GraphDBConfigFactory( backend="neo4j-community", config={ "uri": "bolt://localhost:7687", "user": "neo4j", "password": "12345678", "db_name": "paper", "user_name": "bob", "auto_create": False, "embedding_dimension": 768, "use_multi_db": False, "vec_config": { "backend": "qdrant", "config": { "host": "localhost", "port": 6333, "collection_name": "neo4j_vec_db", "vector_dimension": 768, "distance_metric": "cosine" }, }, }, ) ``` > **Note**: **Example? You bet.** > No blah blah, just go check the code: > `examples/basic_modules/neo4j_example.example_complex_shared_db(db_name="paper", community=True)` ## Extending You can add support for any other graph engine (e.g., **TigerGraph**, **DGraph**, **Weaviate hybrid**) by: 1. Subclassing `BaseGraphDB` 2. Creating a config dataclass (e.g., `DgraphConfig`) 3. Registering it in: * `GraphDBConfigFactory.backend_to_class` * `GraphStoreFactory.backend_to_class` See `src/memos/graph_dbs/neo4j.py` as a reference for implementation. --- # PolarDB Graph Database (/open_source/modules/memories/polardb_graph_db) ## Features - Complete graph database operations: node CRUD, edge management - Vector embedding search: semantic retrieval with IVFFlat index support - Connection pool management: automatic database connection management with high concurrency support - Multi-tenant isolation: supports both physical and logical isolation modes - JSONB property storage: flexible metadata storage - Batch operations: supports batch insertion of nodes and edges - Automatic timestamps: automatically maintains `created_at` and `updated_at` - SQL injection protection: built-in parameterized queries and string escaping ## Directory Structure ``` MemOS/ └── src/ └── memos/ ├── configs/ │ └── graph_db.py # PolarDBGraphDBConfig configuration class └── graph_dbs/ ├── base.py # BaseGraphDB abstract base class ├── factory.py # GraphDBFactory factory class └── polardb.py # PolarDBGraphDB implementation ``` ## Quick Start ### 1. Install Dependencies ```bash # Install psycopg2 driver (choose one) pip install psycopg2-binary # Recommended: pre-compiled version # or pip install psycopg2 # Requires PostgreSQL development libraries # Install MemOS pip install MemoryOS -U ``` ### 2. Configure PolarDB #### Method 1: Using Configuration File (Recommended) ```json { "graph_db_store": { "backend": "polardb", "config": { "host": "localhost", "port": 5432, "user": "postgres", "password": "your_password", "db_name": "memos_db", "user_name": "alice", "use_multi_db": true, "auto_create": false, "embedding_dimension": 1024, "maxconn": 100 } } } ``` #### Method 2: Code Initialization ```python from memos.configs.graph_db import PolarDBGraphDBConfig from memos.graph_dbs.polardb import PolarDBGraphDB # Create configuration config = PolarDBGraphDBConfig( host="localhost", port=5432, user="postgres", password="your_password", db_name="memos_db", user_name="alice", use_multi_db=True, embedding_dimension=1024, maxconn=100 ) # Initialize database graph_db = PolarDBGraphDB(config) ``` ### 3. Basic Operation Examples ```python # ======================================== # Step 1: Add Node # ======================================== node_id = graph_db.add_node( label="Memory", properties={ "content": "Python is a high-level programming language", "memory_type": "Knowledge", "tags": ["programming", "python"] }, embedding=[0.1, 0.2, 0.3, ...], # 1024-dimensional vector user_name="alice" ) print(f"✓ Node created: {node_id}") # ======================================== # Step 2: Update Node # ======================================== graph_db.update_node( id=node_id, fields={ "content": "Python is an interpreted, object-oriented high-level programming language", "updated": True }, user_name="alice" ) print("✓ Node updated") # ======================================== # Step 3: Create Relationship # ======================================== # First create a second node node_id_2 = graph_db.add_node( label="Memory", properties={ "content": "Django is a web framework for Python", "memory_type": "Knowledge" }, embedding=[0.15, 0.25, 0.35, ...], user_name="alice" ) # Create edge edge_id = graph_db.add_edge( source_id=node_id, target_id=node_id_2, edge_type="RELATED_TO", properties={ "relationship": "framework and language", "confidence": 0.95 }, user_name="alice" ) print(f"✓ Relationship created: {edge_id}") # ======================================== # Step 4: Vector Search # ======================================== query_embedding = [0.12, 0.22, 0.32, ...] # Query vector results = graph_db.search_by_embedding( embedding=query_embedding, top_k=5, memory_type="Knowledge", user_name="alice" ) print(f"\n🔍 Found {len(results)} similar nodes:") for node in results: print(f" - {node.get('content')} (similarity: {node.get('score', 'N/A')})") # ======================================== # Step 5: Delete Node # ======================================== graph_db.delete_node(id=node_id, user_name="alice") print(f"✓ Node {node_id} deleted") ``` ## Configuration Details ### PolarDBGraphDBConfig Parameters | Parameter | Type | Default | Required | Description | |------|------|--------|------|------| | `host` | str | - | ✓ | Database host address | | `port` | int | 5432 | ✗ | Database port | | `user` | str | - | ✓ | Database username | | `password` | str | - | ✓ | Database password | | `db_name` | str | - | ✓ | Target database name | | `user_name` | str | None | ✗ | Tenant identifier (for logical isolation) | | `use_multi_db` | bool | True | ✗ | Whether to use multi-database physical isolation | | `auto_create` | bool | False | ✗ | Whether to automatically create database | | `embedding_dimension` | int | 1024 | ✗ | Vector embedding dimension | | `maxconn` | int | 100 | ✗ | Maximum connections in connection pool | ### Multi-Tenant Mode Comparison | Feature | Physical Isolation (`use_multi_db=True`) | Logical Isolation (`use_multi_db=False`) | |------|-----------------------------------|-------------------------------------| | **Isolation Level** | Database level | Application layer tag filtering | | **Configuration Requirements** | `db_name` typically equals `user_name` | Must provide `user_name` | | **Performance** | Better (independent resources) | Good (shared resources) | | **Cost** | High (independent DB per tenant) | Low (shared database) | | **Use Cases** | Enterprise customers, high security requirements | SaaS multi-tenant, development testing | | **Data Migration** | Convenient (full database export) | Requires filtering by tags | ### Configuration Examples #### Example 1: Physical Isolation (Recommended for Enterprise) ```json { "graph_db_store": { "backend": "polardb", "config": { "host": "prod-polardb.example.com", "port": 5432, "user": "admin", "password": "secure_password", "db_name": "customer_001", "user_name": null, "use_multi_db": true, "auto_create": false, "embedding_dimension": 1536, "maxconn": 200 } } } ``` #### Example 2: Logical Isolation (Recommended for SaaS) ```json { "graph_db_store": { "backend": "polardb", "config": { "host": "shared-polardb.example.com", "port": 5432, "user": "app_user", "password": "app_password", "db_name": "shared_memos", "user_name": "tenant_alice", "use_multi_db": false, "auto_create": false, "embedding_dimension": 768, "maxconn": 50 } } } ``` ## Advanced Features ### 1. Batch Insert Nodes ```python # Batch add nodes (high performance) nodes_data = [ { "label": "Memory", "properties": {"content": f"Node {i}", "memory_type": "Test"}, "embedding": [0.1 * i] * 1024, } for i in range(100) ] node_ids = graph_db.add_nodes_batch( nodes=nodes_data, user_name="alice" ) print(f"✓ Batch created {len(node_ids)} nodes") ``` ### 2. Complex Query Examples ```python # Find memories of specific type and sort by time def get_recent_memories(graph_db, memory_type, limit=10): """Get recent memory nodes""" query = f""" SELECT * FROM "{graph_db.db_name}_graph"."Memory" WHERE properties->>'memory_type' = %s AND properties->>'user_name' = %s ORDER BY updated_at DESC LIMIT %s """ conn = graph_db._get_connection() try: with conn.cursor() as cursor: cursor.execute(query, [memory_type, "alice", limit]) results = cursor.fetchall() return results finally: graph_db._return_connection(conn) # Usage example recent = get_recent_memories(graph_db, "WorkingMemory", limit=5) print(f"Recent 5 working memories: {len(recent)} items") ``` ### 3. Vector Index Optimization ```python # Create or update vector index graph_db.create_index( label="Memory", vector_property="embedding", dimensions=1024, index_name="memory_vector_index" ) print("✓ Vector index optimized") ``` ### 4. Connection Pool Monitoring ```python # View connection pool status (for debugging only) import logging logging.basicConfig(level=logging.DEBUG) # Detailed logs will be output when acquiring connection conn = graph_db._get_connection() # [DEBUG] [_get_connection] Successfully acquired connection from pool graph_db._return_connection(conn) # [DEBUG] [_return_connection] Successfully returned connection to pool ``` ## BaseGraphDB Interface PolarDB implements all methods of the `BaseGraphDB` abstract class, ensuring interoperability with other graph database backends. ### Core Methods | Method | Description | Parameters | |------|------|------| | `add_node()` | Add a single node | label, properties, embedding, user_name | | `add_nodes_batch()` | Batch add nodes | nodes, user_name | | `update_node()` | Update node properties | id, fields, user_name | | `delete_node()` | Delete node | id, user_name | | `delete_node_by_params()` | Delete nodes by conditions | params, user_name | | `add_edge()` | Create relationship | source_id, target_id, edge_type, properties, user_name | | `update_edge()` | Update relationship properties | edge_id, properties, user_name | | `delete_edge()` | Delete relationship | edge_id, user_name | | `search_by_embedding()` | Vector similarity search | embedding, top_k, memory_type, user_name | | `get_node()` | Get a single node | id, user_name | | `get_memory_count()` | Count nodes | memory_type, user_name | | `remove_oldest_memory()` | Clean old memories | memory_type, keep_latest, user_name | ### Complete Method Signature Examples ```python from typing import Any # Add node def add_node( self, label: str = "Memory", properties: dict[str, Any] | None = None, embedding: list[float] | None = None, user_name: str | None = None ) -> str: """Add a new node to the graph database""" pass # Vector search def search_by_embedding( self, embedding: list[float], top_k: int = 10, memory_type: str | None = None, user_name: str | None = None, filters: dict[str, Any] | None = None ) -> list[dict[str, Any]]: """Perform similarity search based on vector embedding""" pass # Batch operations def add_nodes_batch( self, nodes: list[dict[str, Any]], user_name: str | None = None ) -> list[str]: """Batch add multiple nodes""" pass ``` ## Extension Development Guide If you need to implement custom functionality based on PolarDB, you can inherit the `PolarDBGraphDB` class: ```python from memos.graph_dbs.polardb import PolarDBGraphDB from memos.configs.graph_db import PolarDBGraphDBConfig class CustomPolarDBGraphDB(PolarDBGraphDB): """Custom PolarDB graph database implementation""" def __init__(self, config: PolarDBGraphDBConfig): super().__init__(config) # Custom initialization logic self.custom_index_created = False def create_custom_index(self): """Create custom index""" conn = self._get_connection() try: with conn.cursor() as cursor: cursor.execute(f""" CREATE INDEX IF NOT EXISTS idx_custom_field ON "{self.db_name}_graph"."Memory" ((properties->>'custom_field')); """) conn.commit() self.custom_index_created = True print("✓ Custom index created") except Exception as e: print(f"❌ Failed to create index: {e}") conn.rollback() finally: self._return_connection(conn) def search_by_custom_field(self, field_value: str): """Search based on custom field""" query = f""" SELECT * FROM "{self.db_name}_graph"."Memory" WHERE properties->>'custom_field' = %s """ conn = self._get_connection() try: with conn.cursor() as cursor: cursor.execute(query, [field_value]) results = cursor.fetchall() return results finally: self._return_connection(conn) # Use custom implementation config = PolarDBGraphDBConfig( host="localhost", port=5432, user="postgres", password="password", db_name="custom_db" ) custom_db = CustomPolarDBGraphDB(config) custom_db.create_custom_index() results = custom_db.search_by_custom_field("special_value") ``` ## Reference Resources - [Apache AGE Official Documentation](https://age.apache.org/) - [PostgreSQL Connection Pool Documentation](https://www.psycopg.org/docs/pool.html) - [PolarDB Official Documentation](https://www.alibabacloud.com/product/polardb) - [MemOS GitHub Repository](https://github.com/MemOS-AI/MemOS) ## Next Steps - Learn about using [Neo4j Graph Database](./neo4j_graph_db.md) - Check out [General Textual Memory](./general_textual_memory.md) configuration - Explore advanced features of [Tree Textual Memory](./tree_textual_memory.md) --- # Performance Tuning (/open_source/best_practice/performance_tuning) ## Embedding Optimization ```python fast_embedder = { "backend": "ollama", "config": { "model_name_or_path": "nomic-embed-text:latest" } } slow_embedder = { "backend": "sentence_transformer", "config": { "model_name_or_path": "nomic-ai/nomic-embed-text-v1.5" } } ``` ## Inference Speed ```python generation_config = { "max_new_tokens": 256, # Limit response length "temperature": 0.7, "do_sample": True } ``` ## System Resource Optimization ### Memory Capacity Limits ```python scheduler_config = { "memory_capacities": { "working_memory_capacity": 20, # Active context "user_memory_capacity": 500, # User storage "long_term_memory_capacity": 2000, # Domain knowledge "transformed_act_memory_capacity": 50 # KV cache items } } ``` ### Batch Processing ```python def batch_memory_operations(operations, batch_size=10): for i in range(0, len(operations), batch_size): batch = operations[i:i + batch_size] yield batch # Process in batches ``` --- # Network Workarounds (/open_source/best_practice/network_workarounds) ## **Downloading Huggingface Models** ### Mirror Site (HF-Mirror) To download Huggingface models using the mirror site, you can follow these steps: #### Install Dependencies Install the necessary dependencies by running: ```bash pip install -U huggingface_hub ``` #### Set Environment Variable Set the environment variable `HF_ENDPOINT` to `https://hf-mirror.com`. #### Download Models or Datasets Use huggingface-cli to download models or datasets. For example: - To download a model: ```bash huggingface-cli download --resume-download gpt2 --local-dir gpt2 ``` - To download a dataset: ``` huggingface-cli download --repo-type dataset --resume-download wikitext --local-dir wikitext ``` For more detailed instructions and additional methods, please refer to [this link](https://hf-mirror.com/). ### Alternative Sources You may still encounter limitations accessing some models in your regions. In such cases, you can use modelscope: #### Install ModelScope Install the necessary dependencies by running: ```bash pip install modelscope[framework] ``` #### Download Models or Datasets Use modelscope to download models or datasets. For example: - To download a model: ```bash modelscope download --model 'Qwen/Qwen2-7b' --local_dir 'path/to/dir' ``` - To download a dataset: ```bash modelscope download --dataset 'Tongyi-DataEngine/SA1B-Dense-Caption' --local_dir './local_dir' ``` For more detailed instructions and additional methods, please refer to the [official docs](https://modelscope.cn/docs/home). ## **Using Poetry** ### Network Errors during Installing To address network errors when using "poetry install" in your regions, you can follow these steps: #### Update Configuration Update the `pyproject.toml` file to use a mirror source by adding the following configuration: ```toml [[tool.poetry.source]] name = "mirrors" url = "https://mirrors.tuna.tsinghua.edu.cn/pypi/web/simple/" priority = "primary" ``` #### Reconfigure Poetry Run the command `poetry lock` in the terminal to reconfigure Poetry with the new mirror source. **Tips:** Be aware that `poetry lock` will modify both Pyproject.toml and poetry.lock files. To avoid committing redundant changes: - Option 1: After successful `poetry install`, revert to the git HEAD node using `git reset --hard HEAD`. - Option 2: When executing `git add`, exclude the Pyproject.toml and poetry.lock files by specifying other files. For future dependency management tasks like adding or removing packages, you can use the `poetry add` command: ```bash poetry add ``` Refer to the [Poetry CLI documentation](https://python-poetry.org/docs/cli/) for more commands and details. --- # Common Errors and Solutions (/open_source/best_practice/common_errors_solutions) ## Configuration Errors ### Missing Required Fields ```python # ✅ Always include required fields llm_config = { "backend": "openai", "config": { "api_key": "your-api-key", "model_name_or_path": "gpt-4" } } ``` ### Backend Mismatch ```python # ✅ KVCache requires HuggingFace backend kv_config = { "backend": "kv_cache", "config": { "extractor_llm": { "backend": "huggingface", "config": { "model_name_or_path": "Qwen/Qwen3-1.7B" } } } } ``` ## Service Connection Issues ```bash # Start required services as needed docker run -p 6333:6333 qdrant/qdrant ollama serve ``` ### Memory Loading Failures ```python try: mem_cube.load("memory_dir") except Exception: mem_cube = GeneralMemCube(config) mem_cube.dump("memory_dir") ``` ### GPU Out Of Memory ```python import os os.environ["CUDA_VISIBLE_DEVICES"] = "0" # Use smaller models if GPU memory is limited: Qwen/Qwen3-0.6B ``` ## User Management ```python # Register user first mos.register_mem_cube(cube_path="path", user_id="user_id", cube_id="cube_id") # Check if user exists try: user_id = mos.create_user(user_name="john", role=UserRole.USER) except ValueError: user = mos.user_manager.get_user_by_name("john") ``` --- # MemOS MCP Integration Guide (/open_source/best_practice/mcp_for_cozespace_and_tools) This guide helps you configure MemOS MCP service in platforms like Coze Space, enabling seamless integration between your agent and the memory system. ## Choose an MCP Deployment Method MemOS provides two MCP deployment options. Choose based on your needs: ### Use MemOS Cloud Service (Recommended) If you want to connect quickly without deploying your own server, MemOS official cloud service is recommended. **Advantages:** - ✅ Out of the box, no deployment required - ✅ High availability guarantees - ✅ Automatic scaling and maintenance - ✅ Supports multiple clients (Claude, Cursor, Cline, etc.) **How to configure:** Visit [MemOS Cloud MCP Configuration Guide](https://memos-docs.openmem.net/cn/mcp_agent/mcp/guide) for detailed instructions. Main steps: 1. Register and get an API Key in [MemOS API Console](https://memos-dashboard.openmem.net/cn/apikeys/) 2. Configure `@memtensor/memos-api-mcp` service in your MCP client 3. Set environment variables (`MEMOS_API_KEY`, `MEMOS_USER_ID`, `MEMOS_CHANNEL`) ### Deploy MCP Service Yourself If you need a private deployment or custom requirements, you can deploy MCP service on your own server. **Advantages:** - ✅ Fully private data - ✅ Configurable and customizable - ✅ Full control of the service - ✅ Suitable for internal enterprise use **Prerequisites:** - Python 3.9+ - Neo4j database (or another supported graph database) - HTTPS domain (required by platforms like Coze) Continue reading for detailed deployment steps. --- ## Self-Hosted MCP Service Configuration The content below applies to users who deploy MCP service themselves. ## Architecture Self-hosted MCP service uses the following architecture: ``` Client (Coze/Claude, etc.) ↓ [HTTPS] MCP Server (port 8002) ↓ [HTTP calls] Server API (port 8001) ↓ MemOS Core Service ``` **Component overview:** - **Server API**: provides REST APIs (`/product/*`) to handle memory CRUD - **MCP Server**: exposes the MCP protocol over HTTP and calls Server API to complete operations - **HTTPS reverse proxy**: platforms like Coze require HTTPS secure connections ### Step 1: Start Server API Server API is the backend for MCP service and provides actual memory management capabilities. ```bash cd /path/to/MemOS python src/memos/api/server_api.py --port 8001 ``` Verify whether Server API is running: ```bash curl http://localhost:8001/docs ``` If it returns the API documentation page, startup succeeded. > **Note**: **Configuration file** > Server API loads configuration automatically. Ensure Neo4j and other dependencies are configured correctly. You can refer to `examples/data/config/tree_config_shared_database.json` as an example configuration. ### Step 2: Start MCP HTTP Service Start MCP service in another terminal: ```bash cd /path/to/MemOS python examples/mem_mcp/simple_fastmcp_serve.py --transport http --port 8002 ``` After MCP service starts, it will show information similar to: ``` ╭──────────────────────────────────────────────────╮ │ MemOS MCP via Server API │ │ Transport: HTTP │ │ Server URL: http://localhost:8002/mcp │ ╰──────────────────────────────────────────────────╯ ``` **Environment variable configuration (optional):** You can configure the Server API address via a `.env` file or environment variables: ```bash export MEMOS_API_BASE_URL="http://localhost:8001/product" ``` > **Note**: **Tool list** > MCP service provides the following tools: > - `add_memory`: add memory > - `search_memories`: search memories > - `chat`: chat with the memory system > > For the full tool list, see `examples/mem_mcp/simple_fastmcp_serve.py` ### Step 3: Configure an HTTPS Reverse Proxy Platforms like Coze require HTTPS. You need to set up an HTTPS reverse proxy (e.g., Nginx) to forward traffic to MCP service. **Nginx configuration example:** ```nginx server { listen 443 ssl http2; server_name your-domain.com; ssl_certificate /path/to/cert.pem; ssl_certificate_key /path/to/key.pem; location /mcp { proxy_pass http://localhost:8002/mcp; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; # SSE support proxy_buffering off; proxy_cache off; } } ``` > **Warning**: **HTTPS certificate** > Make sure you use a valid SSL certificate. Self-signed certificates may not be accepted by platforms like Coze. You can use Let's Encrypt to obtain a free certificate. ### Step 4: Test MCP Service Use the client test script to verify the service: ```bash cd /path/to/MemOS python examples/mem_mcp/simple_fastmcp_client.py ``` Example success output: ``` Working FastMCP Client ======================================== Connected to MCP server 1. Adding memory... Result: Memory added successfully 2. Searching memories... Result: [search result] 3. Chatting... Result: [AI response] ✓ All tests completed! ``` ## Configure MCP in Coze Space After the service is deployed, configure the MCP connection in Coze Space. ### Step 1: Open Coze Space and go to the tool configuration page ![Coze Space configuration page](https://statics.memtensor.com.cn/memos/coze_space_1.png) ### Step 2: Add a custom MCP tool Add a custom tool on the tool configuration page: ![Add a custom tool](https://statics.memtensor.com.cn/memos/coze_space_2.png) ### Step 3: Configure the MCP endpoint URL Configure the MCP endpoint URL with your HTTPS address: ``` https://your-domain.com/mcp ``` Available MCP tools: - **add_memory**: add a new memory - **search_memories**: search existing memories - **chat**: memory-based chat > **Note**: **Test connection** > After configuration, test whether MCP connection works in Coze. Ensure each tool can be called successfully. --- ## Use REST API Directly (Advanced) For scenarios that require more flexible integration, you can call Server API’s REST endpoints directly. ### Step 1: Start Server API ```bash cd /path/to/MemOS python src/memos/api/server_api.py --port 8001 ``` **Port notes** - Server API runs on port 8001 by default - Provides `/product/*` REST API endpoints ### Step 2: Configure custom tools in Coze IDE 1. In Coze, choose the "IDE plugin" creation method 2. Configure requests to your deployed Server API service ![Coze IDE plugin configuration](https://statics.memtensor.com.cn/memos/coze_tools_1.png) ### Step 3: Implement the add_memory tool ![Configure add_memory operation](https://statics.memtensor.com.cn/memos/coze_tools_2.png) **Code example:** configure and publish the `add_memory` operation in the IDE: ![Configure add_memory operation](https://statics.memtensor.com.cn/memos/coze_tools_2.png) Full code is as follows: ```python import json import requests from runtime import Args from typings.add_memory.add_memory import Input, Output def handler(args: Args[Input])->Output: memory_content = args.input.memory_content user_id = args.input.user_id cube_id = args.input.cube_id # Call Server API add endpoint url = "https://your-domain.com:8001/product/add" payload = json.dumps({ "user_id": user_id, "messages": memory_content, # Supports string or message array "writable_cube_ids": [cube_id] if cube_id else None }) headers = { 'Content-Type': 'application/json' } response = requests.post(url, headers=headers, data=payload, timeout=30) response.raise_for_status() return response.json() ``` **Other tool implementations:** Similarly, implement the search and chat tools: ```python # Search tool def search_handler(args: Args[Input]) -> Output: url = "https://your-domain.com:8001/product/search" payload = json.dumps{ "user_id": args.input.user_id, "query": args.input.query, }) headers = { 'Content-Type': 'application/json' } response = requests.post(url, headers=headers, data=payload, timeout=30) response.raise_for_status() return response.json() # Chat tool def chat_handler(args: Args[Input]) -> Output: url = "https://your-domain.com:8001/product/chat/complete" payload = json.dumps({ "user_id": args.input.user_id, "query": args.input.query }) response = requests.post(url, json=payload, timeout=30) return response.json() ``` ### Step 4: Publish and test tools After publishing, you can view the plugin under "My Resources": ![Published plugin resource](https://statics.memtensor.com.cn/memos/coze_tools_3.png) ### Step 5: Integrate into agent workflow Add the plugin into the agent workflow: 1. Create a new agent or edit an existing agent 2. Add the published MemOS plugin to the tool list 3. Configure the workflow to call memory tools 4. Test memory write and retrieval functions --- ## FAQ ### Q1: MCP service cannot connect to Server API **Solution:** - Check whether Server API is running: `curl http://localhost:8001/docs` - Check whether environment variable `MEMOS_API_BASE_URL` is configured correctly - Check MCP service logs and confirm the call address ### Q2: Coze cannot connect to MCP service **Solution:** - Make sure you use HTTPS - Check whether the SSL certificate is valid - Test reverse proxy configuration: `curl https://your-domain.com/mcp` - Check firewall and security group settings ### Q3: Neo4j connection failed **Solution:** - Ensure Neo4j service is running - Check connection info in the configuration file (uri, user, password) - Refer to `examples/data/config/tree_config_shared_database.json` as an example configuration ### Q4: How to see complete API examples? **Reference files:** - MCP server: `examples/mem_mcp/simple_fastmcp_serve.py` - MCP client: `examples/mem_mcp/simple_fastmcp_client.py` - API tests: `examples/api/server_router_api.py` --- ## Summary With this guide, you can: - ✅ Choose a suitable MCP deployment option (cloud or self-hosted) - ✅ Complete the full MCP service deployment process - ✅ Integrate MemOS memory features into platforms like Coze - ✅ Integrate directly via REST API No matter which option you choose, MemOS can provide your agent with powerful memory managementders=headers, data=payload) return json.loads(response.text) > **Note**: **API parameter notes** > - Use the standard Server API parameter format > - `messages`: replaces the previous `memory_content`, supports string or message array > - `writable_cube_ids`: replaces the previous `mem_cube_id`, supports multiple cubes > - Server API runs on port 8001, and the path is `/product/add` > - Ensure it matches MemOS Server API interface. You can refer to the example in `examples/api/server_router_api.py` > **IDE configuration** In the IDE, you can customize tool parameters, return value formats, etc., ensuring consistency with MemOS API. Use this method to implement the search endpoint and user registration endpoint, then click Publish. ### Publish and Use the Plugin After publishing, you can view the plugin under "My Resources" and integrate it into the agent workflow as a plugin: ![Published plugin resource](https://statics.memtensor.com.cn/memos/coze_tools_3.png) ### Build an Agent and Test After building the simplest agent, you can test memory operations: 1. Create a new agent 2. Add the published memory plugin 3. Configure the workflow 4. Test memory write and retrieval functions With the above configuration, you can successfully integrate MemOS memory features in Coze Space and provide powerful memory capabilities for your agent. --- # Contributing to MemOS (/open_source/contribution/overview) - **First-time contributors:** Please start by reading the [Setting Up](./setting_up.md) guide to prepare your development environment. - **Ready to code?** The [Development Workflow](./development_workflow.md) guide will walk you through our process for submitting changes. - **Writing good commit messages:** See our [Commit Guidelines](./commit_guidelines.md). - **Contributing to documentation:** If you're helping us improve our docs, check out the [Writing Documentation](./writing_docs.md) guide. - **Adding or improving tests:** The [Writing Tests](./writing_tests.md) guide is for you. Your contributions make this project better! ✨ If you have any questions, feel free to open an issue or join the discussion or scan the QR codes below to connect with us on Discord or WeChat. QR Code --- # Setting Up Your Development Environment (/open_source/contribution/setting_up) #### Fork & Clone the Repository Set up the repository on your local machine: - Fork the repository on GitHub - Clone your fork to your local machine: ```bash git clone https://github.com/YOUR-USERNAME/MemOS.git cd MemOS ``` - Add the upstream repository as a remote: ```bash git remote add upstream https://github.com/MemTensor/MemOS.git ``` #### Prepare Development Dependencies Ensure the following are installed locally: - Git - Python 3.9+ - Make Verify Python: ```bash python3 --version ``` #### Install Poetry MemOS uses Poetry for dependency management. We recommend using the official installer: ```bash curl -sSL https://install.python-poetry.org | python3 - ``` Verify the installation: ```bash poetry --version ``` If you see `poetry: command not found`, please add the Poetry executable directory to your PATH as prompted by the installer, then restart your terminal and verify again. For more installation options, see the [official installation guide](https://python-poetry.org/docs/#installing-with-the-official-installer). #### Install Dependencies and Set Up Pre-commit Hooks Install all project dependencies and development tools in the repository root: ```bash make install ``` Tip: - If you switch branches or dependencies change, you may need to **re-run `make install`** to keep the environment consistent. ### Understanding Memory Modules and Dependency Selection Before setting up the environment, we need to understand MemOS's memory module classification and their corresponding database dependencies. This will determine which components you need to install. #### Memory Types The MemOS memory system is mainly divided into two categories (identifiers for `backend` config are in parentheses): - **Textual Memory**: Fact-based memory, **you must choose one**. - `tree` (`tree_text`): Tree memory (recommended), highest structure. - `general` (`general_text`): General memory, based on vector retrieval. - `naive` (`naive_text`): Naive memory, no special dependencies (for testing only). - **Preference Memory**: User preferences, **optional**. - `pref`: Used for storing and retrieving user preferences. #### Database Dependency Matrix Different memory types require different database support: | Memory Type | Component Dependency | Note | | :--- | :--- | :--- | | **Tree** | **Graph Database** | Required. Supports Neo4j Desktop, Neo4j Community, PolarDB | | **General** | **Vector Database** | Required. Recommended to use Qdrant (or compatible Vector DB) | | **Naive** | None | No database installation required | | **Pref** | **Milvus** | If Preference Memory is enabled, Milvus must be installed | #### About Tree Memory and Graph Database Selection If you choose the most powerful `tree` memory (which is what most developers choose), you need to prepare a graph database. Currently, there are three options: - **Neo4j Desktop** (Recommended for PC): Install directly on PC, comes with full GUI and features, easiest solution. - **PolarDB**: Graph database service provided by Alibaba Cloud (paid). - **Neo4j Community**: Open source and free, suitable for server or Linux environments. **Special Note**: - If you use **Neo4j Desktop**, it usually handles graph data independently. - If you use **Neo4j Community**, **it does not have native vector retrieval capabilities**. Therefore, you need to pair it with an additional vector database (Qdrant) to supplement vector retrieval capabilities. #### Configuration Scheme for This Tutorial To help developers get started quickly, this tutorial will use the following configuration: - **Memory Type**: `tree` (`tree_text`) - **Graph Database**: **Neo4j Community** (requires you to download installer or use Docker) - **Vector Database**: **Qdrant (Local Mode)** Since Neo4j Community lacks vector capabilities, we will introduce Qdrant. To avoid running an extra Qdrant service (Docker), we will configure Qdrant to run in **Local Embedded Mode** (reading/writing local files directly), so you don't need to install an additional Qdrant server. If no external configuration is provided, the system will automatically create a local database. #### Create Configuration File For .env content, please refer to [env config](/open_source/getting_started/installation#2.-.env-content) under docker installation for quick configuration. For detailed .env configuration, please see [env configuration](/open_source/getting_started/rest_api_server/#running-locally). > **Note**: **Note** > The .env configuration file needs to be placed in the MemOS project root directory. ```bash cd MemOS touch .env ``` #### Configure Dockerfile > **Note**: **Note** > The Dockerfile is located in the docker directory. ```bash # Enter the docker directory cd docker ``` Includes fast mode and full mode, distinguishing between slim packages (arm and x86) and full packages (arm and x86). ```bash ● Slim Package: Simplifies heavy dependencies like nvidia, making the image lightweight for faster local deployment. - url: registry.cn-shanghai.aliyuncs.com/memtensor/memos-base:v1.0 - url: registry.cn-shanghai.aliyuncs.com/memtensor/memos-base-arm:v1.0 ● Full Package: Packages all MemOS dependencies into the image for full functionality. Can be built and started directly by configuring the Dockerfile. - url: registry.cn-shanghai.aliyuncs.com/memtensor/memos-full-base:v1.0.0 - url: registry.cn-shanghai.aliyuncs.com/memtensor/memos-full-base-arm:v1.0.0 ``` ```bash # Current example uses slim package url FROM registry.cn-shanghai.aliyuncs.com/memtensor/memos-base-arm:v1.0 WORKDIR /app ENV HF_ENDPOINT=https://hf-mirror.com ENV PYTHONPATH=/app/src COPY src/ ./src/ EXPOSE 8000 CMD ["uvicorn", "memos.api.server_api:app", "--host", "0.0.0.0", "--port", "8000", "--reload"] ``` #### Start Docker Client ```bash # If docker is not installed, please install the corresponding version from: https://www.docker.com/ # After installation, start docker via client or command line # Start docker via command line sudo systemctl start docker # After installation, check docker status docker ps # Check docker images (optional) docker images ``` #### Build and Start Service > **Note**: **Note** > Build commands are also executed in the docker directory. ```bash # In the docker directory docker compose up neo4j ``` #### Open New Terminal to Start Server ```bash cd MemOS make serve ``` --- # Development Workflow (/open_source/contribution/development_workflow) Follow these steps to contribute to the project. #### Sync with Upstream If you've previously forked the repository, sync with the upstream changes: ```bash git checkout dev # switch to dev branch git fetch upstream # fetch latest changes from upstream git pull upstream dev # merge changes into your local dev branch git push origin dev # push changes to your fork ``` #### Create a Feature Branch Create a new branch for your feature or fix: ```bash git checkout -b feat/descriptive-name ``` #### Make Your Changes Implement your feature, fix, or improvement in the appropriate files. - For example, you might add a function in `src/memos/hello_world.py` and create corresponding tests in `tests/test_hello_world.py`. #### Test Your Changes Run the test suite to ensure your changes work correctly: ```bash make test ``` #### Commit Your Changes Before committing or creating a PR, rebase to the latest upstream/dev: ```bash git fetch upstream git rebase upstream/dev # Replay your feat branch on top of the latest dev ``` Follow the project's commit guidelines (see [Commit Guidelines](./commit_guidelines.md)) when committing your changes. #### Push to Your Fork Push your feature branch to your forked repository: ```bash git push origin feat/descriptive-name ``` #### Create a Pull Request Submit your changes for review: - **Important:** Please create your pull request against - ✅ the `dev` branch of the upstream repository, - ❎ not the `main` branch of the upstream repository. - Go to the original repository on GitHub - Click on "Pull Requests" - Click on "New Pull Request" - Select `dev` as the base branch, and your branch as compare - Fulfill the PR description carefully. --- # Commit Guidelines (/open_source/contribution/commit_guidelines) Please follow the [Conventional Commits](https://www.conventionalcommits.org/) format: - `feat:` for new features - `fix:` for bug fixes - `docs:` for documentation updates - `style:` for formatting changes (no code logic change) - `refactor:` for code refactoring - `test:` for adding or updating tests - `chore:` for other maintenance tasks - `ci:` for CI/CD or workflow related changes **Example:** `feat: add user authentication` --- # Documentation Writing Guidelines (/open_source/contribution/writing_docs) ## Creating New Documents ### Create Markdown File Create a new `.md` file in the `content/` directory or its subdirectories. Choose an appropriate location based on your content type. ### Add Frontmatter Add YAML frontmatter at the top of your file to provide metadata. The frontmatter supports the following fields: **Required Fields:** - `title` (string) - The document title that appears in navigation and page headers **Optional Fields:** - `desc` (string) - Brief description of the document content - `banner` (string) - URL to a banner image displayed at the top of the page - `links` (array) - Array of related links with labels, URLs, and icons ![Frontmatter Example](https://statics.memtensor.com.cn/memos/frontmatter.png) **Complete Frontmatter Example:** ```yaml --- title: MemOS Documentation desc: Welcome to the official documentation for MemOS – a Python package designed to empower large language models (LLMs) with advanced, modular memory capabilities. banner: https://statics.memtensor.com.cn/memos/memos-banner.gif links: - label: 'PyPI' to: https://pypi.org/project/MemoryOS/ target: _blank avatar: src: https://statics.memtensor.com.cn/icon/pypi.svg alt: PyPI logo - label: 'Open Source' to: https://github.com/MemTensor/MemOS target: _blank icon: i-simple-icons-github --- ``` ### Write Content Use Markdown syntax and MDC components to write your documentation content. Take advantage of the available components to create engaging and well-structured content. ### Update Navigation Add the new document to the `nav` section in `content/settings.yml` to make it accessible through the site navigation. ### Merge to Main Branch Once changes are merged into the `main` branch, the documentation will be automatically updated and deployed. ## Component Examples This project uses Nuxt Content's MDC (Markdown Components) syntax, which supports using Vue components within Markdown. These components help create engaging, well-structured documentation with consistent styling and improved user experience. ### Image References When adding images to your documentation, you can use several methods to reference them: #### Local Assets with Base64Image Component For images stored in the `public/assets` directory, use the `Base64Image` component. This component provides better performance by embedding the image directly in the page: ```mdc :Base64Image{src="/assets/memos-architecture.png" alt="MemOS Architecture"} ``` #### Remote Images with Markdown Syntax For remote images (hosted on external servers), use standard Markdown image syntax: ```markdown ![MemOS Architecture](https://statics.memtensor.com.cn/memos/memos-architecture.png) ``` ### Steps Use `steps` to create step-by-step guides from document headings. The `steps` component automatically numbers headings, creating a numbered guide for processes and tutorials. --- class: "[&>div]:*:w-full" --- #### Fork & Clone the Repository Set up the repository on your local machine: - Fork the repository on GitHub - Clone your fork to your local machine: ```bash git clone https://github.com/YOUR-USERNAME/MemOS.git cd MemOS ``` - Add the upstream repository as a remote: ```bash git remote add upstream https://github.com/MemTensor/MemOS.git ``` #### Prepare Development Dependencies Ensure the following are installed locally: - Git - Python 3.9+ - Make Verify Python: ```bash python3 --version ``` #### Install Poetry MemOS uses Poetry for dependency management. We recommend using the official installer: ```bash curl -sSL https://install.python-poetry.org | python3 - ``` Verify the installation: ```bash poetry --version ``` If you see `poetry: command not found`, please add the Poetry executable directory to your PATH as prompted by the installer, then restart your terminal and verify again. For more installation options, see the [official installation guide](https://python-poetry.org/docs/#installing-with-the-official-installer). #### Install Dependencies and Set Up Pre-commit Hooks Install all project dependencies and development tools in the repository root: ```bash make install ``` Tip: - If you switch branches or dependencies change, you may need to **re-run `make install`** to keep the environment consistent. ```python from memos.configs.mem_os import MOSConfig # init MOSConfig mos_config = MOSConfig.from_json_file("examples/data/config/simple_memos_config.json") ``` #### Create a User & Register a MemCube ```python import uuid from memos.mem_os.main import MOS mos = MOS(mos_config) # Generate a unique user ID user_id = str(uuid.uuid4()) # Create the user mos.create_user(user_id=user_id) ``` ::: #code ````mdc #### Install MemOS ```bash pip install MemoryOS ``` #### Create a Minimal Config For this Quick Start, we'll use the built-in GeneralTextMemory. ```python from memos.configs.mem_os import MOSConfig # init MOSConfig mos_config = MOSConfig.from_json_file("examples/data/config/simple_memos_config.json") ``` #### Create a User & Register a MemCube ```python import uuid from memos.mem_os.main import MOS mos = MOS(mos_config) # Generate a unique user ID user_id = str(uuid.uuid4()) # Create the user mos.create_user(user_id=user_id) ``` ```` ### Accordion Use `accordion` and `accordion-item` to create collapsible content sections. Accordions are useful for organizing FAQs, expandable details, or grouped information in an interactive way. --- class: "[&>div]:*:my-0" --- :accordion-item --- icon: i-lucide-circle-help label: Is MemOS compatible with LLMs accessed via API? --- Yes. MemOS is designed to be as compatible as possible with various types of models. However, it's important to note that if you're using API-based models, activation and parametric memories cannot be utilized. :::: : --- icon: i-lucide-circle-help label: How does MemOS improve the effectiveness of large language model applications? --- MemOS enhances large language model applications by providing structured, persistent memory with intelligent scheduling, long-term knowledge retention, and KV cache for fast inference. It supports fine-grained access control and user isolation, ensuring memory security in multi-user environments. Its modular architecture allows seamless integration of new memory types, LLMs, and storage backends, making it adaptable to a wide range of intelligent applications.: : MemOS open-source is free.: ::: #code ```mdc Yes. MemOS is designed to be as compatible as possible with various types of models. However, it's important to note that if you're using API-based models, activation and parametric memories cannot be utilized. MemOS enhances large language model applications by providing structured, persistent memory with intelligent scheduling, long-term knowledge retention, and KV cache for fast inference. It supports fine-grained access control and user isolation, ensuring memory security in multi-user environments. Its modular architecture allows seamless integration of new memory types, LLMs, and storage backends, making it adaptable to a wide range of intelligent applications. MemOS open-source is free. ``` ### Badge Use badge to display status indicators or labels. Badges are great for highlighting version numbers, statuses, or categories within your content. --- label: Preview --- **v1.0.0** #code ```mdc **v1.0.0** ``` ### Callout Use callout to emphasize important contextual information. Callouts draw attention to notes, tips, warnings, or cautions, making key information stand out. Customize with `icon` and `color` props or use `note`, `tip`, `warning`, `caution` shortcuts for pre-defined semantic styles. --- class: "[&>div]:*:my-0 [&>div]:*:w-full" --- This is a `callout` with full **markdown** support. #code ```mdc This is a `callout` with full **markdown** support. ``` : > **Note**: Basic note content > : : > **Note**: Note with link - click to navigate to quick start guide > : : > **Note**: Note with custom icon - learn more about MemCube > : : > **Tip**: Here's a helpful suggestion. > : : > **Warning**: Be careful with this action as it might have unexpected results. > : : > **Caution**: This action cannot be undone. > : #code ```mdc > **Note**: Basic note content > **Note**: Note with link - click to navigate to quick start guide > **Note**: Note with custom icon - learn more about MemCube > **Tip**: Here's a helpful suggestion. > **Warning**: Be careful with this action as it might have unexpected results. > **Caution**: This action cannot be undone. ``` ### Card Use `card` to highlight content blocks. Cards are useful for showcasing features, resources, or related information in visually distinct and interactive containers. Customize with `title`, `icon`, and `color` props. Cards can also act as links using `` properties for navigation. --- class: "[&>div]:*:my-0 [&>div]:*:w-full" --- - [Open Source](https://github.com/MemTensor/MemOS): Use our open-source version #code ```mdc --- title: Open Source icon: i-simple-icons-github to: https://github.com/MemTensor/MemOS target: _blank --- Use our open-source version ``` ### CardGroup Use `card-group` to arrange cards in a grid layout. `card-group` is ideal for displaying collections of cards in a structured, visually appealing, and responsive grid. :- [Minimal Pipeline](/open_source/getting_started/examples#example-1-minimal-pipeline): The smallest working pipeline — add, search, update and dump plaintext memories.: :- [TreeTextMemory Only](/open_source/getting_started/examples#example-2-treetextmemory-only): Use Neo4j-backed hierarchical memory to build structured, multi-hop knowledge graphs.: :- [KVCacheMemory Only](/open_source/getting_started/examples#example-3-kvcachememory-only): Speed up sessions with short-term KV cache for fast context injection.: :- [Hybrid TreeText + KVCache](/open_source/getting_started/examples#example-4-hybrid): Combine explainable graph memory with fast KV caching in a single MemCube.: #code ```mdc - [Minimal Pipeline](/open_source/getting_started/examples#example-1-minimal-pipeline): The smallest working pipeline — add, search, update and dump plaintext memories. - [TreeTextMemory Only](/open_source/getting_started/examples#example-2-treetextmemory-only): Use Neo4j-backed hierarchical memory to build structured, multi-hop knowledge graphs. - [KVCacheMemory Only](/open_source/getting_started/examples#example-3-kvcachememory-only): Speed up sessions with short-term KV cache for fast context injection. - [Hybrid TreeText + KVCache](/open_source/getting_started/examples#example-4-hybrid): Combine explainable graph memory with fast KV caching in a single MemCube. ``` ## Navigation Icons When adding navigation entries in `content/settings.yml`, you can include icons using the syntax `(ri:icon-name)`: ```yaml - "(ri:home-line) Home": overview.md - "(ri:team-line) User Management": modules/mos/users.md - "(ri:flask-line) Writing Tests": contribution/writing_tests.md ``` Available icons can be found at: [https://icones.js.org/](https://icones.js.org/) ## Local Preview To preview the documentation locally, run the following command from the project root: ```bash ## Make sure to install the dependencies: pnpm install ``` ```bash pnpm dev ``` This command will start a local web server, usually accessible at `http://127.0.0.1:3000`. ## Learn More ### Nuxt Content and Typography This project uses Nuxt Content and supports rich Typography components and styles. To learn more about available components and customization options, please refer to: - [Nuxt UI Typography Documentation](https://ui.nuxt.com/getting-started/typography) ## Best Practices > **Note**: **Documentation Writing Tips** > > 1. **Keep document structure clear**: Use appropriate heading levels to organize content logically > 2. **Use components wisely**: Use note, card, and other components to improve readability and engagement > 3. **Code examples**: Provide clear code examples for technical documentation with proper syntax highlighting > 4. **Icon usage**: Use appropriate icons in navigation to enhance user experience and visual hierarchy Remember to test your documentation locally before submitting. Use `npm run dev` to preview your changes and ensure all components render correctly. --- # How to Write Unit Tests (/open_source/contribution/writing_tests) ## Writing a Test 1. Create a new Python file in the `tests/` directory. The filename should start with `test_`. 2. Inside the file, create functions whose names start with `test_`. 3. Use the `assert` statement to check for expected outcomes. Here is a basic example: ```python # tests/test_example.py def test_addition(): assert 1 + 1 == 2 ``` ## Running Tests To run all the tests, execute the following command from the root of the project: ```bash make test ``` This will discover and run all the tests in the `tests/` directory. ## Advanced Techniques Pytest has many advanced features, such as fixtures and mocking. ### Fixtures Fixtures are functions that can provide data or set up state for your tests. They are defined using the `@pytest.fixture` decorator. ### Mocking Mocking is used to replace parts of your system with mock objects. This is useful for isolating the code you are testing. The `unittest.mock` library is commonly used for this, often with the `patch` function. For an example of mocking, see `tests/test_hello_world.py`. --- # Usage Examples (/self_developed_model/extraction_usage_example) MemOS exposes a memory extraction API powered by the in-house **memos-extractor-0.6b** model. Pass conversation turns in and get fact and preference memories in one call. Request/response fields and OpenAPI: [Extract Memory](/api_docs/core/extract_memory). Auth, base URL, and calling conventions match [MemOS Cloud Quick Start](/memos_cloud/getting_started/quick_start). ## When to use memory extraction The extraction API fits when you need: - **Lightweight extraction**: Structured memories from dialogue without running the full add/message pipeline. - **Low latency at high QPS**: A 0.6B in-house model tuned for fast, frequent calls. - **Flexible control**: Request fact memories, preferences, or both via `extraction_types`. ## How it works ![Memory extraction flow](https://cdn.memtensor.com.cn/img/1775554708977_az90s6_compressed.png) The end-to-end flow is: 1. **Data input** You send raw dialogue as `messages` with `role` and `content` on each item. 2. **Format & clean** Content is normalized to a standard shape and the dialogue language is detected. 3. **Task & language selection** Using `extraction_types` and the detected language, the pipeline selects a branch: - **Memory Reader**: fact memories - **Explicit Preference**: stated preferences - **Implicit Preference**: inferred preferences 4. **Prompt build** The prompt template for the chosen branch is assembled into the final inference request. 5. **API call** The request is sent to **memos-extractor-0.6b** in the agreed format. 6. **Final results** The model returns structured fact and/or preference lists, depending on what you asked to extract. ## Get started ```python [Facts + preferences] import os, json, requests os.environ["MEMOS_API_KEY"] = "YOUR_API_KEY" os.environ["MEMOS_BASE_URL"] = "https://memos.memtensor.cn/api/openmem/v1" data = { "messages": [ {"role": "system", "content": "Extract key memories from the dialogue."}, {"role": "user", "content": "I'm Alex, 28, backend dev in Hangzhou, I play badminton."}, {"role": "assistant", "content": "Hi Alex!"}, {"role": "user", "content": "Keep replies short, not too wordy."}, ] } headers = {"Content-Type": "application/json", "Authorization": f"Token {os.environ['MEMOS_API_KEY']}"} url = f"{os.environ['MEMOS_BASE_URL']}/extract/memory" res = requests.post(url, headers=headers, data=json.dumps(data)) print(res.json()) ``` ```python [Facts only] import os, json, requests os.environ["MEMOS_API_KEY"] = "YOUR_API_KEY" os.environ["MEMOS_BASE_URL"] = "https://memos.memtensor.cn/api/openmem/v1" data = { "messages": [{"role": "user", "content": "Flying to Beijing next Wed, staying at Ji Hotel Chaoyang."}], "extraction_types": ["memory"], } headers = {"Content-Type": "application/json", "Authorization": f"Token {os.environ['MEMOS_API_KEY']}"} url = f"{os.environ['MEMOS_BASE_URL']}/extract/memory" res = requests.post(url, headers=headers, data=json.dumps(data)) print(res.json()) ``` ```python [Preferences only] import os, json, requests os.environ["MEMOS_API_KEY"] = "YOUR_API_KEY" os.environ["MEMOS_BASE_URL"] = "https://memos.memtensor.cn/api/openmem/v1" data = { "messages": [ {"role": "user", "content": "Use Markdown for docs, code blocks should have syntax highlighting."}, {"role": "assistant", "content": "Got it."}, {"role": "user", "content": "Also go easy on emoji."}, ], "extraction_types": ["preference"], } headers = {"Content-Type": "application/json", "Authorization": f"Token {os.environ['MEMOS_API_KEY']}"} url = f"{os.environ['MEMOS_BASE_URL']}/extract/memory" res = requests.post(url, headers=headers, data=json.dumps(data)) print(res.json()) ``` ### Sample responses ```json [Facts + preferences] { "code": 0, "message": "ok", "data": { "success": true, "memory_detail_list": [ { "memory_key": "User profile and job", "memory_value": "User Alex, 28, backend developer in Hangzhou, plays badminton.", "memory_type": "UserMemory", "tags": ["person", "job", "location", "hobby"] } ], "preference_detail_list": [ { "preference": "Wants assistant replies to stay concise and not overly verbose.", "reasoning": "User explicitly asked to keep responses short and not too wordy.", "preference_type": "explicit_preference" } ] } } ``` ```json [Facts only] { "code": 0, "message": "ok", "data": { "success": true, "memory_detail_list": [ { "memory_key": "Travel and stay", "memory_value": "User flies to Beijing next Wednesday on business and plans to stay at Ji Hotel in Chaoyang.", "memory_type": "LongTermMemory", "tags": ["travel", "trip", "hotel"] } ] } } ``` ```json [Preferences only] { "code": 0, "message": "ok", "data": { "success": true, "preference_detail_list": [ { "preference": "Prefers Markdown documents with syntax-highlighted code blocks.", "reasoning": "User clearly asked for Markdown and highlighted code blocks.", "preference_type": "explicit_preference" }, { "preference": "Use fewer emoji.", "reasoning": "User directly asked to avoid too many emoji.", "preference_type": "explicit_preference" } ] } } ``` ## Limits - Request size: up to **8,000 tokens** for input. - **Synchronous only** today: the API returns when extraction finishes. - **Text-only dialogue**: each `messages` item only supports `role` and `content`. **No multimodal** input or multimodal memory extraction through this API. ## Compared to add/message | Dimension | Extract Memory | add/message | | --- | --- | --- | | Core behavior | Extract memories from dialogue; returns results only | Writes the dialogue and extracts/stores memories | | Storage | ❌ Does not write to the MemOS memory store | ✅ Writes into the MemOS memory store | | Model | In-house 0.6B extractor, low latency | MemOS built-in pipeline models | | Async | Not supported | ✅ Supported | | Preferences | ✅ Explicit + implicit | ✅ Supported | | Tool / skill memories | ❌ Not supported | ✅ Supported | | Typical use | Offline analysis / pre-processing / QA | Full conversational memory lifecycle | --- # Usage Examples (/self_developed_model/reranker_usage_example) MemOS provides a memory reranking API based on the **memos-reranker** model series (including 0.6B lightweight and 4B enhanced versions, base model uses qwen-reranker post-training). Developers can directly pass a user query and a list of candidate memories to complete memory relevance reranking in one call. Request/response fields and OpenAPI: [Rerank Memory](/api_docs/core/rerank). Auth, base URL, and calling conventions match [MemOS Cloud Quick Start](/memos_cloud/getting_started/quick_start). ## When to use memory reranking The reranking API fits when you need: - **Memory recall optimization**: After retrieving a large number of candidate memories, accurately filter out the memories most relevant to the current query through reranking to improve the quality of context injection. - **Low latency at high QPS**: Based on a 0.6B small model, suitable for latency-sensitive and frequently invoked business scenarios. - **Flexible sorting control**: Supports custom candidate document lists, can be used with any retrieval system, and does not rely on the MemOS memory store. Do not call the reranking API directly in these cases: - You do not have candidate documents yet and only want to search memory content. Call [Search Memory](/memos_cloud/mem_operations/search_memory) first. - You want to write content into memory. The reranking API does not write to the MemOS memory store; use [Add Message](/memos_cloud/mem_operations/add_message) instead. - You want to rank a full long document. Retrieve, split, or truncate candidate content first, then pass shorter candidate snippets to `documents`. ## How it works The memory reranking API and interaction with the model are shown in the figure below: ![Memory Reranking Process](https://cdn.memtensor.com.cn/img/1776755224177_y8jat9_compressed.png) The end-to-end flow of the reranking model is as follows: 1. **Query Input** Developers pass in the user query (`query`) and the candidate memory document list (`documents`). 2. **Encoding & Representation** After model encoding, relevance scores are output. 3. **Relevance Scoring** The relevance scores are mainly divided into 5 stages as shown in the figure. Developers can set thresholds according to actual scenarios. ## Get started ```python [Basic reranking] import os import requests import json # Replace with your MemOS API Key os.environ["MEMOS_API_KEY"] = "YOUR_API_KEY" os.environ["MEMOS_BASE_URL"] = "https://memos.memtensor.cn/api/openmem/v1" data = { # Available models: memos-reranker-0.6b (lightweight) or memos-reranker-4b (enhanced) "model": "memos-reranker-0.6b", "query": "Any liquor recommendations for me?", "documents": [ "User prefers Jiangxiang-flavored baijiu, like Moutai.", "I don't drink alcohol." ] } headers = { "Content-Type": "application/json", "Authorization": f"Token {os.environ['MEMOS_API_KEY']}" } url = f"{os.environ['MEMOS_BASE_URL']}/rerank" res = requests.post(url=url, headers=headers, data=json.dumps(data)) print(f"result: {res.json()}") ``` ```python [Reranking combined with memory retrieval] import os import requests import json # Replace with your MemOS API Key os.environ["MEMOS_API_KEY"] = "YOUR_API_KEY" os.environ["MEMOS_BASE_URL"] = "https://memos.memtensor.cn/api/openmem/v1" data = { # Available models: memos-reranker-0.6b (lightweight) or memos-reranker-4b (enhanced) "model": "memos-reranker-0.6b", "query": "What are the user's hobbies?", "top_n": 3, "documents": [ "User likes playing badminton.", "User is a backend developer in Hangzhou.", "User prefers concise replies.", "User prefers Jiangxiang-flavored baijiu.", "User is going on a business trip to Beijing next Wednesday." ] } headers = { "Content-Type": "application/json", "Authorization": f"Token {os.environ['MEMOS_API_KEY']}" } url = f"{os.environ['MEMOS_BASE_URL']}/rerank" res = requests.post(url=url, headers=headers, data=json.dumps(data)) print(f"result: {res.json()}") ``` ## Limits - `query` is required. Use a clear and concise current question. - `documents` is required and must be a non-empty string array. The total token limit across all candidate documents is **8k**. - `top_n` is optional and returns the top N most relevant results. If omitted, all results are returned. - `model` is optional and supports `memos-reranker-0.6b` and `memos-reranker-4b`. - The API currently supports **synchronous mode only**. Results are returned once reranking is complete. ## Common Errors and Troubleshooting | Error Code | Common Cause | How to Fix | | --- | --- | --- | | `40000` | The request body structure is invalid, or a field type is incorrect | Check whether `query` is a string and whether `documents` is a string array | | `40002` / `40003` | A required field is empty, or `documents` is empty | Provide `query` and a non-empty `documents` array | | `40309` | Token usage exceeds the per-time-window limit | Reduce the number and length of candidate documents, lower concurrency, and retry in batches | | `50000` | Internal server error | Retry later. If it persists, contact support | ## Compared to Embedding Retrieval | Dimension | Reranking API | Embedding Retrieval | | --- | --- | --- | | Core behavior | Precision ranking of candidate docs, outputting relevance scores | Semantic similarity recall, fast coarse filtering | | Storage | ❌ Does not write to the MemOS memory store | ❌ Does not write to the MemOS memory store | | Model | 0.6B/4B reranking models | Embedding model | | Precision | ✅ High (cross-encoding, query-doc interaction) | General (dual-tower encoding, independent representation) | | Speed | Slower (requires pair-by-pair computation) | ✅ Fast (vector approximate retrieval) | | Async | Not supported | Not supported | | Typical use | Post-retrieval precision ranking / Memory quality assessment | Fast recall from massive memory store | --- # Overview (/mcp_agent/overview) MemOS exposes four integration paths for Agents: MCP services, the MemOS plugin, the CLI and the Coze plugin tool, with the plugin available in cloud and local form. The table lists the applicable clients and memory location for each option; for a recommendation based on the client in use, see Choose by client. ## Integration options | Option | Clients | Where memory lives | | --- | --- | --- | | [MCP services](/mcp_agent/mcp/guide) | Claude Desktop, Cursor, VS Code or Trae, Chatbox and other MCP-capable clients | MemOS Cloud, or a self-hosted MCP service | | [Cloud plugin](/openclaw/guide) | OpenClaw, DeepSeek Harness | MemOS Cloud, shared across Agents and devices | | [Local plugin](/openclaw/local_plugin) | OpenClaw, Hermes Agent, DeepSeek Harness | Local SQLite, data never leaves the machine | | [CLI](/mcp_agent/cli/guide) | Agents and terminals that can run shell commands | MemOS Cloud | | [Coze plugin tool](/mcp_agent/agent/guide) | Coze platform Agents, no code required | MemOS Cloud | ## Choose by client - **Claude Desktop, Cursor, VS Code, Trae, Chatbox**: MCP services. Add the MemOS MCP endpoint in the client configuration; no code required. - **OpenClaw**: see [Cloud plugin vs Local plugin](/openclaw/plugin_compare). The cloud plugin suits zero-setup use and cross-device memory; the local plugin suits cases where data must stay on the machine and observability is required. - **Hermes Agent**: the local plugin. Hermes connects to the same local memory core through a Python provider. - **DeepSeek Harness**: both plugins are supported; the choice depends on whether memory may leave the machine. - **Coze**: the plugin tool listed in the Coze store, added to an Agent with nothing to deploy. - **Custom Agent with shell access**: the CLI, which wraps `add`, `search`, `get` and other memory operations as commands and lets several frameworks share one memory. ## Cloud plugin or local plugin Both paths target Agents that run locally — OpenClaw, Hermes Agent and DeepSeek Harness. They differ in where memory is stored and how it is managed. | Dimension | Cloud plugin | Local plugin | | --- | --- | --- | | Memory location | MemOS Cloud | Local SQLite | | Cross-device and multi-Agent sharing | Yes | Local only | | Data leaves the machine | Yes | No | | Observability | Cloud call logs | Local dashboard with task traces, Analytics and Logs | | Best for | Fast setup, cross-device work, production | Privacy-sensitive, local-first, long-term experience accumulation | For the full comparison and installation steps, see [Cloud plugin vs Local plugin](/openclaw/plugin_compare). --- # MemOS MCP Usage Guide (/mcp_agent/mcp/guide) MemOS Memory Management MCP is a powerful AI memory enhancement plugin that supports three core capabilities: **conversation memory access**, **user profile construction**, and **knowledge base full lifecycle management**. By integrating MemOS into mainstream AI clients such as Claude, Cursor, and Cline, users can enable AI to continuously accumulate personal memories, understand user preferences, and efficiently process large-scale professional documents, fundamentally improving the consistency and personalization of AI conversations. ## 1. Capabilities Overview ### 1.1 Conversation Memory Management Provides writing, retrieving, deleting, and quality feedback functions for conversation content, which is the foundational capability module of the MemOS MCP. | Tool | Function Description | |---|---| | `add_message` | Writes a summary of the current conversation content into the user's memory bank for future retrieval. | | `search_memory` | Searches for relevant historical memories in the user's personal memory bank based on search terms. | | `delete_memory` | Deletes specified memory entries from the memory bank. | | `add_feedback` | Submits quality feedback on memory entries to optimize memory management effects. | ### 1.2 User Profile System **`get_user_profile`**: Retrieves the user's full-dimensional memory profile with one click. Unlike single factual memories (Facts), the user profile also integrates explicit/implicit preferences (Preferences) and tool usage experience (Tool Trajectories), allowing AI to answer identity-related questions such as "Who am I?" and "What are my preferences?", achieving true personalized interaction. ### 1.3 Knowledge Base Lifecycle Management Supports creating independent namespace containers for specific projects or domains, facilitating the isolated management of structured documents. | Tool | Function Description | |---|---| | `create_knowledge_base` | Creates an independent knowledge base container for document management in a specific project or domain. | | `remove_knowledge_base` | Removes a knowledge base that is no longer needed and its associated content. | ### 1.4 Intelligent Document Upload **`add_kb_document`**: Supports injecting local files or online resources into a specified knowledge base, which is the core tool of the knowledge base capability. **Core Features:** - **Local File Direct Upload**: Pioneered the MCP internal interception mechanism, allowing LLMs to pass local paths directly. - **Polymorphic Path Recognition**: Perfectly supports Windows (drive letters), Unix (absolute paths), Home directory (~/), and environment variable paths. - **Zero Context Loss**: Silently completes Base64 conversion and MIME type encapsulation locally, completely avoiding long documents overwhelming the context. - **Intelligent Direct Link Completion**: Automatically corrects non-standard URLs (adds http/https) and identifies online resources. - **Circuit Breaker Security Strategy**: Built-in anti-deadlock instruction; once an interface error occurs, it immediately trips the circuit breaker to prevent consuming excess traffic. ### 1.5 Precise Document Control Supports batch query and precise deletion of uploaded documents, achieving dynamic maintenance of the knowledge base. | Tool | Function Description | |---|---| | `get_kb_documents` | Batch retrieves detailed metadata of uploaded documents via a list of File IDs. | | `delete_kb_documents` | Precisely deletes specific documents from a designated knowledge base, achieving dynamic streamlining of the document library. | ## 2. Quick Configuration Fill in the following configuration in the client: ```json { "mcpServers": { "memos-api-mcp": { "timeout": 60, "type": "stdio", "command": "npx", "args": [ "-y", "@memtensor/memos-api-mcp@latest" ], "env": { "MEMOS_API_KEY": "mpg-xxxxxxxxxxxxxxxxxxxxxxxxxxxxx", "MEMOS_USER_ID": "your-user-id", "MEMOS_CHANNEL": "MODELSCOPE" } } } } ``` How to obtain environment variables: - `MEMOS_API_KEY`: Register an account on the MemOS official website's [API Console](https://memos-dashboard.openmem.net/cn/apikeys/), then create a new api-key on the API keys page and copy it here. ![Create a new api-key on the MemOS API Console](https://cdn.memtensor.com.cn/img/1763451978063_251scz_compressed.png) - `MEMOS_USER_ID`: A deterministic user-defined personal identifier. - For the same user, this environment variable needs to remain consistent across different devices/clients; - Please do not use random values, device IDs, or chat session IDs as user identifiers; - Recommended: Use personal email address, full name, or employee ID as the user identifier. - `MEMOS_CHANNEL`: Fill in "MODELSCOPE" here. For more detailed configuration, please refer to: * [npm package](https://www.npmjs.com/package/@memtensor/memos-api-mcp) * [GitHub](https://github.com/MemTensor/memos-api-mcp) ## 3. Using MemOS MCP in Different Clients ### Using in Claude Desktop To use MemOS in Claude Desktop, click the avatar in the lower left corner -> "Settings" -> "Developer" -> "Edit Config", paste the configuration into the `Claude_desktop_config.json` file, and finally restart the client. You can use it in the chat when you observe that the memos-api-mcp service is in the running state. ![Verification of using MemOS in Claude](https://cdn.memtensor.com.cn/img/1763105334517_9ayhrp_compressed.png) To improve the usage effect, it is recommended that users modify the user preference settings that apply to all conversations when using MemOS in Claude Desktop. The specific method is to click the avatar in the lower left corner -> "General", and paste the following content into the input box under "What personal preferences should Claude consider in responses?": ``` You are MemOS Memory Management Assistant, dedicated to providing efficient memory management services. It extracts memories based on users' past conversation content and enhances the consistency and personalization of users' conversations with AI through memory retrieval. Before answering each user's question, you need to call the search_memory service of memos-api-mcp and use appropriate search terms to find memories related to the current topic in the user's personal memory bank. After completing the answer based on these memories, call the add_message service of memos-api-mcp to record a summary of the current conversation content. (Note that calling add_message is mandatory. Regardless of what the user says or asks, it must be recorded; otherwise, in subsequent conversations, search_memory will not be able to obtain more detailed user information, leading to your inability to answer the user's questions accurately.) ``` ![Modifying user preferences for using MemOS in Claude Desktop](https://cdn.memtensor.com.cn/img/1763105312212_yqu9m7_compressed.png) The following is an example of using MemOS in Claude Desktop, by which users can judge whether they have successfully configured MemOS in Claude Desktop. ![Example of using MemOS in Claude Desktop](https://cdn.memtensor.com.cn/img/1763105296073_gtqj1s_compressed.png) ### Using in Cursor To use MemOS in Cursor, go to "Cursor Settings" -> "Tools & MCP" -> "Add Custom MCP" (or "New MCP Server"), and paste the configuration into the pop-up `mcp.json` file editing page. You can use it in the Cursor chat panel when you observe that memos-api-mcp is in the started state and can see tools such as `add_message` and `search_memory` on the tool details page. ![Using MemOS in Cursor](https://cdn.memtensor.com.cn/img/1763105278297_n23ukk_compressed.png) To improve the usage effect, it is recommended that users modify User Rules when using MemOS in Cursor. The specific method is to go to "Cursor Settings" -> "Rules, Memories, Commands" -> "User Rules" -> "+ Add Rule", then copy and paste the following content and save it: ``` You are MemOS Memory Management Assistant, dedicated to providing efficient memory management services. It extracts memories based on users' past conversation content and enhances the consistency and personalization of users' conversations with AI through memory retrieval. Before answering each user's question, you need to call the search_memory service of memos-api-mcp and use appropriate search terms to find memories related to the current topic in the user's personal memory bank. After completing the answer based on these memories, call the add_message service of memos-api-mcp to record a summary of the current conversation content. (Note that calling add_message is mandatory. Regardless of what the user says or asks, it must be recorded; otherwise, in subsequent conversations, search_memory will not be able to obtain more detailed user information, leading to your inability to answer the user's questions accurately.) ``` ![Configuring User rules for using MemOS in Cursor](https://cdn.memtensor.com.cn/img/1763105260337_yqacto_compressed.png) The following is an example of using MemOS in Cursor, by which users can judge whether they have successfully configured MemOS in Cursor. ![Usage example of using MemOS in Cursor](https://cdn.memtensor.com.cn/img/1763105238556_p99epu_compressed.png) ### Using in Visual Studio Code or Trae To use MemOS in VS Code or Trae, install the Cline extension and configure the model, then click the "MCP Servers" icon in the upper right corner inside the Cline panel -> "Configure" -> "Configure MCP Servers", and paste the configuration into the `cline_map_settings.json` file. You can use it in the Cline agent when you observe that memos-api-mcp is in the started state. At the same time, it is recommended to turn on the Auto-approve switch of each tool to avoid the agent asking before each tool call, making the use smoother. ![Configuration process of using MemOS in Cline](https://cdn.memtensor.com.cn/img/1763105211482_g1xclj_compressed.png) To improve the usage effect, it is recommended that users modify global rules when using MemOS in Cline. The specific method is to click the "Manage Cline Rules & Workflows" icon in the lower left corner of the Cline panel -> click the "+" icon on the right below Global Rules -> enter a rules file name in the input box, such as "memos_rules.md" -> copy and paste the following content into the pop-up editor: ```markdown # 🧠 MemOS Automatic Memory System — Mandatory Usage ## ⚠️ Always-On (No User Opt-In Required) This system must run **automatically for every turn**. Do **not** wait for the user to say "use memory", "use MCP", or "call a tool". The **client/orchestrator is responsible** for auto-invoking the tools. ## 🎯 Mandatory 3-Step Workflow (Enforced by Client Each Turn) \`\`\` Every user message → 1) 🔍 search_memory (AUTO, before answering) → 2) 💬 Answer (use only relevant memories; ignore noise) → 3) 💾 add_message (AUTO, after answering) \`\`\` ### 1) 🔍 Search Memory (Auto-invoked BEFORE answering) - **Trigger**: Must be auto-called **before** generating any answer (including simple greetings). - **Tool**: `search_memory` **Relevance rule**: The model must judge relevance and **only use relevant** memories. If results are irrelevant or noisy, **ignore them** and proceed. ### 2) 💬 Answer Use retrieved memories **only if relevant**. If none are relevant, answer normally. ### 3) 💾 Save Conversation (Auto-invoked AFTER answering) - **Trigger**: Must be auto-called after producing the final answer on **every turn**. - **Tool**: `add_message` **Purpose**: Persist Q&A for future personalization and continuity — even if no memory was used this turn. ## ✅ Non-Negotiable Client Responsibilities 1. **Auto-invoke** `search_memory` before **every** answer and `add_message` after **every** answer. 2. **No user opt-in**: Do not wait for the user to mention memory/tools/MCP. 3. **Store both user and assistant** messages every turn. 4. **Sequence** must be strictly: Search → Answer → Save. ``` ![Modifying global rules for using MemOS in VS Code or Trae](https://cdn.memtensor.com.cn/img/1763105181443_v9kg80_compressed.png) The following is an example of using MemOS in Cline, by which users can judge whether they have successfully configured MemOS in Cline. ![Usage example of using MemOS in Cline](https://cdn.memtensor.com.cn/img/1763105156433_jz4k3t_compressed.png) ### Using in [Chatbox](https://chatboxai.app/en) To use MemOS in Chatbox, click "Settings" in the lower left corner -> "MCP" -> "Custom MCP Servers - Add Server" -> "Add Custom Server", and add the memos-api-mcp service according to the following configuration. ``` Name: MemOS Memory Management Type: Local (stdio) Command: npx -y @memtensor/memos-api-mcp@latest Environment Variables: MEMOS_API_KEY={{api_key applied for on the MemOS official website API Console}} MEMOS_USER_ID={{custom USER_ID}} ``` After filling in, click "Test". If you can see tools such as `add_message` and `search_memory` at the bottom of the dialog box, the configuration is successful. ![Verification of using MemOS in Chatbox](https://cdn.memtensor.com.cn/img/1763105136401_xbvcsh_compressed.png) To improve the usage effect, it is recommended that users modify the system_prompt when using MemOS in Chatbox. The specific method is to go to "Settings" in the lower left corner -> "Chat Settings" -> "Default Settings for New Conversation", and modify the prompt as follows: ``` You are MemOS Memory Management Assistant, dedicated to providing efficient memory management services. It extracts memories based on users' past conversation content and enhances the consistency and personalization of users' conversations with AI through memory retrieval. Before answering each user's question, you need to call the search_memory service of memos-api-mcp and use appropriate search terms to find memories related to the current topic in the user's personal memory bank. After completing the answer based on these memories, call the add_message service of memos-api-mcp to record a summary of the current conversation content. (Note that calling add_message is mandatory. Regardless of what the user says or asks, it must be recorded; otherwise, in subsequent conversations, search_memory will not be able to obtain more detailed user information, leading to your inability to answer the user's questions accurately.) ``` ![Modifying system_prompt when using MemOS in Chatbox](https://cdn.memtensor.com.cn/img/1763105111045_trc5fx_compressed.png) The following is an example of using MemOS in Chatbox, by which users can judge whether they have successfully configured MemOS in Chatbox. ![Effect example of using MemOS in Chatbox](https://cdn.memtensor.com.cn/img/1763104980563_q3q7v2_compressed.png) ## 4. Q&A **Q: Why do agents sometimes fail to invoke tools when they should?** A: Due to the different underlying models used, different agents have different proficiency in using tools. When the agent forgets to use the tool, you can guide the model to call the corresponding tool through instructions, or try to use other underlying models. ## 5. Contact Us ![image.png](https://cdn.memtensor.com.cn/img/1758685658684_nbhka4_compressed.png) --- # MemOS CLI (/mcp_agent/cli/guide) MemOS CLI is designed for Agents and development environments that can execute shell commands. It wraps common memory operations into the `memos` command, so you can verify memory flows in a terminal or let an Agent search memories before answering and write useful new memories afterward. ## 1. When to Use It - You want to quickly test memory operations such as `add`, `search`, `get`, and `delete` in a terminal. - Your Agent framework can execute shell commands, but does not have a dedicated MemOS plugin. - You want one reusable Skill to work across multiple Agents instead of writing a separate plugin for each framework. If you use OpenClaw, prefer the [OpenClaw Cloud Plugin](/openclaw/guide). If your client supports MCP natively, see the [MCP Guide](/mcp_agent/mcp/guide). ## 2. Install ```bash npm install -g @memtensor/memos-cloud-cli ``` After installation, confirm that the CLI is available: ```bash memos --help ``` ## 3. Choose a Usage Mode and Configure MemOS CLI has two usage modes: install a memory Skill for an Agent, or manually run `memos` commands in a terminal. ### 3.1 Use with Agents To let an Agent automatically search and write memories, use `memos init` to install the memory Skill. `--agent` is currently required; if it is omitted, the command fails because the CLI needs to know where to install the Skill. ```bash memos init --agent codex ``` You can also write the API Key during initialization: ```bash memos init --api-key YOUR_API_KEY --agent codex ``` The currently supported Agents are listed below. Pass the matching value via `--agent`: | Agent | `--agent` value | | --- | --- | | Codex CLI | `codex` | | Cursor | `cursor` | | Claude Code | `claude` | | OpenClaw | `openclaw` | | Hermes | `hermes` | | Trae | `trae` | | Trae (China) | `trae-cn` | | OpenCode | `opencode` | | Antigravity | `antigravity` | | CodeBuddy | `workbuddy` | | Cline | `cline` | | GitHub Copilot | `copilot` | | DeepSeek Harness | `deepseek` | For example, to install the memory Skill for Cursor: ```bash memos init --agent cursor ``` To connect DeepSeek Harness: ```bash memos init --agent deepseek ``` The command installs the Skill at `~/.dsh/skills/memos-memory/`, or `$DSH_HOME/skills/memos-memory/` when `DSH_HOME` is set. It also writes the matching `AGENTS.md` and registers a native DeepSeek Harness lifecycle plugin. The plugin retrieves relevant memories and injects them into context at the beginning of each turn, then writes new long-term memories after a normally completed turn. Restart DeepSeek Harness to activate it. Once installed, the Agent will automatically load the Skill. During each conversation turn, the Agent will: 1. **Before answering** — automatically run `memos search` to retrieve long-term memories related to the current task 2. **After answering** — automatically run `memos add` to write new facts, preferences, etc. into MemOS If you already have a MemOS plugin installed (e.g. the OpenClaw cloud plugin), add `--memos-plugin` to generate plugin-aware Skill guidance: ```bash memos init --agent openclaw --memos-plugin ``` > **Tip**: Using OpenClaw as an example, in the LOCOMO evaluation, using MemOS CLI alone reduced token usage by about 65.5%; integrating MemOS Cloud + CLI improved accuracy from 66.60% to 77.27%. | Parameter | Description | | --- | --- | | `-k, --api-key` | MemOS API Key | | `--user-id` | Default user ID | | `--conversation-id` | Default conversation ID | | `--memos-plugin` | Generate plugin-aware Skill guidance when a MemOS memory plugin is installed | | `--agent` | Install Skill to a specific Agent directory; required | ### 3.2 Use Directly in Terminal If you only use CLI commands manually in a terminal and do not install an Agent Skill, use `memos config set` to configure CLI variables. After these values are set, later commands automatically use them when the corresponding parameter is not provided. Configure the API Key: ```bash memos config set platform.api_key YOUR_API_KEY ``` Configure the default user ID: ```bash memos config set defaults.user_id user_123 ``` Configure the default conversation ID: ```bash memos config set defaults.conversation_id conv_001 ``` ## 4. Quick Start After completing Agent initialization or terminal configuration above, use the following commands to verify memory operations. Add a memory: ```bash memos add "The user prefers Python programming" ``` Search related memories: ```bash memos search "programming language preference" ``` Chat with memory: ```bash memos chat "Do you know my preference?" ``` Get memories for a user: ```bash memos get user_123 ``` Query the original text of a memory: ```bash memos origin mem_123456 ``` Delete one memory, or delete all memories for a user: ```bash memos delete mem_123456 memos delete --user-id user_123 ``` ## 5. Command Reference ### `memos add` Write a memory into MemOS. ```bash memos add "The user prefers Python for data analysis and often uses pandas" memos add --message "The user frequently uses Jupyter Notebook" --user-id user_123 ``` | Parameter | Description | | --- | --- | | `[MESSAGE]` | Memory content to write; use either this or `--message` | | `-m, --message` | Memory content; alternative to the positional argument | | `--user-id` | User identifier; defaults to `defaults.user_id` in config | | `--format` | Output format; defaults to `agent` | ### `memos search` Search for memories related to a query. ```bash memos search "data analysis tool preference" memos search "programming language" --format json --detail detail ``` | Parameter | Description | | --- | --- | | `[QUERY]` | Search query; use either this or `--query` | | `-q, --query` | Search query; alternative to the positional argument | | `--user-id` | User identifier; defaults to `defaults.user_id` in config | | `--include-preference` | Include preference memories (`true` / `false`); defaults to `true` | | `--include-tool-memory` | Include tool memories (`true` / `false`); defaults to `false` | | `--include-skill-memory` | Include skill memories (`true` / `false`); defaults to `false` | | `--memory-limit-number` | Max number of main memories to recall; defaults to `9` | | `--preference-limit-number` | Max number of preference memories to recall; defaults to `9` | | `--tool-memory-limit-number` | Max number of tool memories to recall; defaults to `6` | | `--skill-memory-limit-number` | Max number of skill memories to recall; defaults to `6` | | `--format` | Output format; defaults to `agent` | | `--detail` | Detail level for non-JSON output; defaults to `simple`; supports `simple`, `detail` | ### `memos get` Get memories by user. ```bash memos get user_123 memos get user_123 --format json --detail detail ``` | Parameter | Description | | --- | --- | | `[USER_ID]` | User identifier; falls back to `defaults.user_id` in config | | `--user-id` | Alias for `[USER_ID]`; same fallback rules | | `--page` | Page number; omitted from request body if not set | | `--size` | Page size; omitted from request body if not set | | `--include-preference` | Include preference memories (`true` / `false`); defaults to API default if not set | | `--include-tool-memory` | Include tool memories (`true` / `false`); defaults to API default if not set | | `--format` | Output format; defaults to `agent` | | `--detail` | Detail level; defaults to `simple`; supports `simple`, `detail` | ### `memos origin` Query the original text of a memory by memory ID. ```bash memos origin mem_123456 memos origin mem_123456 --format json ``` | Parameter | Description | | --- | --- | | `MEMORY_ID` | Memory ID whose original text should be queried; required | | `--format` | Output format; defaults to `agent` | ### `memos delete` Delete one memory, or delete all memories for a user. ```bash memos delete mem_123456 --format json memos delete --user-id user_123 --format json ``` | Parameter | Description | | --- | --- | | `[MEMORY_ID]` | Memory ID to delete; pass this to delete a single memory | | `--user-id` | Delete all memories for this user; use either this or `MEMORY_ID` | | `--format` | Output format; defaults to `agent` | ### `memos chat` Chat using MemOS memories as context. ```bash memos chat "Do you know my preferences?" memos chat "Do you know my preferences?" --user-id user_123 --format table ``` | Parameter | Description | | --- | --- | | `[QUERY]` | Chat question; use either this or `--query` | | `-q, --query` | Chat question; alternative to the positional argument | | `--user-id` | User identifier; defaults to `defaults.user_id` in config | | `--format` | Output format; defaults to `agent` | ### `memos extract` Extract candidate memories from a message without writing them. ```bash memos extract "The user likes coffee and prefers dark mode" --format json ``` | Parameter | Description | | --- | --- | | `[MESSAGE]` | Message to extract from; use either this or `--message` | | `-m, --message` | Message to extract from; alternative to the positional argument | | `--user-id` | User identifier; defaults to `defaults.user_id` in config | | `--format` | Output format; defaults to `agent` | ### `memos rerank` Rerank candidate documents by relevance. ```bash memos rerank "python backend" "Flask guide" "React guide" --format json ``` | Parameter | Description | | --- | --- | | `[QUERY]` | Rerank query; use either this or `--query` | | `[DOCUMENTS]...` | Candidate document texts; multiple positional arguments | | `-q, --query` | Rerank query; alternative to the positional argument | | `--documents` | Candidate document texts; can be repeated | | `--top-n` | Return only the top N results | | `--format` | Output format; defaults to `agent` | ### `memos feedback` Submit feedback to improve memory management quality. ```bash memos feedback "Prefer concise, direct technical answers." --user-id user_123 --format json ``` | Parameter | Description | | --- | --- | | `[FEEDBACK_TEXT]` | Feedback content; use either this or `--feedback-content` | | `--feedback-content` | Feedback content; alternative to the positional argument | | `--user-id` | User identifier; defaults to `defaults.user_id` in config | | `--format` | Output format; defaults to `agent` | ### `memos message` Retrieve original conversation messages. ```bash memos message --user-id user_123 --conversation-id conv_001 memos message --user-id user_123 --limit 10 --format table ``` | Parameter | Description | | --- | --- | | `--user-id` | User identifier; required | | `--conversation-id` | Conversation ID; defaults to `defaults.conversation_id` in config | | `--limit` | Max messages to return; defaults to `6`, max `50` | | `--format` | Output format; defaults to `agent` | ### `memos status` Query the processing status of an async task. The task ID comes from the `task_id` returned by `add` or `feedback` in async mode. ```bash memos status abc123-task-id --format json ``` | Parameter | Description | | --- | --- | | `[TASK_ID]` | Async task ID; required | | `--format` | Output format; defaults to `agent` | Returned status values include `running`, `completed`, and `failed`. ### `memos kb` Knowledge base management subcommand group: create knowledge bases, upload documents, and query or delete files. #### `memos kb create` Create a knowledge base. ```bash memos kb create --name "Product FAQ" --description "Common product questions" --format json ``` | Parameter | Description | | --- | --- | | `--name` | Knowledge base name; required | | `--description` | Knowledge base description; optional | | `--format` | Output format; defaults to `agent` | #### `memos kb remove` Remove (delete) a knowledge base. ```bash memos kb remove base_xxxxx --format json ``` | Parameter | Description | | --- | --- | | `[KB_ID]` | Knowledge base ID; required | | `--format` | Output format; defaults to `agent` | #### `memos kb add-file` Upload documents to a knowledge base. Supports PDF, DOCX, DOC, TXT, JSON, MD, XML. ```bash memos kb add-file --kb-id base_xxxxx --files '["https://example.com/doc.pdf"]' --format json memos kb add-file --kb-id base_xxxxx --files '[{"content":"https://cdn.example.com/file.docx"}]' --format json ``` | Parameter | Description | | --- | --- | | `--kb-id` | Target knowledge base ID; required | | `--files` | JSON array of file entries: URL strings or `{"content": "..."}` objects; required | | `--format` | Output format; defaults to `agent` | #### `memos kb get-file` Get knowledge base file details and processing status. ```bash memos kb get-file --file-ids '["file_id_1", "file_id_2"]' --format json ``` | Parameter | Description | | --- | --- | | `--file-ids` | JSON array of file IDs; required | | `--format` | Output format; defaults to `agent` | #### `memos kb list-file` List files in a knowledge base with pagination, optionally filtered by type. ```bash memos kb list-file --kb-id base_xxxxx memos kb list-file --kb-id base_xxxxx --type skill --page 2 --page-size 10 --format json ``` | Parameter | Description | | --- | --- | | `--kb-id` | Knowledge base ID; required | | `--type` | Filter by type: `document` or `skill`; optional | | `--page` | Page number; defaults to `1` | | `--page-size` | Items per page; defaults to `20` | | `--format` | Output format; defaults to `agent` | #### `memos kb delete-file` Delete files from a knowledge base. ```bash memos kb delete-file --kb-id base_xxxxx --file-ids '["file_id_1"]' --format json ``` | Parameter | Description | | --- | --- | | `--kb-id` | Knowledge base ID; required | | `--file-ids` | JSON array of file IDs to delete; required | | `--format` | Output format; defaults to `agent` | ## 6. Output Formats All commands support `--format`. The default format is `agent`. `search` and `get` also support `--detail`. | Format | Use case | | --- | --- | | `table` | Human-readable terminal output | | `markdown` | Paste into documentation | | `agent` | Default; inject directly into Agent context | | `json` | Scripts, workflows, or structured processing | ```bash memos search "python" memos search "python" --format table --detail simple memos search "python" --format markdown --detail detail memos search "python" --format agent --detail simple memos search "python" --format json --detail detail ``` ## 7. Configuration Commands and Environment Variables View or modify local configuration: ```bash memos config show memos config get platform.api_key memos config set platform.api_key YOUR_API_KEY memos config set defaults.user_id user_123 memos config set defaults.conversation_id conv_001 ``` | Environment Variable | Description | | --- | --- | | `MEMOS_API_KEY` | Your API Key | | `MEMOS_BASE_URL` | API Base URL; defaults to `https://memos.memtensor.cn/api/openmem/v1` | Global options: | Parameter | Description | | --- | --- | | `--api-key TEXT` | Override the API Key in local configuration | | `--base-url TEXT` | Override the API Base URL | | `--version` | Show version number | All CLI requests include a `source=cli` tag. When the framework can be identified from environment variables or parent processes, the `framework` info is also attached to memory API requests. ## 8. CLI, Plugin, and MCP | Integration | Best for | Characteristics | | --- | --- | --- | | Plugin | Agent frameworks with deep MemOS integration | Deepest integration and best experience; requires per-framework adaptation | | CLI + Skill | Any Agent framework that can execute shell commands | Highly portable, low adaptation cost, great for cross-framework automation | | MCP | MCP-native clients | Standardized tool protocol for clients that support MCP | The three approaches are complementary. Plugin is best for deep integration, CLI + Skill for general automation, and MCP for MCP-native clients. ## Next Steps - [Quick Start](/memos_cloud/getting_started/quick_start): Run the basic memory write and search flow with API / SDK - [MCP Guide](/mcp_agent/mcp/guide): Connect MemOS memory tools through MCP clients - [OpenClaw Cloud Plugin](/openclaw/guide): Use the OpenClaw plugin for deeper Agent integration --- # Coze Plugin Tools (/mcp_agent/agent/guide) ## 1. Plugin Listing Information The MemOS Cloud Service Interface Plugin is now available on the Coze Store! You can directly [visit the tool link](https://www.coze.cn/store/plugin/7569918012912893995?from=store_search_suggestion) to add the plugin and achieve zero-code integration. ## 2. Plugin Description ### Plugin Functions * `search_memory`: This tool is used to query user memory data and can return snippets most relevant to the input. It supports real-time memory retrieval during user-AI conversations and can also perform global searches across the entire memory. It can be used to create user profiles or support personalized recommendations. Parameters such as conversation ID, user ID, and query text are required for queries, and the number of returned memory items can also be set. * `add_memory`: This tool allows batch importing of one or more messages into the MemOS memory storage database, facilitating retrieval in future conversations to support chat history management, user behavior tracking, and personalized interaction. Information such as conversation ID, message content, sender role, conversation time, and user ID must be specified when using it. ### Interface Description * search_memory Interface | Parameter Name | Parameter Type | Description | Required | | --- | --- | --- | --- | | memory_limit_number | string | Limits the number of returned memory items; defaults to 6 if not provided | No | | memos_key | string | Authorization key for MemOS cloud service | Yes | | memos_url | string | URL address of MemOS cloud service | Yes | | query | string | User input | Yes | | user_id | string | Unique identifier of the user associated with the memory being queried | Yes | * add_memory Interface | Parameter Name | Parameter Type | Description | Required | | --- | --- | --- | --- | | conversation_id | string | Unique identifier for the conversation | Yes | | memos_key | string | Authorization key for MemOS cloud service | Yes | | memos_url | string | URL address of MemOS cloud service | Yes | | messages | Array | Array of message objects | Yes | | user_id | string | Unique identifier of the user associated with the memory being queried | Yes | ## 3. Agent Call Example ### Agent Persona and Reply Logic Example ``` You are a Q&A robot. Every time, you read the user's memory and interests, and reply with very clear logic to gain the user's favor. ## Workflow Content # 1. Access {search_memory} to retrieve data materials After each user input, first call the retrieval function in MemOS memory relationships -- the {search_memory} plugin, input information: Record the user's name as user_id. If it is the first visit, set user_id to a 16-character string randomly generated by UUID. Use the user's speech content as the query. # 2. Process {search_memory} output content: Get the data content. If there is a memory_detail_list field, regardless of whether the memory_detail_list is empty, directly output the memory_detail_list in JSON format; if the returned message is not "ok", prompt "Plugin retrieval failed". # 3. Answer the user's question based on the retrieved memory_detail_list Extract the memory_value field value of each item in memory_detail_list, concatenate all strings with "\n" as the context material for answering the user's question; the large model can answer the user's query based on the information provided by the context; if the context information is an empty string, the large model can directly answer the user's query. Then record the content answered by the large model into "answer". # 4. Access {add_memory} to store data materials Call the add_memory function to store the user's question and the corresponding answer, input information: chat_time: Call {current_time} to get the current time, format the timestamp as "%I:%M %p on %d %B, %Y UTC". conversation_id: Record the current time point chat_time accurate to the minute, and use the time point string as conversation_id. user_id: Record the user's name as user_id. messages: Record the query input by the user and all answers obtained, respectively as the content of the role and the content of the assistant in messages. chat_time uses the chat_time value just obtained, organized as a message: [ {"role": "user", "content": query, "chat_time": chat_time}, {"role": "assistant", "content": answer, "chat_time": chat_time} ] Get the {add_memory} plugin feedback. If the success field in data is True, it is successful, *no need to inform the user*; if the returned field is not True, prompt the user that add_memory access failed. ## Requirements Every time you access {search_memory} and {add_memory}, you need to pass two fixed parameters: memos_url = "https://memos.memtensor.cn/api/openmem/v1" memos_key = "Token mpg-XXXXXXXXXXXXXXXXXXXXXXXXXXX" Your role is a wise and caring memory assistant named Xiaozhi. If all plugins run smoothly, there is no need to prompt the user for success in the content answered by the large model. Generate user_id with UUID only during the user's first conversation, and reuse this user_id in subsequent work. ``` [Agent Example Link](https://www.coze.cn/s/85NOIg062vQ) ![Agent Workflow](https://cdn.memtensor.com.cn/img/coze_workflow_compressed.png) --- # Cloud Plugin vs Local Plugin (/openclaw/plugin_compare) ## Overview ### Cloud Plugin Stores memories in **MemOS Cloud**. After installing the cloud plugin, a single MemOS Cloud API Key is all you need to get started. It supports multi-agent memory sharing across devices, and benchmarks show up to **72% reduction in Token usage** — ideal for quick setup, cross-device collaboration, and production use. ### Local Plugin The new local plugin is `@memtensor/memos-local-plugin`: a **local-first memory core shared by OpenClaw, Hermes, and DeepSeek Harness**. It stores data in local SQLite and evolves it into four layers: L1 Trace, L2 Policy, L3 World Model, and callable Skills. With feedback-driven self-evolution, three-tier retrieval, and decision repair, the agent accumulates reusable experience on your own machine. It is best for developers who care most about privacy, local deployment, and observability. --- ## Core Differences | Comparison Dimension | ☁️ MemOS Cloud Plugin | 🖥️ MemOS Local Plugin | | --- | --- | --- | | 💾 **Data Storage & Privacy** | **Cloud storage**: Memory data is stored in MemOS Cloud, making cross-device and multi-instance sharing easy. | **Local storage**: Each agent has its own runtime home. OpenClaw defaults to `~/.openclaw/memos-plugin/`, Hermes defaults to `~/.hermes/memos-plugin/`, and DeepSeek Harness also keeps SQLite, skill packages, logs, and config on the local machine. | | 🤖 **Agent Support** | Currently supports OpenClaw and DeepSeek Harness, backed by MemOS Cloud as the unified memory service. | One shared core supports OpenClaw, Hermes, and DeepSeek Harness: OpenClaw integrates through an in-process TypeScript plugin; Hermes integrates through a Python Provider that talks to the Node core over JSON-RPC; DeepSeek Harness integrates through its native plugin mechanism. | | 🔑 **API & Model Config** | Uses a MemOS Cloud API Key. Memory processing, retrieval, and evolution are handled by the cloud service. | Uses the Memory Viewer's Settings panel for model and team-sharing configuration. Embeddings can use the local provider by default or OpenAI-compatible, Gemini, Cohere, Voyage, and Mistral providers. OpenClaw can inherit the host model; Hermes and DeepSeek Harness can configure an LLM provider and API Key in their own panels. | | 🔍 **Retrieval Capability** | Cloud-based semantic vector retrieval + graph retrieval, optimized by the service. | Three-tier retrieval: Tier 1 Skill, Tier 2 Trace/Episode, and Tier 3 World Model. It combines vector, FTS5, keyword pattern, and error-signature channels, then uses RRF + MMR for relevance and diversity. | | 🧠 **Memory Evolution** | Automatically handled by cloud services: written memories are structured, deduplicated, and corrected in natural language. | Local Reflect2Evolve pipeline: conversations and tool calls become L1 Traces, cross-task patterns become L2 Policies, policies roll up into L3 World Models, and high-value strategies crystallize into callable Skills with active / retired lifecycle states. | | 🛠️ **Decision Repair** | Mainly relies on cloud retrieval to bring back more relevant memory and reduce repeated context. | Tool failures, negative feedback, and task outcomes enter the feedback channel. Failure patterns can trigger decision repair, injecting corrective context into the next turn so the agent avoids repeating the same mistake. | | 👥 **Multi-Agent & Sharing** | Supports multi-agent scenarios and cross-device sharing, making it suitable for teams. | Isolated by default: OpenClaw, Hermes, and DeepSeek Harness have separate databases and viewers. Optional Hub sharing can publish locally crystallized Skills and optional trace excerpts inside a LAN / VPN; hub failures degrade back to local-only mode. | | 👀 **Visualization & Observability** | Managed through the MemOS Cloud Dashboard for API Key and cloud memory capabilities. | Includes a local Viewer with Overview, Memories, Tasks, Policies, World Models, Skills, Analytics, Logs, Import, Settings, and Help pages. HTTP + SSE streams expose events, logs, retrieval, skills, and health status in real time. | | 🛠️ **Deployment & Configuration** | **Very simple**: Create one API Key, then finish install and config for OpenClaw or DeepSeek Harness. The flow mainly relies on the cloud service. | **Very simple**: Installation and upgrades are both one command. The installer auto-detects installed OpenClaw, Hermes, or DeepSeek Harness, installs `@memtensor/memos-local-plugin`, creates runtime folders, and restarts the target runtime. | --- ## Quick Install ### Cloud Plugin Create one API Key, then finish install for each agent. OpenClaw and DeepSeek Harness share the same key. **Get your API Key**: [MemOS Cloud Dashboard](https://memos-dashboard.openmem.net/apikeys/) #### OpenClaw 1. **Install the plugin** ```bash openclaw plugins install @memtensor/memos-cloud-openclaw-plugin@latest ``` 2. **Write the API Key** ```bash mkdir -p ~/.openclaw && echo "MEMOS_API_KEY=mpg-..." > ~/.openclaw/.env ``` 3. **Restart the gateway** ```bash openclaw gateway restart ``` **Manually update the plugin**: ```bash openclaw plugins update @memtensor/memos-cloud-openclaw-plugin@latest openclaw gateway restart ``` #### DeepSeek Harness Use the API Key created above. 1. **Install the cloud plugin into the default DSH web profile** ```bash npx @deepseek-ai/dsh plugin --profile web add @memtensor/memos-cloud-dsh-plugin@latest ``` 2. **Configure the API Key and User ID in `~/.dsh/.env`** ```dotenv MEMOS_API_KEY=mpg-your-key MEMOS_USER_ID=your-stable-user-id ``` Use a stable, distinct ID for each user. Keep your existing ID when upgrading; if it was not configured, use the previous default, `deepseek-harness-user`. 3. **Add the minimal config to `~/.dsh/settings.yaml`** ```yaml memos-cloud: apiKeyEnv: MEMOS_API_KEY ``` 4. **Restart DSH Web** After editing `.env`, press `Ctrl+C` in the original terminal to stop DSH, then start it again: ```bash npx @deepseek-ai/dsh web ``` > For migration of older credential configurations to 0.1.1, the alternative `.credentials.yaml` format, and configuration precedence, see the [DeepSeek Harness setup guide](/openclaw/guide#deepseek-harness-setup). ### Local Plugin (one command) ```bash # Install the plugin curl -fsSL https://raw.githubusercontent.com/MemTensor/MemOS/main/apps/memos-local-plugin/install.sh | bash ``` Installation and upgrades use the same command. The installer auto-detects whether OpenClaw, Hermes, or DeepSeek Harness are installed. In an interactive terminal, it asks which agent to install for; in non-interactive environments, it installs for the detected agent(s). | Agent | Code directory | Data and config directory | Viewer | | --- | --- | --- | --- | | OpenClaw | `~/.openclaw/plugins/memos-local-plugin/` | `~/.openclaw/memos-plugin/` | `http://127.0.0.1:18799` | | Hermes | `~/.hermes/plugins/memos-local-plugin/` | `~/.hermes/memos-plugin/` | `http://127.0.0.1:18800` | | DeepSeek Harness | Deployed to the corresponding plugin directory | Isolated local `memos-plugin` directory | `http://127.0.0.1:18801` | > Upgrading or uninstalling plugin code does not delete existing local data, skill packages, or logs. OpenClaw, Hermes, and DeepSeek Harness each run their own Viewer; there is no shared port or read-only peer view. > > Configure models, team sharing, and general options from the Memory Viewer for the target agent: OpenClaw defaults to `http://127.0.0.1:18799`, Hermes defaults to `http://127.0.0.1:18800`, and DeepSeek Harness defaults to `http://127.0.0.1:18801`. --- # Cloud Plugin (/openclaw/guide) > **Note**: **Compatibility recommendation** > To avoid plugin loading or runtime errors, we recommend upgrading OpenClaw after MemOS has completed compatibility adaptation for the latest OpenClaw version. OpenClaw's going viral lately. But if you've actually used it for a while, you'll find two issues you can hardly avoid: 1. **Tokens burn way too quickly**:OpenClaw can handle many long-tail tasks, but the cost is that each run consumes a huge number of tokens. When you have it monitoring your screen, running scheduled tasks, or handling complex workflows, the token consumption is painfully fast. > ("u know token is money🫠") 2. **Its memory function is rather poor**:Many claim OpenClaw's memory outperforms ChatGPT. Yet in practice, you'll find it does retain some information—but often not what you need. Crucial preferences may be forgotten, while trivial chatter is remembered in vivid detail. > ("can u please remember something really matter to me???") > **Tip**: **NOT OpenClaw's fault, ALL AI agents suffering.** This tutorial guides you through using the MemOS OpenClaw plugin to figure out these 3 pain issues: - **Significantly reduce token consumption** — intelligently retrieve relevant memories without indiscriminately loading all history - **Make memories genuinely useful** — professional memory categorisation and management, remembering what should be retained and forgetting what should be discarded - **Preserve OpenClaw's core strengths** — cross-device control, proactive interaction, and human-like experience remain intact --- ## Why is OpenClaw now a Token Killer🥷? ### Issues with OpenClaw ```plaintext 1st convo: 500 tokens 2nd convo: 500 + 800 = 1,300 tokens 3rd convo: 1,300 + 600 = 1,900 tokens 10th convo: 10,000+ tokens ``` When you have OpenClaw monitoring your screen, performing executive tasks, and running on a schedule, this figure increases even more rapidly. ### Three critical points in OpenClaw's native memory management OpenClaw's memories reside in local `.md` files, categorised as global memories and daily memories. While this sounds promising, practical use reveals three unavoidable issues: #### 1. Global memories become booming As global memories accumulate, context overload ensues. Moreover, these memories persistently interfere with current conversations. You might simply wish to ask a straightforward question, yet it dredges up every utterance from three months prior. #### 2. Daily memory recall proves difficult Accumulating daily memories invariably makes retrieval cumbersome. To recall yesterday's activities, one must undergo an additional retrieval process. Maintaining cross-session memory becomes nearly impossible. #### 3. Memory relies on the model's proactive logging OpenClaw's memory system relies on the model to log information itself, rather than automatic logging. This means it frequently misses details—you mention something, and it promptly forgets. > I've encountered this several times myself: I'd explicitly emphasised a particular project configuration, yet when restarting the conversation the next day, it had no recollection whatsoever, requiring me to explain it all over again. --- ## OpenClaw vs OpenClaw + MemOS: Memory Solution Comparison ### OpenClaw Native Memory Solution #### Memory Storage Solution **Core Philosophy: File is Truth** — Abandoning opaque vector databases in favor of Markdown files as the core carrier of memory. ![Memory Storage Solution](https://cdn.memtensor.com.cn/img/1772697758585_b155tx_compressed.png) #### Memory Retrieval Solution: Dual-Engine Drive | Engine | Technology | Features | |-----|------|------| | **Vector Search** | Cosine Similarity | Captures semantic associations, excels at "concept matching", e.g., associating "login flow" with "authentication" | | **BM25 Search** (Lexical Matching) | FTS5-based lexical matching | Handles "exact tokens", such as error codes, function names, or specific IDs | **Retrieval Trigger**: Triggered via Prompt, model decides automatically **Weighted Score Fusion**: `Score = (0.7 * VectorScore) + (0.3 * BM25Score)` #### Pain Points of Existing Solutions - **Rudimentary Retrieval Algorithms**: Unstable recall, weak relevance, Agent repeats trial and error, Token accumulates rapidly - **Excessive Context Injection**: Fixed reading of today + yesterday + long-term memory, high proportion of invalid context - **Lack of Structure and Deduplication in Memory**: Tool call long outputs are written directly and re-transmitted repeatedly, costs snowball ### OpenClaw + MemOS Memory Solution ![MemOS-OpenClaw](https://cdn.memtensor.com.cn/img/1772679552943_lsuh81_compressed.png) #### Three Core Effects **Effect 1: Controllable Token Costs 💰** > From "Full Context Stuffing" to "Precise Recall per Task" OpenClaw no longer stuffs today+yesterday+long-term memory every time. Instead, MemOS retrieves the most relevant few memories based on the current task (recall budget/count can be set), significantly reducing the proportion of invalid context and avoiding Token snowballing. **Effect 2: More Stable and Accurate Retrieval 🎯** > Reduce repeated trial and error and re-asking, improve one-shot hit rate MemOS provides stronger memory organization and retrieval capabilities (structured, hierarchical/multi-granular, semantic retrieval + rule filtering, etc.), making OpenClaw's recalled content more relevant and stable, reducing repeated reasoning and confirmation caused by "unstable recall". **Effect 3: Cleaner and More Usable Memory ✨** > Structured + Deduplicated + High Compression, avoiding "Long Output Pollution" Long outputs from tool calls (such as traversal results, config/schema, etc.) are not written back to the context verbatim repeatedly; MemOS can summarize/compress, deduplicate, and archive, making it "cleaner" over long-term operation, with memory quality improving rather than deteriorating over time. --- ## After integrating the MemOS OpenClaw plugin👇🏻 - ✅ Retrieve only 3–5 relevant memories at a time - ✅ Maintain context stability within 2,000–3,000 tokens - ✅ Cost remains manageable regardless of dialogue length ### MemOS plugins can enhance your OpenClaw | Feature | Description | |-----|------| | **Automatically remember all conversations** | without relying on models to actively log, ensuring no critical information is missed | | **Precise recall** | retrieve relevant memories based on current task intent, avoiding irrelevant historical data | | **Remember user preferences** | categorise and store preference information specifically, remaining effective across sessions | MemOS OpenClaw has restructured the token consumption model, transforming costs from a ‘historical length function’ into a ‘task relevance function’. Your local OpenClaw costs become manageable, and the system operates more stably. --- ## Quick Start Three steps to boost your Agent with basic memory capabilities. ### 1. Install OpenClaw Ensure that the OpenClaw environment is installed on your system: ```bash # Install the newest version npm install -g openclaw@latest # Initialize and configure startup openclaw onboard ``` ### 2. Get and configure your API Key #### 2.1 Get your Key Log in to or register with MemOS Cloud to get your API Key 🔗 [MemOS Cloud](https://memos-dashboard.openmem.net/apikeys/) ![image.png](https://cdn.memtensor.com.cn/img/1772443326905_kkxve6_compressed.webp) #### 2.2 Set Environment Variables The plugin tries env files in order (**openclaw → moltbot → clawdbot**). For each key, the first file with a value wins. If none of these files exist (or the key is missing), it falls back to the process environment. **Where to configure** - Files (priority order): - `~/.openclaw/.env` - `~/.moltbot/.env` - `~/.clawdbot/.env` - Each line is `KEY=value` **Quick setup (shell)** ```bash echo 'export MEMOS_API_KEY="mpg-..."' >> ~/.zshrc source ~/.zshrc # or echo 'export MEMOS_API_KEY="mpg-..."' >> ~/.bashrc source ~/.bashrc ``` **Quick setup (Windows PowerShell)** ```powershell [System.Environment]::SetEnvironmentVariable("MEMOS_API_KEY", "mpg-...", "User") ``` If `MEMOS_API_KEY` is missing, the plugin will warn with setup instructions and the API key URL. **Minimal config** ```env MEMOS_API_KEY=YOUR_TOKEN ``` ### 3. Install Plugins #### Option A — NPM (Recommended) ```bash openclaw plugins install @memtensor/memos-cloud-openclaw-plugin@latest openclaw gateway restart ``` > Note for Windows Users: If you encounter Error: spawn EINVAL, this is a known issue with OpenClaw's plugin installer on Windows. Please use Option B (Manual Install) below. Make sure it’s enabled in ~/.openclaw/openclaw.json: ```json { "plugins": { "entries": { "memos-cloud-openclaw-plugin": { "enabled": true } } } } ``` #### Option B — Manual Install (Workaround for Windows) 1. Download the latest `.tgz` from [NPM](https://www.npmjs.com/package/@memtensor/memos-cloud-openclaw-plugin). 2. Extract it to a local folder (e.g., `C:\Users\YourName\.openclaw\extensions\memos-cloud-openclaw-plugin`). 3. Configure `~/.openclaw/openclaw.json` (or `%USERPROFILE%\.openclaw\openclaw.json`): ```json { "plugins": { "entries": { "memos-cloud-openclaw-plugin": { "enabled": true } }, "load": { "paths": [ "C:\\Users\\YourName\\.openclaw\\extensions\\memos-cloud-openclaw-plugin\\package" ] } } } ``` > **Tip**: Note: The extracted folder usually contains a package subfolder. Point to the folder containing package.json. Restart the gateway after config changes. ### 4. Update Plugin You can manually update the cloud plugin to the latest version using the following commands: ```bash openclaw plugins update @memtensor/memos-cloud-openclaw-plugin@latest openclaw gateway restart ``` ## DeepSeek Harness Setup The cloud plugin connects through DSH's native lifecycle. Before the first model step of each turn, it retrieves relevant memories from MemOS Cloud. After the turn succeeds, it writes the user and assistant messages back. You do not need to change DSH core code. If cloud memory is temporarily unavailable, the current DSH task still continues. Use the same API Key created above. You do not need to create another one. ### 1. Install the cloud plugin into the default DSH web profile ```bash npx @deepseek-ai/dsh plugin --profile web add @memtensor/memos-cloud-dsh-plugin@latest ``` Install, removal, and version management stay on DSH's official plugin mechanism. ### 2. Configure the API Key and User ID in `~/.dsh/.env` (Recommended) Create or edit `~/.dsh/.env`: ```dotenv MEMOS_API_KEY=mpg-your-key MEMOS_USER_ID=your-stable-user-id ``` `MEMOS_USER_ID` identifies the user's memories for both recall and add. Use a stable, distinct ID for each user. The default is `deepseek-harness-user`. When upgrading, keep your existing ID; if you previously used the default, set it to `deepseek-harness-user` to keep accessing those memories. **Upgrading an older configuration to 0.1.1:** If you previously placed `MEMOS_API_KEY` at the top level of `.credentials.yaml`, move the key to `.env` as shown above, or use the credential format below. Alternatively, store the API Key under `refs` in `~/.dsh/.credentials.yaml`. The following example is for a new file. When editing an existing file, merge the key into its `refs` mapping and preserve other credentials and `records`: ```yaml version: 1 refs: MEMOS_API_KEY: mpg-your-key records: {} ``` With the credentials file, configure the user ID through `MEMOS_USER_ID` in `.env` or `memos-cloud.userId` in `settings.yaml`. ### 3. Add the minimal config to `~/.dsh/settings.yaml` ```yaml memos-cloud: apiKeyEnv: MEMOS_API_KEY ``` Set `apiKeyEnv` to the credential name and store the actual key in `.env` or `.credentials.yaml`. Configure ordinary options such as `baseURL`, recall, and add in `settings.yaml`. For options with multiple supported sources, precedence is highest first: values set directly in `settings.yaml` → inherited process environment → credentials in `.credentials.yaml` → launch-directory `.env` → `~/.dsh/.env` → plugin defaults. The credentials file applies only to the API Key. If DSH still uses an old key after an update, check the higher-priority sources. ### 4. Restart DSH Web DSH loads `.env` at startup. After changing the configuration, press `Ctrl+C` in the terminal running DSH, then start it again: ```bash npx @deepseek-ai/dsh web ``` After that, DSH retrieves relevant cloud memory before each task, and writes new context back after a successful turn. For all configuration options and compatibility details, see the [DSH plugin README](https://github.com/MemTensor/MemOS-Cloud-OpenClaw-Plugin/blob/test/packages/dsh/README.md#configuration). ## Advanced Configuration for Open-Source Projects If you wanna unlock further possibilities, you may explore and configure additional features via the MemOS GitHub project! ### Visual Configuration UI (Config UI) Starting from version `v0.1.12`, the Cloud Plugin features a built-in local visual configuration service, allowing you to manage and modify plugin settings more intuitively. **How to access:** 1. Start your OpenClaw node or host gateway. 2. Once the plugin is successfully loaded and detects that the gateway is ready, it will automatically start the Config UI service in the background. 3. An access link will be printed in the terminal console logs (the default URL is typically `http://127.0.0.1:38463`). 4. Open this link in your browser to access the plugin's visual management backend. **Features:** - **Intuitive Editing**: Supports form-based editing of all core configurations (such as Knowledge Base IDs, LLM retrieval parameters, multi-agent override rules, etc.). - **Real-time Synchronization**: Configuration changes saved via the interface take effect immediately during plugin runtime, without requiring a service restart. - **Status Monitoring**: The interface provides heartbeat detection with the host gateway to ensure the configuration synchronization link is healthy. ### Multi-Agent Support & Isolation The plugin provides powerful native support for multi-agent architectures (via the `agent_id` parameter), making it ideal for complex workflows or team agent scenarios. **1. Enable & Data Isolation** - **How to enable**: Set `"multiAgentMode": true` in the config or configure the environment variable `MEMOS_MULTI_AGENT_MODE=true`. - **Automatic Isolation**: When enabled, the plugin automatically reads `ctx.agentId` from the context. This Agent identifier is attached to memory retrieval and writing, ensuring complete data isolation between different Agents under the same user (Note: the default `"main"` Agent is ignored to maintain legacy data compatibility). **2. Memory Switch per Agent (Whitelist Control)** In Multi-Agent mode, if you do not want all Agents to consume memory, you can use `allowedAgents` to precisely control the whitelist: ```json { "plugins": { "entries": { "memos-cloud-openclaw-plugin": { "enabled": true, "config": { "multiAgentMode": true, "allowedAgents": ["research-agent", "coding-agent"] } } } } } ``` *(Tip: 1. If `allowedAgents` is not configured or is an empty array `[]`, it means **all Agents** are allowed to use memory retrieval and writing. 2. If it is configured, Agents not in the configuration will be completely skipped, and only the configured Agents will be effective for memory retrieval and writing, thereby avoiding Token waste.)* **3. Per-Agent Configuration (agentOverrides)** Beyond simple toggles, you can use `agentOverrides` to **configure different memory parameters for each Agent**. For example, giving a research assistant a looser retrieval threshold, while restricting a coding assistant to read only a specific codebase knowledge base: ```json { "plugins": { "entries": { "memos-cloud-openclaw-plugin": { "enabled": true, "config": { "multiAgentMode": true, "allowedAgents": ["research-agent", "coding-agent"], "memoryLimitNumber": 6, "relativity": 0.45, "agentOverrides": { "research-agent": { "knowledgebaseIds": ["kb-research-papers"], "memoryLimitNumber": 12, "relativity": 0.3, "queryPrefix": "research context: " }, "coding-agent": { "knowledgebaseIds": ["kb-codebase"], "memoryLimitNumber": 9, "addEnabled": false } } } } } } } ``` *(In the example above, memory writing is disabled for the `coding-agent`, and it can only retrieve the top 9 highly relevant memories from the `kb-codebase` knowledge base).* ### Deep customisation of environment variables In addition to the required API Key, you may also adjust the plugin's behaviour via environment variables。 Further configuration details can be found in [the MemTensor official plugin repo](https://github.com/MemTensor/MemOS/tree/main/apps/MemOS-Cloud-OpenClaw-Plugin) ## Testing Now, you can engage in multi-turn conversations with your Agent, for example: **First convo:** - "My favourite programming language is Python" - "I'm developing an e-commerce project" **Second convo (new convo):** - "Do you recall which programming language I prefer?" - "How is the project I mentioned previously progressing?" Now, your OpenClaw will retrieve memories from MemOS Cloud and provide accurate responses ✅ --- ## Use with the CLI Tool If you use OpenClaw alongside other Agents that can execute shell commands (e.g. Cursor, Codex, Claude Code), the MemOS CLI lets them all share the same memory space. ### Install CLI and generate plugin-aware Skill ```bash npm install -g @memtensor/memos-cloud-cli memos init --agent openclaw --memos-plugin ``` `--memos-plugin` makes the generated Skill aware of the installed OpenClaw cloud plugin, avoiding duplicate memory writes. > **Tip**: Using OpenClaw as an example, in the LOCOMO evaluation, using MemOS CLI alone reduced token usage by about 65.5%; integrating MemOS Cloud + CLI improved accuracy from 66.60% to 77.27%. ### Install Skill for other Agents ```bash memos init --agent cursor memos init --agent codex ``` Once installed, these Agents will also automatically search and write MemOS memories through the CLI, sharing the same memory space as OpenClaw. ### Test whether the plugin and CLI work together Return to OpenClaw and start a conversation that should produce long-term memory: ```text I am recently working on an e-commerce project, mainly using Python. Please remember this. ``` Then start a new conversation and ask: ```text What project am I working on recently? Which language am I mainly using? ``` If OpenClaw answers using the previous turn, the plugin has written and recalled memory successfully. The generated CLI Skill is also aware of the installed plugin, so it avoids duplicate memory writes. > **Tip**: See the [MemOS CLI Guide](/mcp_agent/cli/guide) for the full command reference and more usage details. --- ## More Integration Methods > **Tip**: In addition to the OpenClaw plugin, MemOS also supports [MCP](/mcp_agent/mcp/guide) (for Cursor, Claude Desktop, and other clients) and [CLI](/mcp_agent/cli/guide) (for any Agent framework that can execute shell commands). See [Use in Agents](/memos_cloud/getting_started/agent_usage) for a full comparison. --- # Local Plugin (/openclaw/local_plugin) > **Note**: **Compatibility recommendation** > Use a version of OpenClaw, Hermes Agent, or DeepSeek Harness supported by the current MemOS Local Plugin release to avoid plugin loading or runtime errors. `@memtensor/memos-local-plugin` is the new MemOS local plugin: one local-first memory core for **OpenClaw**, **Hermes Agent**, and **DeepSeek Harness**. It does not host your memory data in the cloud. Instead, it maintains SQLite data, skill packages, and logs on your own machine so the agent can accumulate reusable experience locally. If you want a cloud-hosted memory service with the simplest API Key setup, see the [Cloud Plugin](/openclaw/guide). If you care more about privacy, local runtime, observability, or using the same local memory capability across OpenClaw, Hermes, and DeepSeek Harness, use this local plugin. ## Core Capabilities | Capability | Description | | --- | --- | | Local-first | OpenClaw, Hermes, and DeepSeek Harness each get an isolated runtime home. SQLite, skills, logs, and config stay on your machine. | | Multi-agent support | OpenClaw integrates through an in-process TypeScript plugin; Hermes integrates through a Python Provider that talks to the same Node.js memory core over JSON-RPC; DeepSeek Harness integrates through its native plugin mechanism. | | Four memory layers | L1 Trace records each execution step, L2 Policy induces cross-task strategies, L3 World Model compresses environment knowledge, and Skill turns high-value experience into callable capabilities. | | Three-tier retrieval | Retrieval runs across Skill → Trace/Episode → World Model, combining vector, FTS5, keyword pattern, and error-signature channels with RRF + MMR. | | Feedback-driven evolution | Tool outcomes, environment feedback, and explicit user feedback update memory value and drive policy induction, skill crystallization, and decision repair. | | Local Viewer | Includes Overview, Memories, Tasks, Policies, World Models, Skills, Analytics, Logs, Import, Settings, and Help pages. | | Import and migration | Supports JSON import/export, legacy plugin migration, and agent-specific native imports for OpenClaw session JSONL, Hermes `MEMORY.md`, or DeepSeek Harness session data. | | Optional team sharing | Isolated by default. Enable sharing from the Memory Viewer's Team Sharing panel to share crystallized Skills and optional trace excerpts over a LAN / VPN. | ## How It Works Before each task, the plugin retrieves relevant context and injects it into the agent. After the task ends, it stores conversations, tool calls, observations, and feedback in the local pipeline. High-value patterns gradually become Policies, World Models, and callable Skills. The next time a similar task appears, the agent receives guidance about what to do and what to avoid. | Stage | What Happens | Output | | --- | --- | --- | | 1. Agent adapter | OpenClaw, Hermes, and DeepSeek Harness send conversations, tool calls, and feedback to the shared `MemoryCore` through their adapters. | Standardized turns, tool outcomes, feedback | | 2. Local capture | `MemoryCore` turns the execution process into grounded, traceable step records. | L1 Trace | | 3. Experience induction | Similar Traces are induced into cross-task strategies, then compressed into environment knowledge. | L2 Policy, L3 World Model | | 4. Skill crystallization | High-value strategies become callable Skills and keep updating reliability from later feedback. | Skill, η, lifecycle status | | 5. Retrieval injection | Before the next task, Retriever recalls context from Skill, Trace/Episode, and World Model tiers. | Local memory context injected into the agent | ## Quick Start ### Step 1: Install or Upgrade with One Command Installation and upgrades use the same command. The current installer targets macOS / Linux: ```bash curl -fsSL https://raw.githubusercontent.com/MemTensor/MemOS/main/apps/memos-local-plugin/install.sh | bash ``` The installer auto-detects whether OpenClaw, Hermes, and/or DeepSeek Harness are installed. In an interactive terminal, it asks which agent to install for; in non-interactive environments, it installs for the detected agent(s). It deploys plugin code, installs production dependencies, and restarts the target runtime when needed. > Do not use direct `npm install` as the primary path. The installer handles agent detection, directory layout, config initialization, and runtime restart. ### Step 2: Open the Memory Viewer After installation, open the corresponding Memory Viewer: | Agent | Memory Viewer | | --- | --- | | OpenClaw | `http://127.0.0.1:18799` | | Hermes | `http://127.0.0.1:18800` | | DeepSeek Harness | `http://127.0.0.1:18801` | If you install OpenClaw, Hermes, and DeepSeek Harness together, they use separate Viewers and separate local data directories. ### Step 3: Configure from the Panel All user-facing configuration is done from the Memory Viewer: - **Settings → AI Models**: configure Embedding, LLM, Skill Evolver, and use Test to confirm connectivity. - **Settings → Team Sharing**: enable or disable team sharing, then configure team address and tokens. - **Settings → General**: configure language, detailed logs, anonymous telemetry, and related options. After saving, the Viewer restarts the plugin and loads the new settings. ### Step 4: Start the Target Agent After installation, start the agent you selected as usual. The plugin retrieves local context before the agent builds its prompt, then writes conversations, tool calls, observations, and feedback into local memory after the turn finishes. | Agent | How to start | Plugin integration | | --- | --- | --- | | OpenClaw | Start or restart the OpenClaw gateway normally | TypeScript plugin calls `MemoryCore` in the OpenClaw process | | Hermes | Run `hermes chat` | Python Provider calls the Node.js memory core over JSON-RPC | | DeepSeek Harness | Run `npx @deepseek-ai/dsh web` | DeepSeek Harness adapter calls `MemoryCore` | If the Hermes machine cannot run Node.js, the Hermes Provider reports unavailable and falls back to Hermes' own in-memory mode. ### Step 5: Verify Memory Back in the Memory Viewer, check: 1. **Overview**: confirm core status, version, and event stream. 2. **Memories**: confirm conversations and tool steps are written as Traces. 3. **Tasks / Policies / World Models / Skills**: inspect how experience is induced and crystallized. 4. **Import**: migrate legacy data, import OpenClaw session JSONL, Hermes `MEMORY.md`, DeepSeek Harness session data, or import/export JSON backups. 5. **Help**: look up field meanings such as `V`, `α`, `R_human`, `η`, support, and gain. ## Agent Differences | Item | OpenClaw | Hermes | DeepSeek Harness | | --- | --- | --- | --- | | Integration | TypeScript plugin, in-process calls to `MemoryCore` | Python `MemoryProvider`, stdio JSON-RPC to Node bridge | DeepSeek Harness adapter calls `MemoryCore` | | Default Viewer | `http://127.0.0.1:18799` | `http://127.0.0.1:18800` | Provided by the DeepSeek Harness runtime | | Model configuration | Configure in OpenClaw Viewer Settings → AI Models | Configure in Hermes Viewer Settings → AI Models | Configure in the DeepSeek Harness Web UI under Settings → Models | | Data sharing | Isolated from Hermes and DeepSeek Harness by default | Isolated from OpenClaw and DeepSeek Harness by default | Isolated from OpenClaw and Hermes by default | All three agents use separate databases and Viewers even when installed on the same machine. Team sharing only starts after you explicitly enable `hub:`. ## Available Tools OpenClaw, Hermes, and DeepSeek Harness expose memory tools through their own host interfaces. Common capabilities include: | Tool | Purpose | | --- | --- | | `memory_search` | Search across relevant Skills, Trace/Episodes, and World Models. | | `memory_get` | Fetch a memory detail. | | `memory_timeline` | Inspect an episode / task timeline. | | `skill_list` | List callable Skills. | | `skill_get` | Fetch a Skill invocation guide. | | `memory_environment` | Query L3 World Models for project structure, environment behavior, and constraints. | The plugin also records tool successes and failures for later decision repair. ## Data Management - **Back up**: export JSON from the Viewer's Import page, or back up the current agent's `~/./memos-plugin/` directory. - **Clear only memory**: after confirming you have a backup, delete `data/` and `skills/` under the runtime home. - **Clear logs**: delete regular files under `logs/`. Audit logs are gzipped monthly and kept by default. - **Full reset**: delete the entire `~/./memos-plugin/` directory. It will be recreated empty on the next start. ## More - [MemOS local plugin project](https://github.com/MemTensor/MemOS/tree/main/apps/memos-local-plugin) - [Cloud Plugin vs Local Plugin](/openclaw/plugin_compare) --- # OpenClaw Plugin Changelog (/openclaw/changes) The OpenClaw plugin changelog has moved to the **Plugin** tab on the main changelog page. This page no longer maintains a duplicate release timeline. Visit [Changelog](/changelog) and switch to the **Plugin** tab to view the latest OpenClaw Cloud Plugin, OpenClaw Local Plugin, and MemOS CLI release notes. --- # Knowledge Base Usage (/openclaw/examples/knowledge_base) ## Cloud Plugin The MemOS OpenClaw cloud plugin can recall both personal memories and selected knowledge base content before each task. This is useful for connecting product docs, company policies, project materials, coding standards, and other long-lived references to OpenClaw so the Agent can automatically use them during execution. ### 1. Create a Knowledge Base and Get Its ID Create the knowledge base in [MemOS Cloud Dashboard](https://memos-dashboard.openmem.net) first. Steps: 1. Log in to [MemOS Cloud Dashboard](https://memos-dashboard.openmem.net). 2. Go to the knowledge base management page and create a new knowledge base. 3. Upload the documents or Skill files that the Agent should retrieve from. 4. Wait until file processing is complete. 5. Copy the knowledge base ID from the knowledge base details page, for example `kb-company-handbook`. > **Warning**: Use the real knowledge base ID copied from the dashboard to replace `kb-company-handbook` in the examples below. The knowledge base name is only a display name; the plugin configuration requires the knowledge base ID. ### 2. Configure a Global Knowledge Base Knowledge base configuration has two directions: - `knowledgebaseIds` / `MEMOS_KNOWLEDGEBASE_IDS`: queries knowledge bases. During `/search/memory`, the plugin recalls content from these knowledge bases. - `allowKnowledgebaseIds` / `MEMOS_ALLOW_KNOWLEDGEBASE_IDS`: writes to knowledge bases. During `/add/message`, the plugin is allowed to write newly generated memories to these knowledge bases. If all OpenClaw sessions should retrieve from the same knowledge base, configure `knowledgebaseIds` in `~/.openclaw/openclaw.json`: ```json { "plugins": { "entries": { "memos-cloud-openclaw-plugin": { "enabled": true, "config": { "apiKey": "YOUR_MEMOS_API_KEY", "knowledgebaseIds": ["kb-company-handbook"], "memoryLimitNumber": 6, "relativity": 0.45 } } } } } ``` Restart the OpenClaw gateway after updating the config: ```bash openclaw gateway restart ``` ### 3. Configure with Environment Variables You can also configure knowledge base IDs in `~/.openclaw/.env`: ```bash MEMOS_API_KEY=YOUR_MEMOS_API_KEY MEMOS_KNOWLEDGEBASE_IDS="kb-company-handbook,kb-product-docs" ``` `MEMOS_KNOWLEDGEBASE_IDS` defines the knowledge base scope for retrieval. The plugin reads from these knowledge bases when calling `/search/memory`. If you need to write newly generated conversation memories into a knowledge base, configure the write parameter separately: ```bash MEMOS_ALLOW_KNOWLEDGEBASE_IDS="kb-company-handbook" ``` > **Warning**: Knowledge base writes can store Agent-generated information into the target knowledge base, but knowledge base content is not filtered by `agent_id`. In other words, if multiple Agents are configured to read the same knowledge base, anything written into that knowledge base may be recalled by all of them, weakening multi-agent memory isolation. > > If you need strict Agent isolation, do not write conversation memories into a shared knowledge base. Configure `allowKnowledgebaseIds` or `MEMOS_ALLOW_KNOWLEDGEBASE_IDS` only when you explicitly want the content to become shared team knowledge. ### 4. Bind Different Knowledge Bases to Different Agents When different Agents own different tasks, enable multi-agent mode and use `agentOverrides` to assign knowledge bases per Agent: ```json { "plugins": { "entries": { "memos-cloud-openclaw-plugin": { "enabled": true, "config": { "multiAgentMode": true, "allowedAgents": ["research-agent", "coding-agent"], "memoryLimitNumber": 6, "relativity": 0.45, "agentOverrides": { "research-agent": { "knowledgebaseIds": ["kb-research-papers"], "memoryLimitNumber": 12, "queryPrefix": "research context: " }, "coding-agent": { "knowledgebaseIds": ["kb-codebase", "kb-api-docs"], "memoryLimitNumber": 9, "includeToolMemory": true, "addEnabled": false } } } } } } } ``` This configuration means: - `research-agent` retrieves from research paper / academic knowledge bases. - `coding-agent` retrieves from codebase and API documentation knowledge bases, and disables memory writes to avoid storing temporary debugging details as long-term memory. - Agents not listed in `agentOverrides` inherit the global configuration. If you enable knowledge base writes in a multi-agent setup, make sure the write target is not a shared knowledge base read by multiple Agents. Otherwise, information from different Agents may become visible to each other through the knowledge base. ### 5. Verify Knowledge Base Recall After configuration, ask OpenClaw a question that can only be answered from the uploaded knowledge base documents: ```text You: According to the company reimbursement policy, what purchase amount for design software requires special approval? OpenClaw: According to the procurement rules in the knowledge base, design software purchases above 1000 require special approval... ``` If the answer does not use knowledge base content, check the following: - Confirm that the knowledge base files have finished processing in the dashboard. - Confirm that `knowledgebaseIds` or `MEMOS_KNOWLEDGEBASE_IDS` uses the knowledge base ID, not the knowledge base name. - Confirm that the OpenClaw gateway has been restarted and loaded the latest config. - If using multi-agent mode, confirm that the current Agent is listed in `allowedAgents` and that the corresponding `agentOverrides` config is correct. ### Config Reference For knowledge base configuration details, see the [official MemOS-Cloud-OpenClaw-Plugin repository](https://github.com/MemTensor/MemOS-Cloud-OpenClaw-Plugin): | Config | Purpose | | --- | --- | | `knowledgebaseIds` | Query knowledge bases. Plugin config for the knowledge base retrieval scope, corresponding to `/search/memory`. | | `MEMOS_KNOWLEDGEBASE_IDS` | Query knowledge bases. Environment variable form of the knowledge base retrieval scope. Separate multiple IDs with commas. | | `allowKnowledgebaseIds` | Write to knowledge bases. Plugin config for knowledge bases that newly generated memories may be written to, corresponding to `/add/message`. | | `MEMOS_ALLOW_KNOWLEDGEBASE_IDS` | Write to knowledge bases. Environment variable form of knowledge bases that newly generated memories may be written to. | | `agentOverrides..knowledgebaseIds` | In multi-agent scenarios, assign knowledge bases to a specific Agent. | --- # Multi-Agent Memory Isolation (/openclaw/examples/multi_agent) ## Cloud Plugin The MemOS OpenClaw Cloud plugin supports complete isolation of memory and message history across multiple Agents. Each Agent can only access its own memory, preventing cross-agent interference. ### How to Use in Cloud Plugin With a simple configuration, different Agents can have independent memory spaces. Both auto-detection and static assignment are supported. #### 1. Enable Multi-Agent Mode Add the following to your `openclaw.json`: ```json { "plugins": { "entries": { "memos-cloud-openclaw-plugin": { "config": { "multiAgentMode": true } } } } } ``` Or set the environment variable: ```bash MEMOS_MULTI_AGENT_MODE=true ``` #### 2. Auto-detect Agent Once enabled, the plugin automatically reads `ctx.agentId` and isolates memory for each Agent. No extra configuration is required. #### 3. Statically Assign Agent (Optional) If you need to pin a specific Agent ID, set it in the config: ```json { "config": { "agentId": "marketing_agent" } } ``` #### 4. Configure Parameters Per Agent (Optional) Beyond isolating memory spaces, you can use `agentOverrides` to override parameters for each Agent, such as knowledge bases, recall limits, relevance threshold, and whether memory writes are enabled. Fields that are not specified inherit from the global config. ```json { "plugins": { "entries": { "memos-cloud-openclaw-plugin": { "enabled": true, "config": { "multiAgentMode": true, "allowedAgents": ["research-agent", "coding-agent"], "knowledgebaseIds": [], "memoryLimitNumber": 6, "relativity": 0.45, "agentOverrides": { "research-agent": { "knowledgebaseIds": ["kb-research-papers", "kb-academic"], "memoryLimitNumber": 12, "relativity": 0.3, "includeToolMemory": true, "captureStrategy": "full_session", "queryPrefix": "research context: " }, "coding-agent": { "knowledgebaseIds": ["kb-codebase", "kb-api-docs"], "memoryLimitNumber": 9, "relativity": 0.5, "addEnabled": false } } } } } } } ``` This configuration means: - `research-agent` uses research / academic knowledge bases, recalls more memories, and includes tool memory. - `coding-agent` only reads from codebase and API documentation knowledge bases, and disables memory writes. - Other Agents, if allowed to use memory, inherit global `knowledgebaseIds`, `memoryLimitNumber`, and `relativity`. You can also configure a JSON string in `.env` with `MEMOS_AGENT_OVERRIDES`, but it has lower priority than `agentOverrides` in `openclaw.json`: ```bash MEMOS_AGENT_OVERRIDES='{"research-agent":{"memoryLimitNumber":12,"relativity":0.3},"coding-agent":{"memoryLimitNumber":9,"addEnabled":false}}' ``` Common overridable fields: | Field | Description | | --- | --- | | `knowledgebaseIds` | Knowledge base IDs retrieved by the current Agent. | | `memoryLimitNumber` | Maximum number of memory items recalled by the current Agent. | | `preferenceLimitNumber` | Maximum number of preference memories recalled by the current Agent. | | `includePreference` | Whether to recall preference memories. | | `includeToolMemory` | Whether to recall tool memories. | | `toolMemoryLimitNumber` | Maximum number of tool memories to recall. | | `relativity` | Relevance threshold, usually between `0` and `1`. | | `recallEnabled` | Whether memory recall is enabled for the current Agent. | | `addEnabled` | Whether memory writes are enabled for the current Agent. | | `captureStrategy` | Capture strategy, such as `last_turn` or `full_session`. | | `queryPrefix` | Search query prefix for the current Agent. | | `recallFilterEnabled` | Whether secondary recall filtering is enabled. | | `allowKnowledgebaseIds` | Knowledge base IDs that the current Agent is allowed to write to. | | `tags` | Tags attached when writing memories. | ### Principles - **/search/memory**: Memory retrieval — returns only the current Agent's memories - **/add/message**: Record insertion — automatically tags data for the current Agent - **Config merging**: the plugin reads global config first, then applies `agentOverrides.` for the current Agent - **Backward compatibility**: Default Agent `"main"` is ignored to keep existing single-Agent data unaffected ### Use Cases - **Multi-role collaboration**: Strategy, business, marketing, and engineering Agents can work in parallel - **Business-line isolation**: Agents from different business lines run independently without interference - **Persona consistency**: Preserve each Agent's long-term persona and behavior style --- ## Local Plugin `@memtensor/memos-local-plugin` supports both OpenClaw and Hermes. By default, each agent uses its own runtime home and local database. If multiple sessions / agents share one runtime, retrieval is scoped toward the current agent context. For cross-instance collaboration, enable team sharing from **Viewer → Settings → Team Sharing**. ### Rules - **Isolated by default**: OpenClaw uses `~/.openclaw/memos-plugin/`, while Hermes uses `~/.hermes/memos-plugin/`. They do not share databases automatically. - **Current agent first**: retrieval prioritizes the current agent / session's Traces, Policies, World Models, and Skills. - **Optional sharing**: when `hub.enabled` is on, instances can share locally crystallized Skills and optional trace excerpts over a LAN / VPN. - **Graceful fallback**: Hub is not on the algorithm critical path. If sharing is unavailable, the plugin falls back to local-only memory. ### Example Workflow ```text OpenClaw: memory_search("deploy config") → prioritizes OpenClaw's local Skill / Trace / World Model store Hermes: memory_search("deploy config") → prioritizes Hermes' local Skill / Trace / World Model store With Hub enabled: OpenClaw / Hermes can pull team-shared Skills private Traces remain local to each machine and runtime home by default ``` ### Expected Results - OpenClaw and Hermes do not read each other's local database by default - Team members can explicitly share high-value Skills to avoid repeating mistakes - Local writes, retrieval, and skill lookup continue to work even if Hub is unavailable --- # Secondary Filtering for Memory Recall (/openclaw/examples/recall_filter) ## Cloud Plugin The MemOS Openclaw cloud plugin supports secondary filtering of recalled memories with a specified large language model. After filtering, only memories that are highly relevant to the current task are injected into context, which reduces irrelevant noise and saves tokens. ### How to Use Just configure an OpenAI-compatible model endpoint (such as local Ollama or a third-party LLM API) and enable the filter switch to turn on secondary memory filtering. #### 1. Enable Memory Filtering When configuring an LLM for memory filtering, you **must** configure the API Key and Base URL. Add the following in your `openclaw.json` config: ```json { "plugins": { "entries": { "memos-cloud-openclaw-plugin": { "config": { "recallFilterEnabled": true, "recallFilterBaseUrl": "http://127.0.0.1:11434/v1", "recallFilterApiKey": "sk-...", "recallFilterModel": "qwen2.5_7b" } } } } } ``` Or set environment variables: ```bash MEMOS_RECALL_FILTER_ENABLED=true MEMOS_RECALL_FILTER_BASE_URL="http://127.0.0.1:11434/v1" MEMOS_RECALL_FILTER_API_KEY="sk-..." MEMOS_RECALL_FILTER_MODEL="qwen2.5_7b" ``` #### 2. Configure Authentication and Advanced Parameters (Optional) If you need to adjust timeout and failure strategy, you can specify them in the config: ```json { "config": { "recallFilterTimeoutMs": 6000, "recallFilterFailOpen": true } } ``` ### How It Works - **Post-recall interception**: Before each conversation round, after memories are recalled from the cloud, the plugin sends candidate memory entries to your configured filtering model for secondary screening. - **Precise retention**: After model judgment, only entries marked as `keep` are retained and injected into the agent context. - **High-availability fallback**: Fail-open (`recallFilterFailOpen: true`) is enabled by default. If the filtering model times out or fails, it automatically falls back to full injection without filtering, so the current conversation is not interrupted. ### Typical Use Cases - **Pruning long-term memory**: In long-running conversations with many accumulated memories, remove content unrelated to the current prompt to significantly reduce main-model context token usage. - **Improving reasoning accuracy**: For agents handling complex tasks, filter out early irrelevant memories to improve reasoning quality on the core task. - **Working with local models**: Use a locally running small model (such as `qwen2.5_7b` via Ollama) as a low-cost pre-filter to improve memory injection quality without increasing main-model API costs. --- ## Local Plugin `@memtensor/memos-local-plugin` includes multi-stage local retrieval filtering. It first recalls candidates from Skill, Trace/Episode, and World Model tiers, then applies RRF + MMR for fusion and deduplication. If an LLM is configured, it can also run a final relevance check before injection to drop items that only share surface keywords with the current task. ### How to Configure Configure this directly in the Memory Viewer for the target agent: | Agent | Memory Viewer | | --- | --- | | OpenClaw | `http://127.0.0.1:18799` | | Hermes | `http://127.0.0.1:18800` | Steps: 1. Open the Memory Viewer. 2. Go to **Settings → AI Models**. 3. In the **LLM** section, choose a provider and fill in endpoint, API Key, model, and related fields. 4. Click **Test** to confirm the model works. 5. Save the settings. The Viewer restarts the plugin and loads the new config. After saving, local retrieval can use that LLM for a relevance check after recall and RRF/MMR ranking. If no LLM is configured, the plugin still uses built-in multi-channel recall and mechanical threshold filtering. ### Local Retrieval Flow ```text User request → Build retrieval query and tags → Tier 1: Skill candidates → Tier 2: Trace / Episode candidates → Tier 3: World Model candidates → Multi-channel recall: vector / FTS5 / pattern / error signatures → RRF fusion + MMR diversity control → Optional LLM relevance check → Inject into the agent ``` ### Expected Results - Injected memory context is more focused and less noisy - Skill, Trace/Episode, and World Model hits are not selected by vector similarity alone - If the LLM is unavailable, retrieval falls back to stricter mechanical thresholds without breaking basic recall --- # Local Plugin Usage (/openclaw/examples/hermes_usage) ## Basic Usage `@memtensor/memos-local-plugin` supports both OpenClaw and Hermes. After installation, start the agent you use as usual. The plugin injects local memory context before each task and writes Trace, Policy, World Model, and Skill data after the task finishes. | Agent | How to start | Viewer | | --- | --- | --- | | OpenClaw | Start or restart the OpenClaw gateway normally | `http://127.0.0.1:18799` | | Hermes | `hermes chat` | `http://127.0.0.1:18800` | ### Verify Memory is Working 1. Have a conversation with OpenClaw or Hermes. 2. Open the corresponding Memory Viewer and confirm the conversation appears in **Memories** / **Tasks**. 3. In a new conversation, ask the agent to recall what you discussed: ```text You: Do you remember what I asked you to help me with before? Agent: (Calls memory_search) Yes, we previously discussed... ``` --- ## Memory Tools The local plugin exposes memory tools through each agent host. Exact tool presentation may differ by host, but the core capabilities are shared. | Tool | Purpose | | --- | --- | | `memory_search` | Search across Skill, Trace/Episode, and World Model tiers. | | `memory_get` | Fetch a memory detail. | | `memory_timeline` | Inspect an episode / task timeline. | | `skill_list` | List currently available Skills. | | `skill_get` | Fetch a Skill invocation guide. | | `memory_environment` | Query L3 World Models for project structure, environment behavior, and constraints. | ### Call Examples ```text Agent call: memory_search("Nginx deployment config") → Returns relevant Skills, Trace snippets, and environment knowledge Agent call: skill_get("nginx-proxy") → Returns executable steps, applicability, and caveats ``` The plugin also records tool successes and failures for later decision repair. --- ## Team Sharing By default, OpenClaw and Hermes use separate local databases. For collaboration, enable Team Sharing from the Memory Viewer to share locally crystallized Skills and optional trace excerpts with other instances on the same LAN / VPN. ### How to Configure Open the Memory Viewer for the target agent, go to **Settings → Team Sharing**, fill in the team address and tokens as prompted, then save. The Viewer restarts the plugin and loads the new settings. ### Expected Results - Private local data stays in the current agent's runtime home by default. - Explicitly shared Skills can be discovered and reused by other instances. - Hub is not on the algorithm critical path. If sharing fails, local writes, retrieval, and Skill lookup continue to work. --- ## Multi-Agent Scenarios When OpenClaw and Hermes are installed on the same machine, their ports and data are isolated: | Resource | OpenClaw | Hermes | | --- | --- | --- | | Viewer | `18799` | `18800` | | Data directory | `~/.openclaw/memos-plugin/` | `~/.hermes/memos-plugin/` | | Config entry | Viewer → Settings | Viewer → Settings | ```text OpenClaw: memory_search("deploy config") → prioritizes OpenClaw's local experience Hermes: memory_search("deploy config") → prioritizes Hermes' local experience With Hub enabled: both can explicitly reuse team-shared Skills ``` --- ## Viewer Management The Memory Viewer provides these common entry points: | Page | Purpose | | --- | --- | | Overview | Inspect core status, version, event stream, and health. | | Memories | Inspect L1 Traces and raw execution records. | | Tasks | Inspect conversations and execution results grouped by task. | | Policies | Inspect strategies induced from multiple Traces. | | World Models | Inspect environment knowledge and constraints. | | Skills | Inspect, search, or retire crystallized Skills. | | Import | Import legacy plugin data, OpenClaw session JSONL, Hermes `MEMORY.md`, or import/export JSON backups. | | Settings | Configure models, team sharing, logs, and telemetry. | | Help | Look up field meanings such as `V`, `α`, `R_human`, `η`, support, and gain. | --- # Overview (/api_docs/start/overview) ## 1. Interface Introduction MemOS provides a complete set of interfaces. Through simple API requests, you can integrate memory-related functions into your AI applications, realizing memory production, scheduling, recall, and lifecycle management for different users and AI agents. > **Tip**: **Quick Start:** Get your API key from the [**MemOS Console**](https://memos-dashboard.openmem.net/apikeys/) and complete your first memory operation in one minute. ## 2. Getting Started Start using MemOS API through these two simple core steps: * [**Add Message**](/api_docs/core/add_message): Store original message content from user conversations and generate memories; * [**Search Memory**](/api_docs/core/search_memory): Retrieve and recall relevant user memory fragments to provide reference for model-generated responses. ### Add Message ```python [Python (HTTP)] import os, requests, json os.environ["MEMOS_API_KEY"] = "YOUR_API_KEY" os.environ["MEMOS_BASE_URL"] = "https://memos.memtensor.cn/api/openmem/v1" data = { "user_id": "user_001", "conversation_id": "conv_001", "messages": [ {"role": "user", "content": "I have a business trip to Beijing next Tuesday"}, {"role": "assistant", "content": "Sure, shall I check the weather or hotels in Beijing for you?"} ] } headers = { "Content-Type": "application/json", "Authorization": f"Token {os.environ['MEMOS_API_KEY']}" } res = requests.post(f"{os.environ['MEMOS_BASE_URL']}/add/message", headers=headers, data=json.dumps(data)) print(res.json()) ``` ```python [Python (SDK)] # pip install MemoryOS -U from memos.api.client import MemOSClient client = MemOSClient(api_key="YOUR_API_KEY") res = client.add_message( user_id="user_001", conversation_id="conv_001", messages=[ {"role": "user", "content": "I have a business trip to Beijing next Tuesday"}, {"role": "assistant", "content": "Sure, shall I check the weather or hotels in Beijing for you?"} ] ) print(res) ``` ```bash [Curl] curl --request POST \ --url https://memos.memtensor.cn/api/openmem/v1/add/message \ --header 'Authorization: Token YOUR_API_KEY' \ --header 'Content-Type: application/json' \ --data '{ "user_id": "user_001", "conversation_id": "conv_001", "messages": [ {"role": "user", "content": "I have a business trip to Beijing next Tuesday"}, {"role": "assistant", "content": "Sure, shall I check the weather or hotels in Beijing for you?"} ] }' ``` ### Search Memory ```python [Python (HTTP)] import os, requests, json os.environ["MEMOS_API_KEY"] = "YOUR_API_KEY" os.environ["MEMOS_BASE_URL"] = "https://memos.memtensor.cn/api/openmem/v1" data = { "query": "What travel plans does the user have recently?", "user_id": "user_001" } headers = { "Content-Type": "application/json", "Authorization": f"Token {os.environ['MEMOS_API_KEY']}" } res = requests.post(f"{os.environ['MEMOS_BASE_URL']}/search/memory", headers=headers, data=json.dumps(data)) print(res.json()) ``` ```python [Python (SDK)] # pip install MemoryOS -U from memos.api.client import MemOSClient client = MemOSClient(api_key="YOUR_API_KEY") res = client.search_memory( query="What travel plans does the user have recently?", user_id="user_001" ) print(res) ``` ```bash [Curl] curl --request POST \ --url https://memos.memtensor.cn/api/openmem/v1/search/memory \ --header 'Authorization: Token YOUR_API_KEY' \ --header 'Content-Type: application/json' \ --data '{ "query": "What travel plans does the user have recently?", "user_id": "user_001" }' ``` ## 3. Interface Categories Explore the rich functional interfaces provided by MemOS: * [**Core Operations API**](/api_docs/core/add_message): Core memory operations including adding messages, searching, deleting, updating memories, and feedback. * [**Profile API**](/api_docs/core/bind_profile_template): Manage Profile template binding, editing, and deletion. * [**Self-developed Model API**](/api_docs/core/extract_memory): Call memory extraction and reranking model capabilities. * [**Message API**](/api_docs/message/get_message): Query historical messages and async task status. * [**Chat API**](/api_docs/chat/chat): Generate chat responses with memory recall and knowledge base enhancement. * [**Knowledge Base API**](/api_docs/knowledge/create_kb): Create and manage knowledge bases and their documents. ## 4. Authentication All API requests require authentication. Please include your API key in the `Authorization` header of the request. Get your API key from the [**MemOS Console**](https://memos-dashboard.openmem.net/apikeys/). > **Warning**: Do not expose your API key in client-side code or public repositories. All requests should be made via environment variables or server-side calls. ## 5. Next Steps * 👉 [**Add Message**](/api_docs/core/add_message): Generate your first memory; * 👉 [**Search Memory**](/api_docs/core/search_memory): Use memory filters to implement advanced memory retrieval. --- # Project Configuration (/api_docs/start/configuration) If you are a new user and have not logged in to the console before, start with the guide that matches your use case: | Use case | What it helps you do | | :--- | :--- | | [Use in Agent](/memos_cloud/getting_started/agent_usage) | Connect MemOS to your personal Agent through plugins, CLI, or similar integration methods | | [Integrate in Your App](/memos_cloud/getting_started/quick_start) | Use the MemOS API / SDK in your application | After login, MemOS automatically creates a default project. Copy the API Key, and you can use all features in that project. Continue reading this page if you want to understand: - How projects and API Keys are related; - How to create, switch, edit, or delete projects; - How to use knowledge bases in a project; - How to troubleshoot configuration errors. ## 1. Projects and API Keys A project is the memory isolation space defined by MemOS. Each project has its own API Key for accessing memories, messages, and request logs under that project. Projects are isolated from each other. An API Key from Project A cannot access resources in Project B. > **Note**: After switching projects, go back to the API Keys page and copy the API Key for the current project. ![API Keys page](https://cdn.memtensor.com.cn/img/1781512378168_9kxrmd_compressed.png) ## 2. Manage Projects When you need to isolate different apps, environments, or business spaces, you can create, switch, edit, and delete projects from [Projects](https://memos-dashboard.openmem.net/projects). ![Projects page](https://cdn.memtensor.com.cn/img/1781512406018_mu57b2_compressed.png) ### 2.1 Create or Switch Projects - Click "New" on the Projects page, then enter the project name and description to create a project. - The project marked as "Current Project" is the project currently selected in the console. - After clicking "Switch to This Project", API Keys, knowledge bases, and request logs all switch to that project scope. ![Create project](https://cdn.memtensor.com.cn/img/1781512406018_mu57b2_compressed.png) ### 2.2 Delete a Project - The current project cannot be deleted directly. Switch to another project first. - Deleting a project clears its memories, messages, knowledge base associations, API Keys, and related data. - Deletion is irreversible. Only delete test projects or deprecated projects that you no longer need. ![Delete project confirmation](https://cdn.memtensor.com.cn/img/1781512428231_x11kqz_compressed.png) ## 3. Associate Knowledge Bases with a Project If your app / Agent needs to refer to fixed documents, create and associate a knowledge base with the project. A project can associate with multiple knowledge bases, and one knowledge base can also associate with multiple projects. On the [Knowledge Base](https://memos-dashboard.openmem.net/knowledgeBase) page: 1. Click "Add Knowledge Base"; 2. Choose "Create Knowledge Base" or "Associate Existing Knowledge Base"; 3. Open the knowledge base detail page, upload documents, and wait for processing to complete; 4. When calling `search/memory` or `chat`, pass `knowledgebase_ids` to specify which knowledge bases can be searched in this request. ![Knowledge base association page](https://cdn.memtensor.com.cn/img/1781512441179_d9uy7m_compressed.png) > **Warning**: If the knowledge base specified in `knowledgebase_ids` is not associated with the project of the current API Key, `search/memory` returns `50123`. Before using a knowledge base, associate it with the target project. For the full workflow, see [Knowledge Base](/memos_cloud/features/knowledge_base). ## 4. Common Configuration Errors | Error code | Common cause | How to fix | | :--- | :--- | :--- | | `40000` | Request field names, types, or structure do not match the API requirements | Check the JSON fields against the API docs; do not mix objects, arrays, and strings incorrectly | | `40002` | Required field is empty | Check required fields such as `user_id`, `messages`, `query`, and `conversation_id` | | `40011` | `conversation_id` is too long | Use a short ID, such as an order ID, conversation ID, or internal trace ID. Do not put the full conversation in `conversation_id` | | `40103` / `40132` | API Key is invalid, expired, or cannot access the current project | Check whether the API Key is complete, valid, and belongs to the current project | | `40300` / `40304` | API request quota or account-level request quota is exhausted | See [Quotas and Limits](/memos_cloud/support/limit), or check the current quota in the console | | `40305` | Single request input exceeds the token limit | Shorten the write, search, or upload content; do not send long conversation history or long documents in one request | | `50123` | Knowledge base is not associated with the current project | Associate the knowledge base with the project on the Knowledge Base page, or remove the incorrect `knowledgebase_ids` | For more error code details, see [Error Codes](/api_docs/help/error_codes). --- # Add Message **POST** `/add/message` This API allows you to add one or more messages to a specific conversation. As illustrated in the examples bellow, you can add messages in real time during a user-assistant interaction, import historical messages in bulk, or enrich the conversation with user preferences and behavior data. All added messages are transformed into memories by MemOS, enabling their retrieval in future conversations to support chat history management, user behavior tracking, and personalized interactions. - operationId: `add_message` ## Request Body | Parameter | Type | Required | Description | |---|---|---|---| | `user_id` | string | No | Unique identifier of the user associated with the message. | | `conversation_id` | string | No | Unique identifier of the conversation associated with the added message. Messages under the same conversation_id are treated as the same context. If omitted, the system generates one automatically. | | `messages` | array | Yes | Array of message objects representing the memory content. The total token limit for the message array is 40k. Each object contains: | | `agent_id` | string | No | Unique identifier of the Agent associated with the added message, primarily used to query exclusive memories between a user and that Agent during retrieval. | | `app_id` | string | No | Unique identifier of the App associated with the added message, primarily used to query exclusive memories of a user under that App during retrieval. | | `tags` | array | No | List of custom tags used to mark the topic or category of the added message. | | `info` | object | No | Custom metadata field capable of storing any structured data related to the added message, such as location, source, version, etc., primarily for precise filtering or source tracking during retrieval. | | `allow_public` | boolean | No | Whether memories generated from the added message are allowed to be written to the public memory store. When enabled, generated memories can be retrieved by other users in the project. | | `allow_knowledgebase_ids` | array | No | Scope of knowledgebases where memories generated from the added message are allowed to be written. | | `async_mode` | boolean | No | Whether to enable asynchronous memory addition. When enabled, memory will be added asynchronously in the background to avoid blocking the call chain. | | `custom_extract_prompt` | object | No | Custom extraction prompts keyed by memory category or input modality, specifying the extraction strategy used for this add-message call. Only effective for the current request. Supported keys for memory categories: detail_factual, preference, skill, profile, event, tool_memory (see Memory Categories); supported keys for input modalities: image (image content) and document (file content). | #### `messages` object | Parameter | Type | Required | Description | |---|---|---|---| | `chat_time` | string | No | Time of the conversation, as a structured timestamp or Chinese text. Providing this parameter allows memory to include time information. | | `role` | string (enum: user, assistant, system, tool) | Yes | Sender role. | | `role_id` | string | No | Speaker ID. Recommended in group chats. | | `role_name` | string | No | Speaker display name. When passed, extracted memories can include the speaker name. Must be passed together with role_id. | | `content` | string | array | Yes | Content of the message. | | `tool_call_id` | string | No | Unique identifier for the tool call message when role is tool. | | `tool_calls` | array | No | List of tool call information when role is assistant, used to pass when triggering tool calls. | #### `tool_calls` object | Parameter | Type | Required | Description | |---|---|---|---| | `id` | string | No | Unique identifier for the tool call, used to associate with this tool call. Required in tool_calls. | | `type` | string (enum: function) | No | Tool call type, currently only supports function. Required in tool_calls. | | `function` | object | No | Defined tool to be called. Required in tool_calls. | #### `function` object | Parameter | Type | Required | Description | |---|---|---|---| | `name` | string | No | Tool (function) name. Required in tool_calls. | | `arguments` | string | No | Tool call arguments, must be a JSON formatted string. Required in tool_calls. | ### Request Example ```json { "user_id": "memos_user_123", "conversation_id": "0610", "messages": [ { "role": "user", "content": "I want to travel during summer vacation, can you recommend something?" }, { "role": "assistant", "content": "Sure! Are you traveling alone, with family or with friends?" }, { "role": "user", "content": "I'm bringing my kid. My family always travels together." }, { "role": "assistant", "content": "Got it, so you're traveling with your children as a family, right?" }, { "role": "user", "content": "Yes, with both kids and elderly, we usually travel as a whole family." }, { "role": "assistant", "content": "Understood, I'll recommend destinations suitable for family trips." } ] } ``` ## Response Successful Response | Parameter | Type | Required | Description | |---|---|---|---| | `code` | integer | Yes | API status code. See Error Code for details | | `data` | object | No | Object representing the result of adding the message. | | `message` | string | Yes | API response message, e.g., "Message added successfully". | #### `data` object | Parameter | Type | Required | Description | |---|---|---|---| | `success` | boolean | No | Indicates if the message was added successfully. true = success, false = failure. | | `task_id` | string | No | Unique identifier of the memory processing task. Use the Get Task Status endpoint to query task results. | | `status` | string (enum: running, completed, failed) | No | Current status of the memory processing task. | ### Response Example ```json { "code": 0, "data": { "success": true, "status": "running" }, "message": "ok" } ``` URL: /api_docs/core/add_message --- # Search Memory **POST** `/search/memory` This API retrieves memories for a specified user or Agent and returns the fragments most relevant to the query. - operationId: `search_memory` ## Request Body | Parameter | Type | Required | Description | |---|---|---|---| | `user_id` | string | Yes | Unique identifier of the user associated with the memory being queried. | | `conversation_id` | string | No | Unique identifier of the conversation containing the memory. Providing this ensures the current conversation’s memories have higher priority over other historical. | | `query` | string | Yes | Text content to search within the memories.The token limit for a single query is 4k. | | `filter` | object | No | Memory filter conditions used to narrow candidate memories before semantic recall. You can use and / or at the root for global filtering, or filter by source under user, public, and knowledgebase. For complete fields and examples, see Memory Filters. | | `knowledgebase_ids` | array | No | Specifies the scope of knowledge bases accessible for the current search. Defaults to empty, meaning no knowledge bases are searched.Pass specific Knowledgebase IDs to search within that designated repository; pass "all" to search across all associated knowledgebases within the project. | | `include_memory_view` | array | No | Allowed memory types to retrieve. When omitted, fact memories (detail_factual) and preference memories (preference) are recalled by default. See Memory Categories for details. | | `memory_limit_number` | integer | No | Maximum number of memories that can be recalled: as long as the relevance threshold (relativity) is met, up to this many memories may be returned. Default is 9, maximum is 25. | | `relativity` | number | No | Relevance threshold (0–1) for recalled memories. Filters out low-relevance memories and, together with the maximum counts for factual and preferred recalls, constrains the final results. When omitted, the system default threshold is used. A value of 0 disables relevance filtering. | #### `filter` object | Parameter | Type | Required | Description | |---|---|---|---| | `and` | array | No | Global AND condition array. Candidate memories enter semantic recall only when all conditions are satisfied. Common fields include agent_id, app_id, tags.contains, create_time, update_time, and custom fields from info. | | `or` | array | No | Global OR condition array. Candidate memories enter semantic recall when any condition is satisfied. | | `user` | object | No | Filter conditions for user personal memories. | | `public` | object | No | Filter conditions for project-level public memories. | | `knowledgebase` | object | No | Filter conditions for knowledge base memories. Only applies within the knowledge base scope allowed by knowledgebase_ids. | #### `user` object | Parameter | Type | Required | Description | |---|---|---|---| | `and` | array | No | AND condition array for user memories. | | `or` | array | No | OR condition array for user memories. | #### `public` object | Parameter | Type | Required | Description | |---|---|---|---| | `and` | array | No | AND condition array for public memories. | | `or` | array | No | OR condition array for public memories. | #### `knowledgebase` object | Parameter | Type | Required | Description | |---|---|---|---| | `and` | array | No | AND condition array for knowledge base memories. | | `or` | array | No | OR condition array for knowledge base memories. | ### Request Example ```json { "query": "Summarize my memories related to reading this year", "user_id": "memos_user_123", "conversation_id": "0928", "knowledgebase_ids": [ "kb_xxx" ], "filter": { "knowledgebase": { "and": [ { "tags": { "contains": "reading" } }, { "create_time": { "gte": "2025-01-01" } }, { "create_time": { "lte": "2025-12-31" } } ] }, "user": { "and": [ { "scene": "chat" } ] } } } ``` ## Response Successful Response | Parameter | Type | Required | Description | |---|---|---|---| | `code` | integer | Yes | API status code. See Error Code for details. | | `data` | object | No | Object containing the query result. | | `message` | string | Yes | API response message. | #### `data` object | Parameter | Type | Required | Description | |---|---|---|---| | `memory_detail_list` | array | No | List of memory fragment details returned. Each item includes: | | `preference_detail_list` | array | No | List of preference memory details returned. Each item includes: | | `profile_detail_list` | array | No | List of profile memory fragment details returned. | | `event_detail_list` | array | No | List of event memory fragment details returned. | | `tool_memory_detail_list` | array | No | List of tool memory fragment details returned. | | `preference_note` | string | No | Preference memory usage note when it is retrieved. | | `skill_detail_list` | array | No | List of Skill details returned. | #### `memory_detail_list` object | Parameter | Type | Required | Description | |---|---|---|---| | `id` | string | No | Unique identifier of fact memory, used internally by the system. | | `memory_key` | string | No | Title or keyword summarizing fact memory. | | `memory_value` | string | No | Detailed content of fact memory. | | `memory_type` | string (enum: WorkingMemory, LongTermMemory, UserMemory) | No | WorkingMemory: short-term working memory, temporarily stored.
LongTermMemory: long-term memory, important information or facts stored persistently.
UserMemory: user-specific memory, personalized information related to a specific user. | | `create_time` | string | No | Creation time of fact memory, usually in ISO 8601 format. | | `conversation_id` | string | No | Unique identifier of the conversation associated with fact memory. | | `status` | string (enum: activated) | No | Fact memory status. All retrieved fact memories are currently activated.
activated: active fact memory, available for retrieval and use. | | `confidence` | number | No | Confidence score of fact memory, ranging from 0 to 1. Values closer to 1 indicate higher reliability.
The score may gradually decay over time or with repeated model reasoning to reflect uncertainty. | | `tags` | array | No | List of tags associated with fact memory for categorization or retrieval. Each element is a string, e.g., ["person", "event", "work"]. | | `update_time` | string | No | Last modification or update time of fact memory, usually in ISO 8601 format. | | `relativity` | number | No | Relevance score of fact memory to the query, ranging from 0 to 1. Higher values indicate stronger relevance. | #### `preference_detail_list` object | Parameter | Type | Required | Description | |---|---|---|---| | `id` | string | No | Unique identifier of preference memory, used internally by the system. | | `preference` | string | No | Detailed content of preference memory. | | `preference_type` | string (enum: explicit_preference, implicit_preference) | No | explicit_preference: Explicit preference memory.
implicit_preference: Implicit preference memory. | | `reasoning` | string | No | The reason why preference memory was extracted. | | `create_time` | string | No | Creation time of preference memory, usually in ISO 8601 format. | | `conversation_id` | string | No | Unique identifier of the conversation associated with preference memory. | | `status` | string (enum: activated) | No | Preference memory status. All retrieved preference memories are currently activated.
activated: active preference memory, available for retrieval and use. | | `update_time` | string | No | Last modification or update time of preference memory, usually in ISO 8601 format. | | `relativity` | number | No | Relevance score of preference memory to the query, ranging from 0 to 1. Higher values indicate stronger relevance. | #### `profile_detail_list` object | Parameter | Type | Required | Description | |---|---|---|---| | `id` | string | No | Unique identifier of the profile memory. | | `memory` | string | No | Profile memory content. | | `memory_type` | string (enum: ProfileMemory) | No | Memory type. Profile memories use ProfileMemory. | | `template_id` | string | No | Profile template ID. | | `profile_category` | string | No | Profile category, for example "Basic Info". | | `profile_field` | string | No | Profile field name, for example "Occupation". | | `profile_path` | string | No | Profile field path, for example "Basic Info.Occupation". | | `status` | string (enum: activated) | No | Profile memory status. Search results currently return activated only. | | `created_at` | string | No | Profile memory creation time in ISO 8601 format. | | `updated_at` | string | No | Last update time of the profile memory in ISO 8601 format. | | `confidence` | number | No | Confidence score of the profile memory, ranging from 0 to 1. | | `relativity` | number | No | Relevance score between the query and this profile field, ranging from 0 to 1. | | `algorithm_updatable` | boolean | No | Whether this profile field can be updated automatically by the algorithm. | #### `event_detail_list` object | Parameter | Type | Required | Description | |---|---|---|---| | `id` | string | No | Unique identifier of the event memory. | | `event_key` | string | No | Title or keyword of the event memory. | | `event_value` | string | No | Detailed content of the event memory. | | `event_type` | string | No | Event memory type, usually EventMemory. | | `create_time` | string | No | Event memory creation time in ISO 8601 format. | | `conversation_id` | string | No | Unique identifier of the conversation associated with the event memory. | | `status` | string (enum: activated) | No | Event memory status. Search results currently return activated only. | | `update_time` | string | No | Last update time of the event memory in ISO 8601 format. | | `relativity` | number | No | Relevance score between the query and the event memory, ranging from 0 to 1. | | `event_time` | array | No | List of event times. | | `event_location` | array | No | List of event locations. | | `event_roles` | array | No | List of event participants. | #### `tool_memory_detail_list` object | Parameter | Type | Required | Description | |---|---|---|---| | `id` | string | No | Unique identifier of the tool memory fragment. | | `tool_type` | string (enum: ToolTrajectoryMemory, ToolSchema) | No | Tool memory type. ToolTrajectoryMemory: tool trajectory memory; ToolSchema: tool info memory. | | `tool_value` | string | No | Specific content of the tool memory. | | `tool_used_status` | array | No | List of tool trajectory memories, each record contains tool used and experience info. | | `create_time` | string | No | Tool memory creation time (ISO 8601 format). | | `conversation_id` | string | No | Unique identifier of the conversation associated with the tool memory. | | `status` | string (enum: activated) | No | Tool memory status, currently activated. | | `update_time` | string | No | Last update time of the tool memory (ISO 8601 format). | | `relativity` | number | No | Relevance score of the tool memory to the query content. | | `experience` | string | No | Procedural experience of the entire trajectory, serving as overall guidance for task completion. | #### `skill_detail_list` object | Parameter | Type | Required | Description | |---|---|---|---| | `id` | string | No | The unique identifier of the Skill, used internally by the system to distinguish different memory entries. | | `skill_value` | object | No | Structured Skill content. You can convert it to a string and inject it into the Agent prompt. | | `skill_url` | string | No | Download link for the Skill. A Markdown Skill can be downloaded as SKILL.md; a ZIP Skill package can include SKILL.md, scripts, references, assets, and other attachments. | | `skill_type` | string | No | The type of the Skill. | | `create_time` | string | No | The creation time of the Skill content, usually in ISO 8601 format. | | `conversation_id` | string | No | The unique identifier of the conversation associated with the Skill. | | `status` | string (enum: activated) | No | The status of the Skill. Currently, all retrieved Skills are 'activated'. activated: Active status, the Skill is currently retrievable and usable. | | `confidence` | number | No | The confidence score of the Skill, ranging from 0 to 1. A value closer to 1 indicates the Skill is more accurate and reliable. The confidence score gradually decays as the model infers this Skill more times, reflecting the uncertainty that may arise over time or usage frequency. | | `tags` | array | No | A list of tags associated with the Skill, used for classification, retrieval, or topic marking. Each element in the array is a string, e.g., ["Person", "Event", "Work"]. | | `update_time` | string | No | The time when the Skill was last modified or updated, usually in ISO 8601 format. | | `relativity` | string | No | The relevance score between the query content and the Skill, ranging from 0 to 1. A value closer to 1 indicates higher relevance. | ### Response Example ```json { "code": 0, "data": { "memory_detail_list": [ { "memory_type": "LongTermMemory", "status": "activated", "confidence": 0.95, "relativity": 0.87 } ], "preference_detail_list": [ { "preference_type": "explicit_preference", "status": "activated", "relativity": 0.87 } ], "profile_detail_list": [ { "memory_type": "ProfileMemory", "status": "activated" } ], "event_detail_list": [ { "status": "activated" } ], "tool_memory_detail_list": [ { "tool_type": "ToolTrajectoryMemory", "status": "activated" } ], "skill_detail_list": [ { "status": "activated" } ] } } ``` URL: /api_docs/core/search_memory --- # Get Memories **POST** `/get/memory` Retrieve paginated memories for a user or Agent. - operationId: `get_memory` ## Request Body | Parameter | Type | Required | Description | |---|---|---|---| | `user_id` | string | No | Unique identifier of the user whose memories are being retrieved. | | `agent_id` | string | No | Unique identifier of the Agent whose memories are being retrieved. Available only when independent Agent memory is enabled. Use either user_id or agent_id. | | `page` | integer | No | Page number for pagination when many results are returned. | | `size` | integer | No | Number of entries returned per memory category on the current page, up to 50. | | `filter` | object | No | Filter conditions, used to precisely limit the memory scope before retrieval. Available fields include: "agent_id", "app_id", "create_time", "update_time", and specific fields in "info". Supports logical operators (and, or) and comparison operators (gte, lte, gt, lt). For the "info" field, supports filtering by "business_type", "biz_id", "scene", and other custom fields. | | `include_memory_view` | array | No | Allowed memory types to retrieve. When omitted, all memory types are returned by default. See Memory Types for values. | ## Response Successful Response | Parameter | Type | Required | Description | |---|---|---|---| | `code` | number | Yes | API status code; refer to the error-code list for details. | | `data` | object | No | | | `message` | string | Yes | API message. | #### `data` object | Parameter | Type | Required | Description | |---|---|---|---| | `memory_detail_list` | array | No | List of factual memory fragment details returned. | | `preference_detail_list` | array | No | List of preference memory fragment details returned. | | `profile_detail_list` | array | No | List of profile memory fragment details returned. | | `event_detail_list` | array | No | List of event memory fragment details returned. | | `tool_memory_detail_list` | array | No | List of tool memory fragment details returned. | | `skill_detail_list` | array | No | List of Skill details returned. | | `total` | integer | No | Maximum count across memory types, used to check if another page exists. | | `size` | integer | No | Number of entries per memory type on the current page. | | `current` | integer | No | Index of the current page. | | `pages` | integer | No | Total number of pages. | #### `memory_detail_list` object | Parameter | Type | Required | Description | |---|---|---|---| | `id` | string | No | Unique identifier of the factual memory. | | `memory_key` | string | No | Title or keyword of the factual memory. | | `memory_value` | string | No | Detailed content of the factual memory. | | `memory_type` | string (enum: WorkingMemory, LongTermMemory, UserMemory) | No | Type of factual memory. | | `create_time` | string | No | Creation time in ISO 8601 format. | | `conversation_id` | string | No | Conversation identifier linked to this memory. | | `status` | string (enum: activated) | No | Factual memory status. Currently only activated is returned. | | `confidence` | number | No | Confidence score between 0 and 1. | | `tags` | array | No | Tag list associated with the factual memory. | | `update_time` | string | No | Last update time in ISO 8601 format. | | `relativity` | number | No | Relevance score between 0 and 1. | | `sources` | array | No | Source messages of the factual memory. | | `info` | object | No | Custom metadata provided when adding the message. | #### `preference_detail_list` object | Parameter | Type | Required | Description | |---|---|---|---| | `id` | string | No | Unique identifier of the preference memory. | | `preference_type` | string (enum: explicit_preference, implicit_preference) | No | Type of preference memory. | | `preference` | string | No | Detailed content of the preference memory. | | `reasoning` | string | No | Reason why the preference memory was extracted. | | `create_time` | string | No | Creation time in ISO 8601 format. | | `conversation_id` | string | No | Conversation identifier linked to this memory. | | `status` | string (enum: activated) | No | Preference memory status. Currently only activated is returned. | | `update_time` | string | No | Last update time in ISO 8601 format. | | `relativity` | number | No | Relevance score between 0 and 1. | | `sources` | array | No | Source messages of the preference memory. | | `info` | object | No | Custom metadata provided when adding the message. | #### `profile_detail_list` object | Parameter | Type | Required | Description | |---|---|---|---| | `id` | string | No | Unique identifier of the profile memory instance. | | `project_id` | string | No | Project ID. | | `profile_template_id` | string | No | Profile template ID. | | `properties` | object | No | Structured profile field tree. | | `status` | string (enum: activated) | No | Profile memory status. Currently only activated is returned. | | `created_at` | string | No | Profile memory creation time in ISO 8601 format. | | `updated_at` | string | No | Last update time of the profile memory in ISO 8601 format. | #### `event_detail_list` object | Parameter | Type | Required | Description | |---|---|---|---| | `id` | string | No | Unique identifier of the event memory. | | `event_key` | string | No | Title or keyword of the event memory. | | `event_value` | string | No | Detailed content of the event memory. | | `event_type` | string | No | Event memory type, usually EventMemory. | | `create_time` | string | No | Event memory creation time in ISO 8601 format. | | `conversation_id` | string | No | Unique identifier of the conversation associated with the event memory. | | `status` | string (enum: activated) | No | Event memory status. Currently only activated is returned. | | `update_time` | string | No | Last update time of the event memory in ISO 8601 format. | | `info` | object | No | Extended information of the event memory. | | `sources` | array | No | Source messages of the event memory. | | `event_time` | array | No | List of event times. | | `event_location` | array | No | List of event locations. | | `event_roles` | array | No | List of event participants. | #### `tool_memory_detail_list` object | Parameter | Type | Required | Description | |---|---|---|---| | `id` | string | No | Unique identifier of the tool memory fragment. | | `tool_type` | string (enum: ToolTrajectoryMemory, ToolSchema) | No | Tool memory type. ToolTrajectoryMemory means tool trajectory memory; ToolSchema means tool schema memory. | | `tool_value` | string | No | Detailed content of the tool memory. | | `tool_used_status` | array | No | Tool trajectory records, each containing the used tool and experience. | | `create_time` | string | No | Creation time in ISO 8601 format. | | `conversation_id` | string | No | Conversation identifier linked to this memory. | | `status` | string (enum: activated) | No | Tool memory status. Currently activated only. | | `update_time` | string | No | Last update time in ISO 8601 format. | | `relativity` | number | No | Relevance score between 0 and 1. | | `source` | string | No | Source information of the tool memory. | | `experience` | string | No | Procedural experience of the entire trajectory. | | `info` | object | No | Custom metadata provided when adding the message. | #### `skill_detail_list` object | Parameter | Type | Required | Description | |---|---|---|---| | `id` | string | No | The unique identifier of the Skill, used internally by the system to distinguish different memory entries. | | `skill_value` | object | No | Structured Skill content. You can convert it to a string and inject it into the Agent prompt. | | `skill_url` | string | No | Download link for the Skill. A Markdown Skill can be downloaded as SKILL.md; a ZIP Skill package can include SKILL.md, scripts, references, assets, and other attachments. | | `skill_type` | string | No | The type of the Skill. | | `create_time` | string | No | The creation time of the Skill content, usually in ISO 8601 format. | | `conversation_id` | string | No | The unique identifier of the conversation associated with the Skill. | | `status` | string (enum: activated) | No | The status of the Skill. Currently, all retrieved Skills are 'activated'. activated: Active status, the Skill is currently retrievable and usable. | | `confidence` | number | No | The confidence score of the Skill, ranging from 0 to 1. A value closer to 1 indicates the Skill is more accurate and reliable. The confidence score gradually decays as the model infers this Skill more times, reflecting the uncertainty that may arise over time or usage frequency. | | `tags` | array | No | A list of tags associated with the Skill, used for classification, retrieval, or topic marking. Each element in the array is a string, e.g., ["Person", "Event", "Work"]. | | `update_time` | string | No | The time when the Skill was last modified or updated, usually in ISO 8601 format. | | `relativity` | string | No | The relevance score between the query content and the Skill, ranging from 0 to 1. A value closer to 1 indicates higher relevance. | ### Response Example ```json { "data": { "memory_detail_list": [ { "memory_type": "WorkingMemory", "status": "activated" } ], "preference_detail_list": [ { "preference_type": "explicit_preference", "status": "activated" } ], "profile_detail_list": [ { "status": "activated" } ], "event_detail_list": [ { "status": "activated" } ], "tool_memory_detail_list": [ { "tool_type": "ToolTrajectoryMemory", "status": "activated" } ], "skill_detail_list": [ { "status": "activated" } ] } } ``` URL: /api_docs/core/get_memory --- # Get Memory **GET** `/get/memory/{memory_id}` Retrieve the details of a single memory by its ID. - operationId: `get_memory_by_id` ## Response Successful Response | Parameter | Type | Required | Description | |---|---|---|---| | `code` | integer | Yes | API status code. | | `data` | object | No | | | `message` | string | Yes | API response message. | #### `data` object | Parameter | Type | Required | Description | |---|---|---|---| | `id` | string | No | Memory ID. | | `memory_view` | string (enum: detail_factual, preference, event, profile, skill, tool_memory) | No | Memory category. | | `title` | string | No | Memory title. | | `content` | any | No | Memory content. | | `conversation_id` | string | No | Source conversation ID. | | `message_ids` | array | No | List of source message IDs. | | `status` | string (enum: activated, resolving, archived, deleted) | No | Memory status. | | `algorithm_updatable` | boolean | No | Whether the algorithm can update this memory automatically. | | `created_at` | string | No | Creation time. | | `updated_at` | string | No | Last update time. | | `user_id` | string | No | Owning user. | | `agent_id` | string | No | Owning Agent. | | `tags` | array | No | Custom tags. | | `info` | object | No | Custom metadata. | ### Response Example ```json { "code": 0, "data": { "memory_view": "detail_factual", "status": "activated" }, "message": "ok" } ``` URL: /api_docs/core/get_memory_by_id --- # Delete Memory **POST** `/delete/memory` Delete memories for a user or Agent. Supports deletion by memory_ids or clearing all memories by user_id/agent_id. - operationId: `delete_memory` ## Request Body | Parameter | Type | Required | Description | |---|---|---|---| | `memory_ids` | array | No | List of memory IDs to delete. | | `user_id` | string | No | Delete all memories of this user in the current project. Mutually exclusive with memory_ids and agent_id. | | `agent_id` | string | No | Delete all memories of this Agent in the current project. Available only when independent Agent memory is enabled. Mutually exclusive with memory_ids and user_id. | ## Response Successful Response | Parameter | Type | Required | Description | |---|---|---|---| | `code` | integer | No | API status code. See Error Code for details. | | `data` | object | No | Returned deletion information | | `message` | string | No | API response message | #### `data` object | Parameter | Type | Required | Description | |---|---|---|---| | `success` | boolean | No | Whether deletion was successful. true for success, false for failure. | ### Response Example ```json { "data": { "success": true } } ``` URL: /api_docs/core/delete_memory --- # Update Memory **POST** `/update/memory` Manually update the content, title, or status of an existing memory. Supports all memory categories, including fact memories, preference memories, Event Memory, and Profile attribute values. - operationId: `update_memory` ## Request Body | Parameter | Type | Required | Description | |---|---|---|---| | `memory_id` | string | Yes | Memory ID, from the id field returned by search/memory or get/memory. | | `content` | string | No | The updated memory content. | | `title` | string | No | The updated memory title. | ### Request Example ```json { "memory_id": "mem_event_001", "title": "Camping at West Lake with Chen Mo", "content": "Last Saturday I went camping by West Lake with my friend Chen Mo. The weather was great and we watched the stars together at night." } ``` ## Response Successful Response | Parameter | Type | Required | Description | |---|---|---|---| | `code` | integer | No | API status code. | | `data` | object | No | | | `message` | string | No | API response message. | #### `data` object | Parameter | Type | Required | Description | |---|---|---|---| | `success` | boolean | No | Whether the update succeeded. | ### Response Example ```json { "data": { "success": true } } ``` URL: /api_docs/core/update_memory --- # Add Feedback **POST** `/add/feedback` This API is used to add feedback to current session messages, allowing MemOS to correct memories based on user feedback. - operationId: `add_feedback` ## Request Body | Parameter | Type | Required | Description | |---|---|---|---| | `user_id` | string | Yes | Unique identifier of the user associated with the feedback content. | | `conversation_id` | string | Yes | Unique identifier of the conversation associated with the feedback content. | | `feedback_content` | string | Yes | Feedback content text. | | `agent_id` | string | No | Unique identifier of the Agent associated with the feedback content, primarily used to query exclusive memories between a user and that Agent during retrieval. | | `app_id` | string | No | Unique identifier of the App associated with the feedback content, primarily used to query exclusive memories of a user under that App during retrieval. | | `feedback_time` | string | No | Time when the feedback occurred, can be a structured timestamp or natural language time description. Providing this parameter allows memory to include time information. | | `allow_public` | boolean | No | Whether memories generated from the feedback content are allowed to be written to the public memory store. When enabled, generated memories can be retrieved by other users in the project. | | `allow_knowledgebase_ids` | array | No | List of knowledgebases where memories generated from the feedback content are allowed to be written. | ## Response Successful Response | Parameter | Type | Required | Description | |---|---|---|---| | `code` | integer | Yes | API status code. See Error Code for details. | | `data` | object | No | | | `message` | string | Yes | API response message | #### `data` object | Parameter | Type | Required | Description | |---|---|---|---| | `success` | boolean | No | Whether addition was successful. true for success, false for failure. | | `status` | string | No | Task status: running, completed | | `task_id` | string | No | Task ID | URL: /api_docs/message/add_feedback --- # Add Profile Template **POST** `/add/profile_template` Create a Profile template in the project and return the template ID. Once created, bind it to users or Agents via Bind Profile Template to create Profile instances. - operationId: `add_profile_template` ## Request Body | Parameter | Type | Required | Description | |---|---|---|---| | `name` | string | Yes | Template name. Must contain at least one character after trimming leading and trailing whitespace. | | `metadata` | object | Yes | Attribute tree structure with up to three levels of nesting; leaf nodes are field value objects. | #### `metadata` object | Parameter | Type | Required | Description | |---|---|---|---| | `{category name}` | object | No | Attribute category (optional intermediate level); the key is a user-defined category name. Skip this level if no category is needed and pass field value objects directly. | #### `{category name}` object | Parameter | Type | Required | Description | |---|---|---|---| | `{field name}` | object | No | A leaf field-value node inside the metadata tree. | #### `{field name}` object | Parameter | Type | Required | Description | |---|---|---|---| | `value` | string | No | The attribute field value. | | `algorithm_updatable` | boolean | No | Whether this field can be automatically updated by the algorithm. Defaults to true. | ### Request Example ```json { "name": "Customer Service User Profile", "metadata": { "Basic Info": { "Name": { "value": "", "algorithm_updatable": false }, "Occupation": { "value": "", "algorithm_updatable": true } }, "Service Preferences": { "Preferred Contact Time": { "value": "Weekday daytime", "algorithm_updatable": true } } } } ``` ## Response Successful Response | Parameter | Type | Required | Description | |---|---|---|---| | `code` | integer | No | API status code. | | `data` | object | No | | | `message` | string | No | API response message. | #### `data` object | Parameter | Type | Required | Description | |---|---|---|---| | `profile_template_id` | string | No | ID of the newly created template. Use this ID for subsequent get, bind, update, and delete operations. | ### Response Example ```json { "code": 0, "data": { "profile_template_id": "tpl_user_001" }, "message": "ok" } ``` URL: /api_docs/core/add_profile_template --- # List Profile Templates **POST** `/list/profile_template` Return a paginated list of Profile template summaries in the project, sorted by creation time descending; ties are sorted by template ID descending. - operationId: `list_profile_template` ## Request Body | Parameter | Type | Required | Description | |---|---|---|---| | `page` | integer | No | Page number, starting from 1. | | `size` | integer | No | Items per page, from 1 to 100. | ### Request Example ```json { "page": 1, "size": 10 } ``` ## Response Successful Response | Parameter | Type | Required | Description | |---|---|---|---| | `code` | integer | No | API status code. | | `data` | object | No | | | `message` | string | No | API response message. | #### `data` object | Parameter | Type | Required | Description | |---|---|---|---| | `profile_templates` | array | No | List of template summaries. Returns an empty array when the project has no templates or the page number is out of range. | | `total` | integer | No | Total number of templates in the project. | | `current` | integer | No | Page number of this response. | | `size` | integer | No | Items per page in this response. | | `pages` | integer | No | Total number of pages. The actual total and page count are preserved when the page number is out of range. | #### `profile_templates` object | Parameter | Type | Required | Description | |---|---|---|---| | `profile_template_id` | string | No | Template ID. | | `name` | string | No | Template name. | | `project_id` | string | No | ID of the project the template belongs to. | | `instance_count` | integer | No | Number of active instances currently bound to the template. Indicates the template's scope of impact; instance field values are read via the memory query APIs. | | `create_time` | string | No | Template creation time in ISO 8601 format. | | `update_time` | string | No | Template's last update time in ISO 8601 format. | ### Response Example ```json { "code": 0, "message": "ok" } ``` URL: /api_docs/core/list_profile_template --- # Get Profile Template **POST** `/get/profile_template` Return the full structure and summary of a Profile template. - operationId: `get_profile_template` ## Request Body | Parameter | Type | Required | Description | |---|---|---|---| | `profile_template_id` | string | Yes | ID of a template in the current project. | ### Request Example ```json { "profile_template_id": "tpl_user_001" } ``` ## Response Successful Response | Parameter | Type | Required | Description | |---|---|---|---| | `code` | integer | No | API status code. | | `data` | object | No | | | `message` | string | No | API response message. | #### `data` object | Parameter | Type | Required | Description | |---|---|---|---| | `profile_template` | object | No | | #### `profile_template` object | Parameter | Type | Required | Description | |---|---|---|---| | `profile_template_id` | string | No | Template ID. | | `name` | string | No | Template name. | | `project_id` | string | No | ID of the project the template belongs to. | | `metadata` | object | No | Attribute tree structure with up to three levels of nesting; leaf nodes are field value objects. | | `instance_count` | integer | No | Number of active instances currently bound to the template. Indicates the template's scope of impact; instance field values are read via the memory query APIs. | | `create_time` | string | No | Template creation time in ISO 8601 format. | | `update_time` | string | No | Template's last update time in ISO 8601 format. | #### `metadata` object | Parameter | Type | Required | Description | |---|---|---|---| | `{category name}` | object | No | Attribute category (optional intermediate level); the key is a user-defined category name. Skip this level if no category is needed and pass field value objects directly. | #### `{category name}` object | Parameter | Type | Required | Description | |---|---|---|---| | `{field name}` | ProfileFieldValue | No | | ### Response Example ```json { "code": 0, "message": "ok" } ``` URL: /api_docs/core/get_profile_template --- # Update Profile Template **POST** `/update/profile_template` Update the template name or attribute structure. Changes are synced to every Profile instance bound to the template. - operationId: `update_profile_template` ## Request Body | Parameter | Type | Required | Description | |---|---|---|---| | `profile_template_id` | string | Yes | ID of a template in the current project. | | `name` | string | Yes | The new template name. When only the name changes, the attribute structure and bound instance values stay unchanged. | | `metadata` | object | Yes | The full attribute tree after the update. Changes are synced to all bound instances: new fields are filled with the template's values and auto-update settings; modified field values or settings overwrite the corresponding fields; removed fields are deleted along with their saved values; unchanged fields stay as they are. | #### `metadata` object | Parameter | Type | Required | Description | |---|---|---|---| | `{category name}` | object | No | Attribute category (optional intermediate level); the key is a user-defined category name. Skip this level if no category is needed and pass field value objects directly. | #### `{category name}` object | Parameter | Type | Required | Description | |---|---|---|---| | `{field name}` | object | No | A leaf field-value node inside the metadata tree. | #### `{field name}` object | Parameter | Type | Required | Description | |---|---|---|---| | `value` | string | No | The attribute field value. | | `algorithm_updatable` | boolean | No | Whether this field can be automatically updated by the algorithm. Defaults to true. | ### Request Example ```json { "profile_template_id": "tpl_user_001", "name": "Customer Service User Profile", "metadata": { "Basic Info": { "Name": { "value": "", "algorithm_updatable": false }, "Occupation": { "value": "", "algorithm_updatable": true }, "City of Residence": { "value": "", "algorithm_updatable": true } }, "Service Preferences": { "Preferred Contact Time": { "value": "Weekday daytime", "algorithm_updatable": true } } } } ``` ## Response Successful Response | Parameter | Type | Required | Description | |---|---|---|---| | `code` | integer | No | API status code. | | `data` | object | No | | | `message` | string | No | API response message. | #### `data` object | Parameter | Type | Required | Description | |---|---|---|---| | `success` | boolean | No | Whether the update succeeded. | | `profile_template_id` | string | No | ID of the updated template. | | `affected_instances` | integer | No | Number of bound Profile instances synced in this update. | ### Response Example ```json { "code": 0, "data": { "success": true }, "message": "ok" } ``` URL: /api_docs/core/update_profile_template --- # Delete Profile Template **POST** `/delete/profile_template` Delete a Profile template along with all of its active instances and bindings; other templates and memories are unaffected. To delete only the instance of a specific user or Agent, use /delete/profile. - operationId: `delete_profile_template` ## Request Body | Parameter | Type | Required | Description | |---|---|---|---| | `profile_template_id` | string | Yes | ID of a template in the current project. | ### Request Example ```json { "profile_template_id": "tpl_user_001" } ``` ## Response Successful Response | Parameter | Type | Required | Description | |---|---|---|---| | `code` | integer | No | API status code. | | `data` | object | No | | | `message` | string | No | API response message. | #### `data` object | Parameter | Type | Required | Description | |---|---|---|---| | `success` | boolean | No | Whether the deletion succeeded. | | `profile_template_id` | string | No | ID of the deleted template. | | `deleted_instances` | integer | No | Number of active instances deleted in this operation; 0 when the template had no bound instances. | ### Response Example ```json { "code": 0, "data": { "success": true }, "message": "ok" } ``` URL: /api_docs/core/delete_profile_template --- # Bind Profile Template **POST** `/bind/profile_template` Bind a Profile template to a user or Agent, creating a Profile memory instance. After binding, the corresponding attribute fields are automatically updated whenever new messages are added. - operationId: `bind_profile_template` ## Request Body | Parameter | Type | Required | Description | |---|---|---|---| | `bind_list` | array | Yes | List of bindings to create in a single call, up to 20 per request. | #### `bind_list` object | Parameter | Type | Required | Description | |---|---|---|---| | `user_id` | string | No | User ID to bind to the Profile template. | | `agent_id` | string | No | Agent ID to bind to the Profile template. Available only when independent Agent memory is enabled; use either user_id or agent_id. | | `profile_template_id` | string | Yes | ID of the Profile template to bind. | ### Request Example ```json { "bind_list": [ { "user_id": "memos_user_123", "profile_template_id": "tpl_user_001" } ] } ``` ## Response Successful Response | Parameter | Type | Required | Description | |---|---|---|---| | `code` | integer | No | API status code. | | `data` | object | No | | | `message` | string | No | API response message. | #### `data` object | Parameter | Type | Required | Description | |---|---|---|---| | `success` | boolean | No | Whether the binding succeeded. | ### Response Example ```json { "data": { "success": true } } ``` URL: /api_docs/core/bind_profile_template --- # Edit Profile **POST** `/edit/profile` Edit a Profile memory instance: add fields, update field values, remove fields, or lock fields against automatic updates by the algorithm. Only the target instance is affected; the template and other instances are not changed. - operationId: `edit_profile` ## Request Body | Parameter | Type | Required | Description | |---|---|---|---| | `user_id` | string | No | User ID. Use either user_id or agent_id. Required for single-perspective projects. | | `agent_id` | string | No | Agent ID. Available only when independent Agent memory is enabled; use either user_id or agent_id. | | `profile_template_id` | string | Yes | ID of the target Profile template. | | `metadata` | object | No | Fields to update. Existing fields are updated with the new value; new fields are added to the current instance. | | `remove_fields` | array | No | List of field paths to remove, e.g. ["Basic Info.Occupation"]. | #### `metadata` object | Parameter | Type | Required | Description | |---|---|---|---| | `{category_name}` | object | No | An optional grouping layer for attribute fields, keyed by a custom category name. Skip this layer and pass field values directly under metadata if categories are not needed. | #### `{category_name}` object | Parameter | Type | Required | Description | |---|---|---|---| | `{field_name}` | object | No | A leaf field-value node inside the metadata tree. | #### `{field_name}` object | Parameter | Type | Required | Description | |---|---|---|---| | `value` | string | No | The attribute field value. | | `algorithm_updatable` | boolean | No | Whether this field can be automatically updated by the algorithm. Defaults to true. | ### Request Example ```json { "user_id": "memos_user_123", "profile_template_id": "tpl_user_001", "metadata": { "Basic Info": { "Location": { "value": "Shanghai", "algorithm_updatable": false } } } } ``` ## Response Successful Response | Parameter | Type | Required | Description | |---|---|---|---| | `code` | integer | No | API status code. | | `data` | object | No | | | `message` | string | No | API response message. | #### `data` object | Parameter | Type | Required | Description | |---|---|---|---| | `success` | boolean | No | Whether the edit succeeded. | ### Response Example ```json { "data": { "success": true } } ``` URL: /api_docs/core/edit_profile --- # Delete Profile **POST** `/delete/profile` Delete a user's or Agent's Profile memory instance. All field values and bindings for that instance are removed. This does not affect the template itself or other instances. - operationId: `delete_profile` ## Request Body | Parameter | Type | Required | Description | |---|---|---|---| | `user_id` | string | No | User ID. Use either user_id or agent_id. | | `agent_id` | string | No | Agent ID. Use either user_id or agent_id. | | `profile_template_id` | string | Yes | ID of the target Profile template. | ### Request Example ```json { "user_id": "memos_user_123", "profile_template_id": "tpl_user_001" } ``` ## Response Successful Response | Parameter | Type | Required | Description | |---|---|---|---| | `code` | integer | No | API status code. | | `data` | object | No | | | `message` | string | No | API response message. | #### `data` object | Parameter | Type | Required | Description | |---|---|---|---| | `success` | boolean | No | Whether the deletion succeeded. | ### Response Example ```json { "data": { "success": true } } ``` URL: /api_docs/core/delete_profile --- # Extract Memory **POST** `/extract/memory` Uses MemOS’s self-developed extraction model to extract and return fact and preference memories directly from conversation messages. - operationId: `extract_memory` ## Request Body | Parameter | Type | Required | Description | |---|---|---|---| | `messages` | array | Yes | Array of message objects from which to extract memories. The combined Token count of all messages must not exceed 8k. | | `extraction_types` | array | No |

Limits which memory types to extract; omit to extract all supported types.

  • memory: factual memories—user-related factual information extracted from the dialogue.
  • preference: preference memories—user preferences from the dialogue, including explicit preferences (clearly stated) and implicit preferences (inferred from behavior).
| #### `messages` object | Parameter | Type | Required | Description | |---|---|---|---| | `role` | string (enum: user, assistant, system) | Yes | Creator role of the message. | | `content` | string | Yes | Message body text. | ### Request Example ```json { "messages": [ { "role": "user", "content": "I’ve planned a summer trip to Guangzhou. What chain hotels can you recommend for accommodation?" }, { "role": "assistant", "content": "You can consider options like 7 Days Inn, All Seasons, Hilton, and others." }, { "role": "user", "content": "I’ll go with 7 Days Inn." }, { "role": "assistant", "content": "Alright—ask me anytime if you have more questions." } ], "extraction_types": [ "memory", "preference" ] } ``` ## Response Successful Response | Parameter | Type | Required | Description | |---|---|---|---| | `code` | integer | Yes | API status code. See Error Code for details. | | `data` | object | No | | | `message` | string | Yes | API response message. | #### `data` object | Parameter | Type | Required | Description | |---|---|---|---| | `success` | boolean | No | Whether extraction succeeded. | | `memory_detail_list` | array | No | Factual memories. Returned when the request includes memory in extraction_types, or when extraction_types is omitted. | | `preference_detail_list` | array | No | Preference memories. Returned when the request includes preference in extraction_types, or when extraction_types is omitted; may mix explicit and implicit preferences. | #### `memory_detail_list` object | Parameter | Type | Required | Description | |---|---|---|---| | `memory_key` | string | No | High-level topic or title summarizing the extracted factual memory. | | `memory_value` | string | No | Detailed content of the extracted factual memory. | | `memory_type` | string | No | Memory type classifier.
Examples: UserMemory, LongTermMemory. | | `tags` | array | No | Tags for categorizing the memory content. | #### `preference_detail_list` object | Parameter | Type | Required | Description | |---|---|---|---| | `preference` | string | No | Concrete preference text extracted from the dialogue. | | `reasoning` | string | No | How this preference was inferred from the conversation. | | `preference_type` | string (enum: explicit_preference, implicit_preference) | No | explicit_preference: clearly stated by the user; implicit_preference: inferred from behavior or context. | ### Response Example ```json { "code": 0, "data": { "memory_detail_list": [ { "memory_key": "User profile basics", "memory_value": "User Zhang San, 28, backend developer in Hangzhou, enjoys badminton.", "memory_type": "UserMemory", "tags": [ "person", "job", "hobby" ] } ], "preference_detail_list": [ { "preference": "The user asked for replies to stay concise.", "reasoning": "The user stated this preference explicitly in the chat.", "preference_type": "explicit_preference" } ] }, "message": "ok" } ``` URL: /api_docs/core/extract_memory --- # Rerank **POST** `/rerank` Provides a memory reranking API based on the memos-reranker small model. It takes a user query and a list of candidate memories and completes memory relevance reranking with a single call. - operationId: `rerank` ## Request Body | Parameter | Type | Required | Description | |---|---|---|---| | `model` | string (enum: memos-reranker-0.6b, memos-reranker-4b) | No | Model name to use. | | `query` | string | Yes | The user query. | | `documents` | array | Yes | A list of document texts to rerank. | | `top_n` | integer | No | Return the top N most relevant results. If omitted, returns all results by default. | ### Request Example ```json { "model": "memos-reranker-0.6b", "query": "What are the user's hobbies?", "documents": [ "User likes playing badminton.", "User is a backend developer in Hangzhou.", "User prefers concise replies.", "User prefers Jiangxiang-flavored baijiu.", "User is going on a business trip to Beijing next Wednesday." ] } ``` ## Response Successful Response | Parameter | Type | Required | Description | |---|---|---|---| | `id` | string | Yes | Unique identifier for this request. | | `model` | string | Yes | Model name used. | | `usage` | object | Yes | Token usage statistics. | | `results` | array | Yes | List of reranked results, sorted in descending order by relevance_score. | #### `usage` object | Parameter | Type | Required | Description | |---|---|---|---| | `prompt_tokens` | integer | Yes | Number of tokens consumed by the prompt. | | `total_tokens` | integer | Yes | Total number of tokens consumed. | #### `results` object | Parameter | Type | Required | Description | |---|---|---|---| | `index` | integer | Yes | The index position of this document in the original documents list. | | `document` | object | Yes | Document object. | | `relevance_score` | number | Yes | Relevance score, ranging from 0 to 1, higher indicates more relevant to the query. | #### `document` object | Parameter | Type | Required | Description | |---|---|---|---| | `text` | string | Yes | The original text content of the document. | URL: /api_docs/core/rerank --- # Get Message **POST** `/get/message` This API retrieves the historical conversation records between a user and the assistant for a specified session, with the option to limit the number of results. As shown in the examples bellow, you can use the returned recent messages as references for the model when generating responses, maintaining dialogue coherence and contextual understanding. It can also be used to restore chat context when a user refreshes or reopens the app, ensuring a seamless user experience and supporting personalized interactions. - operationId: `get_message` ## Request Body | Parameter | Type | Required | Description | |---|---|---|---| | `user_id` | string | Yes | Unique identifier of the user associated with the messages being retrieved. | | `conversation_id` | string | Yes | Unique identifier of the conversation associated with the messages. | | `message_limit_number` | integer | No | Limits the number of messages returned, controlling the length of the message list. Defaults to 6 if not provided. The maximum allowed value is 50. | ### Request Example ```json { "user_id": "memos_user_123", "conversation_id": "0928", "message_limit_number": 6 } ``` ## Response Successful Response | Parameter | Type | Required | Description | |---|---|---|---| | `code` | integer | Yes | API status code. See Error Code for details. | | `data` | object | No | Object containing the retrieved messages. | | `message` | string | Yes | API response message. | #### `data` object | Parameter | Type | Required | Description | |---|---|---|---| | `message_detail_list` | array | No | List of retrieved message details. Each item includes: | #### `message_detail_list` object | Parameter | Type | Required | Description | |---|---|---|---| | `role` | string (enum: user, assistant) | No | Role of the message sender. | | `content` | string | No | Text content of the message. | | `create_time` | string | No | Creation time of the message. | | `update_time` | string | No | Last update time of the message. | ### Response Example ```json { "code": 0, "data": { "message_detail_list": [ { "role": "user" } ] } } ``` URL: /api_docs/message/get_message --- # Get Task Status **POST** `/get/status` Query the processing status of async tasks such as add/message and add/feedback. When a task completes, the response includes memory_views with added/updated/deleted counts and memory IDs grouped by memory category. - operationId: `get_status` ## Request Body | Parameter | Type | Required | Description | |---|---|---|---| | `task_id` | string | Yes | Async task ID returned by add/message, add/feedback, and other async endpoints. | ### Request Example ```json { "task_id": "c464e17e-f2ff-4e9a-a2c2-41cc55ab43b9" } ``` ## Response Successful Response | Parameter | Type | Required | Description | |---|---|---|---| | `code` | integer | Yes | API status code. See Error Code for details. | | `data` | object | No | | | `message` | string | Yes | API response message | #### `data` object | Parameter | Type | Required | Description | |---|---|---|---| | `task_id` | string | No | Async task ID, matching the task_id in the request. | | `status` | string (enum: running, completed, failed) | No | Current task status: running, completed, or failed. | | `memory_views` | object | No | Summary of memory changes produced by the completed task. | #### `memory_views` object | Parameter | Type | Required | Description | |---|---|---|---| | `added` | integer | No | Number of memories added in this task. | | `updated` | integer | No | Number of memories updated in this task. | | `deleted` | integer | No | Number of memories deleted or archived in this task. | | `detail_factual` | object | No | | | `preference` | object | No | | | `event` | object | No | | | `profile` | object | No | | | `skill` | object | No | | | `tool_memory` | object | No | | #### `detail_factual` object | Parameter | Type | Required | Description | |---|---|---|---| | `memory_ids` | array | No | Memory IDs touched by this task under the given memory category. | #### `preference` object | Parameter | Type | Required | Description | |---|---|---|---| | `memory_ids` | array | No | Memory IDs touched by this task under the given memory category. | #### `event` object | Parameter | Type | Required | Description | |---|---|---|---| | `memory_ids` | array | No | Memory IDs touched by this task under the given memory category. | #### `profile` object | Parameter | Type | Required | Description | |---|---|---|---| | `memory_ids` | array | No | Memory IDs touched by this task under the given memory category. | #### `skill` object | Parameter | Type | Required | Description | |---|---|---|---| | `memory_ids` | array | No | Memory IDs touched by this task under the given memory category. | #### `tool_memory` object | Parameter | Type | Required | Description | |---|---|---|---| | `memory_ids` | array | No | Memory IDs touched by this task under the given memory category. | ### Response Example ```json { "data": { "status": "running" } } ``` URL: /api_docs/message/get_status --- # Chat **POST** `/chat` - operationId: `chat` ## Request Body | Parameter | Type | Required | Description | |---|---|---|---| | `user_id` | string | Yes | Unique identifier of the user associated with the conversation. | | `conversation_id` | string | Yes | Unique identifier of the conversation. Providing this clarifies the current session, prioritizing its memory over historical sessions. If omitted, cross-session memory retrieval is performed for more relevant responses. | | `query` | string | Yes | User input content. | | `filter` | object | No | Filter conditions, used to precisely limit the memory scope before retrieval. Available fields include: "agent_id", "app_id", "create_time", "update_time", and specific fields in "info". Supports logical operators (and, or) and comparison operators (gte, lte, gt, lt). For the "info" field, supports filtering by "business_type", "biz_id", "scene", and other custom fields. | | `knowledgebase_ids` | array | No | Specifies the scope of Knowledge Bases accessible for the current search. Defaults to empty, meaning no Knowledge Bases are searched. Pass specific Knowledge Base IDs to search ordinary documents and uploaded Skills in those Knowledge Bases; pass "all" to search across all associated Knowledge Bases within the project. | | `memory_limit_number` | integer | No | Maximum number of memories that can be recalled: as long as the relevance threshold (relativity) is met, up to this many memories may be returned. Default is 9, maximum is 25. | | `include_preference` | boolean | No | Whether to recall preference memories. When enabled, the system intelligently recalls memories related to user preferences based on the query. Default = true. | | `preference_limit_number` | integer | No | Maximum number of preferred memories that can be recalled: as long as the relevance threshold (relativity) is met, up to this many preference memories may be returned. Default is 9, maximum is 25. | | `relativity` | number | No | Relevance threshold (0–1) for recalled memories. Filters out low-relevance memories and, together with the maximum counts for factual and preferred recalls, constrains the final results. When omitted, the system default threshold is used. A value of 0 disables relevance filtering. | | `model_name` | string (enum: qwen3-32b, deepseek-r1, qwen2.5-72b-instruct) | No | Specifies the concrete conversation model. | | `system_prompt` | string | No | Custom system instructions. | | `stream` | boolean | No | Whether to enable streaming response. | | `max_tokens` | integer | No | Indicates the maximum number of generated tokens. | | `temperature` | number | No | Controls generation randomness. Range: 0 ≤ x ≤ 2. | | `top_p` | number | No | Nucleus sampling parameter. Range: 0 ≤ x ≤ 1. | | `add_message_on_answer` | boolean | No | Whether to automatically write user and assistant conversation content into memory. When enabled, developers do not need to call the add/message API to add messages as memory. | | `app_id` | string | No | Unique identifier of the application associated with the conversation. | | `agent_id` | string | No | Unique identifier of the Agent associated with the conversation. | | `tags` | array | No | List of custom tags used to mark the topic or category of the conversation. | | `info` | object | No | Custom metadata field capable of storing any structured data related to the conversation, such as location, source, version, etc., primarily for precise filtering or source tracking during retrieval. | | `allow_public` | boolean | No | Whether to allow adding to public memory. | | `allow_knowledgebase_ids` | array | No | List of knowledgebases where memories generated from added messages are allowed to be written. | ### Request Example ```json { "user_id": "memos_user_123", "stream": false, "query": "What fun places are in Shanghai?", "model_name": "deepseek-r1", "conversation_id": "23006762-a064-456e-a33b-d2452bdfa09f", "knowledgebase_ids": [ "2448808afa784cc5f7595da21ae5a3fd" ], "filter": { "and": [ { "create_time": { "gt": "2025-09-19" } } ] }, "system_prompt": "Recommend parks", "add_message_on_answer": false, "allow_public": false, "allow_knowledgebase_ids": [], "agent_id": "agent_id_2025-12-15-01", "app_id": "app_id_2025-12-15-01", "tags": [], "info": {}, "max_tokens": 8192, "temperature": 0.7, "top_p": 0.95 } ``` ## Response Successful Response | Parameter | Type | Required | Description | |---|---|---|---| | `code` | integer | Yes | API status code. See Error Code List for details. | | `data` | object | No | | | `message` | string | Yes | Message | #### `data` object | Parameter | Type | Required | Description | |---|---|---|---| | `response` | string | No | Specific content of the answer. | URL: /api_docs/chat/chat --- # Create Knowledge Base **POST** `/create/knowledgebase` Create a knowledgebase associated with the project. - operationId: `create_knowledgebase` ## Request Body | Parameter | Type | Required | Description | |---|---|---|---| | `knowledgebase_name` | string | Yes | Knowledgebase Name | | `knowledgebase_description` | string | No | Description information | ## Response Successful Response | Parameter | Type | Required | Description | |---|---|---|---| | `code` | integer | Yes | API status code. See Error Code for details. | | `data` | object | No | | | `message` | string | Yes | API response message | #### `data` object | Parameter | Type | Required | Description | |---|---|---|---| | `id` | string | No | Knowledgebase ID returned after successful creation | URL: /api_docs/knowledge/create_kb --- # Delete Knowledge Base **POST** `/delete/knowledgebase` Delete a knowledge base or remove its association with the current project. - operationId: `delete_knowledgebase` ## Request Body | Parameter | Type | Required | Description | |---|---|---|---| | `knowledgebase_id` | string | Yes | ID of the knowledge base to delete or remove from the current project | | `delete_all` | boolean | No | Whether to permanently delete the knowledge base. Defaults to false, which only removes the association with the project that owns the current API key. Set it to true to delete the knowledge base and its files, and remove its associations with all projects. | ## Response Successful Response | Parameter | Type | Required | Description | |---|---|---|---| | `code` | integer | Yes | API status code. See Error Code for details. | | `data` | object | No | | | `message` | string | Yes | API response message | #### `data` object | Parameter | Type | Required | Description | |---|---|---|---| | `success` | boolean | No | Whether removal was successful. true for success, false for failure. | URL: /api_docs/knowledge/remove_kb --- # Create Knowledge Base File **POST** `/add/knowledgebase-file` Upload files to a specified Knowledge Base. By default, files are uploaded as documents. When file[].type is skill, upload a Markdown Skill file or ZIP Skill package. - operationId: `add_knowledgebase-file` ## Request Body | Parameter | Type | Required | Description | |---|---|---|---| | `knowledgebase_id` | string | Yes | Target Knowledgebase ID | | `file` | array | Yes | List of files to upload. Ordinary documents follow the document parsing pipeline; Skill files follow the Skill validation and parsing pipeline. | #### `file` object | Parameter | Type | Required | Description | |---|---|---|---| | `name` | string | No | File name. Recommended when uploading Base64 content; optional when uploading by URL. | | `type` | string (enum: document, skill) | No | Uploaded file type. document means ordinary Knowledge Base document; skill means Skill file, supporting a .md single file or .zip Skill package. | | `content` | string | No | File content. Supports URL or Base64 encoding. For supported formats, size limits, and quantity limits for ordinary documents and Skill files, see Knowledge Base requirements. | ## Response Successful Response | Parameter | Type | Required | Description | |---|---|---|---| | `code` | integer | Yes | API status code. See Error Code for details. | | `data` | array | No | Processing results for uploaded files. | | `message` | string | Yes | API response message | #### `data` object | Parameter | Type | Required | Description | |---|---|---|---| | `id` | string | No | File ID | | `type` | string (enum: document, skill) | No | File type. document means ordinary document; skill means Skill file. | | `name` | string | No | File name | | `sizeMB` | number | No | File size in MB | | `status` | string (enum: running, completed, failed) | No | File processing status | ### Response Example ```json { "data": [ { "type": "document", "status": "running" } ] } ``` URL: /api_docs/knowledge/add_kb_doc --- # Get Knowledge Base File **POST** `/get/knowledgebase-file` Get file information in one of two ways: pass file_ids to retrieve specific file details, or pass knowledgebase_id to list files under a Knowledge Base. Choose only one mode; passing both knowledgebase_id and file_ids returns an error. - operationId: `get_knowledgebase-file` ## Request Body | Parameter | Type | Required | Description | |---|---|---|---| | `knowledgebase_id` | string | No | Query mode 1: target Knowledge Base ID. Returns files under the Knowledge Base and can be used with type, page, and page_size. Do not pass it together with file_ids. | | `type` | string (enum: document, skill) | No | File type filter, effective only when querying by knowledgebase_id. document returns only ordinary documents; skill returns only Skill files; omit this field to return all files. Do not use it with the file_ids query mode. | | `page` | integer | No | Page number, effective only when querying by knowledgebase_id. Do not use it with the file_ids query mode. | | `page_size` | integer | No | Items per page, effective only when querying by knowledgebase_id. Do not use it with the file_ids query mode. | | `file_ids` | array | No | Query mode 2: file ID list. Returns details for the specified files. When using this mode, pass only file_ids and do not pass knowledgebase_id, type, page, or page_size. | ## Response Successful Response | Parameter | Type | Required | Description | |---|---|---|---| | `code` | integer | Yes | API status code. See Error Code for details. | | `data` | object | No | | | `message` | string | Yes | API response message | #### `data` object | Parameter | Type | Required | Description | |---|---|---|---| | `total` | integer | No | Total number of matched files | | `page` | integer | No | Current page number | | `page_size` | integer | No | Items per page | | `file_detail_list` | array | No | | #### `file_detail_list` object | Parameter | Type | Required | Description | |---|---|---|---| | `id` | string | No | File ID | | `type` | string (enum: document, skill) | No | File type. document means ordinary document; skill means Skill file. | | `name` | string | No | File name | | `size` | string | No | File size | | `status` | string (enum: running, completed, failed) | No | File processing status | ### Response Example ```json { "data": { "file_detail_list": [ { "type": "document", "status": "running" } ] } } ``` URL: /api_docs/knowledge/get_kb_doc --- # Download Knowledgebase File **POST** `/download/knowledgebase-file` Download the current version of a Knowledge Base file. The response body is the file itself. - operationId: `download_knowledgebase-file` ## Request Body | Parameter | Type | Required | Description | |---|---|---|---| | `file_id` | string | Yes | Knowledge Base file ID. | ### Request Example ```json { "file_id": "1f35642253606ed1e9dd8cd8113a8998" } ``` ## Response Binary file stream. URL: /api_docs/knowledge/download_kb_doc --- # Update Knowledgebase File **POST** `/update/knowledgebase-file` Submit new content for an existing Knowledge Base file to create its next version. - operationId: `update_knowledgebase-file` ## Request Body | Parameter | Type | Required | Description | |---|---|---|---| | `file_id` | string | Yes | ID of the Knowledge Base file to update. | | `file` | object | Yes | New version of the file. | #### `file` object | Parameter | Type | Required | Description | |---|---|---|---| | `name` | string | No | File name of the new version. Required for Base64 content to determine the extension. | | `content` | string | Yes | New file content, as a URL or Base64-encoded string. | ### Request Example ```json { "file_id": "1f35642253606ed1e9dd8cd8113a8998", "file": { "name": "Software_Procurement_Reimbursement_Policy.pdf", "content": "https://cdn.memtensor.com.cn/file/Software_Procurement_Reimbursement_Policy_v2.pdf" } } ``` ## Response Successful Response | Parameter | Type | Required | Description | |---|---|---|---| | `code` | integer | Yes | API status code. See Error Code for details. | | `data` | object | No | | | `message` | string | Yes | API response message | #### `data` object | Parameter | Type | Required | Description | |---|---|---|---| | `file_id` | string | No | Logical file ID. Reuse it in later updates and downloads. | | `version` | integer | No | Version number created by this update. | | `current_version` | integer | No | Current version of the file. | | `version_id` | string | No | Version record ID. | | `task_id` | string | No | Processing task ID of the new version, used to query progress. | | `status` | string | No | Version status, PROCESSING after submission. | URL: /api_docs/knowledge/update_kb_doc --- # Delete Knowledge Base File **POST** `/delete/knowledgebase-file` Delete files from a specified Knowledge Base. When a Skill file is deleted, the associated Skill is deleted as well. - operationId: `delete_knowledgebase-file` ## Request Body | Parameter | Type | Required | Description | |---|---|---|---| | `file_ids` | array | Yes | List of file IDs to delete. You can pass ordinary document IDs or Skill file IDs. | ## Response Successful Response | Parameter | Type | Required | Description | |---|---|---|---| | `code` | integer | Yes | API status code. See Error Code for details. | | `data` | object | No | | | `message` | string | Yes | API response message | #### `data` object | Parameter | Type | Required | Description | |---|---|---|---| | `success` | boolean | No | Whether deletion was successful. true for success, false for failure. | URL: /api_docs/knowledge/delete_kb_doc --- # Error Codes (/api_docs/help/error_codes) | Code | Meaning | Resolution | | :--- | :--- | :--- | | **Parameter Errors** | | | | 40000 | Invalid request parameters | Check parameter names, types, and formats | | 40001 | Requested data not found | Check if resource ID (e.g., memory_id) is correct | | 40002 | Required field cannot be empty | Provide missing required fields | | 40003 | Field is empty | Check if the provided list or object is empty | | 40006 | Unsupported type | Check the value of the 'type' field | | 40007 | Unsupported file type | Only upload allowed formats (.pdf, .docx, .doc, .txt, .json, .md, .xml) | | 40008 | Invalid Base64 content | Check if the Base64 string contains illegal characters | | 40009 | Invalid Base64 format | Check if the Base64 encoding format is correct | | 40010 | User ID too long | user_id length cannot exceed 100 characters | | 40011 | Conversation ID too long | conversation_id length cannot exceed 100 characters | | 40020 | Invalid Project ID | Confirm the Project ID format is correct | | **Authentication & Permission Errors** | | | | 40100 | API Key authentication required | Add a valid API Key to the request header | | 40130 | API Key authentication required | Add a valid API Key to the request header | | 40132 | Invalid or expired API Key | Check API Key status or generate a new one | | **Quota & Rate Limit Errors** | | | | 40300 | Rate limit exceeded | [Get more quota](/memos_cloud/support/limit#_4-obtaining-more-quota) | | 40301 | Chat request token quota exceeded | Reduce input content or get more quota | | 40302 | Chat response token quota exceeded | Shorten expected output or get more quota | | 40303 | Chat length exceeds model limit | Reduce single input/output length | | 40304 | Total API call quota exceeded | [Get more quota](/memos_cloud/support/limit#_4-obtaining-more-quota) | | 40305 | Input content exceeds token limit | Reduce input content | | 40306 | delete_memory authentication failed | Confirm if you have permission to delete this memory | | 40307 | Memory for deletion does not exist | Check if the memory_id is valid | | 40308 | User for deletion does not exist | Check if the user_id is correct | | **System & Service Errors** | | | | 50000 | Internal server error | Server busy or anomaly, please contact support | | 50002 | Operation failed | Check operation logic or try again later | | 50004 | Memory service is temporarily unavailable | Retry memory write/fetch operations later | | 50005 | Search service is temporarily unavailable | Retry memory search operations later | | **Knowledge Base & Operations** | | | | 50103 | File count exceeds limit | The number of files for a single upload should not exceed 20 | | 50104 | Single file size exceeds limit | Ensure single file does not exceed 100MB | | 50105 | Total file size exceeds limit | Ensure total upload size does not exceed 300MB | | 50107 | Invalid file format | Check and change file format | | 50120 | Knowledge base not found | Confirm if the knowledgebase_id is correct | | 50123 | Knowledge base not linked to project | Confirm KB is authorized for the current project | | 50131 | Task not found | Check if task_id is correct (common in status queries) | | 50143 | Failed to add memory | Algorithm service anomaly, please try again later | | 50144 | Failed to add message | Failed to save chat history | | 50145 | Failed to save feedback and write memory | Anomaly during feedback processing | --- # Build a Shared Knowledge Base for AI Apps with MemOS (/usecase/shared_knowledge_base) The product handbook lives in a cloud drive, the onboarding guide in a group chat, the support policy on a colleague's laptop. New hires spend half of their first week asking where the latest version actually is. Memmy recently shipped a knowledge-base feature to fix exactly this, built entirely on MemOS knowledge-base APIs: everyone can maintain a personal library, and any library can be shared with colleagues. Recipients query the same retrieval API and read the same content. The interesting part is how it is implemented. MemOS offers no "share knowledge base" endpoint and no "list all knowledge bases" endpoint. Sharing is something Memmy does on its own, in the application layer. That trade-off is what this best practice is really about — so we built a locally runnable demo that walks through the entire split. ## The Split Matters More Than the APIs A shared knowledge base looks like one feature. Underneath, it is two separate jobs: | Who | What it owns | How | | --- | --- | --- | | MemOS | Document text, parsing, chunking, searchable memory snippets | `/create/knowledgebase`, `/add/knowledgebase-file`, `/search/memory`, and friends | | Your app | Who owns each library, who it was shared with, whether the current user may see it | Two tables in your own database: ownership and shares | In one sentence: MemOS answers "what do the documents say", while the app answers "is this person allowed to read them". At search time, the app computes the visible `knowledgebase_ids` for the current user and hands that list to `/search/memory`. The payoff is a permission model you fully control — by team, by project, by expiry date, whatever your product needs — without waiting for MemOS to support a specific sharing semantic. The cost is equally plain: if your permission check is wrong, data leaks. That is why the demo treats "unauthorized users see nothing" as a first-class scenario. ## Three Roles in the Demo ```text alice · product owner Creates "Product Handbook", uploads the handbook and onboarding guide, and shares the knowledge base with bob. bob · customer success Switches to his own account, finds the library under "Shared knowledge bases", and can ask questions. He cannot upload, delete, or share it again. cara · new teammate Is not on the share list, so the library never appears in her sidebar at all. ``` Each role verifies one thing: alice covers the write path, bob covers read-only access, cara covers isolation. ## What Happens Behind One Answer ```text User opens the knowledge-base page │ ├─ App loads two lists for the current user_id: owned and shared-with-me │ ├─ Owner uploads a document │ → /add/knowledgebase-file │ → poll /get/knowledgebase-file until status is completed │ ├─ Owner enters the recipient's user ID │ → app writes a share record in its own database; MemOS is not touched │ ├─ Recipient asks a question │ → app confirms access │ → one /search/memory call: user_id + knowledgebase_ids │ → the model answers from the retrieved snippets │ └─ Optional: /add/message stores the turn as memory for the current user ``` Note the last step: knowledge-base content is one shared copy for authorized members, but user memory always stays scoped to `user_id`. bob can read the handbook alice maintains, yet never sees alice's personal preferences — and bob's preferences never leak back to alice either. ## Run the Demo First The complete project is the [shared-knowledge-base Demo](https://github.com/shinetata/MemOS-KnowledgeBase-Practice). You need a MemOS API key and an OpenAI-compatible model endpoint: ```bash git clone https://github.com/shinetata/MemOS-KnowledgeBase-Practice.git cd MemOS-KnowledgeBase-Practice python3 -m venv .venv source .venv/bin/activate pip install -r requirements.txt cp .env.example .env ``` Fill in `.env`: ```bash MEMOS_API_KEY=YOUR_MEMOS_API_KEY MEMOS_BASE_URL=https://memos.memtensor.cn/api/openmem/v1 OPENAI_API_KEY=YOUR_OPENAI_API_KEY OPENAI_BASE_URL=YOUR_OPENAI_BASE_URL OPENAI_MODEL=YOUR_MODEL_NAME ``` ```bash python app.py ``` Open [http://127.0.0.1:8765](http://127.0.0.1:8765). The demo ships three users — `alice`, `bob`, `cara` — switchable from the avatar in the top-left rail. Sharing works by entering the recipient's user ID (like `bob`); the current user's ID is shown in the sidebar. Suggested walkthrough: create a library as `alice` → upload the sample documents → wait until they show as available → share with `bob` → switch to `bob` and ask a question → switch to `cara` and confirm she sees nothing. `cara` can still ask questions without any library: the reply will state that no knowledge-base content was referenced, which contrasts directly with bob's cited answers. ## Four Decisions Worth Studying Once it runs, the pages matter less than four decision points. The whole demo fits in three files — `memos_client.py`, `store.py`, `app.py` — and every snippet below maps directly onto them. ### Decision 1: Outsource Document Parsing Entirely The ID returned by knowledge-base creation goes straight into the app's own storage, attached to the current user. From then on, that ID is the anchor of the permission tables: ```python kb_id = memos.create_knowledgebase(name, description) store.create_kb(kb_id, owner_id, name, description) ``` Uploads are encoded as Data URIs and handed to `/add/knowledgebase-file`; parsing, chunking, and indexing all happen on the MemOS side: ```python encoded = base64.b64encode(content).decode("ascii") memos.post("/add/knowledgebase-file", { "knowledgebase_id": kb_id, "file": [{ "type": "document", "name": filename, "content": f"data:{mime};base64,{encoded}", }], }) ``` Fresh uploads usually come back as `running`, so the page polls `/get/knowledgebase-file` until `completed` or `failed`. One trap worth knowing: asking questions before parsing finishes means retrieval cannot recall that document. The demo keeps polling while files are still processing rather than leaving users to guess. ### Decision 2: A Share Is Just a Row in Your Database Sharing does not call MemOS — worth repeating. After the owner enters the recipient's ID, the app runs two checks, writes one row, and is done: ```python def share_kb(self, owner_id, kb_id, member_id): if not self.can_manage(owner_id, kb_id): raise PermissionError("only the owner can share") if not self.get_user(member_id): raise KeyError("unknown user id") self.insert_share(kb_id, member_id) ``` The demo matches recipients by a stable user ID. An application can also resolve a phone number or email to an account first, as Memmy does, then store the corresponding user ID. When a recipient opens the page, the app reads from its two tables: ```python owned = store.list_owned(user_id) shared = store.list_shared(user_id) ``` Role decides permission: owners can upload, delete, and share; recipients can only browse files and ask questions. ### Decision 3: knowledgebase_ids Is the Only Exit for Permissions Before any answer is generated, the app validates access, then passes the ID to search: ```python kb = require_view(user_id, kb_id) retrieved = memos.search_memory( query=query, user_id=user_id, knowledgebase_ids=[kb["kb_id"]], conversation_id=conversation_id, ) ``` The public API searches no knowledge base by default; only explicitly passed IDs enter the recall. In other words, `knowledgebase_ids` is not a display-layer filter but the final gate of your permission logic: an unauthorized ID must never appear in that list. The demo asks against the currently open library, so it passes a single ID; if your product needs "ask across everything I can see", pass all IDs the user can access. ### Decision 4: One Recall, Two Kinds of Memory A single `/search/memory` call returns both knowledge-base snippets and the current user's facts and preferences: ```python context_data = { "query": query, "user_id": user_id, "conversation_id": conversation_id, "knowledgebase_ids": [kb_id], "include_memory_view": ["detail_factual", "preference"], "memory_limit_number": 9, "relativity": 0.45, } ``` Weight the two deliberately in your prompt: policies, processes, and quotas come from the knowledge base; personal preferences may shape tone but must never override the written rules. When the knowledge base has no evidence, the assistant should say so instead of inventing a rule the handbook never wrote. Afterwards, the turn can be written back under the current `user_id` via `/add/message`. The next time bob asks something, MemOS brings bob's own preferences along — the most concrete expression of "shared content, isolated memory". ## Acceptance Checklist After integration, walk all three roles; all three statements must hold: 1. `alice` creates a library, uploads documents, waits for "available", and shares with `bob` — the write path works. 2. `bob` sees the library under shared libraries and can ask questions, but the UI offers no upload or delete entry; direct write API calls are also rejected by the server's ownership check. 3. `cara`'s sidebar shows nothing, and even a guessed knowledge-base ID sent straight to the API is rejected by the app layer. `cara` may still ask general questions, but the retrieval scope contains no knowledge base and the answer carries no citations. The third item is the one most often missed: isolation is not achieved by the frontend not rendering something, but by the server recomputing the visible scope before every retrieval. ## Where the Code Lives - Repository: [MemOS-KnowledgeBase-Practice](https://github.com/shinetata/MemOS-KnowledgeBase-Practice) Page layout, left to right: a slim navigation rail, the library list (personal / shared), the file panel of the selected library, and a large Q&A area that asks against the current library. The core retrieval logic is condensed into this one method in `memos_client.py`: ```python def search_memory(self, query, user_id, knowledgebase_ids, conversation_id): return self._post("/search/memory", { "query": query, "user_id": user_id, "conversation_id": conversation_id, "knowledgebase_ids": knowledgebase_ids, "include_memory_view": ["detail_factual", "preference"], "memory_limit_number": 9, "relativity": 0.45, }) ``` Knowledge-base content is shared with authorized members; user memory stays per person. Once your app computes the visible scope correctly, MemOS takes care of the rest. --- # Integrating MemOS Knowledge Bases into Memmy (/usecase/memmy_knowledge_base) Memmy is a desktop agent application that helps users continue work across DeepSeek Harness, Claude Code, Codex, and other agents. Users want agents to consult their own product manuals, project documents, and research reports. Memmy's knowledge bases serve this need: users create libraries, upload files, and select which libraries participate in conversations. Before an agent answers, retrieval runs automatically, and the answer cites its sources. This feature is built entirely on MemOS knowledge base APIs. Unlike a server that calls MemOS directly, Memmy runs on many end users' computers and lets users share materials with each other. These conditions shape its integration. This article follows a product team's workflow through creation, upload, retrieval, sharing, and deletion, explaining what Memmy does at each step and why. Code snippets illustrate application-server calls to public MemOS APIs; they are not a directly runnable application. ## Usage scenario A product team follows this workflow: 1. **Create.** A product manager creates a Memmy knowledge base and uploads *MemOS Product Overview.md* and *MemOS Open Source vs Commercial.md*. Both files move from Processing to Ready. 2. **Share.** The manager enters a sales colleague's phone number in Sharing to share the library. 3. **Ask.** The colleague asks “How do MemOS Open Source and commercial editions differ?” Before answering, the agent automatically retrieves information, then cites *MemOS Open Source vs Commercial*. 4. **Update.** The manager uploads another document. The colleague's next question can retrieve it without extra action. 5. **Revoke.** After the colleague changes roles, the manager revokes sharing. Subsequent questions no longer search this library. *The interface images in this guide are localized illustrations of the Chinese UI.* ![Memmy knowledge base page](https://cdn.memtensor.com.cn/img/memos-best-practices-memmy-list-en-20261028_compressed.png) ## Architecture Memmy consists of a desktop app and a cloud service. Integration has four constraints: 1. **Keep the API key on the server.** Desktop packages and local settings are accessible on users' computers. The MemOS API key stays in Memmy's cloud service; the desktop app authenticates to that service using the user's Memmy credentials. 2. **Determine ownership in the application.** MemOS knowledge bases belong to a developer project and do not identify Memmy end users. Memmy uses one MemOS project for all users. Before each call, its cloud service determines which user owns or can access each library. 3. **Keep settings with the account.** A user may sign in on multiple computers. Each user's Include in Retrieval setting for each library is stored in the cloud service. 4. **Keep cloud credentials away from the agent.** Agents call tools and read local files. The knowledge base hook uses only a local-service access token; the retrieval path does not pass cloud credentials to the agent. The result is three layers: the desktop communicates with Memmy's cloud service, which calls MemOS on the user's behalf. ```mermaid flowchart LR subgraph Desktop["Memmy Desktop"] direction TB Page["Knowledge Base Page"] Hook["Knowledge Base Hook"] Local["Local Service"] Page --> Local Hook --> Local end subgraph Service["Memmy Cloud Service"] direction TB Auth["Identify Signed-In User"] Biz["Ownership · Sharing · Retrieval Settings"] Scope["Map Knowledge Base IDs Calculate Retrieval Scope"] Auth --> Biz --> Scope end subgraph Cloud["MemOS"] direction TB Store["Knowledge Bases and Files"] Index["Parse · Chunk · Index"] Search["Knowledge Retrieval"] Store --> Index --> Search end Desktop -->|Memmy Credentials| Service Service -->|MemOS API Key| Cloud ``` The responsibilities for each feature are as follows. Features without a corresponding MemOS API are implemented entirely in Memmy's application layer. | Memmy feature | Memmy cloud service | MemOS | MemOS API | | --- | --- | --- | --- | | Create a knowledge base | Store the mapping between Memmy and MemOS knowledge base IDs | Create the knowledge base | `/create/knowledgebase` | | Upload files | Verify ownership and map the knowledge base ID | Store files and asynchronously parse, chunk, and index them | `/add/knowledgebase-file` | | File list and processing status | Filter by folder | Return file details and processing status | `/get/knowledgebase-file` | | Rename and folders | Store names and directory structure | — | — | | Include in Retrieval | Store each user's switch for each library | — | — | | Search before an agent answers | Calculate scope and recheck results | Search selected knowledge bases | `/search/memory` | | Share a knowledge base | Maintain memberships | — | — | | Delete a library or file | Remove it from the application first | Clean up libraries and files in the background | `/delete/knowledgebase`, `/delete/knowledgebase-file` | All MemOS calls pass through one entry point. The API key appears only here: ```python MEMOS_BASE_URL = "https://memos.memtensor.cn/api/openmem/v1" MEMOS_API_KEY = os.environ["MEMOS_API_KEY"] # Configure only in the cloud service def memos_post(path, body): resp = requests.post( MEMOS_BASE_URL + path, headers={"Authorization": f"Token {MEMOS_API_KEY}"}, json=body, ) return resp.json()["data"] ``` The remaining examples call MemOS through `memos_post`. Memmy's own data is represented with dictionaries below; a real implementation can use a database. Folder data follows a similar structure and is omitted. ```python knowledge_bases = {} # Memmy KB ID -> {"memos_kb_id", "owner_id", "name"} members = {} # Memmy KB ID -> set of recipient user IDs recall_selected = {} # (user ID, Memmy KB ID) -> included in retrieval def can_access(user_id, kb_id): # The owner or a recipient owner_id = knowledge_bases[kb_id]["owner_id"] return user_id == owner_id or user_id in members.get(kb_id, set()) ``` ## Create and upload ### Create a knowledge base When a user submits a name, the cloud service creates the MemOS knowledge base, then stores the ID mapping: ```python def create_knowledge_base(owner_id, name): data = memos_post("/create/knowledgebase", {"knowledgebase_name": name}) kb_id = str(uuid.uuid4()) # Memmy KB ID returned to the desktop app knowledge_bases[kb_id] = { "memos_kb_id": data["id"], # MemOS KB ID stays in the cloud service "owner_id": owner_id, "name": name, } recall_selected[(owner_id, kb_id)] = True # Included by default return kb_id ``` Subsequent desktop requests carry only the Memmy knowledge base ID. The cloud service does not accept client-supplied MemOS knowledge base IDs, keeping them outside client-controlled input. New libraries are included in retrieval by default. Renaming changes only the name stored in Memmy and makes no MemOS call. ### Upload and manage files Before upload, the desktop and cloud service validate files against MemOS limits: PDF, DOCX, DOC, TXT, JSON, MD, or XML, with a maximum of 100 MB per file. After confirming that the caller is the owner, the service maps the Memmy ID to the MemOS ID and submits the file: ```python def upload_file(user_id, kb_id, filename, content): kb = knowledge_bases[kb_id] if kb["owner_id"] != user_id: raise PermissionError("Only the owner can upload files") mime_type, _ = mimetypes.guess_type(filename) encoded = base64.b64encode(content).decode("ascii") files = memos_post("/add/knowledgebase-file", { "knowledgebase_id": kb["memos_kb_id"], # Map to the MemOS KB ID "file": [{ "name": filename, "content": f"data:{mime_type};base64,{encoded}", }], }) return files[0]["status"] # Usually running while MemOS processes the file ``` For larger files, place the file at an address MemOS can access and pass the URL in `content`. MemOS asynchronously parses, chunks, and indexes the file. Status moves from `running` to `completed`, or to `failed` on failure. Only completed content enters retrieval results. Memmy displays Processing, Ready, or Failed, refreshing periodically while files are processing. Memmy does not duplicate filenames, processing status, or other file details: opening a library queries MemOS directly, providing one status source. Memmy stores only the additional directory structure. MemOS knowledge base files are flat; the cloud service records folder hierarchy and each file's folder, then filters accordingly. Moving a file changes the mapping without uploading or parsing it again. ## Retrieval before the agent answers User isolation ultimately depends on the knowledge base IDs submitted for every search. An incorrect ID can expose another user's materials. The flow is: ```mermaid sequenceDiagram participant User as User participant Hook as Knowledge Base Hook participant Service as Memmy Cloud Service participant MemOS as MemOS participant Agent as Agent User->>Hook: Ask a question Note over Hook: Triggered before the agent runs Hook->>Service: Current question Service->>Service: Calculate retrieval scope alt Empty scope Service-->>Hook: Return without calling MemOS else Nonempty scope Service->>MemOS: /search/memory (knowledgebase_ids = scope) MemOS-->>Service: Knowledge base snippets Service->>Service: Recheck scope, discard results if changed Service-->>Hook: Snippets and sources end Hook->>Agent: Append materials to this run's system prompt Agent-->>User: Answer with source citations Hook->>Hook: Remove injected content after the run ``` The hook automatically retrieves before the agent runs; the agent calls no knowledge base APIs itself. After Include in Retrieval is enabled, users do not need to request a search explicitly. The trade-off is one search per turn, including questions unrelated to the materials. The hook appends materials to the current run's system prompt, then removes them when the run ends. Each new question triggers fresh retrieval, so materials do not accumulate over multiple turns. The cloud service checks scope before and after the MemOS call: first to select libraries, then to confirm that access did not change during retrieval. The retrieval scope is the intersection of: - Libraries the user has enabled for retrieval. - Libraries the user can currently access, including owned and shared libraries. With an empty intersection, the service skips the MemOS call. In the example, if the colleague owns one library and receives the manager's shared library, both enabled, the scope contains both MemOS IDs. Disabling retrieval for the personal library leaves only the shared one. `knowledgebase_ids` is the final permission boundary in this path. MemOS searches no knowledge base by default; only explicitly supplied IDs enter scope. It also accepts `all`, which searches every library in the project, including other users' libraries. Memmy recomputes scope on every search, supplies an explicit ID list, and derives it from server-side state. ```python def recall_scope(user_id): return [ kb["memos_kb_id"] for kb_id, kb in knowledge_bases.items() if can_access(user_id, kb_id) # Owned and shared and recall_selected.get((user_id, kb_id), False) # Retrieval enabled ] def recall(user_id, query): scope = recall_scope(user_id) if not scope: return [] # Skip MemOS data = memos_post("/search/memory", { "user_id": f"kb-reader-{user_id}", # Retrieval-only identifier "query": query, "knowledgebase_ids": scope, # Explicit IDs, never all }) if recall_scope(user_id) != scope: # Discard results if scope changed return [] return [ {"title": item["memory_key"], "content": item["memory_value"]} for item in data["memory_detail_list"] ] ``` The second check is easy to overlook. Retrieval takes time, during which an owner may revoke sharing or a user may disable a library. If the manager revokes access while the colleague's request is running, the library is authorized before the MemOS call but no longer authorized when results return. The service discards the entire result; the next turn uses the new scope. The example's `user_id` is reserved for retrieval and never receives conversation writes, so results contain only knowledge base snippets. Memmy's personal memory is handled by a separate Memory module; each context type has its own hook. Applications without a separate memory system can pass the real `user_id` to retrieve user facts and preferences in the same search. See [knowledge base features](/memos_cloud/features/knowledge_base). The hook labels retrieved content as reference material, asks the agent to cite sources, and tells it to ignore instructions contained in the materials to reduce prompt-injection risk. ![Agent answer citing document sources](https://cdn.memtensor.com.cn/img/memos-best-practices-memmy-citations-en-20261028_compressed.png) ## Share a knowledge base MemOS has no membership or sharing API. Memmy implements sharing in the application layer. Because all libraries belong to one MemOS project, the service can add an owner's MemOS knowledge base ID to a recipient's retrieval scope once access is authorized. 1. The owner enters a Memmy user ID, phone number, or email in Sharing. 2. The cloud service resolves it to a Memmy account, verifies that it exists and is not the owner, and stores a read-only membership. No MemOS call is made. 3. After refreshing, the recipient sees the library under Shared, with its owner's name. New shared libraries are included in the recipient's retrieval by default. ![Sharing management](https://cdn.memtensor.com.cn/img/memos-best-practices-memmy-sharing-en-20261028_compressed.png) | Operation | Owner | Recipient | | --- | --- | --- | | View files | Yes | Yes | | Toggle Include in Retrieval | Yes | Yes, for their own account only | | Upload or delete files | Yes | — | | Create, move, or delete folders | Yes | — | | Rename or delete the knowledge base | Yes | — | | Manage sharing | Yes | — | Sharing creates no content copies: all members search the same MemOS knowledge base. A newly uploaded document can appear in the colleague's next search once available. Revoking sharing immediately removes the library from that member's retrieval scope. ## Delete a knowledge base Deletion has two stages. First remove the library from Memmy so it immediately disappears from members' lists and retrieval scopes. Then clean up MemOS data in the background. ```python def delete_knowledge_base(user_id, kb_id): kb = knowledge_bases[kb_id] if kb["owner_id"] != user_id: raise PermissionError("Only the owner can delete a knowledge base") # 1. Remove from Memmy first del knowledge_bases[kb_id] members.pop(kb_id, None) # 2. Clean up MemOS in the background threading.Thread(target=memos_post, args=("/delete/knowledgebase", { "knowledgebase_id": kb["memos_kb_id"], "delete_all": True, })).start() ``` `delete_all` defaults to `false`, which unlinks the knowledge base from the current project while retaining the library and files. Complete deletion requires explicit `true`. Files and folders follow the same sequence, using `/delete/knowledgebase-file` in the background. Prepare retries or periodic reconciliation for failed cleanup so deleted application data does not remain in MemOS. ## Summary MemOS handles what the documents say; Memmy handles who can use them and which ones are in scope. AI products with clients and end users can follow the same division when integrating MemOS knowledge bases. Memmy permissions apply to the whole knowledge base. For file-level visibility differences, place files with different audiences into separate libraries. --- # Build a Memory-Enhanced Knowledge Base Q&A Assistant (/usecase/knowledge_qa_assistant) ## 1. Overview In AI application development, building a Q&A assistant that can understand context and remember historical interactions has always been a core requirement. Traditional large language models are powerful, but they lack long-term memory—every conversation starts over as if the model has “amnesia.” RAG (Retrieval-Augmented Generation) can retrieve relevant knowledge, but it still can’t truly “remember” user preferences or past interactions. MemOS provides a complete memory operating system ecosystem that gives AI applications real long-term memory. With a MemOS-powered knowledge base, you can provide contextual information to an LLM via prompts, enabling more accurate and personalized responses. This experience is significantly better than chatting with a generic LLM on the public internet. ### 1.1 MemOS Memory Layer vs RAG: Key Differences The core issue with traditional RAG is: **it is stateless**. Each query is independent. The system can only retrieve static knowledge based on semantic similarity, but it cannot remember “who you are,” “what you said before,” or “what you prefer.” It’s like a librarian with amnesia—every time you walk in, they have to ask your needs from scratch, and they can’t personalize recommendations based on your reading history. The core value of the MemOS memory layer is: **it gives AI applications long-term memory**. It can not only retrieve knowledge, but also understand relationships, time, and preferences, and connect the current question with historical memory—so it searches and uses knowledge “with background.” As users keep interacting, MemOS continuously evolves and updates memory from conversation content, enabling the knowledge base to iterate and “self-evolve.” | Dimension | Traditional RAG | MemOS Memory Layer | | --- | --- | --- | | **Memory capability** | Can retrieve, cannot remember — retrieves static knowledge by vector similarity; cannot dynamically record user interaction history | Dynamic memory — automatically captures, stores, and manages conversation history and user behavior | | **Personalization** | Lacks personalization — cannot adjust answers based on the user’s past behavior | Personalized experience — provides tailored answers based on historical preferences | | **Context management** | Fragmented context — hard to manage related info across multi-turn conversations | Intelligent association — builds relationships between memories through semantic understanding | | **Knowledge updates** | Hard to update — adding new knowledge often requires rebuilding vector indexes | Real-time updates — supports incremental memory updates and priority management | ### 1.2 Real-World Scenario Comparison: Enterprise Knowledge Base Assistant Let’s look at one real business scenario to clearly see the difference between RAG and MemOS: ```text DAY 1 Employee asks: My computer is a MacBook Pro 13-inch with an Intel chip. How do I install the company intranet proxy? DAY 1 The assistant provides Intel-version installation steps. DAY 20 Employee asks: The intranet proxy stopped working—what version should I reinstall? ``` #### The Problem with a RAG Approach ```text # Retrieve content related to "intranet proxy" and "not working", # but cannot recall "the user's device model" Retrieved knowledge: 1. Common intranet proxy troubleshooting 2. Mac M1/M2 (ARM) proxy installation instructions 3. Windows intranet proxy client installation instructions 4. Network connectivity and certificate issues 5. General FAQ ❌ Knowledge Base Assistant: Please reinstall the latest Mac M1/M2 (ARM) version or the Windows intranet proxy client. Here are the steps: ... ``` #### The Advantage of MemOS ```text # Retrieve memories related to "intranet proxy" and "not working", # and automatically identify the employee's device model Retrieved memories: 1. The user installed the company intranet proxy 20 days ago; their device is a MacBook Pro 13 (Intel) 2. Common intranet proxy troubleshooting 3. Intel-version intranet proxy installation instructions ✅ Knowledge Base Assistant: You’re using an Intel-based MacBook Pro, so we recommend reinstalling the Intel version of the intranet proxy client. Here’s the Intel download link and installation steps: ... ``` ### 1.3 Why MemOS? From the scenario above, you can clearly see three core advantages of MemOS over traditional RAG: 1. **Understands users: automatically fills in context** RAG is good at retrieving knowledge semantically related to a query, but it is stateless—each query stands alone, with no understanding of the user or context. Users must repeat their background every time. MemOS can understand relationships, time, and preferences. It knows “who you are” and “what you’re doing.” You can simply ask your question, and MemOS will fill in the missing context automatically—no need to repeat things like “my dog doesn’t eat chicken” or “my computer has an Intel chip.” 2. **Personalization: remembers habits and preferences** Users in different roles and work styles need different service approaches. MemOS can remember: "This customer doesn’t like overly aggressive sales pitches" "You use Python more often than Java" "You asked about reimbursement policy last time—do you want to proceed with the application flow now?" This personalization makes an AI application truly “your” assistant, not just a generic tool. 3. **Knowledge evolution: keeps learning from interactions** When a real process contains “experience rules” that aren’t documented, MemOS can distill them into new memories, continuously filling gaps and improving the knowledge system. As end users keep using it, MemOS evolves and updates memory based on conversations—so the knowledge base becomes part of “memory,” not just a static document store. On this foundation, MemOS 2.0 provides knowledge base and multimodal capabilities. Developers can connect business documents to MemOS and quickly build an assistant that understands users—especially when combined with open-source LLMs. ## 2. Setup Tutorial ### 2.1 Prepare the Knowledge Base (5 min) #### Create a knowledge base Create a knowledge base via the [Console](https://memos-dashboard.openmem.net/knowledgeBase/) or API. This article categorizes documents based on [MemOS official docs](https://github.com/MemTensor/MemOS-Docs), MemTensor’s past announcements, and release notes to make future updates and management easier. In this example, you can create just **one** knowledge base and upload a subset of documents for testing. *The interface images below are localized illustrations of the Chinese UI.* ![Create a knowledge base](https://cdn.memtensor.com.cn/img/memos-best-practices-kb-create-en-20261028_compressed.png) #### Upload documents Enter the knowledge base and upload your documents. Note the document requirements: MemOS-Docs are in MD format; you can use an AI tool to convert them to TXT format with one click, then upload them. When uploading, pay attention to the requirements. The rest—**storage, parsing, chunking, and memory generation**—is handled by MemOS. Just wait until processing finishes and the status shows “Available.” ![image.png](https://cdn.memtensor.com.cn/img/memos-best-practices-kb-upload-en-20261028_compressed.png) ### 2.2 Run the Code (5 min) The following demo is shown using a Python runtime. #### 2.2.1 Copy the complete runnable code ```python import os import requests import json from openai import OpenAI from datetime import datetime # Get MEMOS_API_KEY from the cloud console os.environ["MEMOS_API_KEY"] = "mpg-xxx" # Replace with your OpenAI API key os.environ["OPENAI_API_KEY"] = "sk-xxx" os.environ["MEMOS_BASE_URL"] = "https://memos.memtensor.cn/api/openmem/v1" # Replace with your own knowledge base IDs (these are examples only) os.environ["KNOWLEDGE_BASE_IDS"] = json.dumps([ "based540fb25-ddf1-4456-935b-41d901518e04", "base3908d457-da43-4dde-989e-020be132eff4", "base1db3a7ea-6ecc-4925-881a-e87800da8d2e" ]) openai_client = OpenAI(api_key=os.getenv("OPENAI_API_KEY")) class KnowledgeBaseAssistant: def __init__(self): self.openai_client = openai_client self.base_url = os.getenv("MEMOS_BASE_URL") self.knowledge_base_ids = json.loads(os.getenv("KNOWLEDGE_BASE_IDS")) self.headers = { "Content-Type": "application/json", "Authorization": f"Token {os.environ['MEMOS_API_KEY']}" } def search_memory(self, query, user_id): """Query relevant memory""" data = { "query": query, "user_id": user_id, "conversation_id": user_id, "knowledgebase_ids": self.knowledge_base_ids } res = requests.post(f"{self.base_url}/search/memory", headers=self.headers, data=json.dumps(data)) if res.json().get('code') != 0: print(f"❌ Memory search failed, {res.json().get('message')}") return [], [] memory_detail_list_raw = res.json().get('data').get('memory_detail_list', []) # Filter out memories with relevancy < 0.5 memory_detail_list = [ x for x in memory_detail_list_raw if x.get('relativity', 0) >= 0.5 ] preference_detail_list = res.json().get('data').get('preference_detail_list') return memory_detail_list, preference_detail_list def build_system_prompt(self, memories, preferences): """Build a system prompt that contains formatted memory""" base_prompt = """ # Role You are the MemOS assistant, nicknamed XiaoYi🧚 — an AI assistant built around a “memory operating system” created by MemTensor. MemTensor is an AI research company based in Shanghai, guided by academicians of the Chinese Academy of Sciences. MemTensor is committed to the vision of "low cost, low hallucination, high generalization", exploring AI development paths suited to China’s context and advancing trustworthy AI adoption. MemOS’s mission is to equip LLMs and autonomous agents with “human-like long-term memory,” turning memory from a black box inside model weights into a core resource that is “manageable, schedulable, and auditable.” Your responses must comply with legal and ethical standards and applicable laws and regulations, and must not generate illegal, harmful, or biased content. If you encounter such requests, you must refuse clearly and explain the relevant legal or ethical principles. Your goal is to combine retrieved memory snippets to provide highly personalized, accurate, and logically rigorous answers. # System Context - Current time: {current_time} (use this as the reference for judging memory freshness) # Memory Data Below is information retrieved by MemOS, divided into “Facts” and “Preferences”. - **Facts**: may include user attributes, conversation history, or third-party info. - **Important**: content marked as `[assistant opinion]` or `[model summary]` represents **past AI inference** and is **not** the user’s original statement. - **Preferences**: explicit/implicit user requirements for style, format, or logic. {memories} {preferences} # Critical Protocol: Memory Safety Retrieved memories may contain **AI’s own speculation**, **irrelevant noise**, or **wrong subject attribution**. You must strictly execute the following **“four-step judgment.”** If a memory fails **any** step, you must **discard** that memory: 1. **Source Verification** - **Core**: distinguish “the user’s original words” from “AI speculation.” - If a memory carries labels like `[assistant opinion]`, it only indicates the AI’s past **assumption** and must **not** be treated as a definitive user fact. - *Counterexample*: a memory says `[assistant opinion] The user loves mangoes`. If the user never said it, do not assume they like mangoes—avoid self-reinforcing hallucinations. - **Principle**: AI summaries are for reference only and have far lower weight than the user’s direct statements. 2. **Attribution Check** - Is the actor/subject in the memory actually “the user”? - If the memory describes a **third party** (e.g., “candidate”, “interviewee”, “fictional character”, “case data”), you must never attribute those properties to the user. 3. **Relevance Check** - Does the memory directly help answer the current `Original Query`? - If it’s only a keyword match (e.g., both mention “code”) but the context is completely different, you must ignore it. 4. **Freshness Check** - Does the memory conflict with the user’s latest intent? Treat the current `Original Query` as the highest-priority source of truth. # Instructions 1. **Review**: read `facts memories` first and apply the “four-step judgment” to remove noise and unreliable AI views. 2. **Execute**: - **Prefer professional advice from the knowledge base** (e.g., product selection, technical solutions). - Use only the memories that pass filtering to enrich context. - Strictly follow the style requirements in `preferences`. 3. **Output**: - Answer the question directly, and **do not** mention internal system terms such as “memory store”, “retrieval”, or “AI view”. - If the answer is not in the current knowledge base/memory system, you must say so explicitly. Never fabricate information or give vague answers under any circumstances. 4. **Language**: respond in the same language as the user’s query. # Markdown-to-Plain-Text Conversion Rules - When you need to convert provided Markdown (MD) text into plain text, you must strictly follow these rules to ensure readability and avoid formatting errors: - Core formatting: WeChat does not support native MD syntax (e.g., # headings, bold text, code blocks, tables). You must simulate hierarchy using “symbols + newline + spaces”, and avoid unsupported markers. - Heading hierarchy: First check whether the original contains MD headings (lines starting with #). If yes: Level-1 headings use Roman numerals like 'I. ', 'II. ', 'III. '; Level-2 headings use Arabic numerals like '1. ', '2. ', '3. '; Level-3 and below use the '・' bullet. Numbers must auto-increment to match document structure. If the original has no MD headings: do not add heading numbering; keep the original paragraph structure. Examples: '### Title 1' → 'I. Title 1'; '#### Title 2' → '1. Title 2'; '##### Title 3' → '・Title 3'. If no MD headings exist, keep 'Title 1' as 'Title 1'. - Links: Keep Markdown links in 'text' form unchanged. Do not modify or delete any link content. - Lists: Convert '- item' MD lists into ordered lists ('1. item', '2. item') or unordered lists (use '・item'). Each list item must be on its own line, and keep one blank line before and after each item for readability. - Tables: If the MD contains tables, break them into bullet-style sections like '▶ Scenario Type A: XXX' and '▶ Scenario Type B: XXX'. Under each, list items with '1. 2. 3.' without losing info and without keeping table symbols. - Emphasis: Do not use * or **; replace original bold content with '「XXX」'. - Readability: Keep one blank line between major paragraphs. For overly long technical terms or complex descriptions, simplify into more conversational wording without changing meaning. Use Chinese punctuation consistently (e.g., ▶, ・, :) and avoid mixing Chinese/English punctuation that can cause confusion. - Output: Only output the converted plain text; do not add extra notes (e.g., 'conversion complete'); do not change the original meaning—only replace formatting; preserve 100% of the core info (dimensions, features, links, data) without omission; final text must be copy-pastable without further editing. """ # Build memory text (may be empty) if len(memories) > 0: formatted_memories = "## Related memories:\n" for i, memory in enumerate(memories, 1): formatted_memories += f"{i}. {memory.get('memory_value')}\n" else: formatted_memories = "" # Build preference text (may be empty) if len(preferences) > 0: formatted_preferences = "## Preferences:\n" for i, preference_detail in enumerate(preferences, 1): formatted_preferences += f"{i}. {preference_detail.get('preference')}\n" else: formatted_preferences = "" base_prompt = base_prompt.format( current_time=datetime.now().strftime('%Y-%m-%d %H:%M:%S'), memories=formatted_memories, preferences=formatted_preferences, ) return base_prompt def add_message(self, messages, user_id): """Add messages""" data = { "messages": messages, "user_id": user_id, "conversation_id": user_id } res = requests.post(f"{self.base_url}/add/message", headers=self.headers, data=json.dumps(data)) if res.json().get('code') == 0: print(f"✅ Added successfully") else: print(f"❌ Add failed, {res.json().get('message')}") def get_message(self, user_id): """Get messages""" data = { "user_id": user_id, "conversation_id": user_id, "message_limit_number": 15 } res = requests.post(f"{self.base_url}/get/message", headers=self.headers, data=json.dumps(data)) if res.json().get('code') == 0: return res.json().get('data').get('message_detail_list') else: print(f"❌ Get messages failed, {res.json().get('message')}") return [] def chat(self, query, user_id): """Main chat function with memory integration""" # 1. Fetch recent conversation history chat_history = self.get_message(user_id) # 2. Search relevant memories memories, preferences = self.search_memory(query, user_id) # 3. Build system prompt with memory system_prompt = self.build_system_prompt(memories, preferences) messages = [ {"role": "system", "content": system_prompt}, *chat_history, {"role": "user", "content": query} ] # 4. Use OpenAI to generate an answer response = self.openai_client.chat.completions.create( model="gpt-4o", messages=messages, temperature=0.3, top_p=0.9 ) answer = response.choices[0].message.content # 5. Save the conversation into memory messages = [ {"role": "user", "content": query}, {"role": "assistant", "content": answer} ] self.add_message(messages, user_id) # 6. Return the answer return answer ai_assistant = KnowledgeBaseAssistant() user_id = "memos_knowledge_base_user_123" def demo_questions(): return [ 'Who are you?' ] def main(): print("💡 Welcome to the Knowledge Base Q&A Assistant!\n") print("\n🎯 Here are some sample questions—you can continue chatting with the assistant:") for i, question in enumerate(demo_questions(), 1): print(f" {i}. {question}") while True: user_query = input("\n🤔 Enter your question (or type 'exit' to quit): ").strip() if user_query.lower() in ['quit', 'exit', 'q']: print("👋 Thanks for using the Knowledge Base Q&A Assistant!") break if not user_query: continue print("🤖 Processing...") answer = ai_assistant.chat(user_query, user_id) print(f"💡 [Assistant]: {answer}") print("-" * 60) if __name__ == "__main__": main() ``` #### 2.2.2 Initialize the runtime environment ```bash pip install openai requests ``` #### 2.2.3 Replace environment variables in the code ##### Get the key (API_KEY) Log into the console at [https://memos-dashboard.openmem.net/apikeys/](https://memos-dashboard.openmem.net/apikeys/) and copy the key. ![image.png](https://cdn.memtensor.com.cn/img/memos-best-practices-kb-apikey-en-20261028_compressed.png) ```python os.environ["MEMOS_API_KEY"] = "mpg-xx" ``` ##### LLM client ```python # Replace with your OpenAI API key os.environ["OPENAI_API_KEY"] = "sk-xx" # [Optional] Replace with your BASE_URL os.environ["OPEN_API_BASE_URL"] = "http://xxx.xxx" openai_client = OpenAI( api_key=os.getenv("OPENAI_API_KEY"), base_url=os.getenv("OPEN_API_BASE_URL") or None, ) ``` ##### Get the knowledge base ID For the knowledge base you just uploaded to, copy the ID and save it. ![image.png](https://cdn.memtensor.com.cn/img/memos-best-practices-kb-id-en-20261028_compressed.png) ```python # Replace with your own knowledge base ID (this is an example only) os.environ["KNOWLEDGE_BASE_IDS"] = json.dumps([ "based540fb25-ddf1-4456-935b-41d901518e04" ]) ``` ##### Execute the code ```bash python knowledge_qa_assistant.py ``` ![image.png](https://cdn.memtensor.com.cn/img/memos-best-practices-kb-terminal-en-20261028_compressed.png) ### 2.3 Code walkthrough 1. Set your MemOS API key, OpenAI API key, and knowledge base IDs via environment variables. 2. Instantiate `KnowledgeBaseAssistant`. 3. Use `main()` to start an interactive chat loop. 4. The assistant calls `chat()` to handle the interaction. Inside `chat()`, it performs: * Call `get_message` to fetch historical chat messages. * Call `search_memory` to retrieve facts and preferences. * Build a prompt based on the memory system. * Use the LLM to generate an answer. * Call `add_message` to store the user query and model answer as long-term memory. * Return the model answer. --- # Help a Support Agent Remember Users: Cross-Session Customer Service with MemOS (/usecase/customer_service_assistant) A customer reports a faulty headset in web chat, then follows up by email the next day—only to be asked for the order number and problem description again. For the customer, service continuity has broken. The system often has a straightforward gap: the new conversation did not receive previously confirmed information. Support agents need two kinds of memory. Customer-specific information includes orders, pending work, and notification preferences. Agent-level information includes reusable tool workflows for similar problems. Formal after-sales policies remain in a centrally maintained knowledge base. This article combines all three through Python examples. ## Key ideas - Write user facts and preferences with both `user_id` and `agent_id`; use `related_id` to select the current user's memories during retrieval. - Submit each complete task trace to the support agent's independent memory, requesting Skill generation only. MemOS decides whether to create or update a Skill. - Store policies in a knowledge base and include them in the same search using `knowledgebase_ids`. - Call `/search/memory` once before answering to retrieve user facts, preferences, Agent Skills, and policies together. - The agent maintains current conversation history; MemOS handles cross-session memory. ## What you will build The example has three stages: ```text DAY 1 · Web chat customer_001 requests a headset exchange. The agent queries the order, checks policy, creates a ticket, and records delivery timing, address, and SMS notification requirements. DAY 4 · Email ticket customer_001 follows up using a new conversation_id. DAY 7 · Web chat customer_002 reports a similar buzzing issue. The agent tries to reuse a Skill derived from the earlier task. ``` DAY 4 checks continuity of user facts and preferences across sessions. DAY 7 switches customers to check isolation while testing reuse of general Agent Skills. ## Separate the three information scopes 1. **User memory:** orders, faults, ticket status, addresses, and notification preferences belonging to the current `user_id`. 2. **Agent Skills:** general workflows derived from complete task traces and associated with a stable `agent_id`. 3. **Policy knowledge base:** formal returns, warranty, shipping, and invoice rules maintained by the business. Policies determine what the rules require, user memories show the customer's progress, and Agent Skills supply the usual steps for completing that type of task. ## End-to-end flow ```text Customer request | +-- Agent reads current conversation history from the application | +-- One combined search: agent_id + knowledgebase_ids | filter selects the current user's memories (related_id) | and Agent Skills (SkillMemory) | -> user facts, preferences, Skills, policies | +-- Assemble context and execute order, ticket, and notification tools | +-- Model generates a final response based on tool results | +-- Write 1: user_id + agent_id -> facts and preferences | +-- Write 2: agent_id -> request Skill generation or updates ``` Both writes submit the same task record but select different types through `allow_memory_view`. The user write supplies both IDs, assigning memory to the user and associating it with the support agent's memory space. The Skill write supplies only `agent_id`. The user view does not generate Skills; the Agent view does not duplicate user facts and preferences. Retrieval uses one `/search/memory` call. `related_id` limits facts and preferences to the current user, `SkillMemory` allows Agent Skills to return across users, and `knowledgebase_ids` includes policy material in the same search. ## Prerequisites The [complete Demo](#complete-demo) below can be copied and run locally. You need a MemOS API key and an OpenAI or OpenAI-compatible model endpoint. Create a Python environment and install dependencies: ```bash python3 -m venv .venv ./.venv/bin/python -m pip install openai requests ``` Configure these values: ```python MEMOS_API_KEY = "YOUR_MEMOS_API_KEY" OPENAI_API_KEY = "YOUR_OPENAI_API_KEY" MEMOS_BASE_URL = "YOUR_MEMOS_BASE_URL" OPENAI_MODEL = "YOUR_MODEL_NAME" OPENAI_BASE_URL = "YOUR_OPENAI_BASE_URL" AGENT_ID = "YOUR_AGENT_ID" ``` Derive `user_id` from authentication or your CRM. Keep `agent_id` stable for the same support agent across customers and conversations. Enable **Create Independent Memory for Agent** in the project console. It is off by default. Without it, `agent_id` provides tagging and filtering, rather than an independent subject for Agent Skill writes or retrieval. See [multi-agent isolation](/memos_cloud/introduction/isolation_filters). ## Prepare the policy knowledge base During initialization, create a policy knowledge base, upload the policy document, and wait for processing: ```python def create_policy_knowledge_base(): headers = { "Content-Type": "application/json", "Authorization": f"Token {MEMOS_API_KEY}", } # 1. Create knowledge base: POST /create/knowledgebase res = requests.post( f"{MEMOS_BASE_URL}/create/knowledgebase", headers=headers, json={ "knowledgebase_name": "Consumer After-Sales Policy Knowledge Base", "knowledgebase_description": "Consumer returns, exchanges, warranty, shipping, and invoice policies", }, ) body = res.json() if body.get("code") != 0: sys.exit(f"Failed to create knowledge base: {body.get('message')}") policy_kb_id = body["data"]["id"] # 2. Upload policy: POST /add/knowledgebase-file # Encode file content as base64 and pass a data URL encoded = base64.b64encode(POLICY_DOC_MD.encode("utf-8")).decode("utf-8") res = requests.post( f"{MEMOS_BASE_URL}/add/knowledgebase-file", headers=headers, json={ "knowledgebase_id": policy_kb_id, "file": [{ "type": "document", "name": "consumer-after-sale-policy.md", "content": f"data:text/markdown;base64,{encoded}", }], }, ) if res.json().get("code") != 0: sys.exit(f"Failed to upload policy: {res.json().get('message')}") # 3. Poll parsing status: POST /get/knowledgebase-file print("Policy document uploaded; waiting for parsing...") for _ in range(40): time.sleep(3) res = requests.post( f"{MEMOS_BASE_URL}/get/knowledgebase-file", headers=headers, json={"knowledgebase_id": policy_kb_id, "page": 1, "page_size": 20}, ) files = res.json().get("data", {}).get("file_detail_list", []) statuses = {str(item.get("status", "")).lower() for item in files} if files and statuses <= {"completed", "available", "failed"}: if "failed" in statuses: sys.exit("Policy parsing failed") break print(f"Policy knowledge base ready: {policy_kb_id}") return policy_kb_id ``` Use the ID returned by the creation API to initialize the assistant: ```python policy_kb_id = create_policy_knowledge_base() assistant = CustomerServiceAssistant(policy_kb_id) ``` ## Write back the complete task trace Each message uses `role_id` to identify the actual speaker. User messages use `user_id`; support responses and tool calls use `agent_id`: ```python # Complete message list written to MemOS for the DAY 1 exchange request memory_messages = [ # 1. User message: role_id identifies the current user { "role": "user", "role_id": user_id, # For example, customer_001 "content": "The left ear of my noise-canceling headphones buzzes; I want an exchange", }, # 2. Tool call: the support Agent queries the order; role_id is agent_id { "role": "assistant", "role_id": AGENT_ID, "content": "", "tool_calls": [{ "id": "call_1", "type": "function", "function": { "name": "query_order", "arguments": '{"order_id": "20260820-88"}', }, }], }, # 3. Tool result: tool_call_id links to the call above; no role_id is needed { "role": "tool", "tool_call_id": "call_1", "content": '{"order_id": "20260820-88", "status": "delivered"}', }, # 4. Final response: also attributed to the support Agent { "role": "assistant", "role_id": AGENT_ID, "content": "Exchange ticket EX20260821-03 has been created, with free shipping both ways...", }, ] ``` The agent maintains current conversation history in the application. For MemOS writes, the user request, tool calls, tool results, and final response form a complete task record: ```text user → assistant.tool_calls → tool → assistant ``` MemOS derives Skills and user facts/preferences from the same trace. ### Separate the write types Users and agents use different write views, while retrieval includes all three types: ```python USER_WRITE_VIEWS = ["detail_factual", "preference"] AGENT_SKILL_WRITE_VIEWS = ["skill"] CONTEXT_VIEWS = ["detail_factual", "preference", "skill"] ``` The same trace can enter both memory spaces without generating the same memory types twice. ### Write user facts and preferences The first `/add/message` request supplies both `user_id` and `agent_id`: ```python def add_user_memories(self, messages, user_id, conversation_id, channel): """First write: generate only user facts and preferences.""" user_data = { "user_id": user_id, "agent_id": AGENT_ID, "conversation_id": conversation_id, "info": {"channel": channel, "scene": "consumer_support"}, "allow_memory_view": USER_WRITE_VIEWS, "messages": messages, } # POST /add/message: writes run asynchronously; after receiving task_id, # poll /get/status until completed (see the full Demo below) res = requests.post( f"{MEMOS_BASE_URL}/add/message", headers=self.headers, json=user_data, ) if res.json().get("code") != 0: print(f" [MemOS] Failed to write user facts/preferences: {res.json().get('message')}") ``` The memory belongs to the current user and is associated with the support agent's memory space, so the agent-scoped combined search can select it through `related_id`. MemOS decides whether the conversation produces facts or preferences. A turn without a stable preference can produce only facts. ### Write Agent Skills The second `/add/message` request supplies only `agent_id` and permits only Skill generation: ```python def add_agent_skill(self, messages, conversation_id, channel): """Second write: request only Agent Skill generation or updates.""" skill_data = { "agent_id": AGENT_ID, "conversation_id": conversation_id, "info": {"channel": channel, "scene": "consumer_support"}, "allow_memory_view": AGENT_SKILL_WRITE_VIEWS, "custom_extract_prompt": {"skill": SKILL_EXTRACT_PROMPT}, "messages": messages, } # Also POST /add/message, without user_id and with only skill in allow_memory_view res = requests.post( f"{MEMOS_BASE_URL}/add/message", headers=self.headers, json=skill_data, ) if res.json().get("code") != 0: print(f" [MemOS] Failed to write Agent Skill: {res.json().get('message')}") ``` Skills belong to the Agent view and are reusable across users. Submit this write after every response. The caller declares the allowed memory type; MemOS compares the task trace with existing Skills and decides whether to generate, update, or skip. ## Keep Skills general MemOS performs Skill extraction. Use `custom_extract_prompt.skill` to add customer-service generalization requirements: - Identify a Skill by its business goal, trigger conditions, core tool chain, and success criteria. - Prefer merging the same workflow into an existing Skill; skip duplicates when no new general information is added. - Remove names, addresses, user IDs, order and ticket numbers, and specific dates. - Replace instance values with parameters such as `order_id`, `ticket_id`, and `shipping_address`. - Keep personal preferences and one customer's deadlines out of general rules. - Retain only executed steps evidenced by tool results. MemOS compares and updates existing Skills; callers do not need to manage Skill IDs or implement merging. ## Run one combined retrieval Before generating a response, the assistant makes one `/search/memory` call for user facts, preferences, Agent Skills, and policy knowledge: ```python def search_memory(self, query, user_id): """One combined retrieval: user facts/preferences + Agent Skills + policy knowledge.""" context_data = { "query": query, "agent_id": AGENT_ID, "knowledgebase_ids": self.knowledgebase_ids, "include_memory_view": CONTEXT_VIEWS, "memory_limit_number": 9, "preference_limit_number": 6, "filter": { "user": { "or": [ {"related_id": [user_id]}, {"memory_type": "SkillMemory"}, ] } }, } # POST /search/memory: retrieve user facts, preferences, Agent Skills, and policies in one call res = requests.post( f"{MEMOS_BASE_URL}/search/memory", headers=self.headers, json=context_data, ) result = res.json().get("data") or {} return ( result.get("memory_detail_list", []), # User facts result.get("preference_detail_list", []), # User preferences result.get("skill_detail_list", []), # Agent Skill ) ``` The two `filter` conditions are joined by OR: `related_id` selects the current user's memories, keeping personal facts and preferences isolated; `memory_type: "SkillMemory"` returns Agent Skills across users. `knowledgebase_ids` includes policy material without a separate search. Together, policies explain the rules, user memories supply case progress, and Agent Skills provide reusable task steps. ## Verify memory behavior Check all three stages: 1. After DAY 1, confirm that facts and preferences enter the User Cube and the same trace is submitted to the Agent Cube for Skill evaluation. 2. On DAY 4, use a new `conversation_id` and confirm that `customer_001` can still retrieve the earlier order, fault, and notification requirements. 3. On DAY 7, use `customer_002` and confirm that the first customer's facts remain absent while general Skills belonging to the support agent can be retrieved. Clear boundaries let the agent remember the current customer, follow common policies, and turn completed work into reusable capability. ## Complete Demo Expand the block, use its copy button, and save the code as `app.py`. Fill in Demo configuration before running. **Expand and copy the complete Python Demo** ```python # -*- coding: utf-8 -*- """ MemOS customer service best practice: a cross-channel memory-enabled support assistant Scenario: after-sales support. MemOS supplies memory infrastructure for the support agent with three capabilities: 1. Request user fact/preference and Agent Skill writes separately each turn; MemOS decides what to retain 2. Store after-sales policies in a knowledge base and retrieve them alongside memory 3. One combined /search/memory call: related_id selects the current user's memories; SkillMemory returns Agent Skills across users Enable only the three types needed here: factual, preference, and skill memory. MemOS asynchronously derives skills from submitted task traces (user -> assistant.tool_calls -> tool -> assistant), without requiring a skill upload in advance. Run: pip install openai requests # Fill in the parameters under Demo configuration below python app.py """ import base64 import sys import time from datetime import datetime import requests try: from openai import OpenAI except ImportError: OpenAI = None # --------------------------------------------------------------------------- # Demo configuration # --------------------------------------------------------------------------- MEMOS_API_KEY = "YOUR_MEMOS_API_KEY" OPENAI_API_KEY = "YOUR_OPENAI_API_KEY" MEMOS_BASE_URL = "https://memos.memtensor.cn/api/openmem/v1" OPENAI_MODEL = "YOUR_MODEL_NAME" OPENAI_BASE_URL = "YOUR_OPENAI_BASE_URL" AGENT_ID = "YOUR_AGENT_ID" # Users and the Agent write different memory types; retrieval uses one combined search USER_WRITE_VIEWS = ["detail_factual", "preference"] AGENT_SKILL_WRITE_VIEWS = ["skill"] CONTEXT_VIEWS = ["detail_factual", "preference", "skill"] SKILL_EXTRACT_PROMPT = """Extract Skills reusable across users from complete customer service task traces. A Skill is identified by its business objective, trigger conditions, core tool chain, and success criteria. Compare existing Skills before extraction: - If an existing Skill covers the same objective, triggers, and core tool chain, merge new information into it; avoid creating a duplicate Skill. - Skip generation when the trace adds no new general steps, decision branches, or verification evidence. - Create a new Skill only when the business objective or core workflow materially differs. Generalize the Skill content: - Remove names, contact details, addresses, user/Agent/conversation IDs, order and ticket numbers, and specific dates. - Replace instance values with parameters such as order_id, ticket_id, and shipping_address. - Exclude personal preferences and avoid turning one user's deadlines or notification choices into general rules. - Do not copy specific policy conclusions; describe the step as checking and validating the current policy. - Retain steps evidenced by tool results; do not describe suggestions or unexecuted actions as verified experience. Use stable, concise Skill names based on the issue type and resolution goal, excluding user or case details. """ # Relevance threshold: exclude lower-scoring memories from the prompt to reduce noise RELATIVITY_THRESHOLD = 0.5 # --------------------------------------------------------------------------- # Example policy uploaded to the policy knowledge base # --------------------------------------------------------------------------- POLICY_DOC_MD = """# Consumer After-Sales Policy (Example) ## Returns and exchanges - Unopened, resalable products may be returned within 7 days starting the day after delivery. - Products with functional faults may be exchanged within 15 days, with free shipping both ways. - Customized products are excluded from no-fault returns and exchanges. ## Warranty - The main product has a 12-month warranty; included accessories have a 6-month warranty. - Non-user-caused damage is repaired free during warranty; user-caused damage is charged at cost. ## Shipping - SF Express is used by default; an SMS with tracking details is sent when a replacement ships. - The delivery address may be changed once before the replacement ships. ## Invoices - Standard electronic invoices are available by self-service on the order page after completion. """ # --------------------------------------------------------------------------- # Support assistant: combined retrieval -> prompt -> response -> two writes # --------------------------------------------------------------------------- class CustomerServiceAssistant: def __init__(self, policy_kb_id): self.openai_client = OpenAI( api_key=OPENAI_API_KEY, base_url=OPENAI_BASE_URL or None, ) self.headers = { "Content-Type": "application/json", "Authorization": f"Token {MEMOS_API_KEY}", } self.knowledgebase_ids = [policy_kb_id] # The Agent maintains current conversation history without MemOS message reads self.conversation_histories = {} # ---- MemOS reads and writes ---- def search_memory(self, query, user_id): """One combined retrieval: user facts/preferences + Agent Skills + policy knowledge.""" context_data = { "query": query, "agent_id": AGENT_ID, "knowledgebase_ids": self.knowledgebase_ids, "include_memory_view": CONTEXT_VIEWS, "memory_limit_number": 9, "preference_limit_number": 6, "filter": { "user": { "or": [ {"related_id": [user_id]}, {"memory_type": "SkillMemory"}, ] } }, } context_res = requests.post( f"{MEMOS_BASE_URL}/search/memory", headers=self.headers, json=context_data, ) context_body = context_res.json() if context_body.get("code") != 0: print(f" [MemOS] Combined retrieval failed: {context_body.get('message')}") return [], [], [] context_result = context_body.get("data") or {} memories = [ m for m in context_result.get("memory_detail_list", []) if m.get("relativity", 0) >= RELATIVITY_THRESHOLD ] preferences = context_result.get("preference_detail_list", []) skills = context_result.get("skill_detail_list", []) return memories, preferences, skills def add_user_memories(self, messages, user_id, conversation_id, channel): """First write: generate only user facts and preferences.""" user_data = { "user_id": user_id, "agent_id": AGENT_ID, "conversation_id": conversation_id, "info": {"channel": channel, "scene": "consumer_support"}, "allow_memory_view": USER_WRITE_VIEWS, "messages": messages, } self._post_memory(user_data, "user facts and preferences", timeout_seconds=120) def add_agent_skill(self, messages, conversation_id, channel): """Second write: request only Agent Skill generation or updates.""" skill_data = { "agent_id": AGENT_ID, "conversation_id": conversation_id, "info": {"channel": channel, "scene": "consumer_support"}, "allow_memory_view": AGENT_SKILL_WRITE_VIEWS, "custom_extract_prompt": {"skill": SKILL_EXTRACT_PROMPT}, "messages": messages, } self._post_memory(skill_data, "Agent Skill", timeout_seconds=300) def _post_memory(self, data, label, timeout_seconds): res = requests.post( f"{MEMOS_BASE_URL}/add/message", headers=self.headers, json=data ) body = res.json() if body.get("code") != 0: print(f" [MemOS] Failed to write {label}: {body.get('message')}") return details = body.get("data") or {} if details.get("status") == "running" and details.get("task_id"): self._wait_for_task(details["task_id"], label, timeout_seconds) def _wait_for_task(self, task_id, label, timeout_seconds): """Wait for the asynchronous memory task to complete.""" deadline = time.time() + timeout_seconds while time.time() < deadline: time.sleep(2) res = requests.post( f"{MEMOS_BASE_URL}/get/status", headers=self.headers, json={"task_id": task_id}, ) body = res.json() if body.get("code") != 0: sys.exit(f"Failed to query memory task: {body.get('message')}") status = (body.get("data") or {}).get("status") if status == "completed": print(f" [MemOS] {label} write completed") return if status in {"failed", "error", "cancelled", "canceled"}: sys.exit(f"Memory task failed: {task_id} -> {status}") sys.exit(f"Timed out waiting for {label} task: {task_id}") # ---- Prompt and generation ---- def build_system_prompt(self, channel, memories, preferences, skills): channel_name = {"webchat": "Web chat", "email": "Email ticket"}.get(channel, channel) memory_text = "\n".join( f"{i}. {m.get('memory_value')}" for i, m in enumerate(memories, 1) ) or "(No related memories)" preference_text = "\n".join( f"{i}. {p.get('preference')}" for i, p in enumerate(preferences, 1) ) or "(No preferences)" # Inject only Skills with structured content; skip matches without returned content valid_skills = [ s for s in skills if isinstance(s.get("skill_value"), dict) and s["skill_value"].get("name") ] skill_text = "\n".join( f"{i}. {s['skill_value']}" for i, s in enumerate(valid_skills, 1) ) or "(No matching Skills)" return f"""# Role You are the brand's official support assistant, serving a customer through {channel_name}. Use retrieved memories, preferences, after-sales policies, and Skills to give accurate, personalized, actionable answers. # Current time {datetime.now().strftime('%Y-%m-%d %H:%M:%S')} # Retrieved user memories, after-sales policies, and Agent Skills {memory_text} {preference_text} {skill_text} # Memory usage rules 1. Distinguish direct customer statements from system inferences; give inferences less weight. 2. Confirm that each memory concerns the current customer, rather than another user or a historical case. 3. Use only directly relevant memories; ignore keyword matches from a different context. 4. When memory conflicts with the customer's current input, follow the current input. 5. Use the policy knowledge base as the authority for policies, deadlines, and amounts. # Response requirements 1. Answer directly without exposing internal memory or retrieval implementation details. 2. Continue pending work without asking customers to repeat information already provided. 3. Reply in the language used by the customer.""" def generate_reply(self, system_prompt, messages): response = self.openai_client.chat.completions.create( model=OPENAI_MODEL, messages=[{"role": "system", "content": system_prompt}, *messages], temperature=0.3, top_p=0.9, ) return response.choices[0].message.content # ---- Main workflow ---- def chat(self, query, user_id, conversation_id, channel, tool_steps=None): # 1. Read current conversation history from the Agent's local state history_key = (user_id, conversation_id) history = self.conversation_histories.get(history_key, []) # 2. One combined retrieval: user facts/preferences, Agent Skills, and policies memories, preferences, skills = self.search_memory(query, user_id) self._print_retrieved(memories, preferences, skills) # 3. Assemble the current task trace so the model answers from tool results llm_turn = [{"role": "user", "content": query}] memory_messages = [{"role": "user", "role_id": user_id, "content": query}] for step in tool_steps or []: tool_call = { "role": "assistant", "content": "", "tool_calls": [{ "id": step["id"], "type": "function", "function": { "name": step["name"], "arguments": step["arguments"], }, }], } tool_result = { "role": "tool", "tool_call_id": step["id"], "content": step["result"], } llm_turn.extend([tool_call, tool_result]) memory_messages.extend([ {**tool_call, "role_id": AGENT_ID}, tool_result, ]) system_prompt = self.build_system_prompt(channel, memories, preferences, skills) reply = self.generate_reply(system_prompt, [*history, *llm_turn]) # 4. Save conversation locally; write user context and general Skills separately to MemOS self.conversation_histories.setdefault(history_key, []).extend([ {"role": "user", "content": query}, {"role": "assistant", "content": reply}, ]) memory_messages.append({ "role": "assistant", "role_id": AGENT_ID, "content": reply, }) self.add_user_memories(memory_messages, user_id, conversation_id, channel) self.add_agent_skill(memory_messages, conversation_id, channel) return reply @staticmethod def _print_retrieved(memories, preferences, skills): print(" ---- MemOS Agent retrieval results ----") for m in memories: value = str(m.get("memory_value", "")).replace("\n", " ") print(f" [Memory {m.get('relativity', 0):.2f}] {value[:80]}") for p in preferences: print(f" [Preference] {p.get('preference')}") for s in skills: value = s.get("skill_value") or {} label = value.get("name") or f"id={s.get('id')}" print(f" [Skill {s.get('relativity', 0):.2f}] {label}") print(f" [Skill details] {value}") print(" ------------------------") # --------------------------------------------------------------------------- # Initialize the policy knowledge base # --------------------------------------------------------------------------- def _b64_md(text): encoded = base64.b64encode(text.encode("utf-8")).decode("utf-8") return f"data:text/markdown;base64,{encoded}" def _create_kb(headers, name, description): res = requests.post( f"{MEMOS_BASE_URL}/create/knowledgebase", headers=headers, json={"knowledgebase_name": name, "knowledgebase_description": description}, ) body = res.json() if body.get("code") != 0: sys.exit(f"Failed to create knowledge base: {body.get('message')}") kb_id = body.get("data", {}).get("id") or body.get("data", {}).get("knowledgebase_id") if not kb_id: sys.exit(f"Knowledge base created, but no ID returned: {name}") print(f"Knowledge base created: {name} -> {kb_id}") return kb_id def _upload_file(headers, kb_id, name, text): res = requests.post( f"{MEMOS_BASE_URL}/add/knowledgebase-file", headers=headers, json={ "knowledgebase_id": kb_id, "file": [{"type": "document", "name": name, "content": _b64_md(text)}], }, ) if res.json().get("code") != 0: sys.exit(f"Failed to upload file: {res.json().get('message')}") def _wait_kb_ready(headers, kb_id): for _ in range(40): time.sleep(3) res = requests.post( f"{MEMOS_BASE_URL}/get/knowledgebase-file", headers=headers, json={"knowledgebase_id": kb_id, "page": 1, "page_size": 20}, ) files = res.json().get("data", {}).get("file_detail_list", []) statuses = {str(item.get("status", "")).lower() for item in files} if files and statuses <= {"completed", "available", "failed"}: if "failed" in statuses: sys.exit(f"File parsing failed in policy knowledge base {kb_id}") return sys.exit(f"Timed out waiting for policy knowledge base {kb_id}") def create_policy_knowledge_base(): headers = { "Content-Type": "application/json", "Authorization": f"Token {MEMOS_API_KEY}", } policy_kb_id = _create_kb( headers, "Consumer After-Sales Policy Knowledge Base", "Consumer returns, exchanges, warranty, shipping, and invoice policies", ) _upload_file( headers, policy_kb_id, "consumer-after-sale-policy.md", POLICY_DOC_MD, ) print("Policy document uploaded; waiting for parsing...") _wait_kb_ready(headers, policy_kb_id) print(f"Policy knowledge base ready: {policy_kb_id}") return policy_kb_id # --------------------------------------------------------------------------- # Demo: user context isolation and Agent Skill reuse across users # --------------------------------------------------------------------------- CUSTOMER_ID = "customer_001" # Use a stable authenticated user ID in production CUSTOMER_ID_2 = "customer_002" # Second customer for testing Skill reuse and user isolation def run_demo(): policy_kb_id = create_policy_knowledge_base() assistant = CustomerServiceAssistant(policy_kb_id) print("=" * 64) print("DAY 1 · Web chat: a customer reports headphone noise, requests an exchange, and gives timing and notification preferences") print("=" * 64) chat_conv = "conv_chat_0821" q1 = ("Hi, I received order 20260820-88 on August 20. The left ear of the noise-canceling headphones has " "a constant, noticeable buzzing sound. I would like an exchange.") print(f"\n[Customer] {q1}") # The support Agent's business-system workflow (orders, tickets, notifications), # written with the conversation as a task trace for automatic Skill extraction tool_steps = [ {"id": "call_1", "name": "query_order", "arguments": '{"order_id": "20260820-88"}', "result": '{"order_id": "20260820-88", "product": "noise-canceling headphones", "sign_date": "2026-08-20", "status": "delivered"}'}, {"id": "call_2", "name": "check_exchange_policy", "arguments": '{"order_id": "20260820-88", "issue": "buzzing in the left ear"}', "result": '{"eligible": true, "policy": "exchange within 15 days for functional faults", "shipping": "free shipping both ways"}'}, {"id": "call_3", "name": "create_exchange_ticket", "arguments": '{"order_id": "20260820-88", "reason": "buzzing in the left ear", "type": "exchange for a quality issue"}', "result": '{"ticket_id": "EX20260821-03", "status": "created"}'}, {"id": "call_4", "name": "update_ticket", "arguments": '{"ticket_id": "EX20260821-03", "address": "100 Century Avenue, Pudong, Shanghai", "deliver_before": "this Friday", "notify": "sms"}', "result": '{"ticket_id": "EX20260821-03", "updated": true}'}, {"id": "call_5", "name": "schedule_notification", "arguments": '{"ticket_id": "EX20260821-03", "channel": "sms", "events": ["shipped", "out for delivery"]}', "result": '{"scheduled": true, "channel": "sms"}'}, ] print(f"[Support assistant] {assistant.chat(q1, CUSTOMER_ID, chat_conv, 'webchat', tool_steps=tool_steps)}") q2 = ("I'm traveling next week. Please deliver the replacement to my office by this Friday: " "100 Century Avenue, Pudong, Shanghai. Please send progress updates by SMS.") print(f"\n[Customer] {q2}") print(f"[Support assistant] {assistant.chat(q2, CUSTOMER_ID, chat_conv, 'webchat')}") print() print("=" * 64) print("DAY 4 · Email ticket: the same customer asks for progress in a new conversation and channel") print("=" * 64) mail_conv = "conv_mail_0824" q3 = "Hi, what is the status of the headphone exchange I requested?" print(f"\n[Customer] {q3}") print(f"[Support assistant] {assistant.chat(q3, CUSTOMER_ID, mail_conv, 'email')}") print() print("=" * 64) print("DAY 7 · Web chat: another customer has a similar issue (Agent Skill reuse)") print("=" * 64) conv_2 = "conv_chat_0828" q4 = "Hi, my new noise-canceling headphones make a buzzing sound. What should I do?" print(f"\n[Customer] {q4}") print(f"[Support assistant] {assistant.chat(q4, CUSTOMER_ID_2, conv_2, 'webchat')}") print() print("Demo complete. Check three things:") print("1. The User Cube generates facts/preferences; the Agent Cube generates Skills only.") print("2. DAY 4 combined retrieval returns customer_001's order, issue, and notification preferences.") print("3. DAY 7 excludes customer_001's facts/preferences but can retrieve") print(f" generalized Skills belonging to {AGENT_ID}.") if __name__ == "__main__": config = { "MEMOS_API_KEY": MEMOS_API_KEY, "OPENAI_API_KEY": OPENAI_API_KEY, "MEMOS_BASE_URL": MEMOS_BASE_URL, "OPENAI_MODEL": OPENAI_MODEL, "OPENAI_BASE_URL": OPENAI_BASE_URL, "AGENT_ID": AGENT_ID, } missing = [name for name, value in config.items() if not value or value.startswith("YOUR_")] if missing: sys.exit(f"Configure these values at the top of the file first: {', '.join(missing)}") if OpenAI is None: sys.exit("Install openai first: pip install openai") run_demo() ``` --- # Let the Financial Assistant Understand Customer Preferences Behind Behaviors (/usecase/financial_assistant) ## 1. Overview In intelligent investment advisory products, users leave behind a large number of **behavioral traces**: * **Traffic Source**: Which ad or post did the user click? (e.g., clicked the “Retirement Finance” ad) * **In-App Operations**: Which fund products did they browse? Which financial products did they bookmark? * **Communication Records**: Conversations with financial advisors and interactions with the AI financial assistant. These are just raw behaviors. If stored directly as logs, they are of limited help to large models. **The key is how to abstract behaviors into "memories."** ### 1.1 How are behaviors abstracted into memories? | User Behavior (Raw Trace) | Corresponding Memory (Semantic Abstraction) | | --- | --- | | Clicked “Retirement Finance” ad to enter the app | Memory: “User has potential interest in retirement finance” | | Frequently browsed low-risk fund detail pages | Memory: “User’s risk preference is conservative” | | Bookmarked “low-risk financial products” | Memory: “User tends to choose low-risk financial products” | | Said in conversation: “I don’t want to take too much risk” | Memory: “Explicitly expressed low-risk demand” | When the user later asks, “What kind of investment suits me?”, the financial assistant does not need to scan through a pile of logs but instead directly uses these semantic memories to drive the model to generate personalized answers. ### 1.2 Why not traditional RAG? RAG is more suitable for knowledge Q&A, such as explaining “What is a bond.” But it does not summarize preferences from user behaviors: | Traditional RAG | MemOS | | --- | --- | | Returns static financial knowledge snippets | Abstracts user behaviors into semantic memories (interests, preferences, profiles) | | Cannot answer “What kind of investment suits me?” | Can combine memories to generate personalized advice | ### 1.3 Why not build it yourself? Of course, developers can store behaviors themselves, but they will face three challenges: * **Lack of abstraction**: Simply storing “clicked Fund A” is not useful; it needs to be transformed into “risk preference = low risk.” * **Integration complexity**: Before calling the model, developers must manually build prompts by abstracting scattered behaviors into semantic information. * **Poor scalability**: As more channels, products, and communication scenarios are added, the code quickly becomes unmanageable. ### 1.4 Why use MemOS? When making a technology selection, you can directly compare three approaches: | Approach | Characteristics | Limitations | Advantages of MemOS | | --- | --- | --- | --- | | **Traditional RAG** | Retrieves knowledge base documents | Does not process user behaviors, cannot build profiles | Suitable for FAQ, but not for personalized financial advisory | | **Self-Built Storage** | Directly stores behavior logs | Requires manual abstraction from behavior → memory; high prompt engineering cost | Requires extensive glue code | | **MemOS** | Two interfaces: `addMessage` for writing, `searchMemory` for retrieval | —— | Automatically abstracts behavior traces into memories for direct use by the model | ### 1.5 What will this case demonstrate? This case demonstrates how to use MemOS cloud services to quickly build an intelligent financial assistant that “turns user behaviors into memories.” In the demo: * **D1 Traffic Behavior**: Clicking the “Retirement Finance” ad → generates memory “Interest in retirement finance.” * **D2 In-App Behavior**: Browsing and bookmarking low-risk funds → generates memory “Risk preference = low risk.” * **D3 Conversational Behavior**: Saying “I don’t want to take risks” → generates memory “Explicit low-risk demand.” When the user asks, “What kind of investment suits me?”: * `searchMemory` retrieves the above memories * The large model generates an answer that combines these profiles → outputs “More suitable for low-risk fixed income products.” When running this case script, developers will see in the console: * Each `addMessage` request/response (behaviors stored) * Each `searchMemory` request/response (semantic memories retrieved) * The model’s final personalized investment recommendation ## 2. Example ### 2.1 Environment Setup Use pip to install required dependencies: ```shell pip install MemoryOS -U ``` ### 2.2 Full Code ```python import os import uuid from openai import OpenAI from memos.api.client import MemOSClient os.environ["MEMOS_API_KEY"] = "mpg-xx" # Get MemOS_API_KEY from cloud service console os.environ["OPENAI_API_KEY"] = "sk-xx" # Replace with your own API_KEY conversation_counter = 0 def generate_conversation_id(): global conversation_counter conversation_counter += 1 return f"conversation_{conversation_counter:03d}" class FinancialManagementAssistant: """AI financial management assistant with memory capability""" def __init__(self): self.memos_client = MemOSClient(api_key=os.getenv("MEMOS_API_KEY")) self.openai_client = OpenAI(api_key=os.getenv("OPENAI_API_KEY")) def search_memory(self, query, user_id, conversation_id): """Search relevant memories based on query""" response = self.memos_client.search_memory(query, user_id, conversation_id) return [memory_detail.memory_value for memory_detail in response.data.memory_detail_list] def build_system_prompt(self, memories): """Construct a system prompt including formatted memories""" base_prompt = """ You are a knowledgeable and professional financial management assistant. You can access conversational memories to help you provide more personalized answers. Use memories to understand the user’s background, preferences, and past interactions. If memories are provided, naturally reference them when relevant, but do not explicitly mention having memories. """ if memories: # Format memories as a numbered list formatted_memories = "## Memories:\n" for i, memory in enumerate(memories, 1): formatted_memories += f"{i}. {memory}\n" return f"{base_prompt}\n\n{formatted_memories}" else: return base_prompt def add_message(self, messages, user_id, conversation_id): """Add messages to MemOS so they can be processed into memories""" self.memos_client.add_message(messages, user_id, conversation_id) def get_message(self, user_id, conversation_id): """Retrieve the raw messages stored in MemOS (for debugging/inspection)""" response = self.memos_client.get_message(user_id, conversation_id) return response.data.message_detail_list def chat(self, query, user_id, conversation_id): """Main chat function for handling conversations with memory integration""" # 1) Search relevant memories memories = self.search_memory(query, user_id, conversation_id) # Build system prompt with memories system_prompt = self.build_system_prompt(memories) # 2) Use OpenAI to generate an answer response = self.openai_client.chat.completions.create( model="gpt-4o", messages=[ {"role": "system", "content": system_prompt}, {"role": "user", "content": query} ] ) answer = response.choices[0].message.content # 3) Save the interaction back to MemOS messages = [ {"role": "user", "content": query}, {"role": "assistant", "content": answer} ] self.memos_client.add_message(messages, user_id, conversation_id) return answer ai_assistant = FinancialManagementAssistant() user_id = "memos_financial_management_user_123" def demo_questions(): return [ "What is my risk preference?", "Recommend some investments suitable for me" ] def preset_user_behaviors(): """Show preset user behavior memories""" conversation_id = generate_conversation_id() print(f"\n📊 Preset user behavior memories(conversation_id={conversation_id}):") print("=" * 60) behaviors = [{ "role": "user", "content": "Clicked 'Retirement Finance' ad to enter app" }, { "role": "user", "content": "Browsed and bookmarked low-risk funds" }] for i, behavior in enumerate(behaviors, 1): print(f"{i}. {behavior['content']}") ai_assistant.add_message(behaviors, user_id, conversation_id) print("=" * 60) print("💡 The above behavioral memories have been recorded by MemOS. The assistant will provide personalized recommendations based on them.") def main(): print("💰 Welcome to see how MemOS is used in a financial management assistant!") print("💡 With MemOS, your financial assistant becomes smarter and more caring! 😊 \n") # Ask whether to preload user behavior memories (consumes 1 add quota) while True: pre_chat = input("🤔 Do you want to preload user behavior memories? This will consume 1 add quota. Proceed? (y/n): ").strip().lower() if pre_chat in ['y', 'yes']: preset_user_behaviors() break elif pre_chat in ['n', 'no']: print("📝 Starting a new conversation...") break else: print("⚠️ Please enter 'y' for yes or 'n' for no") print("\n⚡️ Each question you enter next will take place in a brand-new conversation (with a new conversation ID). MemOS will automatically recall your historical behavioral memories across conversations to provide you with continuous and personalized service.") print("\n🎯 Here are some example questions you can continue to ask the assistant:") for i, question in enumerate(demo_questions(), 1): print(f" {i}. {question}") while True: user_query = input("\n🤔 Please enter your question (or type 'exit' to quit): ").strip() if user_query.lower() in ['quit', 'exit', 'q']: print("👋 Thanks for using the financial management assistant!") break if not user_query: continue print("🤖 Processing...") conversation_id = generate_conversation_id() answer = ai_assistant.chat(user_query, user_id, conversation_id) print(f"\n💬 conversation_id: {conversation_id}\n💡 [Assistant]: {answer}\n") print("-" * 60) if __name__ == "__main__": main() ``` ### 2.3 Code Explanation 1. Set your MemOS API key and OpenAI API key in environment variables 2. Instantiate **FinancialManagementAssistant** 3. Choose whether to execute preset conversations, which will consume 1 add and 2 search quotas 4. Use the `main()` function to interact with the assistant through a conversation loop 5. The assistant will call `chat`, first performing a `search` to retrieve memories, then calling OpenAI for conversation, and finally performing an `add` to store memories --- # A Writing Assistant with Memory is More Useful (/usecase/writting_assistant) ## 1. Overview In writing assistant products, users often hope that the assistant can **remember their writing style and habits** instead of starting from scratch each time. * **Writing Style** "When helping me write a summary, keep the tone light." * **Common Information** "Remember that I am in charge of the Marketing Department at XX company." * **Writing Preferences** "From now on, always start emails with 'Dear Customer.'" * **Context Continuity** "Please further optimize yesterday’s proposal summary by adding the budget section." Without memory, this information is lost once the conversation ends. Users must repeatedly remind the assistant, which makes the experience feel fragmented and unprofessional. ### 1.1 Why Not Use Traditional RAG? In the writing assistant scenario, RAG is not suitable. | Traditional RAG | MemOS | | --- | --- | | Relies on a static knowledge base, requiring constant manual document maintenance | Information generated in the conversation can be directly written in, no extra maintenance required | | Retrieval results are usually generic knowledge fragments | Can store and retrieve personalized style, tone, and commonly used expressions | | More suitable for “company documents/encyclopedia knowledge” | More suitable for “continuous iteration and personalization” in writing assistants | ### 1.2 Why Not Build It Yourself? Of course, you could try to save user preferences and context in a database, but this brings several challenges: * **Complex storage and retrieval logic**: You need to distinguish main text, preferences, and user profiles, and design retrieval strategies. * **Troublesome integration with large models**: Storing is only the first step; before calling the large model, you still need to “insert” the relevant information into the prompt. * **Poor scalability**: As user needs increase (writing style, common phrases, contextual links), the code will quickly become bloated. ### 1.3 Why Use MemOS? When making a choice, you can directly compare the three approaches: | Approach | Features | Limitations | Advantages of MemOS | | --- | --- | --- | --- | | **Traditional RAG** | Retrieves documents from a vector knowledge base and inserts into the prompt | Requires manual maintenance of static documents; unsuitable for personalized writing habits | Automatically captures styles and preferences revealed by users during conversations | | **Self-built Storage Solution** | Build your own tables/caches to save preferences and content | Complex logic: must distinguish main text/preferences/profiles; manual prompt insertion needed; difficult to scale | MemOS encapsulates storage + retrieval + prompt injection, reducing development burden | | **MemOS** | Just two APIs: `addMessage` for writing, `searchMemory` for retrieval | —— | Supports long-term tracking of writing styles and reuse of common information; out-of-the-box and easy to expand | ### 1.4 What Will This Case Show? This case demonstrates how to use the MemOS cloud service to quickly implement a writing assistant that “remembers the user.” In this demo, the user may: * Set preferences: “When helping me write a summary, keep the tone light.” * Reuse background: “Remember that I am in charge of the Marketing Department at XX company.” * Iterate tasks: “Please further optimize yesterday’s proposal summary by adding the budget section.” With MemOS, the writing assistant can: 1. **Maintain Style**: Keep consistent tone and formatting as required by the user. 2. **Reuse Information**: Automatically include the user’s common background information. 3. **Iterate Quickly**: Modify based on existing content instead of starting over. When running this case script, developers will see in the console: * Each `addMessage` and `searchMemory` request/response * Retrieved memories such as writing style and background information * The final model-generated answer (if no large model is connected, it will display [No model connected]) ## 2. Example ### 2.1 Environment Setup Install the required dependencies via pip: ```shell pip install MemoryOS -U ``` ### 2.2 Complete Code ```python import os import uuid from openai import OpenAI from memos.api.client import MemOSClient os.environ["MEMOS_API_KEY"] = "mpg-xx" # Get MemOS_API_KEY from cloud service console os.environ["OPENAI_API_KEY"] = "sk-xx" # Replace with your own API_KEY conversation_counter = 0 def generate_conversation_id(): global conversation_counter conversation_counter += 1 return f"conversation_{conversation_counter:03d}" class WritingAssistant: """AI Writing Assistant, helps users write with memory capability""" def __init__(self): self.memos_client = MemOSClient(api_key=os.getenv("MEMOS_API_KEY")) self.openai_client = OpenAI(api_key=os.getenv("OPENAI_API_KEY")) def search_memory(self, query, user_id, conversation_id): """Search relevant memories based on query""" response = self.memos_client.search_memory(query, user_id, conversation_id) return [memory_detail.memory_value for memory_detail in response.data.memory_detail_list] def build_system_prompt(self, memories): """Build a system prompt that includes formatted memories""" base_prompt = """ You are a professional writing assistant who can remember the user’s writing style and preferences. You can call conversation memories to provide more personalized replies. Please use these memories to understand the user’s background, preferences, and past interactions. If memories are provided, naturally reference them where relevant, but do not explicitly mention having memory capabilities. """ if memories: # Format memories as a numbered list formatted_memories = "## Memories:\n" for i, memory in enumerate(memories, 1): formatted_memories += f"{i}. {memory}\n" return f"{base_prompt}\n\n{formatted_memories}" else: return base_prompt def add_message(self, messages, user_id, conversation_id): """Add messages to MemOS so they can be processed into memories""" self.memos_client.add_message(messages, user_id, conversation_id) def get_message(self, user_id, conversation_id): """Retrieve the raw messages stored in MemOS (for debugging/inspection)""" response = self.memos_client.get_message(user_id, conversation_id) return response.data.message_detail_list def chat(self, query, user_id, conversation_id): """Main chat function to handle dialogue with memory integration""" # 1. Search relevant memories memories = self.search_memory(query, user_id, conversation_id) # Build system prompt with memories system_prompt = self.build_system_prompt(memories) # 2. Use OpenAI to generate an answer response = self.openai_client.chat.completions.create( model="gpt-4o", messages=[ {"role": "system", "content": system_prompt}, {"role": "user", "content": query} ] ) answer = response.choices[0].message.content # 3. Save the conversation into memories messages = [ {"role": "user", "content": query}, {"role": "assistant", "content": answer} ] self.memos_client.add_message(messages, user_id, conversation_id) return answer ai_assistant = WritingAssistant() user_id = "memos_writing_user_123" def demo_questions(): return [ "Help me write a notification email for a team dinner", "Help me write a client email summarizing the new features of our upcoming finance app", ] def pre_configured_conversations(): """Return pre-configured dialogue pairs""" return [ { "user": "I work in the marketing department at an internet company. Keep the tone light when writing emails, and start with 'Dear XX'." }, { "user": "When writing summaries, I prefer to list three bullet points first." } ] def execute_pre_conversations(): """Execute pre-configured dialogues""" conversations = pre_configured_conversations() conversation_id = generate_conversation_id() print(f"\n🔄 Executing pre-configured dialogues(conversation_id={conversation_id})...") print("=" * 60) for i, conv in enumerate(conversations, 1): print(f"\n💬 Dialogue {i}") print(f"👤 User: {conv['user']}") # Execute dialogue answer = ai_assistant.chat(conv['user'], user_id, conversation_id) print(f"🤖 Assistant: {answer}") print("-" * 40) print("\n✅ Pre-configured dialogues completed!") print("=" * 60) def main(): print("📝 Welcome to the MemOS writing assistant example!") print("💡 With MemOS, your writing assistant better understands your style and preferences! ✍️ \n") # Ask whether to execute pre-configured dialogues first while True: pre_chat = input("🤔 Do you want to execute the pre-configured dialogues first? This will consume 2 add and 2 search calls. Execute? (y/n): ").strip().lower() if pre_chat in ['y', 'yes', 'Y']: execute_pre_conversations() break elif pre_chat in ['n', 'no', 'N']: print("📝 Starting a brand-new writing assistant dialogue...") break else: print("⚠️ Please enter 'y' for yes or 'n' for no") print("\n⚡️ Each question you enter next will take place in a brand-new conversation (with a new conversation ID). MemOS will automatically recall your historical behavioral memories across conversations to provide you with continuous and personalized service.") print("\n🎯 Here are some example questions. You can continue chatting with the writing assistant:") for i, question in enumerate(demo_questions(), 1): print(f" {i}. {question}") while True: user_query = input("\n🤔 Please enter your writing request (or type 'exit' to quit): ").strip() if user_query.lower() in ['quit', 'exit', 'q']: print("👋 Thank you for using the writing assistant. Happy writing!") break if not user_query: continue print("🤖 Creating...") conversation_id = generate_conversation_id() answer = ai_assistant.chat(user_query, user_id, conversation_id) print(f"\n💬 conversation_id: {conversation_id}\n💡 [Assistant]: {answer}\n") print("-" * 60) if __name__ == "__main__": main() ``` ### 2.3 Code Explanation 1. Set your MemOS API key and OpenAI key in environment variables. 2. Instantiate `WritingAssistant`. 3. Choose whether to run pre-configured dialogues, which will consume 2 add and 2 search calls. 4. Use the `main()` function to interact with the assistant through a dialogue loop. 5. The assistant will call `chat`: first execute `search` to retrieve memories, then call OpenAI for dialogue, and finally execute `add` to store memories. --- # Building a Home Life Assistant with Memory (/usecase/home_assistant) ## 1. Overview When developing a home life assistant product, developers often encounter a problem: **once the dialogue context ends, user information is lost**. * User casually assigns a to-do (“Take the kids to the zoo on Saturday”) * User expresses a habit (“When reminding, first list the key points, then give one action suggestion”) * User introduces family information (“My wife is Xiaoyun, the child is 6 years old”) If the assistant cannot remember this information, it will appear “heartless”: the next day when the user asks, “What plans do I have for the weekend?”, the assistant will have no idea what they are referring to. ### 1.1 Why not traditional RAG? Many people’s first thought is: can we use RAG (Retrieval-Augmented Generation)? But the characteristics of traditional RAG determine that it is not suitable for this kind of “personalized assistant” scenario: | Traditional RAG | MemOS | | --- | --- | | Relies on static knowledge bases, requiring manual document maintenance | Information generated during dialogue can be directly written in, no extra maintenance needed | | Can only mechanically return fragments, does not learn preferences | Automatically forms to-do items, preferences, and profiles from conversations | | Focuses on “common knowledge”, unsuitable for personal information | Designed for individualized scenarios, supports long-term tracking and invocation | ### 1.2 Why not build your own solution? Of course, you could try to store this information yourself, but this brings several challenges: * **Complex storage and retrieval logic**: must distinguish dialogue content, long-term memory, preferences, and facts, and ensure they can be retrieved as needed. * **Troublesome integration with LLMs**: not only storing data, but also embedding relevant information into the prompt before generating responses. * **Poor scalability**: as features increase (to-dos, preferences, profiles), the code becomes increasingly hard to maintain. ### 1.3 Why use MemOS? When making a technical choice, you can intuitively compare three approaches: | Approach | Characteristics | Limitations | Advantages of MemOS | | --- | --- | --- | --- | | Traditional RAG | Retrieves documents from a vector database and appends them into the prompt | Requires manual static document maintenance; cannot store personal to-dos/preferences; only mechanically returns fragments | Automatically captures key information from dialogues, supports personalization and dynamic updates | | Self-built storage solution | Custom tables/cache to save dialogue information | Complex logic: must distinguish dialogues/long-term memory/preferences/profiles; still need to manually build prompt before model calls; poor scalability | MemOS encapsulates storage + retrieval + prompt injection, reducing developer burden | | MemOS | Only two interfaces: `addMessage` for writing, `searchMemory` for retrieval | —— | Supports long-term tracking, preference retention, and profile integration; ready-to-use and easily extendable | Only two API calls are needed: * `addMessage`: writes user or assistant messages into the system * `searchMemory`: retrieves relevant memories before model response and injects them into the prompt With this, the assistant can truly appear “with memory”: * **Track to-dos** * User says “Take the kids to the zoo on Saturday” * A few days later asks “What plans do I have for the weekend?” → Assistant can answer accurately * **Maintain preferences** (future versions will support more fine-grained instruction completion) * User says “When reminding, first list three key points + one short suggestion” * Later asks “Help me plan next week’s housework distribution” → Assistant outputs in the preferred style * **Incorporate profiles** * User says “My wife is Xiaoyun, the child is 6 years old” * Later asks “Arrange a weekend activity for the family?” → Suggests a family-friendly activity plan ### 1.4 What does this case demonstrate? We will use MemOS cloud service to quickly implement a home life assistant “that remembers the user.” When running the example script, developers will see complete logs: * Requests/responses for each `addMessage` and `searchMemory` call * Matched memory entries * Concatenated and full instructions ← TODO: coming soon * Model responses (if LLM is not connected, a message will indicate [LLM not connected]) ## 2. Example ### 2.1 Environment Setup Install required dependencies with pip: ```shell pip install MemoryOS -U ``` ### 2.2 Full Code ```python import os import uuid from openai import OpenAI from memos.api.client import MemOSClient os.environ["MEMOS_API_KEY"] = "mpg-xx" # Get MemOS_API_KEY from cloud service console os.environ["OPENAI_API_KEY"] = "sk-xx" # Replace with your own API_KEY conversation_counter = 0 def generate_conversation_id(): global conversation_counter conversation_counter += 1 return f"conversation_{conversation_counter:03d}" class HomeAssistant: def __init__(self): self.memos_client = MemOSClient(api_key=os.getenv("MEMOS_API_KEY")) self.openai_client = OpenAI(api_key=os.getenv("OPENAI_API_KEY")) def search_memory(self, query, user_id, conversation_id): """Search relevant memories based on query""" response = self.memos_client.search_memory(query, user_id, conversation_id) return [memory_detail.memory_value for memory_detail in response.data.memory_detail_list] def add_message(self, messages, user_id, conversation_id): """Add messages to MemOS so they can be processed into memories""" self.memos_client.add_message(messages, user_id, conversation_id) def get_message(self, user_id, conversation_id): """Retrieve the raw messages stored in MemOS (for debugging/inspection)""" response = self.memos_client.get_message(user_id, conversation_id) return response.data.message_detail_list def build_system_prompt(self, memories): """Builds a system prompt containing formatted memories""" base_prompt = """ You are a knowledgeable and considerate home life assistant. You can leverage conversation memories to provide more personalized responses. Use these memories to understand the user’s context, preferences, and past interactions. If memory content is provided, naturally reference it when relevant, but do not explicitly state you have memory functions. """ if memories: # Format memories as a numbered list formatted_memories = "## Memories:\n" for i, memory in enumerate(memories, 1): formatted_memories += f"{i}. {memory}\n" return f"{base_prompt}\n\n{formatted_memories}" else: return base_prompt def chat(self, query, user_id, conversation_id): """Main chat function handling memory-integrated conversation""" # 1. Search relevant memories memories = self.search_memory(query, user_id, conversation_id) # Build system prompt including memories system_prompt = self.build_system_prompt(memories) # 2. Use OpenAI to generate response response = self.openai_client.chat.completions.create( model="gpt-4o", messages=[ {"role": "system", "content": system_prompt}, {"role": "user", "content": query} ] ) answer = response.choices[0].message.content # 3. Save dialogue into memory messages = [ {"role": "user", "content": query}, {"role": "assistant", "content": answer} ] self.memos_client.add_message(messages, user_id, conversation_id) return answer ai_assistant = HomeAssistant() user_id = "memos_home_management_user_123" def demo_questions(): return [ "What plans do I have for the weekend?", "Help me plan next week’s housework distribution" ] def pre_configured_conversations(): """Return pre-configured dialogue pairs""" return [ { "user": "Take the kids to the zoo on Saturday, please remember it.", }, { "user": "For future reminders or plans, please first list three key points, then add one short suggestion.", } ] def execute_pre_conversations(): """Execute pre-configured dialogues""" conversations = pre_configured_conversations() conversation_id = generate_conversation_id() print(f"\n🔄 Executing pre-configured dialogues(conversation_id={conversation_id})...") print("=" * 60) for i, conv in enumerate(conversations, 1): print(f"\n💬 Dialogue {i}") print(f"👤 User: {conv['user']}") # Execute dialogue answer = ai_assistant.chat(conv['user'], user_id, conversation_id) print(f"🤖 Assistant: {answer}") print("-" * 40) print("\n✅ Pre-configured dialogues completed!") print("=" * 60) def main(): print("🏠 Welcome to the example of MemOS applied in a home assistant!") print("💡 With the power of MemOS, your product can deliver a real butler-like experience! 😊 \n") # Ask whether to execute pre-configured dialogues first while True: pre_chat = input("🤔 Would you like to execute the pre-configured dialogues first? This will consume 2 add calls and 2 search calls. Proceed? (y/n): ").strip().lower() if pre_chat in ['y', 'yes']: execute_pre_conversations() break elif pre_chat in ['n', 'no']: print("📝 Starting a new dialogue...") break else: print("⚠️ Please enter 'y' for yes or 'n' for no") print("\n⚡️ Each question you enter next will take place in a brand-new conversation (with a new conversation ID). MemOS will automatically recall your historical behavioral memories across conversations to provide you with continuous and personalized service.") print("\n🎯 Here are some sample questions you can continue to ask the assistant:") for i, question in enumerate(demo_questions(), 1): print(f" {i}. {question}") while True: user_query = input("\n🤔 Please enter your question (or type 'exit' to quit): ").strip() if user_query.lower() in ['quit', 'exit', 'q']: print("👋 Thank you for using the home assistant!") break if not user_query: continue print("🤖 Processing...") conversation_id = generate_conversation_id() answer = ai_assistant.chat(user_query, user_id, conversation_id) print(f"\n💬 conversation_id: {conversation_id}\n💡 [Assistant]: {answer}\n") print("-" * 60) if __name__ == "__main__": main() ``` ### 2.3 Code Explanation 1. Set your MemOS API key and OpenAI key in environment variables 2. Instantiate `HomeAssistant` 3. Choose whether to run pre-configured dialogues (consumes 2 add calls and 2 search calls) 4. Use the `main()` function to interact with the assistant in a dialogue loop 5. The assistant calls `chat`, first performing `search` to retrieve memories, then using OpenAI for conversation, and finally performing `add` to store the memory --- # Claude MCP (/usecase/frameworks/claude_mcp) ## 1. Configure MCP and MemOS Cloud Add the following MCP configuration to your client: ```json { "mcpServers": { "memos-api-mcp": { "timeout": 60, "type": "stdio", "command": "npx", "args": [ "-y", "@memtensor/memos-api-mcp" ], "env": { "MEMOS_API_KEY": "mpg-xxxxxxxxxxxxxxxxxxxxxxxxxxxxx", "MEMOS_USER_ID": "your-user-id", "MEMOS_CHANNEL": "MODELSCOPE" } } } } ``` Set the environment variables as follows: - `MEMOS_API_KEY`: Create an account in the [MemOS API console](https://memos-dashboard.openmem.net/apikeys/), create an API key, and copy it into the configuration. *The console image below is a localized illustration of the Chinese UI.* ![Create an API key in the MemOS console](https://cdn.memtensor.com.cn/img/memos-best-practices-claude-apikey-en-20261028_compressed.png) - `MEMOS_USER_ID`: A stable, user-defined personal identifier. Use the same value for the same person across devices and clients. An email address, full name, or employee ID is suitable; random values, device IDs, and chat session IDs are unsuitable. - `MEMOS_CHANNEL`: Set it to `MODELSCOPE`. ## 2. Use MemOS in Claude Desktop To use MemOS in Claude Desktop, click the avatar in the lower left corner -> "Settings" -> "Developer" -> "Edit Config", paste the configuration into the Claude_desktop_config.json file, and finally restart the client. You can use it in the chat when you observe that the memos-api-mcp service is in the running state. ![MemOS MCP configuration and expected running state](https://cdn.memtensor.com.cn/img/memos-best-practices-claude-status-en-20261028_compressed.png) To improve the usage effect, it is recommended that users modify the user preference settings that apply to all conversations when using MemOS in Claude Desktop. The specific method is to click the avatar in the lower left corner -> "General", and paste the following content into the input box under "What personal preferences should Claude consider in responses?": ``` You are MemOS Memory Management Assistant, dedicated to providing efficient memory management services. It extracts memories based on users' past conversation content and enhances the consistency and personalization of users' conversations with AI through memory retrieval. Before answering each user's question, you need to call the search_memory service of memos-api-mcp and use appropriate search terms to find memories related to the current topic in the user's personal memory bank. After completing the answer based on these memories, call the add_message service of memos-api-mcp to record a summary of the current conversation content. (Note that calling add_message is mandatory. Regardless of what the user says or asks, it must be recorded; otherwise, in subsequent conversations, search_memory will not be able to obtain more detailed user information, leading to your inability to answer the user's questions accurately.) ``` ![Modifying user preferences for using MemOS in Claude Desktop](https://cdn.memtensor.com.cn/img/1763105312212_yqu9m7_compressed.png) The following is an example of using MemOS in Claude Desktop, by which users can judge whether they have successfully configured MemOS in Claude Desktop. ![Example of using MemOS in Claude Desktop](https://cdn.memtensor.com.cn/img/1763105296073_gtqj1s_compressed.png) --- # Edge–Cloud Collaboration: Building Long-Term Memory for Smart Devices (/usecase/edge_cloud_terminal_memory) **MemOS helps smart devices remember and understand users over time.** Earbuds travel with us, watches track daily activities, home speakers and robots become part of everyday life, and phones and computers support our work. As these devices accompany users over time, MemOS memory helps them build a lasting understanding of each person, supporting ongoing assistance and personalized services. > Turn everyday interactions into context for future services, so devices gradually get to know their users.
Earbud interactions form memories that a home speaker retrieves to continue helping the same user

Build an understanding of users through everyday interactions

A home speaker, phone and kitchen display use the same user's memories

Continue the same activity across devices and over time

MemOS maintains memories and their scope while a fitness app uses current context to plan workouts

Keep the device's understanding up to date as users' needs change

The MemOS edge–cloud memory solution provides memory formation, organization, updates and retrieval for devices, companion apps, system features and agents. **The product supplies interaction and business data. MemOS determines what to remember, organizes it and maintains it as new information arrives. The product queries MemOS when it needs that context.** These services can run on customer-managed servers, in the MemOS managed service, or on selected local nodes, with responsibilities distributed as needed. Customers choose where services run based on device resources, data-management requirements and model selection. ## How MemOS provides memory services for devices > These experiences combine the device product, its backend and MemOS: the product supplies information, MemOS forms and maintains memory, and product features query and use it when needed. ### Ingest interaction and business data The product submits authorized information to MemOS together with identifiers such as the user, conversation, timestamp or existing business ID. When multiple devices connect, the product's existing account and device systems identify the current user and associate authorized requests with that same user. **Speech transcription and exercise-event recognition are input processing; deciding what to remember and how to organize it is MemOS memory processing.** The integration does not need to select valuable sentences, extract preferences or produce standardized memories first. ![Earbud speech, watch events and app data enter MemOS through existing input pipelines](https://cdn.memtensor.com.cn/img/memos-edge-cloud-04-en-20261027_compressed.png){width="720" class="mx-auto"} ### Form memories and maintain them as new inputs arrive MemOS understands facts, preferences, events and context in the input, links them to the same user's existing memories, and handles duplicates, changes and scope. It saves newly formed or updated memories and their indexes to the data nodes of the selected deployment. Later expressions and business context follow the same processing path. The integration does not need to locate old memories and decide how to overwrite them first. Users can view, correct or delete existing memories through management features provided by the product. Everyday updates continue to enter through the normal input flow. See [Memory Types](/memos_cloud/introduction/memory_types) and [Add Message](/memos_cloud/mem_operations/add_message) for memory categories and processing details. ![New inputs link to existing memories, update them within their scope and save them in the selected deployment](https://cdn.memtensor.com.cn/img/memos-edge-cloud-05-en-20261027_compressed.png){width="720" class="mx-auto"} ### Retrieve relevant memory for the current device feature The product queries MemOS with the current question and context. MemOS retrieves relevant content from stored memories and indexes, then returns it to the product's business services, tools or models. The product completes the current feature and presents the result on the device. **MemOS supplies memory context; product features perform route planning, content recommendations, calculations and device actions.** New interactions and business outcomes can become inputs for later memory maintenance. Earbuds, phones and home speakers can each use their own conversations to query the same user's accumulated memories. Adding another device does not change where the data is stored. ![The product queries MemOS with the current question and uses the returned memories in its business features](https://cdn.memtensor.com.cn/img/memos-edge-cloud-06-en-20261027_compressed.png){width="720" class="mx-auto"} ## Deployment options Providing persistent memory for earbuds, watches, phones or computers involves four decisions: **where MemOS runs, where memory data is stored, where LLM computation happens and how devices access the services.** The following four common patterns show how these parts work together. | Deployment pattern | MemOS and memory data | LLM location | Device access | | --- | --- | --- | --- | | Home hub with edge–cloud collaboration | MemOS runs on the home hub; memories and indexes stay local | Customer-hosted or selected remote LLM | Devices access the hub. Requests undergo local privacy processing before remote inference; results return to the hub for storage and use. | | Customer-managed deployment | Customer-managed servers; the customer stores and manages the data | In this example, LLMs and supporting processing run in the customer environment | Devices write and query memory through the product backend, then use it in product features. | | MemOS managed service | MemOS runs and stores data in its managed environment | The managed service provides the LLMs needed for memory processing | The product backend calls the managed APIs and uses the returned memories in its own features. | | Fully local home hub | MemOS, memories and indexes run on the home hub or colocated nodes | LLMs and supporting processing also run locally | Devices access local memory and product features over the home network. | ### Edge–cloud collaboration: local memory with privacy processing before remote LLM calls This pattern **keeps memory local, processes configured sensitive information on the hub and calls remote LLMs as needed**. Mobile apps, home speakers, kitchen displays and other devices access MemOS on the home hub through authorized entry points. Memories, retrieval indexes and mappings between real values and placeholders remain on the hub. LLMs run on the customer's inference servers or a selected model service. The internal MemOS privacy module replaces selected information locally and restores returned results. Requests that need a remote model during memory processing or querying follow the corresponding privacy path. In this example, lightweight tasks such as retrieval remain on the hub, and devices receive usable memory context with the original values restored. An always-on mini PC or home server can serve as the hub. For a household with a few users, 32 GB of RAM, a 1 TB NVMe SSD and Gigabit or 2.5 GbE wired networking provide a reference configuration. The hub handles local services, memory storage, retrieval, privacy processing and device access, while remote nodes handle LLM computation. The hub stays in a fixed location with continuous power and network access. It keeps running when a phone or laptop leaves. Devices at home connect over the LAN; remote access uses a controlled gateway or companion service. Memory writes first save the input record and return an acknowledgment. Privacy processing and LLM calls then run in the background. > **Note**: For the technical approach behind this privacy processing, see [MemPrivacy: Privacy-Preserving Personalized Memory for Edge–Cloud Agents](https://arxiv.org/abs/2605.09530). ![The home hub runs MemOS and stores memory, replacing sensitive fields locally before calling remote LLMs](https://cdn.memtensor.com.cn/img/memos-edge-cloud-07-en-20261027_compressed.png){width="720" class="mx-auto"} **How MemOS on the home hub handles sensitive information in remote requests** For example, a phone or home speaker submits an interaction containing a friend's name, a meeting time and an address through the hub's integration service. When MemOS prepares a memory-processing request, its internal privacy module replaces the selected name and address with placeholders and keeps the mappings on the hub. After the remote model returns a result, MemOS restores those values internally and continues organizing, maintaining and storing the memory. ```text MemOS receives: Meet at Wang Chen's home at 10 a.m. on Saturday. The address is a particular apartment in a residential complex. Sent to the model after internal processing: Meet at [PERSON_01]'s home at 10 a.m. on Saturday. The address is [ADDRESS_01]. Local hub mappings: [PERSON_01] → Wang Chen; [ADDRESS_01] → the specified residential complex, building and apartment. After the model returns: MemOS restores the selected values internally, then continues organizing and saving memory. ``` ![Sensitive fields are replaced before remote inference and restored inside the hub when results return](https://cdn.memtensor.com.cn/img/memos-edge-cloud-08-en-20261027_compressed.png){width="720" class="mx-auto"} ### Customer-managed deployment: run MemOS on customer-controlled servers **A customer-managed deployment can use public-cloud infrastructure.** A customer can rent servers in its own public-cloud account, deploy services, store data and manage LLMs there. This is still a customer-managed deployment. It differs from both a local hub in an end user's home and direct use of the MemOS managed service. Consider an earbud manufacturer. The earbuds connect to the manufacturer's product backend through a companion mobile app. The backend handles accounts, authorization and business requests. **MemOS runs on customer-managed servers, with input records, formed memories and retrieval indexes stored on customer-selected data nodes.** In this example, LLMs also run in the customer environment to support memory understanding, organization and maintenance. The customer can use data-center servers, existing virtual machines or servers in its own cloud account. After a device submits information, MemOS saves the record and calls the LLM in the background to process and maintain memory. When context is needed later, MemOS retrieves relevant memories from customer-stored data and returns them to the product backend for Q&A, recommendations or planning. The customer manages services, data, LLMs and access permissions throughout. If an external LLM API is used instead, the memory store can remain in the customer environment, while the relevant request content is sent to that service. ![MemOS and memory data run on customer-managed servers, with devices connecting through the product backend](https://cdn.memtensor.com.cn/img/memos-edge-cloud-09-en-20261027_compressed.png){width="720" class="mx-auto"} ### Managed cloud service: use memory services operated by MemOS Using the same earbud and companion-app example, the customer's product handles device interactions and business features, while the product backend calls the MemOS managed APIs. **MemOS runs in the managed environment, which stores memories and indexes and provides the LLMs and supporting processing needed for memory operations.** The customer does not need to maintain servers or LLM runtimes for these memory capabilities. For writes, the product backend submits authorized information and receives an acknowledgment; MemOS processes and stores it in the background. For queries, the product submits the current question and receives relevant memories to use in its own Q&A, recommendations or planning features. The customer product still manages the models and tools used by those business features and identifies which memory content they receive during integration. The user's memories accumulate in the managed environment. Devices access them through the product backend under its authorization controls. ![The product backend calls MemOS managed APIs, with memories and indexes stored in the managed environment](https://cdn.memtensor.com.cn/img/memos-edge-cloud-10-en-20261027_compressed.png){width="720" class="mx-auto"} ### Fully local operation: memory and models on a fixed home AI hub To keep both memory and LLM computation at home, use a fixed host with sufficient compute capacity, such as a compact AI workstation or home server. Phones, speakers, kitchen displays and other devices access it through authorized entry points on the home network. **This pattern keeps memory storage and LLM computation local.** MemOS runs on the hub, memories and indexes reside on its local SSD, and LLMs and supporting processing run on the hub or colocated fixed nodes. MemOS saves, processes and maintains submitted information locally. When context is needed, it retrieves local memories for the current product feature. The diagram also places business models for Q&A, speech and similar features locally. Fully offline operation requires local tools and reference materials as well, with the actual capabilities of the entire chain verified. One host can handle services, storage and LLMs, or connect to colocated compute nodes. For a household with a few users, a compact AI host with 64–128 GB of unified memory and 2–4 TB of SSD storage provides a reference resource range. With a discrete GPU, size system RAM and VRAM separately, then validate against the selected LLM, context length and concurrency. See the [DGX Spark hardware documentation](https://docs.nvidia.com/dgx/dgx-spark/hardware.html) for an example compact form factor. Manage retained source materials, memory backups and logs using local directories and permissions. A NAS can store materials and backups. Whether an existing NAS can also run the memory service or an LLM depends on its processor, memory and software environment. ![Memory and business models run on the home hub or colocated nodes, accessed by devices over the home network](https://cdn.memtensor.com.cn/img/memos-edge-cloud-11-en-20261027_compressed.png){width="720" class="mx-auto"} ## API integration: writes, status tracking and memory queries After choosing a deployment, connect information ingestion, processing-status tracking and memory queries. The examples below use the MemOS managed API, followed by the integration flow for a home hub. Replace demonstration users and credentials with your actual configuration. ### Backend APIs: asynchronous writes and queries across devices In this managed-API example, the product backend holds the project API key and checks user access against the product's account system. For customer-managed deployments, use the service addresses, authentication and APIs specified for the delivered version. `user_id` identifies the memory user, and `conversation_id` identifies the current conversation. Different devices belonging to the same user can use separate conversation IDs. See [Project Configuration](/api_docs/start/configuration) for the scope of API keys. ![Device interactions flow through the product backend, with writes, processing and queries tied to the same user account](https://cdn.memtensor.com.cn/img/memos-edge-cloud-12-en-20261027_compressed.png){width="720" class="mx-auto"} After the mobile app transcribes an earbud interaction, the product backend submits the full expression for MemOS to process: ```bash curl --request POST \ --url 'https://memos.memtensor.cn/api/openmem/v1/add/message' \ --header 'Authorization: Token YOUR_MEMOS_API_KEY' \ --header 'Content-Type: application/json' \ --data '{ "user_id": "demo_user_001", "conversation_id": "weekend_plan_001", "messages": [ {"role": "user", "content": "I want to take my parents to Suzhou on Saturday morning and return on Sunday evening. Also, my mom cannot eat spicy food."} ], "async_mode": true }' ``` This example uses `async_mode: true`. The write API returns an acknowledgment with `data.task_id` and `data.status`. MemOS continues processing in the background and saves memories and indexes according to the managed-service configuration. Acceptance and processing completion are separate states. The product backend stores the task ID to track progress as needed. See [Add Message API](/api_docs/core/add_message) and [Async Mode](/memos_cloud/features/async_mode) for fields and processing behavior. On Friday, the user adds in the mobile app: “I have something to do on Saturday morning. Let's leave after lunch and visit the gardens on Sunday.” The product backend submits the new expression and conversation context asynchronously and records the new task ID. To check the complete processing result of a write or update, query its corresponding `task_id`: ```bash curl --request POST \ --url 'https://memos.memtensor.cn/api/openmem/v1/get/status' \ --header 'Authorization: Token YOUR_MEMOS_API_KEY' \ --header 'Content-Type: application/json' \ --data '{"task_id": "YOUR_TASK_ID"}' ``` The task's `data.status` can be `running`, `completed` or `failed`. During integration testing, inspect the complete processing result after `completed`. In production, queries can use memories that have already been processed and made available; searchable content may exist while a task is still `running`. See [Get Task Status](/api_docs/message/get_status) for status fields and failure information. Back at home, the user asks the home speaker about the trip. The speaker service queries through the product backend using the same `user_id` and the current speaker conversation's `conversation_id`: ```bash curl --request POST \ --url 'https://memos.memtensor.cn/api/openmem/v1/search/memory' \ --header 'Authorization: Token YOUR_MEMOS_API_KEY' \ --header 'Content-Type: application/json' \ --data '{ "user_id": "demo_user_001", "conversation_id": "home_speaker_continue_002", "query": "What is the latest plan for our weekend trip to Suzhou? Anything else to keep in mind?" }' ``` The current conversation ID contributes query context; devices can use separate conversations. In the response, facts appear in `data.memory_detail_list[].memory_value`, and preferences in `data.preference_detail_list[].preference`. The product backend passes relevant memories to its Q&A or itinerary features to generate the speaker's answer. The mobile app can also query and use memories on its planning page. Actual retrieval depends on the inputs and processing results. See [Search Memory API](/api_docs/core/search_memory) for response fields. During integration testing, use the same demo user for the initial write, a later update and a query from another device. Verify processing status, retrieved content and how the product uses the result. For precise management of existing content, connect [Update Memory](/api_docs/core/update_memory) and [Delete Memory](/memos_cloud/mem_operations/delete_memory) to the product's memory-management interface. ### Hub APIs: local writes and queries When MemOS runs on a home hub, phones, speakers and other devices submit information and query memories through the hub's authorized service entry points. The edge–cloud and fully local patterns share the same memory workflow, with memories and indexes stored locally on the hub. LLM placement follows the deployment pattern described above. ![Devices write and query through the hub's authorized entry point, while memories and indexes stay local](https://cdn.memtensor.com.cn/img/memos-edge-cloud-13-en-20261027_compressed.png){width="720" class="mx-auto"} The examples below follow the MemOS Cloud API format. First set `MEMOS_ADD_MESSAGE_URL`, `MEMOS_GET_STATUS_URL` and `MEMOS_SEARCH_MEMORY_URL` to the full write, status-query and memory-search endpoint URLs provided by your hub deployment. Set `MEMOS_API_KEY` to the access credential. Actual addresses, paths, authentication and storage configuration depend on the delivered version. **Write interaction data.** Submit the full expression together with user and conversation identifiers to MemOS on the hub: ```bash curl --request POST \ --url "${MEMOS_ADD_MESSAGE_URL}" \ --header "Authorization: Token ${MEMOS_API_KEY}" \ --header 'Content-Type: application/json' \ --data '{ "user_id": "demo_user_001", "conversation_id": "home_hub_dinner_001", "messages": [ {"role": "user", "content": "I am exhausted after work. Let us keep dinner simple. Oh, and no cilantro."} ], "async_mode": true }' ``` After the write API acknowledges the request, MemOS forms, maintains and saves memories in the background. The integration stores the returned `data.task_id` and uses it to query processing status. Replace `YOUR_TASK_ID` below with that task ID. `data.status` is `running`, `completed` or `failed`. Memory queries use content that has already been processed and made available. ```bash curl --request POST \ --url "${MEMOS_GET_STATUS_URL}" \ --header "Authorization: Token ${MEMOS_API_KEY}" \ --header 'Content-Type: application/json' \ --data '{"task_id": "YOUR_TASK_ID"}' ``` **Query relevant memories.** When the user later asks the home speaker about dinner, query MemOS as the same user with the current question: ```bash curl --request POST \ --url "${MEMOS_SEARCH_MEMORY_URL}" \ --header "Authorization: Token ${MEMOS_API_KEY}" \ --header 'Content-Type: application/json' \ --data '{ "user_id": "demo_user_001", "conversation_id": "home_speaker_dinner_002", "query": "What should we have for dinner tonight? Something easy to make." }' ``` MemOS retrieves relevant content from the hub's stored memories and indexes and returns it to the product's Q&A or menu-planning feature. The product combines the current question and relevant memories to generate an answer. During integration testing, verify that processing status can be tracked for writes and queries return useful context. Also check memory retrieval after a restart and the scope of backups and deletion. See [Quick Start](/memos_cloud/getting_started/quick_start) for more backend integration examples. --- # How to Measure the Cost of a Correct Memory-Assisted Task (/usecase/blog/memory_assisted_task_cost) ![image](https://cdn.memtensor.com.cn/img/1793953465890_3w7y0l_compressed.png) A useful memory cost report should answer a product question: can the agent complete the same work, to the required standard, at a lower total cost? Start with a task customers repeat. A support assistant might need to find the current agreement and recommend the right replacement. It has to use the correct policy and the right customer’s information each time. A shorter prompt can help, but it is only part of the calculation. When evaluating MemOS, include the work needed to create, retrieve, and update memory alongside the cost of producing each answer. ## Find the reuse point before comparing request prices Memory moves some processing ahead of later requests. A system may extract facts, build an index, or prepare a state. That preparation needs enough later use to recover its cost. Consider an illustrative setup with three assumed costs. These numbers are examples for the calculation, not MemOS prices: | **Input** | **Assumed cost** | | --- | --- | | Prepare a reusable history | $0.24 | | Process a later request without it | $0.01 | | Process a later request with it | $0.01 | In this example, each later request saves $0.006. Dividing the $0.24 preparation cost by that saving gives a break-even point of 40 uses. At 40 uses, the two paths cost the same; after that, the memory setup begins to save money. After 10 uses, the baseline costs $0.14 and the memory setup costs $0.32. After 100 uses, the figures are $1.40 and $1.04. The per-request saving matters only if the prepared history is reused enough times. Now suppose the history changes often enough to require four full preparations across those 100 uses. Preparation costs $0.96, and the 100 later requests cost another $0.80. The total is $1.76. In this example, the same memory setup costs less when the history stays stable and more when it has to be prepared four times. For a real pilot, replace full preparation with the update path your application actually uses. In MemOS Cloud, a team can [update a known memory](https://memos-docs.openmem.net/memos_cloud/mem_operations/update_memory/) directly or submit [natural-language feedback](https://memos-docs.openmem.net/memos_cloud/mem_operations/add_feedback/) to correct relevant information. Measure those operations under your own workload. Updating an existing record may involve less work than preparing the full history again, but the result depends on how the application uses and updates memory. ## Decide what a passing task must achieve Write the success conditions before testing. For the support assistant, the recommendation must match the current agreement and include the information needed to complete the next step. Include cases where the correct next step is a question. If the customer’s product version is missing, asking for it may be better than giving an unsupported recommendation. Define in advance whether that question counts as a passing result for the task being measured. Use the same tasks, answer model, and success conditions for both configurations. Compare short histories with short histories, and separate first use from repeated use. That makes it easier to see when preparing memory pays off. Calculate total processing costs divided by the number of tasks that pass. Keep unsuccessful attempts and retries at the cost. If no task passes, report the failure directly. Also set essential quality conditions. A system that applies another customer’s agreement has failed the task, however little it costs. Resolve that problem before selecting a cheaper configuration. ## Include the work around the visible answer A memory-assisted request can involve processing, retrieval, generation, storage, and updates. Record the services used in each stage, then apply their actual billed units. [MemOS Cloud’s async mode](https://memos-docs.openmem.net/memos_cloud/features/async_mode/) makes one distinction especially relevant: initial processing can make information available while refinement continues in the background. The time until the application receives a response and the time needed to finish processing are therefore worth measuring separately. For an asynchronous operation that returns a `task_id`, associate that ID with the business task. The [task-status interface](https://memos-docs.openmem.net/api_docs/message/get_status/) reports processing status and, after completion, summarizes memory changes and the relevant memory IDs. Use usage and billing records to assess cost; task status helps explain what happened during processing. For hosted services, use the units shown in usage and billing records. For self-hosting, state how shared compute and storage are allocated. Count each preparation or update once in total. If you also show an average cost per task, spread that cost across the tasks it supports without adding it a second time. When a task fails, inspect the useful evidence: what information was stored, what retrieval returned, and what reached the answer model. This helps locate the change that could improve both quality and cost. ## Choose a workload the product will actually serve The final comparison needs four figures: preparation and update cost, cost per passing task, completion time, and reuse count. For a stable customer history used throughout the day, more preparation may pay back quickly. For a short-lived conversation used once, a simpler request path may be better. Frequent corrections can move the break-even point again. Report the range of outcomes as well as the average. A slower first request may be acceptable if later work becomes faster; a long delay after every correction may affect the experience users care about most. Use these findings to decide where MemOS fits in the workflow and when memory needs to be updated. Some tasks may benefit from reusing customer history; others may be cheaper to handle without preparing it first. As the product grows, rerun the comparison with the workload customers actually create. The decision can then change with reuse, update frequency, and the quality the task requires. --- # Choosing an Agent Memory Framework by the Code You Need to Own (/usecase/blog/choosing_agent_memory_framework) ![image](https://cdn.memtensor.com.cn/img/1793953501310_edwezn_compressed.png) What happens when an agent remembers a policy that has changed? Consider a support assistant answering a return request. The standard policy allows 30 days, but one customer’s contract extends that window to 60 days. The assistant needs to find the right agreement, explain it to the right customer, and stop using the exception if the contract changes. A “remember my name” demo won’t tell you much about this case. You need to know whether the assistant can find the customer’s agreement, distinguish it from the standard policy, and use the updated terms when the agreement changes. That makes the return request a useful way to evaluate a memory framework: follow the information from the first conversation through the next policy change. ## Start with the change, then choose the layer Write down what the task needs: the current return policy, the customer’s contract, and any approved exception. Keep shared policy separate from customer-specific information, and preserve the source and scope of each fact. Then look at what your application already provides. A workflow with durable state may need a searchable store. An application that follows changing relationships may benefit from a temporal graph. A team that needs to process, retrieve, and correct several kinds of memory may want a dedicated memory layer. The options cover different parts of this path: | **Option** | **Useful starting point** | **Question for your project** | | --- | --- | --- | | [LangGraph](https://docs.langchain.com/oss/python/concepts/memory){target="_blank"} | Thread state and long-term stores | Which memory rules belong in the workflow? | | [Graphiti](https://github.com/getzep/graphiti){target="_blank"} | Time-aware facts and relationships | Does the task depend on how relationships change? | | [Mem0](https://docs.mem0.ai/open-source/overview){target="_blank"} | A dedicated memory layer | How much of the write-and-retrieve path does it cover? | | [MemOS](https://memos-docs.openmem.net/open_source/modules/mos/overview) | Memory processing, retrieval and correction components | Where can the required behavior be extended? | A small preference store may be enough for a simple assistant. For a support workflow with changing agreements, look at how each option handles the information your application needs to maintain. With MemOS, teams can choose how they want to deploy and maintain that memory. The [open-source framework](https://memos-docs.openmem.net/open_source/modules/mos/overview/) lets teams configure and extend the components in their own environment. [MemOS Cloud](https://memos-docs.openmem.net/memos_cloud/getting_started/cloud_and_opensource/) provides a managed service for adding memory through APIs. Both give applications a way to carry information into later interactions. The choice depends on how much of the infrastructure and customization the team wants to manage. ## Put business decisions where they can be changed In the returns example, the assistant can retrieve the relevant agreement and explain it. The order service applies the current return entitlement. That gives the product a clear place to update the rule when a contract changes. Identity matters here, too. Resolve the customer through the authenticated session, then select the information that customer is allowed to use. The model can interpret the question using the information the application provides. In MemOS Cloud, the standard return policy can be stored as shared information in a [knowledge base](https://memos-docs.openmem.net/memos_cloud/features/knowledge_base/), while customer-specific information can be organized within the appropriate [user and project scope](https://memos-docs.openmem.net/memos_cloud/introduction/isolation_filters/). The application can bring both into the same request after it has determined which customer is asking and what they are allowed to access. In a self-hosted MemOS implementation, the [Components and Handlers architecture](https://memos-docs.openmem.net/open_source/modules/mos/overview/) separates these steps. MemReader processes conversations or documents into memory items. MemCube organizes memory for users and application scenarios. SearchHandler retrieves relevant memories, while FeedbackHandler handles corrections. That separation gives the team a place to start when the assistant gives the wrong answer. If the 60-day term was missed, inspect how the agreement was processed. If the term is saved but doesn’t appear for the customer, check retrieval and scope. If the saved term is outdated, send a correction and verify the result. Suppose a conversation includes a request for a longer return period that has not been approved. The application needs to preserve that distinction when it processes the request. Making the request easier to retrieve won’t turn it into an approved agreement. ## Run a correction through a complete customer task Build a short evaluation around policy change. Ask about an ordinary customer, the customer with a special contract, and an order placed under the previous policy. Then withdraw the exception and repeat the current question. The answer should reflect the updated agreement. Now ask about an order placed while the 60-day exception was still active. The application may need the terms that applied to that order, depending on the company’s return rules. Keep that historical agreement or order record available so the assistant can distinguish it from the current policy. Keep the input, retrieved information, and results together. If the answer is wrong, the team can check whether the agreement was processed incorrectly, the wrong scope was selected, or the evidence was interpreted incorrectly. In the self-hosted MemOS architecture, requests marked as feedback can enter the correction path. Use an explicit correction when you intend to change a saved fact. An ordinary conversation message and a correction to an existing memory can serve different purposes. For teams using MemOS Cloud, there are two ways to submit a correction. If the application knows which record contains the 60-day exception, it can [update that memory directly](https://memos-docs.openmem.net/memos_cloud/mem_operations/update_memory/). If an authorized user explains the change in a conversation, the application can submit [natural-language feedback](https://memos-docs.openmem.net/memos_cloud/mem_operations/add_feedback/) with the conversation context. After the update, search again to check that the current agreement is returned for the right customer. Keep the historical order case in the test as well. Finally, introduce a second source for the same agreement. Check whether your application can preserve its origin and identify the latest approved terms. This gives the team another useful case to test before a full production migration. ## Prefer changes that survive the next upgrade For each extension, record where it lives: application code, configuration, a documented handler, or a framework fork. A change in one well-defined place is easier to review than logic spread across several extraction prompts and retrieval hooks. Keep the policy cases as a small regression set. Run them when the framework, model, or retrieval configuration changes, and keep a readable export of the information they depend on. By the end, the team should know where the standard policy lives, how the customer’s exception is retrieved, and what needs to change when that exception is withdrawn. That is a more useful basis for choosing a memory framework than a demo that only shows the assistant remembering a fact. The better test is whether the team can keep that fact useful when the agreement changes. --- # Agent Memory Architecture: Building Cross-Session Memory with MemOS (/usecase/blog/agent_memory_architecture) A user has set email as the default for their weekly reports. A week later, they switch to Slack. Then they ask the assistant, “Email this report; I need to forward it to a client.” The assistant should email that report and return to Slack for the next one. To do that across conversations, it needs to distinguish the user’s standing preference from a request for a single task. MemOS provides a memory layer for the application to store that preference, retrieve it in a new conversation, and update it when the user changes their mind. ## Decide when each instruction applies The reporting assistant has to distinguish a lasting preference from an instruction for the current task: | User instruction | Scope | Expected behavior | | --- | --- | --- | | “Send my weekly reports by email by default.” | Ongoing preference | Use email until the user changes the default. | | “Use Slack for future weekly reports.” | Updated preference | Use Slack for later reports. | | “Email this report.” | One report | Use email for this report and keep Slack as the default. | | “Forget my report-delivery preference.” | Saved preference | Remove the preference and ask where to send a future report if no other instruction applies. | A question like “Would Slack work?” opens a discussion. “Use Slack from now on” establishes a preference. The email request can remain in the task history while the application applies it only to that report. MemOS Cloud can extract [preference memories](/memos_cloud/introduction/memory_types) from user statements and interaction history. Your application can combine a retrieved preference with the current request and apply its own rules for defaults and exceptions. ## See how the MemOS components work together The [MemOS v2.0 open-source architecture](/open_source/modules/mos/overview) separates memory processing into components coordinated by handlers: | Component | Role in the open-source architecture | | --- | --- | | MemReader | Processes inputs into memory items that can be stored. | | MemCube | Holds memory modules for users and application scenarios. | | MemScheduler | Coordinates background processing, including storage and indexing. | | MemChat | Coordinates memory retrieval, response generation, and storage of new memories. | | MemFeedback | Processes natural-language corrections, additions, and replacements. | If a saved preference is wrong, you can inspect how the input was processed. If the preference is correct but the assistant misses it, check retrieval and the context passed to the model. [MemOS Cloud](/memos_cloud/getting_started/overview) provides managed APIs for adding, retrieving, and updating memories. The components above belong to the open-source framework; the reporting workflow below uses Cloud APIs. ## Keep the same user across conversations Send the user’s messages to the [Add Message API](/memos_cloud/mem_operations/add_message). A typical request includes a `user_id`, a `conversation_id`, and a `messages` array containing each message’s role and content. MemOS extracts memories, including facts and preferences, and checks new information for duplication or conflicts with existing memories. When the user starts another conversation, call the [Search Memory API](/memos_cloud/mem_operations/search_memory) with the same `user_id` and a query about the task. For a weekly report, the application can search for the user’s current delivery preference and pass the relevant result to the model alongside the current request. Search combines semantic and keyword retrieval with ranking and filters. Fact and preference memories are included by default, so the assistant can retrieve a delivery preference without reconstructing it from earlier conversations. Keep the user ID stable across conversations, with a separate conversation ID for each interaction. When you include `conversation_id` in a search, MemOS gives memories from that conversation greater weight while still allowing the user’s historical memories to be retrieved. For applications serving multiple users, [user and agent memory boundaries](/memos_cloud/introduction/isolation_filters) help determine whose information is retrieved. Your backend should select the user ID from the authenticated account and enforce the permissions appropriate to your application. The application’s email or Slack integration sends the report. ## Update a preference when it changes When the user says, “Use Slack for future weekly reports,” MemOS can process the new information as messages are added and update conflicting memories. MemOS Cloud also supports direct edits and natural-language corrections. If your application knows which record needs editing, use [Update Memory](/api_docs/core/update_memory) with its `memory_id`. You can change the content or title of an existing memory, including a preference. This works well when a user edits a saved preference in your application. For a correction made in conversation, submit [natural-language feedback](/memos_cloud/mem_operations/add_feedback) with `user_id`, `conversation_id`, and `feedback_content`. MemOS uses the feedback and conversation context to locate relevant memories and apply the correction, so the user does not need to find a memory ID. Keep the one-report email request in the current task context, and make sure it is not saved as a new default. That allows the application to honor the immediate request while using Slack for a later report. MemOS Cloud’s [time awareness](/memos_cloud/introduction/time_awareness) keeps historical versions of information that changes and uses time clues during retrieval. “Where should this week’s report go?” calls for the current preference; “What was my previous default?” calls for an earlier one. When importing historical conversations, you can provide `chat_time` to preserve the original timing. ## Allow for background processing MemOS Cloud processes added messages [asynchronously by default](/memos_cloud/features/async_mode). An initial processing stage makes recent messages available for retrieval, while further refinement continues in the background. You can use the returned `task_id` with the [task-status API](/api_docs/message/get_status) to follow processing through completion. If a user changes a preference and starts another task right away, keep the latest instruction in the current context while memory processing continues. For workflows that need to wait for message processing to finish, you can also use synchronous mode when adding messages. ## Decide what to delete Use [Delete Memory](/memos_cloud/mem_operations/delete_memory) with `memory_ids` to remove selected memories, or with `user_id` to clear a user’s memories within the current project. To forget only the report-delivery preference, identify and delete the relevant memories. Clearing all memories for the user is a separate operation. After deletion, search again to check the result. If there is no other delivery instruction, the assistant can ask where the next report should go. If your application also retains summaries or source conversations, handle those records according to the request’s scope so a later import does not recreate the deleted preference. ## Choose the right form of memory The reporting assistant uses editable information stored outside the model. Our [research framework](https://arxiv.org/abs/2507.03724){target="_blank"} describes three forms of memory: * Plaintext memory stores information outside the model, where it can be retrieved and updated. * Activation memory holds runtime states, such as KV caches. * Parametric memory holds knowledge in model weights. MemCube brings memory content and metadata together so memory can be organized and managed. The open-source [KV-cache module](/open_source/modules/memories/kv_cache_memory) supports reuse of cached context during inference. For a preference that users may change or delete, external memory is a practical starting point: your application can update the saved information without retraining the model. ## Test the whole flow You can try the reporting scenario across several conversations with the same user: 1. Save email as the default, then retrieve it in a new conversation. 2. Change the default to Slack and check the retrieved preference and assistant response. 3. Request email for one report, then check that a later report still uses Slack. 4. Search as a different user and confirm the first user’s private preference is not returned. 5. Delete the preference, start a new conversation, and check that it is no longer retrieved. When a result needs investigation, compare the original instruction with the processing status, retrieved memory, and context sent to the model. That helps you see where the preference was captured, selected, or applied differently than intended. Use the [MemOS Cloud quickstart](/memos_cloud/getting_started/quick_start) to add memory to your application, or explore the [open-source architecture](/open_source/modules/mos/overview) for a self-hosted deployment. --- # Why AI Agents Need to Know When a Memory Is Out of Date (/usecase/blog/outdated_agent_memory) An AI agent can remember a project plan correctly and still give the wrong deadline. A software release is scheduled for Thursday. Testing runs long, and the project lead moves it to the following Monday. In a new conversation, someone asks when the release ships. The agent pulls up the original brief and answers Thursday. The brief was accurate when it was written. The plan has changed since then. Over a week of project work, an assistant may encounter the original brief, a revised schedule, and several conversations about both. It needs enough context to tell which project each piece of information belongs to, where it came from, and whether it still applies. ## Which date applies now? [LangGraph’s memory documentation](https://docs.langchain.com/oss/python/concepts/memory){target="_blank"} distinguishes between memory within a conversation thread and longer-term information shared across threads. That helps explain how an agent can carry context into a new conversation. Keeping that context current is another part of the job. In the release example, Monday belongs in the answer to “When are we shipping?” Thursday still matters if someone asks, “What was the original plan?” Both dates can be useful, provided the agent understands their place in the project’s history. Now add a message from a teammate asking, “Could we still make Thursday?” The teammate is reopening the discussion. The approved date remains Monday. Your application needs to preserve that difference and know who can approve a schedule change. Sorting messages by recency alone won’t settle it. ## Keeping useful details with each memory In [MemOS](/memos_cloud/getting_started/overview), memory is managed throughout its lifecycle. The system extracts useful information from inputs, organizes it for retrieval, and updates it as new information arrives. Your application can carry project details into later conversations, so users can pick up their work without explaining the plan again in every chat. Our [MemOS paper](https://arxiv.org/abs/2507.03724){target="_blank"} introduces MemCube, a memory unit that combines content with metadata such as its source and version history. In a release workflow, useful context would include the project, the message announcing the change, and the date it takes effect. Keeping these details together helps your application distinguish an approved schedule from a draft under discussion. MemOS Cloud’s [time awareness](/memos_cloud/introduction/time_awareness) handles information that changes over time. It maintains versions of evolving states, such as preferences or goals, and uses time clues in a question to retrieve current or historical information. Separate events retain their own details. In the release example, a question about the current schedule calls for Monday, while a question about the original plan calls for Thursday. When you import older conversations, you can supply the original message time through `chat_time`. Otherwise, MemOS uses the ingestion time. Preserving that timestamp helps prevent an old conversation imported today from looking like a fresh update. ## A correction needs to change the next answer When the assistant gets the date wrong, a user should be able to correct it without tracking down a database record. MemOS Cloud supports both direct editing and conversational correction. Use the [update API](/memos_cloud/mem_operations/update_memory) when you know which record needs attention. You can revise its content or title, or change its status to archive outdated information. This gives developers and administrators direct control over a specific memory. For corrections made during a conversation, [natural-language feedback](/memos_cloud/mem_operations/add_feedback) lets a user say, “The release has been approved for Monday. Please update the schedule.” Once your application submits that feedback with the user and conversation context, MemOS locates relevant memories and applies corrections. It can add new information and update or override conflicting memories. The user can correct the schedule where the problem appeared, without finding a memory ID. For ongoing chat, MemOS Cloud’s [asynchronous message processing](/memos_cloud/features/async_mode) makes recent messages available for retrieval after an initial processing stage, while further refinement runs in the background. Your assistant can use that information in the next turn. A task-status API lets you follow the background work through completion. ## When a memory should be removed Some information should stay in the project history. Other information needs to be removed at the user’s request. With MemOS Cloud’s [deletion API](/memos_cloud/mem_operations/delete_memory), you can delete specific memories or clear a user’s or agent’s memories within the current project. Use targeted deletion to remove particular records, or the broader options when a user or agent needs to start with a cleared memory. If your application keeps a separate summary containing the schedule, or regularly imports the same project brief, include those sources in your deletion workflow where they fall within the request’s scope. This prevents a later import from recreating information the user asked to remove. Once the relevant memories and copies have been removed, the assistant should ask for the schedule again when it needs it. ## Build with MemOS We offer [MemOS Cloud and an open-source framework](/memos_cloud/getting_started/cloud_and_opensource) for different deployment needs. MemOS Cloud manages the memory infrastructure so you can integrate through APIs and focus on your application. Choose self-hosting when you need more control over configuration, customization, and infrastructure. In the [MemOS v2.0 open-source architecture](/open_source/modules/mos/overview), MemReader turns inputs into memory items, MemScheduler handles background processing, and MemFeedback processes corrections. MemChat coordinates retrieval, response generation, and storage. You can work with these components to adapt how your application captures information and uses it later. Our [research framework](https://arxiv.org/abs/2507.03724){target="_blank"} covers three forms of memory, including external text, runtime states such as KV caches, and parametric memory encoded in model weights. For the release schedule, editable external records give your application a practical way to keep the plan current as decisions change. ## Try the workflow across conversations Start with the Thursday brief, add the approved move to Monday, then introduce a question about whether Thursday is still possible. In a new conversation, ask for both the current schedule and the original plan. The answers should reflect the change and its history. Then remove the schedule within the intended scope and check that routine retrieval or imports don’t bring it back. Comparing the source messages, retrieved memories, and context passed to the model will help you see how each change reaches the assistant. A teammate returning the next morning should be able to pick up the conversation with the revised plan already in place. --- # ChatGPT Upgrades Background Memory Synthesis: Why Enterprise Agents Need Independent Long-Term Memory Infrastructure (/usecase/blog/chatgpt_dreaming_long_term_memory) > **Key takeaway:** OpenAI's Dreaming upgrade signals a shift from saving an occasional preference to continually synthesizing, updating, and using the right information over years. For enterprise agents, larger context windows, RAG, or a vector database alone cannot solve this problem. Production systems also need long-term memory infrastructure covering writes, retrieval, feedback, updates, deletion, permissions, and auditing. --- In June 2026, OpenAI released an upgraded architecture for Dreaming. Dreaming did not first appear that month: an early version arrived in April 2025, followed by further restructuring to address stale memories, conflicts, and scaling during long-term use. The new version focuses on preserving valuable context, following user preferences and constraints correctly, and keeping memory up to date. The significance extends beyond another personalization feature in ChatGPT. As AI moves from one-off answers toward ongoing companionship, continuous work, and autonomous execution, the difficult question becomes how a system decides what deserves to be remembered, when to update it, where to use it, and how users and enterprises can control it. AI memory is becoming an independent infrastructure capability. ## From remembering a few facts to managing years of state Early AI memory resembled a simplified notebook. A user says “Remember that I don't eat spicy food,” the system saves a preference, and the next restaurant recommendation includes it in context. This improves the experience, but things become more complex as days turn into years and user counts reach millions or more. For example: - If someone previously avoided spicy food but changes their preference, should the system overwrite the old memory or retain the history? - How should “I'm going to Shanghai next week” change a week later so it does not remain a future plan forever? - A conversation contains stable preferences and temporary emotions. What deserves long-term retention? - Which information about the same person at work, at home, and across devices may be connected, and which must remain isolated? - How should confidence be managed for a memory inferred by a model rather than explicitly stated by the user? - When a user requests an edit or deletion, how does the system confirm that related copies, indexes, and derived information have been handled? These questions require more than expanding context or putting more historical text into a vector database. | Technology | Primary role | What it cannot solve alone | | --- | --- | --- | | Context window | Lets a model see the current input and some history in one inference | Cross-session persistence, ongoing updates, permissions, and deletion | | RAG | Retrieves material relevant to a question from external knowledge sources | Evolving user state, preference conflicts, and memory lifecycles | | Vector database | Stores vectors and performs similarity search | What to write, when to forget, and who may access it | | Long-term memory system | Manages information state across sessions, tasks, and time | Still needs coordination with models, agents, business permissions, and data governance | For product leaders, the practical questions are whether an agent can use still-valid information when a user returns six months later; whether changed preferences can be corrected; whether memories can be found and handled when an employee leaves or a user requests deletion; and whether a team can trace an incorrect fact to its source and the tasks that used it. ## Three engineering challenges highlighted by the Dreaming upgrade ### 1. Freshness: keeping memory current Time does not stop when a conversation ends. Trips end, tasks finish, preferences change, and organizational rules evolve. A long-term memory system needs to recognize relationships between old and new information and update, downrank, archive, or forget memories, rather than retain every historical statement as an equally current fact. This calls for temporal information, version relationships, feedback, and lifecycle policies. ### 2. Continuity: making information useful across sessions Continuity requires more than copying the entire chat history into the next conversation. Raw records are often lengthy, repetitive, and full of information that mattered only at the time. Repeated concatenation increases token costs and buries important facts in noise. Systems need to identify facts, preferences, events, relationships, and task state, then retrieve the parts appropriate to the current situation. ### 3. Relevance: deciding what to use now Semantic similarity alone does not make a memory suitable for the current task. Identity, business context, time, permissions, task stage, and confidence also determine whether it should enter the current inference. Long-term memory needs an orchestratable scheduling mechanism alongside retrieval. ## Work backward from user needs: five questions a production system must answer Enterprises buy or build a system that can operate reliably over time. It must explain how information enters memory, how a task finds the right memories, how old and new information are reconciled, how errors are corrected, and how information is deleted when no longer needed. MemTensor focuses on long-term memory and continual learning for large models, defining MemOS as a memory operating system for the agent era. Models handle understanding, reasoning, and generation; agents handle planning, tool use, and execution; MemOS provides an independent layer for memory production, organization, scheduling, governance, and evolution. In MemTensor's architecture, MemOS sits between agentic AI and large language models, organizing capabilities previously scattered across application code, databases, and conversation histories: - **Production:** identifies information with lasting value in conversations, documents, tasks, and business events, reducing the noise of simply retaining raw messages. - **Organization:** manages memory in layers according to purpose and form. - **Scheduling:** selects memories according to user, task, context, time, and permissions. - **Governance:** manages provenance, logs, versions, permissions, privacy, rollback, deletion, and forgetting. - **Evolution:** uses ongoing feedback to turn recurring, effective experience into reusable knowledge and capabilities. The goal is to maintain accurate, continuous, manageable understanding over longer periods. The following table connects these requirements to publicly documented MemOS capabilities and provides evidence readers can inspect after publication. | Production question | Public MemOS capability | Official reference | | --- | --- | --- | | How do conversations enter memory? | Add Message accepts messages into memory processing | [Add Message](https://memos-docs.openmem.net/memos_cloud/mem_operations/add_message/) | | How does a task retrieve relevant content? | Search Memory supports query-based retrieval | [Search Memory](https://memos-docs.openmem.net/memos_cloud/mem_operations/search_memory/) | | How can usage feedback correct memory? | Add Feedback sends feedback into memory processing | [Add Feedback](https://memos-docs.openmem.net/memos_cloud/mem_operations/add_feedback/) | | How is unwanted information handled? | Delete Memory provides an explicit deletion operation | [Delete Memory](https://memos-docs.openmem.net/memos_cloud/mem_operations/delete_memory/) | | How are memory capabilities connected to agents? | Open-source MOS organizes and invokes memory modules | [MOS architecture](https://memos-docs.openmem.net/open_source/modules/mos/overview/) | An API establishes an available operation; it does not automatically satisfy every enterprise governance requirement. Permission models, approval rules, log retention, isolation, and compliance policies still require design around the deployment and business systems. ## Why MemOS uses layered memory Different information benefits from different storage and access methods. MemOS distinguishes plaintext, activation, and parameter memory. Plaintext memory is convenient to update, revise, and trace; activation memory supports efficient reuse during inference; parameter memory holds stable capabilities developed through training or consolidation. The system can organize and transform memory forms according to task and runtime conditions. This design balances three goals: 1. Information should be inspectable, editable, and traceable. 2. Memory access should keep real-time inference latency acceptable. 3. Accumulated experience should have a path toward more stable capabilities. A production memory system therefore extends beyond a particular database. Vector and graph databases can provide storage, while the memory layer manages creation, invocation, updates, and governance. ## The full lifecycle of a memory MemOS provides APIs and management capabilities across the memory lifecycle. Information enters through [`/add/message`](https://memos-docs.openmem.net/memos_cloud/mem_operations/add_message/) and is processed into memory. Applications retrieve it with [`/search/memory`](https://memos-docs.openmem.net/memos_cloud/mem_operations/search_memory/). New feedback enters the update flow through [`/add/feedback`](https://memos-docs.openmem.net/memos_cloud/mem_operations/add_feedback/). When information becomes invalid or a user requests removal, [`/delete/memory`](https://memos-docs.openmem.net/memos_cloud/mem_operations/delete_memory/) provides deletion. APIs are only part of long-term memory, but they make writing, retrieval, feedback, and deletion explicit system actions that an application can invoke and manage. ## Personal assistants and enterprise agents face different memory problems ChatGPT's Dreaming primarily addresses the long-term personal experience. Enterprise agents face more complex constraints. AI companions and games emphasize character consistency, shared experiences, and relationship development. Smart devices need cross-device continuity alongside local privacy. Support agents need service histories connected across channels. Finance and industrial scenarios place greater emphasis on permissions, provenance, auditing, private deployment, and deletion. Enterprise memory infrastructure therefore needs different deployment and governance approaches. MemTensor's product materials describe MemOS Cloud, private deployments, edge deployments, and edge–cloud collaboration. Available forms, feature boundaries, and delivery conditions depend on the project version and official materials. Applications can use different production, scheduling, and storage strategies within a common governance boundary. ## Evaluating long-term memory takes more than retrieval hits Traditional retrieval systems often emphasize recall, but production memory needs at least five dimensions. **Continuity:** does useful history carry across sessions? **Freshness:** are expired plans and changed preferences updated? **Relevance:** are suitable memories used in suitable tasks? **Control:** can users and enterprises inspect, correct, delete, and constrain memory? **Operational efficiency:** as time and usage grow, can processing and retrieval keep latency, token use, and storage costs under control? These dimensions determine whether a demonstration can become a durable production system. Remembering a birthday once does not prove months of state changes, user isolation, or large-scale concurrency can be managed. A larger context window likewise does not replace lifecycle management and governance. ## Frequently asked questions ### Why does AI forget preferences and past conversations? Most models do not inherently retain cross-session state. When a session ends, history must be stored and supplied again by an external system. Keeping all chat logs still leaves extraction, freshness, conflict handling, and context-dependent use to be solved. ### How do AI memory, context windows, RAG, and vector databases differ? A context window carries input for one inference. RAG finds material in external sources. A vector database supplies storage and similarity retrieval. Long-term memory manages state over time, including writes, updates, feedback, permissions, auditing, deletion, and forgetting. These capabilities work together. ### What belongs in a production agent memory architecture? At minimum: writing and extraction, identity and scope isolation, retrieval and reranking, conflict and freshness handling, feedback and updates, deletion and forgetting, permissions and auditing, and evaluation of latency, cost, and quality. The architecture must also connect to models, agent orchestration, business data, and compliance systems. ### What is MemOS? MemOS is the memory operating system developed by MemTensor to organize memory capabilities scattered across model context, application code, and databases into independent infrastructure. Public documentation covers message ingestion, memory retrieval, feedback, deletion, and module orchestration. ## AI competition is moving toward understanding over time Models continue improving, but long-term intelligence depends on more than parameter counts and context length. As AI participates in personal life and enterprise workflows over time, its ability to retain important information, understand changes, retrieve appropriate history, reject untrusted memories, and support editing and deletion directly affects the experience and production reliability. OpenAI's continued restructuring of ChatGPT Memory shows that long-term memory is a core systems challenge for leading AI products. MemTensor's path—from Memory³ research through MemOS engineering, agent and memory infrastructure, and exploration of memory-native general-purpose foundation models—addresses the same long-term question: How can AI progress from one-off generation to continuous understanding, learning, and self-evolution? This transition is beginning. Valuable AI will need to answer intelligently in one conversation, understand more accurately and act more consistently over time, and remain accountable for its memory. ## About MemTensor MemTensor (Shanghai) Technology Co., Ltd. is a next-generation large-model and long-term intelligence infrastructure company incubated by the Shanghai Institute for Algorithms Innovation, with a member of the Chinese Academy of Sciences serving as chief advisor. Focused on reducing hallucinations, personalization, and self-learning and evolution, the company studies long-term memory and continual learning for large models. Its roadmap connects Memory³ research, the MemOS memory operating system, agent and memory infrastructure products, and exploration of memory-native general-purpose foundation models, progressing from theory to systems engineering and model research to advance AI beyond one-off generation toward long-term intelligence. MemTensor has established close collaborations with partners including China Merchants, Haicheng, and HONOR, and commercial deployments in AI companionship, games, smart devices, finance, and industry. It has raised nearly RMB 200 million in total, with investors including CICC, Futeng Capital, Hubble, SenseTime, and MSA Capital. --- # Memory Poisoning: Six Long-Term Memory Controls Enterprise Agents Need (/usecase/blog/memory_poisoning_controls) > **Key takeaway:** Memory poisoning occurs when untrusted information enters persistent memory and is reused in future sessions, tasks, or across agents. Enterprises need lifecycle controls around provenance, writing, updates, isolation, retrieval, and deletion alongside output safeguards. MemOS provides system entry points for writing, retrieval, feedback, deletion, and orchestration, working with identity and permissions, input validation, approvals, monitoring, and security operations. --- With one-off Q&A, a wrong answer's effects usually end with the session. When agents have long-term memory across sessions, errors can be stored, recalled, and propagated through later tasks and other agents. In August 2026, Forcepoint published *Agentic AI Security Risks: What CISOs Need to Know*. Drawing on X-Labs research, it discussed persistent risks from contaminated memory and context: false context, fabricated preferences, or incorrect behavioral patterns written into persistent state can affect subsequent decisions. In a multi-agent architecture, one agent's contaminated output can become another's input. Compared with ordinary prompt injection, memory poisoning is harder to handle because its effects may appear later and survive the original session. A false memory can resurface weeks afterward as a fact the system supposedly already knows. ## From prompt injection to memory poisoning: what changes? Prompt injection typically attempts to alter behavior during the current interaction. A web page might contain hidden instructions that steer an agent away from its rules or toward inappropriate tool calls. In a stateless system, the effect may end with the task. A persistent agent can write the resulting content into long-term state: - Save an attacker-supplied contact as a trusted supplier. - Summarize an abnormal operation as successful experience for reuse. - Mistake instructions on a malicious page for a lasting user preference. - Share contaminated task conclusions across agents. - Treat false information as historical evidence more trustworthy than external sources during future retrieval. Long-term memory expands both agent capability and the time and scope over which an attack can persist. Traditional controls are better suited to checking individual requests, connections, or tool calls. Memory poisoning requires observing information throughout ingestion, processing, storage, retrieval, feedback, and deletion. ## How contaminated information becomes a lasting risk | Stage | What can happen | Controls to establish | | --- | --- | --- | | Input | Web pages, emails, tool results, or external agents carry untrusted content | Label source, trust level, and data type; validate high-risk inputs | | Writing | A model summarizes temporary content or malicious instructions as lasting facts | Write permissions, policy validation, approval of sensitive operations | | Persistence | Incorrect information loses its context and becomes a stable memory | Preserve source, time, creator, version, and validity period | | Retrieval | Similarity search recalls a poisoned memory in the wrong situation | Identity and scope filters, freshness checks, reranking, confidence thresholds | | Action | An agent uses it to call tools, make recommendations, or change business state | Least privilege, confirmation of critical actions, output and tool-call monitoring | | Propagation | Results enter other agents, summaries, knowledge bases, or derived memories | Lineage, limits on cross-domain sharing, traceability, and bulk remediation | This chain gives security teams an acceptance criterion: can contaminated information be identified, blocked, traced, and removed? ## Six governance questions a production memory system must answer ### 1. Where did this memory come from? Distinguish explicit user statements, business records, external documents, model inferences, and agent summaries. When different sources are compressed into indistinguishable text, later systems struggle to judge reliability. Preserve provenance, creation time, creator, related task, and processing history for traceability. ### 2. Who can write and modify it? Reading and writing long-term memory need separate permissions. Web pages, email, tool results, and third-party agents can all carry untrusted input. Define writing boundaries for users, organizations, applications, agents, and external sources, with validation or human confirmation for high-risk updates. ### 3. How does new information relate to old memory? Long-term memory needs more than an append-only log. When a new fact arrives, determine whether it supplements, corrects, replaces, or contradicts an earlier one. Simply retaining both can make an agent retrieve incompatible conclusions in the future. ### 4. How are different subjects isolated? Multiple users, agents, and business systems generate many memories. Define personal, team, organization, task, and agent ownership, along with permitted sharing and access boundaries. Isolation that relies on ad hoc parameter assembly becomes harder to maintain as systems grow, increasing unauthorized access and cross-scope leakage risks. ### 5. Can incorrect memories be corrected, rolled back, and deleted? Finding an error is the first step. A system also needs to locate its copies and derived information and stop further use. Feedback, versions, rollback, precise deletion, and forgetting are core controls for long-term memory. ### 6. Can the system keep detecting anomalies? Memory poisoning can change behavior slowly and cumulatively. Reviewing individual answers may miss long-term drift. Record memory writes, updates, retrievals, and deletions. Observe which memories an agent used, what data it accessed, which tools it called, and whether its behavior departed from the normal baseline. ## How MemOS places memory governance in the architecture MemTensor treats long-term memory as a system resource requiring independent management. MemOS sits between agentic AI and large language models, separating memory writes, retrieval, feedback, deletion, and module orchestration from scattered application logic. Publicly documented capabilities and their security value include: | Governance goal | MemOS capability | Contribution | Official reference | | --- | --- | --- | --- | | Make writes explicit | Add Message | Applications choose which messages enter memory processing | [Add Message](https://memos-docs.openmem.net/memos_cloud/mem_operations/add_message/) | | Constrain retrieval by query and scope | Search Memory | Applications retrieve as needed at a task stage | [Search Memory](https://memos-docs.openmem.net/memos_cloud/mem_operations/search_memory/) | | Provide a correction channel | Add Feedback | Sends inaccurate, changed, or unsuitable information back into the memory flow | [Add Feedback](https://memos-docs.openmem.net/memos_cloud/mem_operations/add_feedback/) | | Provide a removal channel | Delete Memory | Explicitly removes incorrect, expired, or unwanted memories | [Delete Memory](https://memos-docs.openmem.net/memos_cloud/mem_operations/delete_memory/) | | Organize memory modules | Open-source MOS | Orchestrates agents' access to different memory modules | [MOS architecture](https://memos-docs.openmem.net/open_source/modules/mos/overview/) | These capabilities provide a governance foundation. They do not promise automatic immunity to memory poisoning, and an API alone does not establish that an enterprise control has been deployed. A complete flow also needs identity management, least privilege, input validation, human approvals, DLP, SIEM, business logs, and incident response. ## Why feedback and deletion need formal APIs Prototypes often focus on adding and retrieving memories. Updates and deletion are equally important for security and governance. MemOS provides [`/add/message`](https://memos-docs.openmem.net/memos_cloud/mem_operations/add_message/), [`/search/memory`](https://memos-docs.openmem.net/memos_cloud/mem_operations/search_memory/), [`/add/feedback`](https://memos-docs.openmem.net/memos_cloud/mem_operations/add_feedback/), and [`/delete/memory`](https://memos-docs.openmem.net/memos_cloud/mem_operations/delete_memory/). Feedback lets applications report that a memory is inaccurate, a preference has changed, or a result should no longer be reused. Deletion makes removal of incorrect, stale, or unsuitable information an explicit operation. Enterprise applications connect these APIs to identity, permissions, auditing, and business approvals. Governance records should identify the actor, the basis for a change, affected objects, and completion status. ## Layered memory brings layered risks Plaintext, activation, and parameter memories have different visibility and modification costs. Plaintext is easier to inspect, edit, and trace. Activation memory is closer to real-time inference. Parameter memory can carry stable learned capabilities. Incorrect information has different effects and remediation paths at each layer. Governance therefore needs to check whether information has reached caches, graph relationships, derived summaries, skills, and other reusable state as well as the original stored text. Layering also makes it possible to set different writing thresholds, update strategies, and audit methods for different memory forms. ## Private and edge deployments still need governance Private or edge deployment can reduce the risk of data leaving organizational or device boundaries, but incorrect writes, excessive permissions, unclear provenance, and internal contamination remain concerns. An incorrect local memory remains incorrect, and excessive privileges in a private environment can still permit unauthorized access. Production governance needs to consider: - Where data resides. - Who can read, write, modify, and delete it. - How external information is validated before ingestion. - How sources and versions are recorded. - How anomalous calls are detected. - How users and administrators correct system state. MemOS supports cloud, private, edge, and edge–cloud deployment approaches. Deployment addresses data boundaries, performance, and operations; memory governance applies across them. ## Different industries need different memory risk models AI companions emphasize persona consistency, user control, and sensitive preferences. Smart hardware needs user isolation and local privacy. Financial agents emphasize policy freshness, business permissions, and auditing. Industrial agents need to distinguish equipment facts, expert experience, and field anomalies. Treating all information as the same kind of searchable text hides these differences. Define by industry and task what can be written automatically and what requires confirmation; what may be shared and what stays isolated; what can remain indefinitely and what expires; and what errors can be corrected through feedback versus requiring immediate suspension and audit. ## A pre-launch enterprise checklist - Record source, creator, time, scope, and validity period for each memory. - Distinguish read, write, update, delete, and cross-subject sharing permissions. - Treat external pages, emails, and tool outputs as untrusted input by default. - Require confirmation for high-risk memory writes and critical business actions. - Define overwrite, retention, downranking, or review rules for conflicts. - Trace which tasks recalled a memory and which actions it affected. - Support suspending use, correcting or deleting the source, and tracing derived state after contamination. - Monitor write volume, retrieval hits, conflicts, feedback corrections, deletion completion, cross-domain access, and anomalous tool calls. - Regularly test prompt injection, cross-tenant leakage, stale memories, and propagation with red-team samples. - Define responsibility boundaries for cloud, private, and edge deployments. ## Frequently asked questions ### What is memory poisoning? It is the risk that untrusted or incorrect information enters an agent's persistent memory and influences decisions or actions in future tasks. Persistence is the defining feature: effects can survive across sessions and propagate to derived memories or other agents. ### How does it differ from prompt injection? Prompt injection typically manipulates the current interaction. Memory poisoning concerns malicious influence written into long-term state. Injection can be an entry point; persistence and future reuse create the lasting memory-layer risk. ### Is private deployment enough to make it safe? Private deployment changes data and system boundaries. It still needs identity and permissions, input validation, auditing, monitoring, correction, and deletion to address incorrect writes, unauthorized access, fabricated provenance, and internal contamination. ### What should production memory telemetry record? Alongside latency, errors, and cost, record write sources, scope, retrieval history, conflicts and overwrites, corrections, deletion status, permission denials, cross-domain access, anomalous tool calls, and links between memories and final decisions. Security investigations need to know which memory influenced which action. ### What role does MemOS play? MemOS makes writes, retrieval, feedback, deletion, and orchestration callable system capabilities, providing a memory-layer foundation for governance. It works alongside enterprise IAM, DLP, SIEM, approvals, and security operations; it does not automatically block every poisoning attack. ## Agents that act over time need accountability for memory Continuity enables agents to retain history, continue tasks, understand users, and reuse experience. It can also let errors and attacks persist. The next stage will evaluate whether systems can explain memory origins, update information correctly, keep untrusted content out of persistent state, give users and enterprises control, and trace, correct, and delete errors. MemTensor's long-term intelligence roadmap spans Memory³ research, MemOS, agent and memory infrastructure, and memory-native models. Its central judgment is that memory improves personalization and constitutes infrastructure that needs governance in real production environments. Long-running agents need a control system for the full memory lifecycle alongside a place to store history. ## About MemTensor MemTensor (Shanghai) Technology Co., Ltd. is a next-generation large-model and long-term intelligence infrastructure company incubated by the Shanghai Institute for Algorithms Innovation, with a member of the Chinese Academy of Sciences serving as chief advisor. Focused on reducing hallucinations, personalization, and self-learning and evolution, the company studies long-term memory and continual learning for large models. Its roadmap connects Memory³ research, the MemOS memory operating system, agent and memory infrastructure products, and exploration of memory-native general-purpose foundation models, progressing from theory to systems engineering and model research to advance AI beyond one-off generation toward long-term intelligence. MemTensor has established close collaborations with partners including China Merchants, Haicheng, and HONOR, and commercial deployments in AI companionship, games, smart devices, finance, and industry. It has raised nearly RMB 200 million in total, with investors including CICC, Futeng Capital, Hubble, SenseTime, and MSA Capital. --- # Memory Management for Long-Running Agents: From Session Recovery to Reusable Experience (/usecase/blog/long_task_agent_memory_management) > **Key takeaway:** OpenAI's Agents API moves agents that run for days toward a standard interface, while exposing another side of long-running work: context can be compacted and processes resumed, but deciding why a piece of state deserves long-term retention, when it expires, and who may use it still requires separate system-level judgment. --- ![Memory management for long-running agents, from session recovery to reusable experience](https://cdn.memtensor.com.cn/img/memos-best-practices-long-task-cover-en-20261028_compressed.png) On September 10, 2026, OpenAI released the public beta of its Agents API, bringing session orchestration, context compaction, and task recovery into a managed agent harness. Developers can start agents through an API, configure tool calls and subagent collaboration, and continue existing tasks in later interactions. As agents move beyond single-turn Q&A into continuous execution across sessions and tools, systems need to track task progress, user requirements, and intermediate results. Reasoning, tool execution, and state management together affect the quality of long-running work. Context management helps retain information needed for the current step. Content intended for reuse across sessions raises four further questions: what deserves long-term storage, which version wins when information conflicts, what agents can share, and what should be deleted when a task ends. Long-term memory management addresses these questions. It associates information with users, tasks, or agents, manages retention across sessions and updates over time, and determines its scope of use alongside context management, retrieval, and underlying storage. ## Why do long-running agents need memory management? Short tasks can usually keep the necessary information in current context. Long tasks continually generate tool results, files, plans, error logs, feedback, and intermediate conclusions. Repeatedly putting the full history back into context creates three issues. First, history increases input size. If every request carries the complete history, inputs grow with the task, repeatedly including information unrelated to the current step. Selecting what is needed helps control input size; actual cost and latency also depend on the model, caching, and other mechanisms. Second, compaction needs to retain provenance and status. Summaries shorten text, but missing labels can blur user requirements, model assumptions, tool-returned facts, and obsolete plans. Later tasks need those distinctions to decide what can be reused and what still requires verification. Third, the scope of information use needs to be clear. Has a subagent's intermediate conclusion been verified, and can other agents use it? Which parts of a failed attempt deserve retention as experience, and which belong only in execution logs? These choices determine how history affects later work. Four management objects help clarify responsibility. | Object | Typical content | Responsibility | | --- | --- | --- | | Task execution state | Progress, tool call records, pending steps | Stored by the harness and application for continuation and recovery | | Working context | Current instructions, plans, recent tool results, retrieved information | Organizes information visible to the model for this inference, compacting or replacing it as needed | | External knowledge | Product manuals, project documents, business policies | Retrieved from source systems, with document versions and access scopes maintained | | Long-term memory | User preferences, historical requirements, reusable task experience | Defines ownership, scope, update behavior, and deletion paths | These responsibilities work together. The context window bounds one inference's input. RAG uses retrieved information to support generation and can retrieve external knowledge or historical memories. A vector database supplies vector storage and similarity search. Long-term memory management focuses on writing information, retaining it across sessions, updating it over time, and controlling where it is used. For a report spanning multiple sessions, execution state records progress, working context contains the chapter currently being edited, a knowledge base supplies product references, and long-term memory stores the user's continuing format requirements. The next report can retrieve those requirements and apply them alongside current instructions. Operations involving payment status or approval outcomes should use current state confirmed by the relevant business system. Historical descriptions in memory provide background. ## Memory management in production Memories change throughout a long task. New requirements update old plans, and agents taking over the same work need clearly scoped shared information. The architecture needs a continuous flow connecting writing, use, updates, and deletion. | Responsibility | What it manages | | --- | --- | | Writing | Selects content, distinguishes user statements, tool results, and model inferences, and records verifiable sources, times, and associated subjects | | Organization | Establishes project, user, or agent ownership and separates personal memory from shared knowledge | | Retrieval | Selects memory types, filters, and result counts for the task, with access control enforced server-side | | Updates | Distinguishes additions, state changes, and corrections; verifies updated content and subsequent retrieval | | Deletion and retention | Defines retention periods, deletion targets, and verification; application copies, logs, and caches follow their own retention rules | | Operational records | Connects tasks, memory operations, and the memories actually sent to the model for troubleshooting | These operations need to form one flow. If a user changes a report format, the system should update the memory, make the new requirement available to retrieval, and retain a verifiable change record. With multiple agents, their respective read and update scopes also need to be defined. ## How MemOS separates memory responsibilities from application logic MemOS organizes memory reads, writes, and maintenance as independent system capabilities. Developers can configure memory processing through [components and interfaces](https://memos-docs.openmem.net/open_source/modules/mos/overview/), managing what is stored, when it is retrieved, and how it is updated and deleted. With MemOS Cloud, applications can call [write, search, update, feedback, and deletion APIs](https://memos-docs.openmem.net/api_docs/start/overview/), using project API keys, user identifiers, and agent filters to set [retrieval scopes](https://memos-docs.openmem.net/memos_cloud/introduction/isolation_filters/). The `conversation_id` increases the retrieval weight of memories related to the current conversation; it does not enforce isolation. For changing preferences and state, [time awareness](https://memos-docs.openmem.net/memos_cloud/introduction/time_awareness/) uses temporal cues in a query to select current or historical memories. User corrections can trigger updates through [natural-language feedback](https://memos-docs.openmem.net/memos_cloud/mem_operations/add_feedback/); precise edits can [update a specific memory entry](https://memos-docs.openmem.net/memos_cloud/mem_operations/update_memory/). Applications can inspect the processed content and retrieval results. Tool usage and task experience can also inform later work. After the application writes tool parameters, actual results, and their associations, MemOS Cloud can extract and retain [tool trajectories](https://memos-docs.openmem.net/memos_cloud/features/tool_calling/). For reusable task methods, [self-evolving memory](https://memos-docs.openmem.net/memos_cloud/features/self-evolving/) can derive skills from historical conversations and accepts uploaded skill files. Selecting the relevant memory types during [search](https://memos-docs.openmem.net/memos_cloud/mem_operations/search_memory/) retrieves trajectories or skills for the agent to consult. MemOS Cloud can [delete memories by ID](https://memos-docs.openmem.net/memos_cloud/mem_operations/delete_memory/) within the current project, with results verified through queries. The open-source architecture uses a [Components + Handlers](https://memos-docs.openmem.net/open_source/modules/mos/overview/) pattern separating system components from request handling. [MemCube](https://memos-docs.openmem.net/open_source/modules/mem_cube/) organizes memory modules into containers for users and scenarios. Handlers coordinate adding, searching, feedback, and other operations. [MemScheduler](https://memos-docs.openmem.net/open_source/modules/mem_scheduler/) dispatches updates, organization, and feedback work in the background, providing task status and operation logs for tracking asynchronous processing. Applications connect these operations to authentication, business authorization, and monitoring. The application server derives read and write scopes from business rules and handles its own copies and caches. ## How to validate memory flows in long-running tasks Validation needs multiple interactions: can a new session find retained information, do corrections reach subsequent tasks, and do retrieval scopes follow expectations when users or agents change? Start with seven questions. 1. When a task resumes across sessions, does it use raw history, a summary, or structured state? Which layer stores and restores each? 2. Does a long-term memory retain its source, time, subject, and scope? 3. After a model, embedding model, or agent upgrade, are retrieval and use of existing memories tested for compatibility? 4. Are concurrency and conflict rules clear when several subagents write simultaneously? 5. Can incorrect memories receive feedback, be corrected, and be deleted? If they affected later tasks, can the related records be located and handled? 6. Can retrieval scopes be set according to identity, permissions, freshness, and task stage, with access controls enforced by the application server? 7. Can an abnormal action be linked to its input, the memories actually sent to the model, and tool execution results? As agents participate in more tasks and sessions, memory needs to be designed and maintained alongside models, tools, and execution environments. MemOS makes reading, writing, updating, and deleting memories callable capabilities, allowing information accumulated across sessions to be maintained and used in later tasks as needed. Learn more: [MemOS website](https://memos.memtensor.net/) | [Documentation](https://memos-docs.openmem.net/) | [GitHub](https://github.com/MemTensor/MemOS) ## About MemTensor MemTensor (Shanghai) Technology Co., Ltd. is a next-generation large-model and long-term intelligence infrastructure company incubated by the Shanghai Institute for Algorithms Innovation, with a member of the Chinese Academy of Sciences serving as chief advisor. Focused on reducing hallucinations, personalization, and self-learning and evolution, the company studies long-term memory and continual learning for large models. Its roadmap connects Memory³ research, the MemOS memory operating system, agent and memory infrastructure products, and exploration of memory-native general-purpose foundation models, progressing from theory to systems engineering and model research to advance AI beyond one-off generation toward long-term intelligence. MemTensor has established close collaborations with partners including China Merchants, Haicheng, and HONOR, and commercial deployments in AI companionship, games, smart devices, finance, and industry. It has raised nearly RMB 200 million in total, with investors including CICC, Futeng Capital, Hubble, SenseTime, and MSA Capital. --- # From Data Ownership to Deletion: Four Questions for Self-Hosted Agent Memory (/usecase/blog/self_hosted_agent_memory_four_questions) > **Key takeaway:** Enterprises usually choose self-hosted agent memory to bring data storage, model calls, and operations under their own management. As agents work across sessions and teams, the deployment plan also needs to answer more specific questions: what information deserves to be retained, who can use it, how errors are corrected, and when it should be deleted. --- At MemTensor, we offer MemOS Cloud and an open-source self-hosted path. Enterprises can configure memory services around their infrastructure and connect memory management to existing business processes. ## 1. Who owns a memory, and where does it travel? “Customer A prefers email” is personal information about a customer; a support team's operating procedure is suitable for sharing within an authorized scope. Ownership determines where a memory should be stored and which agents can access it. Before deployment, map the complete data flow: which business system supplies messages, which model and embedding services process them, and where the resulting memories, indexes, and logs reside. Include model services, operational access, and backup locations in the same map. The MemOS [self-hosted deployment](https://docs.openmem.net/open_source/getting_started/rest_api_server/) provides REST APIs for adding, searching, retrieving, and providing feedback on memories, with configurable model and embedding services. The reference deployment includes components such as Neo4j and Qdrant. Enterprises can plan service connections and storage locations around their existing environment. If data must be processed on an internal network, include model, embedding, and other external calls in the deployment design. This establishes the data boundary during planning. ## 2. Who can write, read, update, and delete—and who approves sharing? Agents within one enterprise often have different responsibilities. Support agents need customer preferences, while development assistants need project conventions. Their memory access should follow business permissions. Start by distinguishing personal, project, and organization-wide information, then assign responsibility for writing, reading, updating, deleting, and sharing. For example, users maintain their personal preferences, project owners confirm project procedures, and organization-wide rules are reviewed before broader use. In MemOS, [MemCube](https://memos-docs.openmem.net/open_source/modules/mem_cube/) organizes and manages memory spaces. It supports operations within a single space and retrieval across multiple spaces through composed views. Applications can combine identity and business permissions to determine the readable and writable memory scope of each request, allowing agents to reuse information within authorized boundaries. Connect enterprise accounts and roles to these memory spaces. Adjust access when employees leave, projects end, or sharing is revoked. During a pilot, test access with different users and projects to catch missing permission rules early. ## 3. Can you explain where a memory came from when something goes wrong? User-confirmed preferences, model inferences from chats, and business records returned by tools need to retain their respective sources. When an agent gives a wrong answer, those sources help determine whether the information was stored incorrectly, the wrong memory was retrieved, or the correct content was not used in the response. The MemOS [memory scheduler](https://memos-docs.openmem.net/open_source/modules/mem_scheduler/) coordinates memory flow and updates, providing task status, processing times, and memory operation logs. Enterprises can connect these records to their monitoring systems and correlate business requests, memory processing, and agent responses. For example, a system might mistake a user's one-time choice for a lasting preference. After the user corrects it, the team can inspect feedback processing, changes to the relevant memory, and the next retrieval result to confirm that subsequent interactions use the new information. Prefer memory IDs, source references, and operation records in logs, with detailed content accessible according to permissions. This supports troubleshooting while reducing duplication of sensitive information across operational systems. ## 4. When a user requests deletion, what exactly gets removed? Memory management should distinguish correction, expiration, and deletion. A changed contact detail calls for an update; a completed temporary task can be cleaned up according to retention rules; a request to delete historical information requires identifying the affected records and copies. MemOS Cloud provides [deletion by memory, user, or agent](https://memos-docs.openmem.net/memos_cloud/mem_operations/delete_memory/) within the current project. Agent-level deletion applies to agents with independent memory enabled. For self-hosted deployments, enterprises can integrate cleanup into their own data management processes around the memory modules and storage components they use. Include application-generated summaries, caches, and backups in the cleanup plan, and define processing times and owners. After deletion, search through the relevant business entry points to check whether old information still enters the agent's context. This makes deletion an executable, traceable routine operation and gives teams a clear way to explain request progress to users. ## Put the four questions into practice with a pilot Choose a real business scenario and prepare two projects, two users, and one test memory. Run through writing, retrieval, sharing, correction, and deletion. Check that authorized users receive the information they need, other users remain isolated, and subsequent tasks reflect updates and deletions. MemOS provides memory organization, retrieval, feedback, and scheduling. Enterprises connect identity rules, storage policies, and operational processes. The pilot should produce a clear launch plan: where data lives, who can use it, how problems are traced, and how records are retired—so agents can continue accumulating useful experience in the enterprise's own environment. ## About MemTensor MemTensor (Shanghai) Technology Co., Ltd. is a next-generation large-model and long-term intelligence infrastructure company incubated by the Shanghai Institute for Algorithms Innovation, with a member of the Chinese Academy of Sciences serving as chief advisor. Focused on reducing hallucinations, personalization, and self-learning and evolution, the company studies long-term memory and continual learning for large models. Its roadmap connects Memory³ research, the MemOS memory operating system, agent and memory infrastructure products, and exploration of memory-native general-purpose foundation models, progressing from theory to systems engineering and model research to advance AI beyond one-off generation toward long-term intelligence. MemTensor has established close collaborations with partners including China Merchants, Haicheng, and HONOR, and commercial deployments in AI companionship, games, smart devices, finance, and industry. It has raised nearly RMB 200 million in total, with investors including CICC, Futeng Capital, Hubble, SenseTime, and MSA Capital. --- # Why Long-Term Memory Still Matters with a Million-Token Context Window (/usecase/blog/million_token_context_long_term_memory) > **Key takeaway:** Users want an AI assistant to understand a long document and remember arrangements confirmed last time. They should not have to explain a budget again in a new session; recommendations should adapt when preferences change; and information they no longer want retained should be deletable. --- A large context window expands how much information a model can process at once. Long-term memory concerns how that information carries into the next interaction: what deserves to be retained, whom it belongs to, when it changes, and when to stop using it. At MemTensor, we use MemOS to manage this process, helping agents accumulate useful information through ongoing interactions and retrieve it in later tasks. These cross-session management needs remain even with a million-token context window. ## How do the four capabilities work together? Context windows, RAG, vector databases, and long-term memory operate at different layers and can serve the same task together. | Capability | Role | Use in customer support | | --- | --- | --- | | Context window | Holds the information a model needs for the current request | Contains the current question, recent conversation, and retrieval results | | RAG | Retrieves external material to ground an answer | Finds product manuals and warranty policies | | Vector database | Stores vector representations and supports semantic similarity search | Supplies candidate documents or memories | | Long-term memory system | Manages storage, use, updates, and forgetting of facts and experience across sessions | Continues from confirmed customer preferences and service progress | RAG can use vector databases alongside keyword, graph, and other retrieval methods. Long-term memory can use these capabilities too, bringing information suitable for the current task into context. The model handles understanding and reasoning; the memory system continually maintains usable information. ## Follow a user fact as it changes On Monday, a user tells a travel assistant: “My nightly budget for this Shanghai trip is RMB 800.” On Wednesday, she adds: “The company will reimburse it, so raise the limit to RMB 1,200, but stay close to the venue.” On Friday, she opens a new session to continue choosing a hotel. The assistant needs to resume that trip with the latest budget and location requirements, without asking her to repeat the earlier conversations. If she asks about the initial plan, it should also be able to find the historical RMB 800 budget. Scope matters too: RMB 1,200 is the budget for this business trip, rather than a default for every future trip. Memories need task, time, and source information so later retrieval can select applicable facts. A larger context window gives the model room to understand the full history. Long-term memory lets the application maintain the trip over time and bring back the relevant details when the user returns. ## How MemOS connects the steps With [MemOS Cloud](https://memos-docs.openmem.net/memos_cloud/getting_started/overview/), developers submit conversation messages for processing and storage as memories, then retrieve them in subsequent requests. The travel example involves three steps. **Organize information by purpose.** MemOS supports [fact, preference, profile, event, skill, tool, and knowledge base memories](https://memos-docs.openmem.net/memos_cloud/introduction/memory_types/). Facts and events can capture trip requirements and arrangements; preferences help personalize recommendations; knowledge bases can supply the company's travel policy. During retrieval, applications can select memory types and combine user memories with knowledge base content to provide a fuller basis for hotel recommendations. **Keep memories aligned with changes.** MemOS [time awareness](https://memos-docs.openmem.net/memos_cloud/introduction/time_awareness/) helps retrieval distinguish current information from historical records. After the budget changes, the current task should use the new conditions; reviewing the original plan can still draw on the earlier record. Developers can [update a memory by ID](https://memos-docs.openmem.net/memos_cloud/mem_operations/update_memory/) or submit [natural-language feedback](https://memos-docs.openmem.net/memos_cloud/mem_operations/add_feedback/), such as “The budget for this trip has changed,” so the system can locate and update relevant memories. **Give users control over retained information.** MemOS Cloud offers [memory deletion](https://memos-docs.openmem.net/memos_cloud/mem_operations/delete_memory/) for specific memories or a user's memories within a project. Agent-level deletion is also available when independent agent memory is enabled. Applications can connect these operations to settings or support workflows and handle their own related copies, making memory management part of the product experience. ## Start with a task that benefits from memory For one-off document analysis, prioritize large context and on-demand retrieval. For an ongoing travel assistant, support agent, or development assistant, long-term memory helps users continue where they left off, reduces repetition, and reuses confirmed information. Choose one concrete scenario and test four actions: retrieve information across sessions, change a fact, check access boundaries between users, and delete a test memory. Observe whether subsequent answers reflect these changes to judge whether memory serves the task. Context capacity determines how much information fits into one request. When users keep working with an agent, they experience whether it can continue established plans and adapt to new requirements. Long-term memory makes that continuity a product capability that can be designed and maintained. ## About MemTensor MemTensor (Shanghai) Technology Co., Ltd. is a next-generation large-model and long-term intelligence infrastructure company incubated by the Shanghai Institute for Algorithms Innovation, with a member of the Chinese Academy of Sciences serving as chief advisor. Focused on reducing hallucinations, personalization, and self-learning and evolution, the company studies long-term memory and continual learning for large models. Its roadmap connects Memory³ research, the MemOS memory operating system, agent and memory infrastructure products, and exploration of memory-native general-purpose foundation models, progressing from theory to systems engineering and model research to advance AI beyond one-off generation toward long-term intelligence. MemTensor has established close collaborations with partners including China Merchants, Haicheng, and HONOR, and commercial deployments in AI companionship, games, smart devices, finance, and industry. It has raised nearly RMB 200 million in total, with investors including CICC, Futeng Capital, Hubble, SenseTime, and MSA Capital. --- # Why Agents Need Memory Management Even with a Vector Database (/usecase/blog/vector_database_memory_management) > **Key takeaway:** An agent learns a project's testing workflow on Monday and can reuse it when returning to the task on Friday. If the team changes the workflow on Wednesday, the agent also needs to follow that change in subsequent tasks. --- Vector databases provide a foundation for semantic retrieval. A memory architecture for continuously running agents also needs to manage how information is written, updated, shared, and retired, so past experience remains applicable to the current task. At MemTensor, we implement these requirements through MemOS memory management. The following six questions help teams review their architecture and provide a starting point for checking the user experience before launch. ## 1. What deserves to be written? A successful tool call, a confirmed project decision, or a lasting user preference can help an agent with its next task. Temporary attempts and unconfirmed assumptions need their background preserved so they are not repeatedly treated as general rules. MemOS Cloud [Add Message](https://memos-docs.openmem.net/memos_cloud/mem_operations/add_message/) accepts conversations, files, tool calls, and other inputs, automatically extracts information, and handles duplicates and conflicts with existing memories. Applications can submit messages in real time, by conversation turn, or in batches according to business needs. We organize information into [different memory types](https://memos-docs.openmem.net/memos_cloud/introduction/memory_types/). A failed test can be retained as an event, working habits as preferences, and reusable task steps as skills. This organization helps later tasks find suitable experience. ## 2. What comes back for the next task? When a user asks “How should I run the tests now?”, an agent needs the workflow applicable to the current project and enough context to complete the task. Retrieval design should consider relevance, scope, and changes over time. MemOS Cloud [Search Memory](https://memos-docs.openmem.net/memos_cloud/mem_operations/search_memory/) supports memory type selection, filters, and knowledge base retrieval. A development assistant can combine a developer's earlier issues with project testing documentation; a support agent can consult customer history alongside product manuals. During integration, inspect several real tasks: were essential facts retrieved, was irrelevant content included, and did the context sent to the model help it complete the work? ## 3. What happens to old facts when a user changes their mind? After a workflow changes, the agent should use the new procedure. Historical records still help when a user asks why a different command was used before. Memory management needs to support current work and historical review. MemOS Cloud offers two correction paths. [Update Memory](https://memos-docs.openmem.net/memos_cloud/mem_operations/update_memory/) edits a known record by ID. [Natural-language feedback](https://memos-docs.openmem.net/memos_cloud/mem_operations/add_feedback/) lets users describe changes so the system can locate and update relevant memories. Administrators can maintain content precisely, while users can correct it through conversation. Together with [time awareness](https://memos-docs.openmem.net/memos_cloud/introduction/time_awareness/), retrieval can distinguish current information from historical versions, grounding “how to do it now” and “how it used to work” in the appropriate records. ## 4. When should a memory stop being used? A memory's value changes with the task. A temporary workaround may expire when an incident is resolved, an old workflow becomes historical after an update, and a user may request deletion of personal information. Define these behaviors during product design: which content expires, which history is retained, and what users can delete at any time. MemOS Cloud [deletion](https://memos-docs.openmem.net/memos_cloud/mem_operations/delete_memory/) supports specific memories or a user's memories within a project, plus agent-level deletion when independent agent memory is enabled. Connect these operations to settings and data management workflows, and handle related summaries or caches stored by the application, so users can manage retained information. ## 5. Who can read this memory? Project testing standards can be shared within a team, while a developer's personal habits belong within that user's scope. Collaborating agents need access appropriate to their tasks and identities. MemOS Cloud [multi-user and multi-agent memory management](https://memos-docs.openmem.net/memos_cloud/introduction/isolation_filters/) distinguishes memory scopes through project API keys and user identifiers, with agent filters also available. With independent memory enabled, agents can accumulate their own long-term experience for collaboration across users and sessions. The application maps these scopes to authenticated identities and business permissions. Clear sharing rules allow team experience to be reused while protecting personal information and project boundaries. ## 6. How do you know memory helped the user? Memory's value appears in tasks: did users avoid repeating background, did the agent follow the right procedure, and did subsequent actions adapt after an update? Choose cross-session tasks and compare completion with and without memory, focusing on task success, repeated questions, and incorrect information. Add correction and deletion to see how the architecture handles everyday changes. MemOS Cloud provides [request logs and trace analysis](https://memos-docs.openmem.net/memos_cloud/getting_started/cloud_and_opensource/) to trace memory requests and processing. For local agents, the [MemOS Local Plugin management UI](https://docs.openmem.net/openclaw/local_plugin/) provides task trajectories, Analytics, and Logs views for inspecting accumulated experience. Combined with application task outcomes, these records help teams diagnose problems and improve. Start with one user journey connecting writing, retrieval, correction, isolation, and deletion. Expand to more users and agents as the scenario matures. MemOS organizes these operations into maintainable capabilities so experience from each interaction can help the next task. ## About MemTensor MemTensor (Shanghai) Technology Co., Ltd. is a next-generation large-model and long-term intelligence infrastructure company incubated by the Shanghai Institute for Algorithms Innovation, with a member of the Chinese Academy of Sciences serving as chief advisor. Focused on reducing hallucinations, personalization, and self-learning and evolution, the company studies long-term memory and continual learning for large models. Its roadmap connects Memory³ research, the MemOS memory operating system, agent and memory infrastructure products, and exploration of memory-native general-purpose foundation models, progressing from theory to systems engineering and model research to advance AI beyond one-off generation toward long-term intelligence. MemTensor has established close collaborations with partners including China Merchants, Haicheng, and HONOR, and commercial deployments in AI companionship, games, smart devices, finance, and industry. It has raised nearly RMB 200 million in total, with investors including CICC, Futeng Capital, Hubble, SenseTime, and MSA Capital. --- # Agent Memory Is Not RAG: A 2026 Production Field Guide (/usecase/blog/agent_memory_is_not_rag) An agent can retrieve a policy PDF, remember that a customer prefers concise answers, keep a workflow alive across tool calls, and query a live order system. Those are four different jobs. Calling all of them “memory” makes production design—and vendor comparison—needlessly vague. The useful distinction is simple. Retrieval-augmented generation (RAG) finds external evidence needed to answer now. Agent memory preserves useful state across turns, sessions, or workflows. A larger context window gives a model more working material for one inference; it does not itself decide what should persist, update an outdated preference, or enforce a deletion request. Oracle’s developer guidance makes the same operational point: durable memory needs explicit identity and scope, provenance, lifecycle rules, and permission-aware recall. [Oracle Developers](https://blogs.oracle.com/developers/agent-memory-is-not-rag) That is why “we have a vector database” is not an answer to “how does our agent remember?” A vector index can be an excellent retrieval component. It is not, by itself, a policy for promotion, correction, expiration, isolation, or audit. Choosing an AI memory solution starts with understanding what you need it to remember, where that information should be available, and how it should change over time. Different products approach these needs through memory APIs, temporal graphs, stateful agents, or broader memory-management systems. In this guide, we compare Mem0, Zep/Graphiti, Letta, MemOS, and Supermemory across memory lifecycle, retrieval, deployment, and application fit. We explain where MemOS fits among these approaches and outline the questions that can help you choose a solution for your workflow. The goal is to make the differences clear enough to support a practical decision, whether you are exploring AI memory or evaluating a system for production. ## Start with the four layers **Prompt context** is the bounded set of tokens visible to the model for a specific inference. It can include the current user message, system instructions, tool outputs, a running summary, retrieved documents, and selected memories. Context engineering is the process of selecting, filtering, compressing, and refreshing that set at decision time—not merely writing a better prompt. [Redis](https://redis.io/blog/ai-agent-context/) **RAG** retrieves evidence from a corpus: source documents, records, tables, or other authorized materials. Its primary obligation is grounding: use relevant, accessible, current source material and preserve enough provenance for the answer to be checked. RAG may be stateless. A good RAG pipeline uses tenant and ACL filters, document versions, chunking or structured retrieval, and citations where the user needs evidence. It is the right mechanism for “What does the current policy say?” **A vector database or vector index** stores embeddings and enables similarity retrieval; many products also provide filtering, keyword search, metadata, or hybrid retrieval. It is infrastructure, not an agent-memory policy. It can power RAG, semantic recall, or both. It does not decide whether “the user changed their preferred language yesterday” supersedes an old fact, nor does it supply a cross-session identity model. **Agent memory** is durable, scoped state selected for later use. Its units are typically preferences, facts with timestamps, task state, summaries, decisions, learned procedures, or previously validated tool results. The hard problems are not only storage and search. They are promotion (what gets saved), scope (which user, tenant, agent, thread, and permission context may retrieve it), evolution (what updates or invalidates it), and governance (who can inspect, correct, delete, or audit it). In a production stack, these layers often coexist. A support agent might assemble: current prompt instructions; a thread summary; customer memories scoped to the customer and tenant; policy citations from RAG; and real-time account status from a tool. Do not replace the last item with memory: live operational data should remain a live source of truth. ## Where MemOS fits We built MemOS to make long-term memory a manageable part of AI applications and agents. It provides a dedicated layer for retaining useful context, retrieving it when relevant, and updating it as preferences, facts, and tasks change. This supports applications that need continuity across conversations, personalized interactions, or reusable context across agent workflows. MemOS combines memory storage and retrieval with support for multiple memory types and memory scheduling. Its Cloud API provides operations for adding conversations, searching memories, updating and deleting records, and incorporating feedback to correct remembered information. Filters, tags, asynchronous processing, knowledge-base features, and chat APIs support different integration needs. You can access MemOS through our managed Cloud service, open-source framework, and supported agent integrations. These options let you choose how much infrastructure you want to operate and how closely you want to customize memory behavior for your application. [MemOS website](https://memos.openmem.net/) · [MemOS Cloud overview](https://memos-docs.openmem.net/memos_cloud/getting_started/overview/) · [MemOS API overview](https://memos-docs.openmem.net/api_docs/start/overview/) · [MemOS GitHub](https://github.com/MemTensor/MemOS) MemTensor is the company behind MemOS. We build memory infrastructure for AI applications and research long-term memory and continual learning, with the goals of reducing hallucinations, improving personalization, and helping AI systems make better use of prior experience. Our work spans Memory³ research, the MemOS memory system, agent memory infrastructure, and research into foundation models with native memory. Across these efforts, we connect research with practical systems for storing, retrieving, and maintaining useful information over time. MemOS brings this focus into applications that need to carry context beyond a single conversation. > **Product boundary: MemOS is not Memmy.** > > MemOS and Memmy address different needs within our product lineup. MemOS provides memory capabilities for AI applications and agents through APIs, open-source components, and integrations. It is suited to workflows where memory needs to become part of an application or an existing agent setup, with a choice of managed services and components you can operate yourself. > > Memmy is our personal AI agent and local memory hub. It brings together a desktop app, a local memory service, a CLI, and integrations that help individuals reuse context across supported AI tools. Its focus is the day-to-day experience of maintaining personal context and continuing work across connected agents. > > Choose MemOS when you want to add or customize memory capabilities in an application or agent workflow. Choose Memmy when you want a personal agent and local memory hub that brings supported tools together around shared context. > > [Memmy website](https://memmy.bot/) · [Memmy official GitHub](https://github.com/MemTensor/memmy-agent) ## A production selection rubric Before comparing products, write a one-page memory contract. Name the data classes you may store; the scopes that must never cross; who owns correction and deletion; the authoritative sources of truth; and the failure behavior when memory is unavailable. Then evaluate products against these seven dimensions. ### 1. Lifecycle Can the system selectively add, update, delete, expire, merge, or roll back memories? Can the application keep a raw event, an extracted memory, and the rule that promoted it separate? Look for timestamps, source references, conflict handling, retention controls, and an explicit correction path. “We embed every message” is ingestion, not lifecycle design. ### 2. Retrieval and context assembly Ask what is retrieved—documents, facts, graph edges, profiles, memory blocks, summaries, or a mix—and how filtering happens before generation. Test tenant, user, agent, conversation, time, memory type, and permission filters. Evaluate result quality and context budget together: a relevant ten-line memory may be more useful than twenty similar chunks. Retrieval should be measurable by task quality, leakage rate, recall precision, and added latency. ### 3. Deployment and data boundary Choose an operating model before choosing an SDK. Does the public documentation show a library, a self-hosted service, a managed cloud service, or multiple paths? Identify each dependency: model provider, embeddings, database, graph store, object store, telemetry service, and outbound network path. A self-hosted package does not automatically establish a complete private-deployment architecture or every enterprise control. ### 4. Governance and isolation Treat a memory read as a data access decision. Require explicit tenant, user, agent, thread or conversation, request, and permission identifiers where relevant. Define redaction and secret-exclusion rules before ingestion. Verify per-scope deletion, correction, retention, access control, and audit evidence in the exact product edition you will run. Cloudflare’s agent-memory discussion similarly frames scoped, durable state—not a growing transcript—as the operating problem. [Cloudflare](https://blog.cloudflare.com/introducing-agent-memory/) ### 5. Observability For each model turn, record the retrieval request, filters, candidate IDs, selected memory IDs, source/provenance, timestamps, token count, model response, and user feedback. Instrument promotion, mutation, deletion, and rollback separately. You need to answer: “Why was this item supplied?” and “Why was this old item still present?” without dumping sensitive memory into logs. ### 6. Ecosystem and application fit Evaluate the interfaces you will actually use: Python, TypeScript, REST, MCP, agent frameworks, tool calling, or cloud platform. Prefer an integration path that preserves your identity and authorization model. Availability of an integration is not evidence that it implements your organization’s governance policy. ### 7. Operational maturity in your environment Maturity is not a star count, a benchmark result, or a product label. Test upgrade behavior, backups, disaster recovery, model-provider failures, rate limits, schema changes, migrations, and incident support against your requirements. Public sources can establish that code, docs, or a deployment option exist; they do not establish that a product meets your particular SLA or compliance program. ## Five AI memory solutions compared ### Mem0 **Overview.** Mem0’s official repository documents a memory library, a self-hosted server, and a managed platform. The self-hosted setup uses Docker Compose and documents default-on authentication, an administrator/bootstrap flow, API keys, and a dashboard. The same repository documents Python and npm installation and a CLI with add and search commands keyed by a user ID. Its repository is published under Apache-2.0. [Mem0 repository](https://github.com/mem0ai/mem0) · [self-hosted setup](https://github.com/mem0ai/mem0/blob/main/docs/open-source/setup.mdx) **Best suited for.** Consider Mem0 when a team wants a memory-focused integration surface and can choose among library, managed, or self-hosted paths. Its documented self-hosted path gives a concrete starting point for teams that will operate their own stack; the hosted platform is a separate operating choice. **What to consider** Confirm how the extraction and retrieval configuration behaves for corrections, conflicting facts, per-tenant isolation, deletion propagation, and your own authorization model. Benchmark retrieval quality and cost with your model and data rather than assuming an SDK abstraction selects the right memory. ### Zep/Graphiti **Overview.** Graphiti and Zep are related but distinct choices. Graphiti is Zep’s Apache-2.0 open-source temporal context-graph framework; its repository documents episode ingestion, hybrid retrieval, graph-distance reranking, an MCP server, and graph-store options. Zep is a managed agent-memory service built on Graphiti. Zep’s documentation describes users and threads, context assembly, and deployment and governance options including Zep Cloud, BYOK, and BYOC. [Graphiti repository](https://github.com/getzep/graphiti) · [Zep versus Graphiti](https://help.getzep.com/zep-vs-graphiti) · [Zep concepts](https://help.getzep.com/concepts) · [Zep security and compliance](https://help.getzep.com/v3/security-compliance) **Best suited for.** Consider Graphiti when temporal relationships and graph-aware retrieval are central and the team wants to build and operate the surrounding memory service. Consider Zep when the same class of context-graph capability is wanted as a managed service with documented user/thread abstractions and enterprise deployment options. **Trade-offs to test.** Graphiti puts graph infrastructure, extraction, entity resolution, temporal invalidation, concurrency, and authorization design on the implementing team. Zep reduces some of that operating burden but introduces a commercial service, contract, and data-boundary decision. In either path, test whether time-bounded relationships improve the real task enough to justify the additional graph and ingestion complexity. ### Letta **Overview.** Letta presents a platform for building stateful agents and documents an API, Python and TypeScript clients, self-hosted base-URL use, and memory blocks that can be attached to or detached from agents. The official repository is Apache-2.0 and calls Letta an open-source project; it also documents a local CLI and an API path. The official TypeScript documentation describes sharing a block by attaching it to more than one agent. [Letta repository](https://github.com/letta-ai/letta) · [Letta TypeScript documentation](https://docs.letta.com/api/typescript) **Best suited for.** Consider Letta when memory is closely coupled to the agent runtime and an agent-centric state model—rather than an independently selected retrieval service—is the intended abstraction. Shared blocks may be useful when shared-agent context is deliberate and access-controlled. **Trade-offs to test.** Agent-attached memory can be compelling, but teams should test isolation, block sharing, edits, deletion, export, model behavior, tool state, and migration as first-class cases. Decide whether your system needs portable application-level memory independent of a single agent runtime. ### MemOS **Overview.** MemOS brings memory storage, retrieval, updates, and management into a dedicated layer for AI applications and agents. Our Apache-2.0 open-source framework supports multiple memory types and scheduling. MemOS Cloud provides APIs for memory extraction, search, updates, deletion, and feedback-based correction, alongside knowledge-based and chat capabilities. We also offer private deployment and custom integration options for enterprise needs. [MemOS repository](https://github.com/MemTensor/MemOS) · [MemOS Cloud docs](https://memos-docs.openmem.net/memos_cloud/getting_started/overview/) · [MemOS API overview](https://memos-docs.openmem.net/api_docs/start/overview/) · [MemOS website](https://memos.openmem.net/) **Best suited for.** MemOS is a strong fit for applications that need persistent context across conversations and agent workflows, with explicit control over how memories are retrieved and maintained. Choose the Cloud API for managed integration, or explore our open-source framework and agent integrations to match your setup. **Trade-offs to test.** Test the specific memory types and scheduling behaviors needed for your workload, the identity/scope fields carried through every call, lifecycle behavior under correction and deletion, integration fit, and the operational design of the selected edition. A broad memory abstraction can add flexibility; it also requires a clear policy for what is allowed to become reusable memory. ### Supermemory **Overview.** Supermemory’s official repository is MIT-licensed and documents a memory/context API, JavaScript and Python SDKs, container tags, document ingestion, semantic and hybrid search, and API-key authentication. Its public repository documents a self-hosting quick start with a local server and embedded engine, and says the SDKs can point to a self-hosted base URL. [Supermemory repository](https://github.com/supermemoryai/supermemory) · [self-hosting quick start](https://github.com/supermemoryai/supermemory/blob/main/apps/docs/self-hosting/quickstart.mdx) · [SDK documentation](https://github.com/supermemoryai/supermemory/blob/main/apps/docs/integrations/supermemory-sdk.mdx) **Best suited for.** Consider Supermemory when a team wants an API-oriented path that combines user-context patterns with document retrieval, and wants to evaluate both managed-style API usage and the documented local/self-hosted route. **Trade-offs to test.** Evaluate whether a container-tag design maps cleanly to your tenant, user, agent, and conversation boundaries. Test profile or extracted-memory freshness, document-versus-memory retrieval, deletion propagation, model/provider dependency, and the scale and persistence properties of the self-hosted design under your workload. ## A short path from comparison to decision Avoid a universal ranking. A product may be an excellent fit for one memory shape and a poor fit for another. A graph-first system can be appropriate for temporally changing relationships; an agent-runtime system for stateful agent control; a memory API for fast integration; and a broader memory operating layer for lifecycle and scheduling across several forms of memory. Run a time-boxed proof of concept with your own data contract. Give every request tenant, user, agent, thread, conversation, and request identifiers as applicable. Create known-correct facts, deliberately stale facts, conflicting updates, sensitive values that must never persist, and cross-tenant near-duplicates. Measure retrieval precision, task success, latency, token cost, write cost, deletion completion, and the ease of explaining each selected item. Include a simulated provider failure and a restore exercise. The decision is production-ready when the team can explain, for every memory: who it belongs to, why it was saved, what supersedes it, who may retrieve it, where it is stored, how it is observed, and how it is removed. RAG then remains what it should be: a companion system for source-grounded evidence, not an overloaded substitute for durable agent state. --- # Agent Memory Observability: 12 Measures That Matter After Launch (/usecase/blog/agent_memory_observability_12_measures) *A production checklist from MemTensor* An agent may return the right answer while relying on an outdated preference. It may also retrieve a record outside the caller’s authorized scope or keep using one after a correction. At MemTensor, we recommend tracing memory from the initial write through retrieval and later changes, so you can see which records reached the model and investigate the result. ## Start with the user outcome Choose a task that memory should improve: a support case resumed after a week, a coding agent applying a project rule, or an assistant using a corrected preference. Compare matched tasks with and without authorized memory. Keep the model, base prompt, tools, and scoring criteria fixed. Track task success alongside retrieval quality and latency. This connects changes in the memory system to the work the agent actually completes. ## The twelve-measure starter set We recommend the following measures for your application’s evaluation. Define the labels, sampling method, and thresholds before the pilot. | Stage | Measure | How to measure it | | --- | --- | --- | | Write | **1. Memory acceptance rate** | Share of sampled generated memories judged accurate, correctly attributed, and useful enough to retain. | | Write | **2. Duplicate write rate** | Share of newly stored records that unnecessarily duplicate an active memory. Exclude intentional historical versions. | | Write | **3. Write-to-searchable latency** | Time from write submission to the first successful retrieval by a predefined authorized query. Report p50 and p95. | | Retrieve | **4. Fact recall@k** | Distinct required facts covered by the top *k* results, divided by all required facts for the task. | | Retrieve | **5. Precision@k** | Relevant records in the top *k* results, divided by *k*. Unfilled result slots count as misses. | | Retrieve | **6. Stale recall rate** | Share of retrieved records that are obsolete for the question’s requested time. | | Retrieve | **7. Cross-scope exposure rate** | Share of scope tests that return any unauthorized memory, whether or not it appears in the final answer. | | Retrieve | **8. Read latency p95** | The 95th-percentile time from sending a retrieval request to receiving its response, segmented by workload and data size. | | Update | **9. Correction propagation time** | Time from submitting a correction until current-state queries return the new value without presenting the old value as current. | | Update | **10. Unresolved conflict rate** | Share of reviewed fact groups with incompatible current values for the same entity, attribute, scope, and effective time. | | Forget | **11. Deletion completion rate** | Requests verified complete across the declared scope by their deadline, divided by all requests due. | | Outcome | **12. Task success delta** | Difference in success rate on matched tasks with and without authorized memory, expressed in percentage points. | Set latency budgets for the workload and report failed or timed-out operations alongside successful timings. Review each scope violation and incomplete deletion individually, even when overall rates are low. ## Follow identifiers, not copies of private content Link each request to its authenticated scope, search query, returned memory IDs, injected memory IDs, answer, and feedback. For writes, updates, and deletions, record the affected memory IDs, source reference, actor, and timestamps. Keep sensitive payloads in their designated store rather than copying full conversations into telemetry. MemOS Cloud’s [asynchronous writes](https://memos-docs.openmem.net/memos_cloud/features/async_mode/) return a task ID while processing continues in the background. Use [Get Task Status](https://memos-docs.openmem.net/api_docs/message/get_status/) to track completion and identify affected memories by category. Log that completion time alongside the first successful retrieval. Our [Cloud console](https://memos-docs.openmem.net/memos_cloud/getting_started/cloud_and_opensource/) provides call logs and request-chain inspection for debugging API behavior. The [MemOS Local Plugin Viewer](https://docs.openmem.net/openclaw/local_plugin/) brings memory records, tasks, analytics, and logs into one interface for inspecting local runs. With our [open-source deployment](https://memos-docs.openmem.net/memos_cloud/getting_started/cloud_and_opensource/), you can extend service-side instrumentation in your own infrastructure. ## Three failures to rehearse before release **Try a wrong-scope read.** Exercise your application with test accounts from different users and projects, including requests with altered identifiers. MemOS Cloud’s [project and user isolation](https://memos-docs.openmem.net/memos_cloud/introduction/isolation_filters/) separates records by project API key and `user_id`. Bind those IDs to authenticated callers in your backend, then check that unauthorized requests cannot expose another scope’s records. **Correct a preference and repeat the task.** [Update Memory](https://memos-docs.openmem.net/memos_cloud/mem_operations/update_memory/) edits a known record by ID. [Add Feedback](https://memos-docs.openmem.net/memos_cloud/mem_operations/add_feedback/) interprets a natural-language correction and locates the relevant memories to update. Measure propagation against your deadline; historical records can remain available without being treated as current. **Delete a test memory and search again.** [Delete Memory](https://memos-docs.openmem.net/memos_cloud/mem_operations/delete_memory/) supports deleting selected memories or a user’s memories within the API key’s project. Agent-wide deletion requires independent Agent memory to be enabled. Query every retrieval route your application uses, and verify completion in the underlying stores covered by your deletion policy, including application copies. Start with one user journey and a small labeled task set. Expand the measurements when they help you diagnose a failure or make a release decision. --- # Choosing a MemOS Integration for Your AI Agent (/usecase/blog/choosing_memos_integration) Imagine a customer returning three days after a replacement was approved. They want to know when it will ship, and they have a new delivery address. The agent handling this conversation needs the earlier approval, the updated address, and the current shipping status from the order system. That gives you a useful starting point for choosing a memory system. You can follow a specific piece of information from the conversation where it first appeared to the task that needs it later. We built MemOS to help applications [carry context across conversations](https://memos-docs.openmem.net/memos_cloud/getting_started/quick_start/). You can connect through a managed API, run the open-source service on your infrastructure, or add memory to a supported agent through a plugin. The right starting point depends on what you’re building and how you want to operate it. ## Choose where the integration will run For an application your team is developing, the first decision is whether to use our hosted service or manage the deployment yourself. If you’re adding memory to an existing agent environment, a plugin handles the connection between the agent and its memory. | What you’re building | Where to start | What your team manages | | --- | --- | --- | | An application that needs a hosted memory service | [MemOS Cloud API](https://memos-docs.openmem.net/memos_cloud/getting_started/quick_start/) | Application integration, user identity, and how recalled memories enter the model’s context | | A service running on your infrastructure | [MemOS open-source framework](https://github.com/MemTensor/MemOS) | The service, storage dependencies, model configuration, and operations | | An OpenClaw or DeepSeek Harness setup using cloud memory | [MemOS Cloud Plugin](https://memos-docs.openmem.net/openclaw/guide/) | The agent environment and plugin configuration | | An OpenClaw, Hermes Agent, or DeepSeek Harness setup with local memory storage | [MemOS Local Plugin](https://docs.openmem.net/openclaw/local_plugin/) | The local runtime, model connections, and backups | With MemOS Cloud, we operate the memory service. Self-hosting gives you control over the code and infrastructure; our [reference Docker deployment](https://github.com/MemTensor/MemOS) runs the MemOS API alongside Neo4j and Qdrant. The plugins connect memory to the agent’s normal execution. MemOS Cloud Plugin recalls relevant memories before a run and saves new messages afterward. MemOS Local Plugin maintains SQLite storage on the machine and combines vector and lexical retrieval. It also turns execution experience into reusable policies and Skills, with a Memory Viewer for inspecting the results. Its [local configuration](https://docs.openmem.net/openclaw/local_plugin/) includes model connections and optional team sharing, which you should review when deciding where data will be processed. Once you’ve chosen a path, test the workflow you actually need. The examples below use MemOS Cloud’s interfaces. ## Decide what the next conversation needs to remember In the replacement case, the customer’s notification preference belongs with their personal history. The company’s replacement policy belongs in shared business knowledge. A procedure for checking an order and opening a replacement ticket may be useful across many customers. Our [customer service example](https://memos-docs.openmem.net/usecase/customer_service_assistant/) separates these into user memories, Agent Skills, and a policy knowledge base. That lets the agent retrieve customer context alongside general procedures while continuing to consult the order and ticket systems for current business state. MemOS Cloud provides [different memory categories](https://memos-docs.openmem.net/memos_cloud/introduction/memory_types/) for these purposes. Facts and preferences capture customer context. Event Memory preserves details about what happened, while Skills and Tool Memory capture reusable task experience. Profiles organize information into predefined fields when your application needs a structured view of a user. The setup varies by category. A Profile requires a template bound to the user. Tool Memory needs tool-call information in the input, and a knowledge base needs uploaded content. Use `allow_memory_view` to choose which categories may be generated from a write. During development, inspect what the system extracts from a few representative conversations. “Please text me when it ships” is a preference. “If I move next month, I’ll need to change my address” is conditional. Your test should check whether that condition survives extraction. For a closer look, our [memory extraction endpoint](https://memos-docs.openmem.net/self_developed_model/extraction_usage_example/) returns factual and preference candidates without writing them to the memory store. It supports synchronous extraction from text conversations, so your application can inspect the results or apply its own checks. After using the full write pipeline, inspect the stored records as well. ## Make the returning customer easy to recognize When the customer comes back through another channel, use the same `user_id`. Your application should derive that identifier from its authenticated customer record. MemOS Cloud’s [project and user scopes](https://memos-docs.openmem.net/memos_cloud/introduction/isolation_filters/) determine which personal memories a request searches. The API Key selects the project, and `user_id` identifies the customer within it. Keep the API Key on your server and connect each request to your application’s access rules. If several agents serve the same customer, you can tag memories with `agent_id` and filter by the agent that produced them. An agent can also have its own independent memory, for example to accumulate reusable support Skills. Enable **Create Independent Memory for Agent** in the project settings for that behavior; it is disabled by default. A new conversation can still use the customer’s earlier memories. The `conversation_id` supplies conversational context and can influence relevance, but it does not automatically restrict retrieval to that session. To find the information needed for the next response, our [Search Memory API](https://memos-docs.openmem.net/memos_cloud/mem_operations/search_memory/) combines keyword and vector retrieval with ranking, filtering, and deduplication. You can select memory categories with `include_memory_view`, set the number of results with `memory_limit_number`, and narrow the search using `filter`. In this case, inspect whether the search returns the replacement approval and relevant delivery details. Then check the context your application actually sends to the model. Our [application integration workflow](https://memos-docs.openmem.net/memos_cloud/getting_started/quick_start/) shows where recalled memories are added to the prompt. ## Handle the address change Information that was accurate on Monday may need updating on Thursday. MemOS Cloud’s [time-aware memory handling](https://memos-docs.openmem.net/memos_cloud/introduction/time_awareness/) supports changing states and historical questions, so current information and earlier versions can serve different requests. When importing older conversations, provide `chat_time` to preserve when the information was recorded. You also need a way to fix mistakes. If your support team knows which record is wrong, it can [update the memory by ID](https://memos-docs.openmem.net/memos_cloud/mem_operations/update_memory/), changing its content, title, or status. If the customer gives a correction in conversation, your backend can submit it through [natural-language feedback](https://memos-docs.openmem.net/memos_cloud/mem_operations/add_feedback/) with the relevant user and conversation context. Follow the operation through to completion. Cloud writes use [asynchronous processing](https://memos-docs.openmem.net/memos_cloud/features/async_mode/) by default. Use the returned `task_id` to check `get/status`; a completed task includes a summary of memory changes. Then retrieve the affected information again and confirm that the next response uses the updated address. For the shipment itself, your application should still verify the address and order status through the business system before taking action. ## Be specific about deletion If the customer asks to remove their history, decide which records the request covers. Our [`delete/memory` endpoint](https://memos-docs.openmem.net/memos_cloud/mem_operations/delete_memory/) accepts one of three targets per call: specific `memory_ids`, a `user_id`, or an `agent_id`. Each operation stays within the API Key’s project. Agent-wide deletion requires independent Agent memory to be enabled. That endpoint does not accept a conversation ID or knowledge base ID as a deletion target. Knowledge Base files have a [separate deletion endpoint](https://memos-docs.openmem.net/api_docs/knowledge/delete_kb_doc/) that accepts `file_ids`. After deleting, repeat the relevant searches. Include any copies your application keeps in caches, exports, or logs when defining the full deletion workflow. ## Try the whole case before rolling it out Use the same replacement scenario throughout your pilot. A few variations will tell you more about the integration than a collection of unrelated prompts. 1. **Return in a new session.** Record the approval, then open another conversation for the same customer. Check whether the agent can continue the case without asking for information already provided. 2. **Change a detail.** Update the delivery address or switch the notification preference from email to text. Inspect the stored change and the next response. 3. **Include a conditional statement.** Try “If I move to Seattle, I’ll need to update my address.” Check that a possible move has not become a confirmed address change. 4. **Use another customer account.** Repeat the question as a different user. Inspect the request’s identity mapping and make sure the original customer’s personal information is absent. 5. **Remove the test records.** Delete the intended memories and search again. If the workflow uses Knowledge Base files, test their removal separately. Track how long new information takes to become retrievable, along with p95 latency, token usage, and time spent investigating failures. Compare task outcomes with and without memory: whether the agent gives the correct next step, how often the customer has to repeat themselves, and whether corrections carry into later conversations. Keep a short record of the configuration, results, and issues still to resolve. That record should make it clear why the chosen deployment fits your application. Our [Cloud quick start](https://memos-docs.openmem.net/memos_cloud/getting_started/quick_start/) walks through the first write and retrieval. If you’re running the service yourself, begin with the [self-hosting instructions](https://github.com/MemTensor/MemOS). Bring one complete customer case through the integration before expanding to more workflows. --- # Claude Made Memory Editable. Production Agents Still Need a Governed Memory Layer (/usecase/blog/claude_editable_memory_governed_layer) Claude’s memory updates are a meaningful marker in the evolution of AI products: memory is becoming visible, categorized, editable, and subject to an explicit sensitive-topic setting. That is a material improvement in user control. It is also a useful reminder that a production agent needs more than a model-specific memory feature. It needs a governed memory layer. An assistant’s built-in memory helps it retain context within the app. Here, a governed memory layer means a service with explicit rules for what gets stored, who can retrieve it, and how it is updated or deleted. Applications with multiple users or tenants may also need access controls and change history tied to those boundaries. Anthropic’s release notes make the product change concrete. On July 10, 2026, Claude memory changed from a daily summary to individual categorized entries that Claude reads and updates in conversations. On August 25, memory was extended across Chat and Cowork in the cloud; remembered items became editable or deletable as Topics; health and beliefs were excluded unless a user enabled sensitive topics; and the feature was listed as on by default for Free, Pro, and Max, and off by default for Team and Enterprise organizations. Those are real controls, not cosmetic ones. [Anthropic’s release notes](https://support.claude.com/en/articles/12138966-release-notes) are the appropriate record of what has been publicly announced. But editable memory is not, by itself, a portable enterprise memory layer. A production system may use multiple models, agent frameworks, tools, knowledge sources, identity systems, and deployment environments. It must retain context without turning every past interaction into an unscoped, permanent prompt attachment. The implementation question is therefore larger than “does the assistant remember?” It is “can the organization govern remembered state throughout its life?” ## Why editability changes the conversation Memory was often treated as a background mechanism: useful when it worked and hard to inspect when it did not. Editable Topics change that expectation. They acknowledge three operational truths. First, a memory can be wrong. A preference can change, a project decision can be reversed, and an automatically generated summary can flatten an important qualification. Editing and deleting therefore make memory correctable rather than merely persistent. Second, memories vary in sensitivity. Anthropic’s setting for sensitive topics is a product-level example of a broader design requirement: Applications need explicit rules for which information may be saved as long-term memory and which requires additional consent or should be excluded. Third, organization-level defaults matter. A user feature may be helpful, while an enterprise still needs an administrator-controlled starting point, defined ownership, and evidence that retrieval respected the relevant boundary. The Team and Enterprise default described by Anthropic is an illustration of how memory decisions become organizational, not only personal. This is a welcome direction. Yet production systems cannot stop at a settings page. They must answer questions that emerge when memory is shared across agents, connected to tools, or retained longer than a single conversation. ## A feature is not a governed data layer “Portable” here does not mean that every memory should be copied everywhere. It means that the organization can govern memory independently of any one chat surface or model runtime, using explicit interfaces and policy. A portable layer should make a memory’s boundaries and handling rules intelligible when the agent changes, the session ends, or the model provider changes. Oracle’s developer guidance offers a useful separation: retrieval-augmented generation (RAG) retrieves documents or data to ground an answer, whereas agent memory persists useful state across interactions. RAG should preserve source evidence; memory may retain scoped preferences, decisions, summaries, task state, and tool results when they remain valid and allowed. Oracle also stresses that memory should be correctable and deletable, and that scope should use explicit user, tenant, agent, and conversation identifiers rather than a user ID alone. [Oracle Developers’ “Agent Memory Is Not RAG”](https://blogs.oracle.com/developers/agent-memory-is-not-rag) is direct on both the distinction and the operating implications. That separation produces a practical design rule: > Use RAG for source-grounded evidence and live knowledge. Use durable memory for scoped state that has been deliberately promoted, remains useful, and is permitted to be recalled. Neither component replaces the other. An agent preparing a customer response may retrieve the current policy document through RAG, recall a customer’s approved communication preference from memory, and query a live system for order status. Treating all three as “context” hides different update, provenance, and authorization rules. ## What to define before adding persistent memory The following is a reference workflow for application design, not a description of a specific MemOS deployment. Verify which controls the selected product provides and which the application must implement. ```text Conversation or tool result | v Decide what to save |----> discard, redact, or keep for this session v Stored memory (content, owner, source, timestamps, status) | |----> update or delete under application rules v Retrieve within the caller's allowed scope | v Agent context ``` The capture path is not an invitation to store every turn. It is a filter. A production design should distinguish a transient observation from a candidate memory, and a candidate from an approved durable record. For example, “the user is having a bad day” may be transient and sensitive; “the user prefers a weekly project summary in plain English” can be useful, scoped, and reviewed under a defined policy. The record itself needs more than text and an embedding. At minimum, it should carry a memory identifier; owner and tenant; agent, thread, or conversation scope where relevant; category; source or provenance; creation and last-confirmed timestamps; status; retention or expiry rule; and the permission context required for recall. A correction should create a discernible lifecycle event, not silently overwrite the reason an earlier fact was used. A deletion request should be testable from request through removal or tombstone, including derived indexes where applicable. At recall time, relevance is necessary but insufficient. The retrieval path should first apply the caller’s authority and purpose, then retrieve within the allowed scope, then make clear which memory was selected and why. This is the difference between “the agent found a related sentence” and “the system can account for the state it injected into an action.” ## A lifecycle, not a scrapbook Long-lived agent memory has a lifecycle. Designing it explicitly prevents both accidental amnesia and accidental accumulation. 1. **Capture.** Receive a conversation event or tool result with the identity and session context that produced it. 2. **Classify.** Identify its type: preference, task state, decision, validated fact, summary, or sensitive/transient content. 3. **Promote or reject.** Apply a policy for durability, sensitivity, consent, and expected usefulness. Some information should remain session-only; secrets should not be stored as agent memory. 4. **Scope and annotate.** Bind the record to the permitted user, tenant, agent, thread, conversation, or domain scope, and attach provenance and timestamps. 5. **Retrieve selectively.** Match the current task against allowed memory; avoid broad, automatic retrieval that increases noise, latency, or cross-boundary exposure. 6. **Correct, supersede, or provide feedback.** Let authorized users and operators revise false or obsolete state. Preserve enough event history to explain the transition. 7. **Expire or delete.** Enforce retention rules and deletion requests across the memory’s usable representations. 8. **Audit and measure.** Record writes, recalls, policy outcomes, and lifecycle actions. Evaluate whether memory actually improved the workflow enough to justify its cost and risk. Oracle makes two points that align with this lifecycle: promotion should be deliberate, and memories need provenance and timestamps. It also recommends defining storage scope and promotion, update, delete, and retrieval rules before wiring memory into an agent loop. [Its implementation guidance](https://blogs.oracle.com/developers/agent-memory-is-not-rag) is sensible even when the underlying platform differs. ## What is public about Claude memory — and what is not established It is important not to infer a product architecture from a release note. The following table separates announced behavior from questions a production buyer should still ask. |Publicly announced by Anthropic|Not established by the cited release notes| |---|---| |Categorized memory entries replaced daily summaries on July 10, 2026.|A cross-provider or cross-model export and portability contract.| |Memory works across Chat and Cowork in the cloud.|An enterprise memory schema that an organization can operate independently of Claude’s product surfaces.| |Users can edit or delete remembered Topics.|The complete retention, deletion-propagation, audit, and provenance semantics an external production workflow may require.| |Sensitive topics are excluded unless the user enables the setting.|A general-purpose policy engine for every organization’s data classifications and business purposes.| |Team and Enterprise memory is off by default.|How any particular organization should configure memory for its risk profile.| The right-hand column is not a claim that these capabilities do not exist elsewhere in Anthropic’s products or documentation. It is a discipline: do not represent them as established by the specific public release notes cited here. Architecture and procurement decisions should be based on verified product documentation, contracts, and a scoped technical evaluation. ## Where MemTensor and MemOS fit in this discussion MemTensor builds memory infrastructure for AI applications and researches long-term memory and continual learning. Its work includes Memory³ research, the MemOS memory system, and research into foundation models with native memory. The broader goal is to help AI applications retain useful context, support personalization, and make better use of information over time. MemOS is a memory system for AI applications, designed to help them retain useful context across conversations and tasks. Its Cloud API supports turning conversations into memories, retrieving relevant information, updating and deleting records, and correcting memories through feedback. These capabilities can help applications remember preferences and carry relevant context into later interactions. MemOS also offers managed Cloud and open-source deployment options. See the [MemOS Cloud overview](https://memos-docs.openmem.net/memos_cloud/getting_started/overview/) and [API overview](https://memos-docs.openmem.net/api_docs/start/overview/) for the public product record. For users, well-managed memory can mean less repetition and better continuity as preferences and projects change. For the applications they use, a separate memory layer provides a way to manage that context over time, with explicit operations for retrieval, updates, and deletion. ## A governance checklist for production agents Before enabling durable memory in an agent workflow, a team should be able to answer these questions in writing: - **Purpose:** What decision or workflow does each memory category support? What must never be retained? - **Scope:** Which combinations of user, tenant, agent, project, thread, and conversation are allowed to write and recall it? - **Promotion:** Who or what can convert an interaction into durable memory? What review or confidence rule applies? - **Provenance:** Can an operator identify the source event, tool result, policy version, timestamps, and last confirmation for a recalled item? - **Permissions:** Is recall evaluated using the same identity and authorization context as the underlying business data? - **Sensitivity:** How are secrets, regulated fields, and sensitive personal topics rejected, redacted, or subject to explicit consent? - **Correction:** Can the subject or an authorized operator edit, supersede, or contest a memory without creating a new hidden inconsistency? - **Deletion and retention:** What is the retention schedule, and how is deletion verified in records, indexes, caches, and downstream representations? - **Observability:** Are memory writes, retrievals, and policy denials logged so that an agent action can be reconstructed? - **Evaluation:** Does the team measure both the benefits of recall and failures such as stale recall, irrelevant recall, and scope leakage? The checklist is deliberately operational. A strong memory experience should feel simple to users; that simplicity is earned by precise handling underneath. ## The implication of Claude’s update Claude’s editable memory is news because it puts control over remembered state closer to the user and treats memory as a collection of items rather than an opaque daily artifact. That direction raises the baseline for every agent experience. As AI becomes part of everyday work, useful memory can reduce repetition and keep relevant context available over time. Claude’s updates show the value of making that memory easier to manage. MemOS brings memory capabilities to other AI applications, helping them retain and reuse context across interactions. The practical question is what an application remembers, where it uses that information, and how users can keep it accurate. --- # How to Keep Bad Assumptions Out of Agent Memory (/usecase/blog/keep_bad_assumptions_out_of_agent_memory) > Standfirst: Retrieval quality cannot repair a memory that was wrong when written. Production agents need an admission layer that distinguishes user statements, environment facts, model inferences, procedures, and high-impact state before any of them become durable memory. MemTensor's MemOS provides an operating-layer architecture in which those lifecycle controls can be made explicit. --- An agent may carry a mistaken assumption from one task into the next. Checking what it learns, keeping the source, and revisiting memories when conditions change can help prevent that mistake from spreading. MemOS gives developers tools to support this work, from processing new information to correcting existing memories. When an agent gives a wrong answer, it is natural to inspect what it retrieved. The problem may have started earlier, with a memory built from an incomplete observation or a conclusion that was never checked. In [*Grounding Agent Memory: Environment-Probing Curation for Enterprise Agents*](https://arxiv.org/html/2609.11060v1), Microsoft researchers gave a memory curator read-only access to the environment after a task ended. It could check uncertain claims and revise or skip records before later tasks used them. In the paper's 40-question CLBench experiment with schema changes, using GPT-5.4 in a GitHub Copilot SDK harness, the system with memory and environment probing reached a mean pass rate of 73%. The system with memory alone reached 70%, while the no-memory baseline reached 39%. Adding probing to the memory system also reduced average queries per question from 5.6 to 4.7 and task-agent cost from $1.99 to $1.68. These costs exclude the separate distillation and curation stages. Those results describe the researchers' setup. They raise a practical question for developers building with memory: what should an agent check before passing something it has learned to the next task? ## A useful observation can become a misleading rule Consider a database agent that finds the records it needs in a table called `customers_current`. It finishes the task and saves a note saying, "Use customers_current for active accounts." The query may have worked for one region or reporting period. The saved note leaves those conditions out, so another agent could apply it to a much broader question. Checking the table definition and the relevant business rules would help establish where the advice holds. Even a carefully checked note can become outdated. A month later, the table might be replaced by a compatibility view that updates less frequently. Future agents need a way to recognize that change and update the memory. Similar problems arise when an agent keeps recommending an API workaround after a fix, saves a temporary approval process as a permanent procedure, or records a failed command as a successful solution. A policy can lose its effective date during summarization. A rule for one customer can become advice for every customer. In each case, the memory is missing something a future task needs: evidence, conditions, or an update. Retrieval can find the note, but the agent still needs enough information to judge whether it applies. ## Check the claim before making it reusable A memory workflow often starts with a conversation or task history, extracts useful information, and saves it for later retrieval. A verification step can check the extracted claims before they become reusable advice. The original conversation and tool results can still be retained as evidence. The decision is which conclusions to make available to future tasks, and with what limits. Keeping that distinction also allows a team to inspect how a summary was produced if something goes wrong. The check should match the information being saved. | Information | What to check | |-----------|-------------| | A user statement or preference | Keep who said it, when, and the relevant context. "I prefer concise weekly summaries" can be recorded directly and changed when the user updates it. | | A fact about the environment | Check the relevant system, such as a schema, repository, API specification, or policy document. Record the version or time observed. | | An agent's inference | Preserve the evidence and identify the conclusion as an inference. "This customer may be price-sensitive" should remain distinguishable from something the customer explicitly said. | | A procedure or skill | Keep its prerequisites and the evidence that it worked. Use a test or acceptance condition appropriate to the procedure. | Sensitivity and impact apply across these categories. A preference about report length needs less review than a remembered procedure that could change access permissions or authorize a payment. Read-only checks are often enough to resolve uncertainty. A coding agent can inspect a symbol definition, and a database agent can examine a schema or query a limited sample. Procedures with side effects need a suitable test environment or other evidence of a successful result. ## How MemOS supports the workflow [MemOS](https://github.com/MemTensor/MemOS) provides operations for adding, finding, correcting, and removing memories. Developers can use these operations alongside checks against their own business systems. The application chooses the authoritative source and implements the environment checks described above. ### Keep the source with the memory In the open-source service, [MemReader](https://memos-docs.openmem.net/open_source/modules/mem_reader/) processes conversations, documents, and images into memory items with source information. Developers can use the Add API's [metadata](https://memos-docs.openmem.net/api-reference/add-memories/) to attach details such as the source location and application-supplied validation results. For the database example, this could include the schema version, the time it was checked, and the business context in which the table should be used. If a later answer looks wrong, the team has a starting point for investigating it. The verification step needs to cover the extracted claim. Checking an input document alone can miss an error introduced when the system turns that document into a shorter memory. ### Keep preferences and inferences distinguishable MemOS Cloud's [memory extraction API](https://memos-docs.openmem.net/api_docs/core/extract_memory/) distinguishes explicit preferences from preferences inferred from behavior and returns the reasoning behind them. That distinction helps an application handle "I prefer budget hotels" differently from a guess based on one booking. Developers can decide whether the inferred preference is useful for a recommendation or needs confirmation before affecting a more consequential action. ### Update memories as information changes MemOS Cloud supports conflict and duplicate handling as part of [memory maintenance](https://memos-docs.openmem.net/changelog/). Its [time-aware memory handling](https://memos-docs.openmem.net/memos_cloud/introduction/time_awareness/) preserves changing states so retrieval can distinguish a current fact from an earlier one. These features help process changes that reach the memory system. In the database example, the application still needs to detect the schema change or provide the new evidence. It can then use [feedback](https://memos-docs.openmem.net/memos_cloud/mem_operations/add_feedback/) to correct the remembered advice, or update or remove the affected entry through the relevant memory operations. ### Choose where a memory can be used The open-source service organizes memories in [MemCubes](https://memos-docs.openmem.net/open_source/modules/mos/overview/). Requests can specify cubes to read from or write to, allowing an application to keep project memories separate or make selected information available across agents. The application must connect these choices to its authorization rules. Session context has a different role. In the open-source [Search API](https://memos-docs.openmem.net/api-reference/search-memories/), `session_id` helps prioritize relevant memories; it is not a hard boundary between sessions. ### Check the result of background work Memory writes and corrections can run in the background. The open-source service provides [scheduling and status operations](https://memos-docs.openmem.net/open_source/modules/mos/overview/) to track that work. With MemOS Cloud, the [task-status API](https://memos-docs.openmem.net/api_docs/message/get_status/) reports processing status and, on completion, the affected memory IDs and a summary of what changed. This gives applications a way to follow a submitted operation through to its result. They can inspect the affected memories and check what subsequent searches return. ## Put the checks into a working flow Start with one kind of memory whose accuracy matters to the task, such as database guidance or a frequently reused support procedure. 1. **Extract the candidate.** Identify the claim or procedure worth keeping and retain its source. 2. **Check the evidence.** Inspect the authoritative system and test the conditions the candidate depends on. If the evidence is incomplete, narrow the claim or hold it for review. 3. **Save the conditions with it.** Include where it applies, when it was checked, and what should trigger another check. Make only approved candidates available for reuse. 4. **Inspect the result.** After writing or correcting a memory, check the operation's outcome and the records available to later tasks. 5. **Revisit it when its source changes.** A schema migration, policy revision, or API change should prompt a review of memories that depend on it. For `customers_current`, a useful record would include the applicable region and reporting period, the evidence behind the recommendation, and the schema version checked. A migration affecting that table gives the application a concrete reason to review the record. ## Follow the memory into the next task Teams also need to see whether the process is helping. The following questions can guide monitoring across the application and its memory service. | Stage | What to inspect | |-----|---------------| | Candidate review | Which sources produced candidates, what evidence was checked, and why a candidate was accepted, revised, or rejected | | Write | Which records were added or changed, where they were saved, and whether processing completed | | Retrieval | Which memories were returned and which were actually included in the model's context | | Use | Task completion, repeated errors, user corrections, and results compared with a no-memory baseline | | Maintenance | Entries affected by changed sources, overdue checks, and corrections that have reached later searches | | Deletion | Whether removal completed in the memory store and any application-managed copies or caches | Linking these records makes failures easier to investigate. A retrieved memory may never have reached the model, and a memory included in the prompt may not explain the action that followed. The trace gives the team evidence to examine; testing is still needed to establish the cause. For a first evaluation, save a checked memory, use it in a later task, then change the underlying information. Confirm that the correction appears in subsequent retrieval and that the agent completes the task with the updated information. This exercises the part of memory that matters in ongoing work: carrying useful knowledge forward while keeping it open to correction. ## About MemTensor and MemOS MemTensor develops memory infrastructure for AI applications and agents. Our work spans [Memory³ research, MemOS, agent-memory infrastructure, and research into models with native memory](https://memos-docs.openmem.net/usecase/blog/agent_memory_is_not_rag/). MemOS brings this work into applications through APIs, open-source components, and integrations for storing, retrieving, and maintaining information across tasks. --- # Persistent Agent Memory Should Make the Next Task Easier (/usecase/blog/persistent_agent_memory_next_task) *How we think about continuity, correction, and boundaries at MemTensor* Suppose a team discovers on Tuesday that integration tests fail unless the database is started first. On Friday, another agent picks up a related task. It needs the confirmed setup procedure, including when it applies. When the team changes that procedure, the stored instruction needs to change with it. That is the experience we are building toward with MemOS: useful knowledge that carries over between tasks and stays open to correction. ## A large context window is not a memory policy A larger context window gives an agent more material to read. The application still needs to decide what to retain, who can reuse it, and how to handle updates. In the testing example, the failure is an event. The confirmed setup sequence is a reusable procedure, with the relevant environment and conditions attached. MemOS Cloud [organizes memory by type](https://memos-docs.openmem.net/memos_cloud/introduction/memory_types/) so these records can serve different purposes. Event memories retain details such as when something happened; skills capture reusable task steps. Facts and preferences provide context about the user. You can control which categories are generated and which are included in a search. ## Continuity is a four-step loop **Capture.** Through [Add Message](https://memos-docs.openmem.net/memos_cloud/mem_operations/add_message/), MemOS Cloud extracts memories from conversations, checks for duplicated or conflicting information, and updates existing records when needed. You can attach custom metadata, such as the source and environment, using `info`. For Tuesday’s test run, submit the discussion that confirms the setup sequence and identifies where it applies. The metadata also gives your application fields to filter on later. **Retrieve.** [Search Memory](https://memos-docs.openmem.net/memos_cloud/mem_operations/search_memory/) combines keyword and vector retrieval, ranks memories by relevance, and removes duplicate results. Filters narrow the results by tags, time, Agent, or custom metadata. Memory-type selection lets you include skills, while a result limit controls how many memories are returned. For Friday’s task, retrieve the relevant testing instructions and pass them to the model with the current request. **Correct.** Suppose the team introduces a script that starts the database automatically. If you know which record needs changing, [Update Memory](https://memos-docs.openmem.net/memos_cloud/mem_operations/update_memory/) lets you edit it by ID. With [natural-language feedback](https://memos-docs.openmem.net/memos_cloud/mem_operations/add_feedback/), a user can describe the new procedure, and MemOS locates and updates the relevant memories. For changing facts and preferences, our [time-awareness mechanism](https://memos-docs.openmem.net/memos_cloud/introduction/time_awareness/) maintains historical versions and uses time cues in a query to distinguish current information from earlier states. **Stop using or delete.** An outdated procedure can be archived through the update API. [Delete Memory](https://memos-docs.openmem.net/memos_cloud/mem_operations/delete_memory/) supports removing specific memories or clearing a user’s memories within the API key’s project. Include any copies kept in application caches or summaries in your deletion workflow. ## Sharing needs an owner Before sharing a procedure across agents, decide who maintains it and which users or projects should be able to use it. MemOS Cloud’s [isolation controls](https://memos-docs.openmem.net/memos_cloud/introduction/isolation_filters/) separate memory by project and user. Agent filters narrow a user’s records to a particular Agent; enabling independent Agent memory gives that Agent its own long-term memory across users and conversations. Map `user_id` values to authenticated users in your backend. A `conversation_id` influences retrieval context and does not enforce access control. For shared setup guides, our [knowledge bases](https://memos-docs.openmem.net/memos_cloud/features/knowledge_base/) turn uploaded documents into searchable memory that can be retrieved alongside user memory. A task can then combine the team’s documented procedure with context from earlier interactions. In supported agent hosts, [MemOS Local Plugin](https://docs.openmem.net/openclaw/local_plugin/) stores memory in a local SQLite database and connects capture and retrieval to the host’s task lifecycle. It records conversations, tool calls, and feedback after a task, then supplies relevant context before the next one. Recurring patterns can develop into reusable skills. To check this in your application, use three sessions: establish the procedure, have an authorized agent apply it, then change it and ask again. Repeat the request from a different project and after deletion. Inspect the retrieved memories and the context passed to the model, alongside its answer, to spot stale instructions or scope errors. --- # MemOS 概览 (/cn/memos_cloud/getting_started/overview) MemOS 是面向 AI 应用与 Agent 的记忆托管平台。把信息写入 MemOS,系统会自动生成、召回和更新记忆,在后续请求中持续为 AI 提供精简、准确的上下文。 你不需要重复解决“AI 如何记忆”的问题,调用云服务接口,即可接入长期记忆能力。 ## MemOS 带给你什么? - **让 AI 长期连续**:跨会话保留用户事实、偏好和任务进展,让 AI 不再每次从零开始。 - **记忆始终有用**:持续抽取、去重、更新和修正记忆,保证记忆准确、有效。 - **降低工程成本**:生产级记忆平台,托管生产、调度、召回与生命周期管理的全流程,降低自建记成本。 - **扩展能力**:支持知识库、Skill、工具记忆、多模态和 Agent 工作流,覆盖更多业务场景。 ## 核心工作流程 ![MemOS 如何工作](https://cdn.memtensor.com.cn/img/1779180005737_hr407r_compressed.png) ### 添加原始信息 把用户聊天、行为事件、知识文件、图片、技能等一系列原始信息传入给 MemOS。 ### 生成并更新记忆 MemOS 会在后台把原始信息加工成可检索的记忆内容,并持续自动更新、实时调度、基于自然语言反馈修正记忆,管理记忆的全生命周期。 ### 检索记忆 在检索记忆时,MemOS 筛选并召回最相关的记忆,用于模型回答、Agent 决策或业务流程,让 AI 在后续请求中保持连续理解。 ## 选择如何开始 - [快速开始](/cn/memos_cloud/getting_started/quick_start): 从这里开始创建第一个项目 - [MemOS 工作原理](/cn/memos_cloud/introduction/mem_production): 想要先理解 MemOS 的记忆机制 - [云服务与开源方案](/cn/memos_cloud/getting_started/cloud_and_opensource): 没想好使用云服务还是开源自部署?先看这里 - [在 Agent 中使用](/cn/memos_cloud/getting_started/agent_usage): 接入 OpenClaw、Hermes 或其他 AI 工具 --- # 云平台与开源方案 (/cn/memos_cloud/getting_started/cloud_and_opensource) ## 1. 最适合你的 MemOS 方案 MemOS 为 AI 应用提供了两种“记忆”解决方案。您可以选择: * MemOS 云平台 ——简化开发,轻松管理:5分钟内一键使用云服务,适合 AI 应用快速搭建与迭代。 * MemOS 开源方案 —— 自主部署,完全可控:部署到自有环境,根据业务需求二次开发与深度集成。 > _无论是 云服务 还是 开源框架,MemOS 都能让你的 AI 轻松获得持久记忆。_ > _你可以先用云服务快速体验,再根据业务需要切换到本地化部署。_ ## 2. 选择指南 ### 选择 MemOS 云平台 * **快速落地**:仅需几分钟,即可让你的 AI 应用具备自带记忆。你可以专注于业务逻辑与功能实现,无需投入时间维护复杂的存储与记忆管理体系。 * **零成本验证**:提供充足的免费试用额度,帮助你以最低成本验证方案可行性与产品效果。 * **日志与监控**:在控制台中实时查看调用日志,获取完整的调用链分析,便于调试、监控与性能优化。 * **高级功能**:知识库与持续对话能力全量开放于 API,实现更灵活的自定义与深度集成。 ### 选择 MemOS 开源方案 * **自定义配置**:可自由选择 LLM 提供商、推理后端、部署策略等,实现更高的灵活性与可控性。 * **代码扩展**:可直接修改代码库,按需扩展自定义功能,并将改进贡献回社区。 ## 3. 还未确定? * [试用免费平台](/cn/memos_cloud/getting_started/quick_start):注册并登录 [MemOS 云平台](https://memos-dashboard.openmem.net/cn/quickstart),免费试用所有功能。 * [探索开源方案](/cn/open_source/getting_started/installation):克隆项目仓库,直接在本地运行试用。顺便点个 Star 支持我们吧! --- # 在 Agent 中使用 (/cn/memos_cloud/getting_started/agent_usage) 除了自行接入云服务接口,如果你正在使用: - OpenClaw、Hermes 等 Agent 框架 - Cursor、VS Code、Claude Desktop 等 AI 客户端 - 任何可以执行命令行的 Agent 或开发环境 可以通过 MemOS 插件、MCP、CLI 等形式,将 MemOS 接入到你的 AI 工作流中,节省 Token,同时提升长期记忆能力。 ## 前期准备 - 注册并登录 MemOS 云平台 [(点击注册)](https://memos-dashboard.openmem.net/quickstart) ## 快速接入(推荐) 你可以通过与Agent自然对话的方式自动接入 MemOS,接入完成后即可进行对话,无需其他操作。 ### 接入插件 MemOS 目前提供深度适配 **OpenClaw** 的云服务插件,如果你正在使用 OpenClaw,优先考虑插件接入。将以下提示词复制并粘贴到你的 OpenClaw 聊天中: **展开查看 OpenClaw 插件配置提示词** ```text api-key=用户提供的Key 帮我配置 MemOS OpenClaw 插件,按以下步骤执行: 1. 确认 API Key 检查第 2 步命令中 MEMOS_API_KEY 的值: - 如果已是以 mpg- 开头的真实 API Key,直接进入第 2 步 - 如果是中文占位符,引导用户打开 https://memos-dashboard.openmem.net/cn/quickstart/ 获取 API Key,并用真实 Key 替换命令中的占位符 2. 配置 API Key 环境变量 首先检测当前操作系统,然后按对应方式写入: macOS / Linux: mkdir -p ~/.openclaw echo 'MEMOS_API_KEY=用户提供的Key' >> ~/.openclaw/.env Windows PowerShell: [System.Environment]::SetEnvironmentVariable("MEMOS_API_KEY", "用户提供的Key", "User") 3. 安装并启用插件 openclaw plugins install @memtensor/memos-cloud-openclaw-plugin@latest openclaw gateway restart 4. 验证安装 读取 ~/.openclaw/openclaw.json(Windows 为 %USERPROFILE%\.openclaw\openclaw.json), 确认 plugins.entries 下 memos-cloud-openclaw-plugin 的 enabled 为 true ``` OpenClaw 会安装插件,并提示你获取 API Key,完成所有配置。 ### 接入 MemOS CLI MemOS CLI 提供更通用的 Agent 交互方式,适合任何可执行命令行的 Agent 框架,将以下提示词复制并发送给你的 Agent: **展开查看 CLI 配置提示词** ```text api-key=用户提供的Key 帮我配置 MemOS CLI 开发环境,按以下步骤执行: 1. 安装 MemOS CLI 到全局 npm i -g @memtensor/memos-cloud-cli 2. 初始化 CLI 配置 memos init --api-key 用户提供的Key --agent 执行第 2 步时,根据当前用户使用的 Agent 传入对应的 --agent 参数。 若 --api-key 的值已是以 mpg- 开头的真实 Key,直接执行;若是中文占位符, 先引导用户打开 https://memos-dashboard.openmem.net/cn/ 获取 API Key 并替换。 ``` Agent会自动完成 MemOS CLI 的安装,并配置相应的Skill。([查看支持的Agent](/cn/mcp_agent/cli/guide#_31-在-agent-中使用)) ## 手动配置 ### 1. 调用前准备 - 获取 API Key [(点击获取)](https://memos-dashboard.openmem.net/apikeys) ### 2. 使用插件 #### 配置 API Key 插件会读取 OpenClaw 相关的环境变量或 `.env` 文件。最小配置如下: ```env MEMOS_API_KEY=YOUR_API_KEY ``` 也可以直接写入 OpenClaw 的环境文件: ```bash [macOS / Linux] mkdir -p ~/.openclaw echo 'MEMOS_API_KEY=YOUR_API_KEY' >> ~/.openclaw/.env ``` ```powershell [Windows PowerShell] [System.Environment]::SetEnvironmentVariable("MEMOS_API_KEY", "YOUR_API_KEY", "User") ``` #### 安装并启用插件 ```bash openclaw plugins install @memtensor/memos-cloud-openclaw-plugin@latest openclaw gateway restart ``` > **Tip**: Windows 用户如果遇到 `Error: spawn EINVAL`,可以查看 [OpenClaw 云插件 - 手动安装](/cn/openclaw/guide) 使用替代安装方式。 确认 `~/.openclaw/openclaw.json` 中插件已启用: ```json { "plugins": { "entries": { "memos-cloud-openclaw-plugin": { "enabled": true } } } } ``` #### 开始对话 现在,可以与你的 OpenClaw 进行多轮对话: - 第一次会话:「我偏好使用 Python 语言」 - 第二次会话(新启动):「你还记得我喜欢用什么编程语言吗?」 > **Tip**: OpenClaw 插件还有多 Agent 隔离、Config UI、过滤和更细的配置项。完整配置请查看 [OpenClaw 云插件](/cn/openclaw/guide)。 ### 3. 使用 MCP 支持 MCP 的主流客户端,例如 **Cursor、Claude Desktop、Cline、VS Code / Trae 和 Chatbox** 等。以 Cursor 为例,配置完成后,Cursor 可以直接调用 MemOS 提供的记忆操作工具,实现跨客户端的记忆。 #### 添加 MCP Server 在 Cursor 中进入: ```text Cursor Settings → Tools & MCP → Add Custom MCP ``` 然后在 `mcp.json` 中添加: ```json { "mcpServers": { "memos-api-mcp": { "timeout": 60, "type": "stdio", "command": "npx", "args": [ "-y", "@memtensor/memos-api-mcp@latest" ], "env": { "MEMOS_API_KEY": "YOUR_API_KEY", "MEMOS_USER_ID": "your-user-id", "MEMOS_CHANNEL": "MODELSCOPE" } } } } ``` 配置后,确认 Cursor 的 MCP 工具列表中能看到 `add_message`、`search_memory` 等工具。 #### Cursor Rules 为了让 Cursor 更稳定地使用记忆,建议在 User Rules 中加入: ```text 回答用户问题前,先调用 MemOS 的 search_memory 搜索与当前任务相关的长期记忆。 回答完成后,如果本轮对话出现新的用户事实、偏好、项目背景或长期有用的信息,调用 add_message 写入 MemOS。 只使用和当前任务相关的记忆;如果记忆不相关、过期或主体不一致,应忽略。 不要向用户暴露“记忆库”“检索结果”等内部实现细节。 ``` #### 开始对话 - 现在,可以在聊天框中进行多轮对话: - 第一次会话:告诉它你是谁、你的爱好、职业,并让它记住 - 第二次会话(新启动):询问它你是谁 > **Tip**: Claude Desktop、Cline、Chatbox 等客户端的配置方式类似,入口位置不同,更多示例请查看 [MCP 使用指南](/cn/mcp_agent/mcp/guide)。 ### 4. 使用 CLI 如果你的 Agent 框架可以执行 shell 命令(例如 Cursor、Codex、Hermes、DeepSeek Harness 等),可以通过 MemOS CLI 一键安装记忆 Skill,让 Agent 自动检索和写入记忆。 > **Tip**: 以 OpenClaw 为例,在 LOCOMO 评测中,单独接入 MemOS CLI 后 Token 消耗降低约 65.5%;接入 MemOS Cloud + CLI 后,正确率从 66.60% 提升到 77.27%。 #### 安装 CLI ```bash npm install -g @memtensor/memos-cloud-cli ``` #### 初始化并安装 Skill ```bash memos init --agent cursor memos init --api-key YOUR_API_KEY --agent cursor ``` `--agent` 会将 MemOS 记忆 Skill 安装到对应 Agent 的 skills 目录。当前 `--agent` 为必填参数,不传会直接报错,因为 CLI 需要知道 Skill 应该安装到哪个 Agent 目录。支持的目标: ```bash memos init --agent cursor # ~/.cursor/skills/memos/ memos init --agent codex # ~/.codex/skills/memos/ memos init --agent claude # ~/.claude/skills/memos/ memos init --agent openclaw # ~/.openclaw/skills/memos/ memos init --agent hermes # ~/.hermes/skills/memos/ memos init --agent deepseek # ~/.dsh/skills/memos-memory/ ``` DeepSeek Harness 初始化时还会注册原生生命周期插件:每轮开始前检索相关记忆并注入上下文,正常结束后写入新记忆。设置 `DSH_HOME` 后,Skill 会安装到 `$DSH_HOME/skills/memos-memory/`。完成初始化后请重启 DeepSeek Harness。 #### 开始对话 安装后,Agent 启动时会自动加载该 Skill。在每轮对话中,Agent 会: 1. **回答前**自动执行 `memos search`,检索与当前任务相关的长期记忆 2. **回答后**自动执行 `memos add`,将本轮出现的新事实、偏好等写入 MemOS 你可以用同样的方式验证效果: - 第一次会话:「我偏好使用 Python 语言」 - 第二次会话(新启动):「你还记得我喜欢用什么编程语言吗?」 > **Tip**: CLI 还支持在终端中手动操作记忆(`add`、`search`、`get`、`origin`、`delete` 等)。如果只在终端中使用 CLI,不安装 Agent Skill,请通过 `memos config set` 配置 API Key、默认用户 ID 和默认会话 ID。完整命令参考请查看 [MemOS CLI](/cn/mcp_agent/cli/guide)。 ### 选择哪种接入方式? | 接入方式 | 适合谁 | 优先级 | | ----------- | -------------------------------------------- | ------------ | | 插件 | OpenClaw 等 MemOS 已深度适配的 Agent 环境 | 优先使用,自动化程度最高 | | CLI + Skill | 任何可执行命令行的 Agent 框架 | 通用性最强,跨框架适用 | | MCP | Cursor、Claude Desktop、Cline、Chatbox 等 AI 客户端 | 客户端支持 MCP 协议 | | API / SDK | 自研 Agent、Chatbot 或业务应用 | 控制力最强,适合生产集成 | ### 下一步 - [OpenClaw 云插件](/cn/openclaw/guide): 查看 OpenClaw 插件的完整安装、启用和高级配置 - [MemOS CLI](/cn/mcp_agent/cli/guide): 查看 CLI 完整命令参考和 Skill 安装说明 - [MCP 使用指南](/cn/mcp_agent/mcp/guide): 查看 Cursor、Claude Desktop、Cline 等客户端如何配置 MCP - [API / SDK](/cn/memos_cloud/getting_started/quick_start): 如果你在开发自己的 Agent 或应用,从这里开始 --- # 在应用中集成 (/cn/memos_cloud/getting_started/quick_start) ## 使用 MemOS Skill 为 AI 应用快速集成 MemOS Cloud (推荐) 若你正在使用 Claude Code、Cursor 等 Agent 工具开发自己的 AI 应用,可直接将以下提示词复制并发送给你的工具: **展开查看 Skill 配置提示词** ```text 帮我为本项目接入 MemOS Cloud,为我的 Agent 产品添加长期记忆能力。 请按以下步骤操作: 1. 安装 MemOS Skill(如已安装则跳过): npx skills add https://github.com/MemTensor/MemOS-Cloud-Skill --skill memos-cloud -g -y 根据当前 Agent 环境自动填充 --agent 参数。 2. 读取该 Skill 安装路径下的 SKILL.md,严格按照其中的指令顺序执行。 3. 结合本项目的实际技术栈和架构,生成完整的 MemOS Cloud 集成代码。 ``` 你的 Agent 工具会自动安装并使用 MemOS Skill,并为你的 AI 应用集成 MemOS Cloud。 ## 手动接入 你开发 AI 应用时接入 MemOS 的完整流程,如下图所示,MemOS 提供了两个核心接口[(查看 API 文档)](/api_docs/core/add_message) - `addMessage` :把原始对话交给我们,我们自动加工并存储记忆; - `searchMemory` :在后续对话中召回记忆,让 AI 回答更贴近用户需求。 ![image.svg](https://cdn.memtensor.com.cn/img/1762434889291_h9co0h_compressed.png) ### 1. 调用前准备 - 注册并登录 MemOS 云平台 [(点击注册)](https://memos-dashboard.openmem.net/quickstart); - 获取 API Key [(点击获取)](https://memos-dashboard.openmem.net/apikeys); - 准备一个可发送 HTTP 请求的环境,Python 或 cURL。 ### 2. 创建记忆 #### 安装 SDK 如果你选择 Python SDK,请确保已安装 Python 3.10+,然后执行: ```bash pip install MemoryOS -U ``` #### 设置接口密钥 ```python [Python (HTTP)] import requests API_KEY = "YOUR_API_KEY" BASE_URL = "https://memos.memtensor.cn/api/openmem/v1" ``` ```python [Python (SDK)] from memos.api.client import MemOSClient client = MemOSClient(api_key="YOUR_API_KEY") ``` ```bash [Curl] export MEMOS_API_KEY="YOUR_API_KEY" export MEMOS_BASE_URL="https://memos.memtensor.cn/api/openmem/v1" ``` #### 添加原始信息 会话 A 发生在 2025-06-10,用户选择“七天”酒店(便捷酒店)作为暑期旅游住宿地点。如下所示,你只需要把原始的对话记录传给MemOS。 ```python [Python (HTTP)] data = { "user_id": "memos_user_123", "conversation_id": "0610", "messages": [ {"role": "user", "content": "我暑假定好去广州旅游,住宿的话有哪些连锁酒店可选?"}, {"role": "assistant", "content": "您可以考虑【七天、全季、希尔顿】等等"}, {"role": "user", "content": "我选七天"}, {"role": "assistant", "content": "好的,有其他问题再问我。"} ] } res = requests.post( f"{BASE_URL}/add/message", headers={"Authorization": f"Token {API_KEY}"}, json=data ) print(res.json()) ``` ```python [Python (SDK)] messages = [ {"role": "user", "content": "我暑假定好去广州旅游,住宿的话有哪些连锁酒店可选?"}, {"role": "assistant", "content": "您可以考虑【七天、全季、希尔顿】等等"}, {"role": "user", "content": "我选七天"}, {"role": "assistant", "content": "好的,有其他问题再问我。"} ] res = client.add_message( messages=messages, user_id="memos_user_123", conversation_id="0610" ) print(res) ``` ```bash [Curl] curl "$MEMOS_BASE_URL/add/message" \ -H "Authorization: Token $MEMOS_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "user_id": "memos_user_123", "conversation_id": "0610", "messages": [ {"role": "user", "content": "我暑假定好去广州旅游,住宿的话有哪些连锁酒店可选?"}, {"role": "assistant", "content": "您可以考虑【七天、全季、希尔顿】等等"}, {"role": "user", "content": "我选七天"}, {"role": "assistant", "content": "好的,有其他问题再问我。"} ] }' ``` #### 查询相关记忆 会话 B 发生在 2025-09-28,用户提出让 AI 推荐国庆节旅游目的地与住宿。如下所示,将用户发言作为查询内容,检索 MemOS 记忆。 ```python [Python (HTTP)] data = { "query": "我国庆想出去玩,帮我推荐个没去过的城市,以及没住过的酒店品牌", "user_id": "memos_user_123", "conversation_id": "0928" } res = requests.post( f"{BASE_URL}/search/memory", headers={"Authorization": f"Token {API_KEY}"}, json=data ) print(res.json()) ``` ```python [Python (SDK)] res = client.search_memory( query="我国庆想出去玩,帮我推荐个没去过的城市,以及没住过的酒店品牌", user_id="memos_user_123", conversation_id="0928" ) print(res) ``` ```bash [Curl] curl "$MEMOS_BASE_URL/search/memory" \ -H "Authorization: Token $MEMOS_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "query": "我国庆想出去玩,帮我推荐个没去过的城市,以及没住过的酒店品牌", "user_id": "memos_user_123", "conversation_id": "0928" }' ``` ##### 输出 MemOS 会自动召回【事实记忆:曾去过哪里】【偏好记忆:订酒店的偏好】供 AI 参考,从而让 AI 推荐更加个性化的旅游计划。如下所示,为了方便理解此处做了简化。 ```text { preference_detail_list [ { "preference_type": "implicit_preference", #隐性偏好 "preference": "用户可能偏好性价比较高的酒店选择。", "conversation_id": "0610" } ], memory_detail_list [ { "memory_key": "暑假广州旅游计划", "memory_value": "用户计划在暑假期间前往广州旅游,并选择了七天连锁酒店作为住宿选项。", "conversation_id": "0610" } ] } ``` #### 拼装到 Prompt 把召回的记忆拼装进你自己的模型 Prompt 中,让模型在回答时参考这些长期记忆。 **展开查看完整 Prompt 模板** ```text # Role 你是一个拥有长期记忆能力的智能助手 (MemOS Assistant)。你的目标是结合检索到的记忆片段,为用户提供高度个性化、准确且逻辑严密的回答。 # Memory Data 以下是 MemOS 检索到的相关信息,分为“事实”和“偏好”。 - **事实 (Facts)**:可能包含用户属性、历史对话记录或第三方信息。 - **特别注意**:其中标记为 '[assistant观点]'、'[模型总结]' 的内容代表 **AI 过去的推断**,**并非**用户的原话。 - **偏好 (Preferences)**:用户对回答风格、格式或逻辑的显式/隐式要求。 -[2025-12-26 21:45] 用户计划在暑假期间前往广州旅游,并选择了七天连锁酒店作为住宿选项。 -[2025-12-26 21:45] [隐式偏好] 用户可能偏好性价比较高的酒店选择。 # Critical Protocol: Memory Safety 检索到的记忆可能包含 AI 自身的推测、无关噪音或主体错误。使用前请先判断: 1. 来源真值:区分“用户原话”与“AI 推测”,不要把 AI 过去的假设当作用户事实。 2. 主语归因:确认记忆描述的是用户本人,而不是第三方、案例或虚构角色。 3. 强相关性:只使用对当前问题有直接帮助的记忆。 4. 时效性:如果记忆与用户最新意图冲突,以当前问题为准。 # Instructions 1. 先筛选可用记忆,丢弃噪音和不可靠推断。 2. 仅使用通过筛选的记忆补充背景。 3. 直接回答用户问题,不要提及“记忆库”“检索”或系统内部术语。 # Original Query 我国庆想出去玩,帮我推荐个没去过的城市,以及没住过的酒店品牌 ``` ### 3. 下一步 - [核心操作](/cn/memos_cloud/mem_operations/add_message): 查看更多核心记忆操作的详细用法 - [在 Agent 中使用](/cn/memos_cloud/getting_started/agent_usage): 接入 OpenClaw、Hermes 或其他 AI 工具 - [API 参考](/cn/api_docs/core/add_message): 查看完整接口文档 --- # 原始输入内容 (/cn/memos_cloud/introduction/raw_inputs) 原始输入内容是记忆生产的起点。你只需要直接提供聊天文本、图片、业务文档、工具调用信息等原始内容,MemOS 会自动从中提取有长期价值的信息,加工成可检索记忆。 ## 1. 文本内容 原始文本、聊天、事件信息或任何字符串内容。 ```json { "user_id": "memos_user_123", "conversation_id": "0910", "messages": [ { "role": "user", "content": "我是小王,喜欢吃辣。" } ] } ``` **最适合用于**:传入聊天信息、用户偏好设置、行为事件、结构化数据。 --- ## 2. 图片 MemOS 可以从图片中提取视觉信息,并结合随图片一起传入的文本上下文生成记忆。 ```json { "role": "user", "content": [ { "type": "text", "text": "这是我正在研究的 MemOS 图片。" }, { "type": "image_url", "image_url": { "url": "https://cdn.memtensor.com.cn/img/1758706201390_iluj1c_compressed.png" } } ] } ``` 如果上传本地图片,也可以把 `url` 换成 Base64 data URL: ```json { "type": "image_url", "image_url": { "url": "data:image/jpeg;base64,{base64_image}" } } ``` **最适合用于**:记录截图中的操作状态、票据中的关键信息、设计稿里的方案细节,或图表中的结论。 --- ## 3. 文档 MemOS 可以读取 PDF、Word、Markdown、JSON、XML、TXT 等文件内容,并结合随文档一起传入的文本上下文生成记忆。 ```json { "role": "user", "content": [ { "type": "file", "file": { "file_data": "https://cdn.memtensor.com.cn/file/MemOS 2.pdf" } } ] } ``` 如果上传本地文档,也可以将 `file_data` 设置为 Base64 字符串。 **最适合用于**:从报告中提取结论、从需求文档中沉淀约束、从政策资料中记录规则,或从配置文件中保留关键设定。 --- ## 4. 工具调用(Tool Call) Agent 的工具调用决策和返回结果。MemOS 会生成工具记忆,帮助 Agent 更稳定地调用工具。 ```json { "messages": [ { "role": "assistant", "tool_calls": [{ "id": "call_123", "type": "function", "function": { "name": "get_weather", "arguments": "{\"location\":\"Beijing\"}" } }] }, { "role": "tool", "tool_call_id": "call_123", "content": [{ "type": "text", "text": "{\"temperature\":\"7°C\"}" }] } ] } ``` **最适合用于**:记录工具选择、参数和返回结果,提升后续调用成功率。详见 [工具记忆](/cn/memos_cloud/features/tool_calling)。 --- ## 5. 自然语言反馈 用户对回答、记忆或知识的纠错与补充。直接传入反馈文本即可,无需定位具体记忆。 ```json { "user_id": "memos_user_123", "feedback_content": "办公类软件的采购上限是600元,而不是800元。", "allow_knowledgebase_ids": ["kb_xxx"] } ``` **最适合用于**:修正错误记忆、更新过期信息、补充遗漏内容。详见 [Add Feedback](/cn/memos_cloud/mem_operations/add_feedback)。 --- ## 6. 知识库与 Skill 项目级知识文档或 Agent 技能包。与用户记忆分开管理。 ```json { "knowledgebase_id": "kb_xxx", "file": [ { "type": "document", "content": "https://cdn.memtensor.com.cn/file/MemOS 2.pdf" }, { "type": "skill", "name": "退货流程.md", "content": "data:text/markdown;base64,{base64_skill}" } ] } ``` **最适合用于**:导入产品文档、政策制度、SOP、FAQ,或上传 Agent 技能包。详见 [知识库](/cn/memos_cloud/features/knowledge_base) 和 [记忆自进化](/cn/memos_cloud/features/self-evolving)。 --- ## 7. 内容限制 | 类型 | 限制 | | --- | --- | | 文本消息 | 单次 40,000 tokens | | 文件 | 支持 URL 和 Base64,单次 ≤ 20 个,单文件 ≤ 100 MB / 500 页 | | 图片 | 支持 URL 和 Base64 data URL | | 知识库文档 | 支持 URL 和 Base64,单次 ≤ 20 个,单文件 ≤ 100 MB / 500 页 | | Skill 单文件 | 支持 URL 和 Base64,≤ 100 KB,需包含 name 和 description | | Skill ZIP 包 | 支持 URL 和 Base64,≤ 20 MB,解压后 ≤ 200 文件,需含 SKILL.md | --- ## 8. 接口总览 | 入口 | 可传入的内容 | 典型用途 | | --- | --- | --- | | `add/message` | 文本、图片、文档、Tool Call | 写入用户记忆(事实、偏好、工具经验等) | | `chat` | 用户本轮问题 | 自动召回记忆 + 生成回答 + 写入新对话 | | `extract/memory` | 纯文本消息 | 只抽取事实/偏好,不写入长期记忆库 | | `add/feedback` | 自然语言反馈 | 修正或补充已有记忆 | | `add/knowledgebase-file` | 知识文档、Skill 文件 | 建立项目知识库和 Agent 技能库 | --- ## 9. 探索不同接口 - [Add Message](/cn/memos_cloud/mem_operations/add_message): 写入文本、图片、文档和 Tool Call - [Chat](/cn/memos_cloud/mem_operations/chat): 使用带记忆召回的对话接口 - [知识库](/cn/memos_cloud/features/knowledge_base): 管理项目文档、政策资料和 SOP - [Add Feedback](/cn/memos_cloud/mem_operations/add_feedback): 修正错误记忆或补充遗漏信息 --- # 记忆种类 (/cn/memos_cloud/introduction/memory_types) MemOS 会生成并使用不同种类的记忆,这些记忆在后续召回时承担的作用不同:有的用于确认事件,有的用于判断偏好,有的用于总结用户画像与完整事件,有的用于指导 Agent 任务怎么做,有的用于补充知识。区分记忆种类,可以在检索时返回更相关的内容,为模型提供更准确的上下文。 ## 1. 事实记忆 事实记忆描述相对客观的信息,通常来自用户明确说过的内容、行为事件、文件或反馈。 常见例子: - 用户住在上海。 - 用户的设备是 MacBook Pro 13 寸 Intel 版本。 事实记忆适合回答“用户是谁”“用户做过什么”“用户现在处于什么状态”“某件事是否发生过”等问题。 > **Note**: 记忆可能随时间变化,MemOS 会结合 [时间感知](/cn/memos_cloud/introduction/time_awareness) 和 [记忆生命周期管理](/cn/memos_cloud/introduction/mem_lifecycle) 处理这类变化。 ## 2. 偏好记忆 偏好记忆描述用户长期或阶段性的倾向,既可以来自用户明确表达,也可以来自行为的总结或推断。 常见例子: - 用户喜欢简洁直接的回答风格。 - 用户规划旅行时偏好文化景点,不喜欢购物商场。 - 用户买宠物食品时需要避开鸡肉口味。 偏好记忆适合用于推荐、生成、排序和个性化决策。它不只是回答“用户说过什么”,而是帮助 Agent 判断“怎样做更符合这个用户”。 ## 3. 属性记忆 属性记忆(Profile)可用于构建结构化的画像,对话中的零散信息被抽取并映射到预先定义好的属性字段,并随对话深入自动更新、补全。核心特点包括: - **结构化**:画像由预先定义的字段构成,统一存储、可直接取用,不分散在零散的记忆中; - **持续更新**:随对话深入,MemOS 自动更新属性字段,让画像始终贴合用户的最新状态; - **字段级可控**:支持自定义每个字段是否允许自动更新,关键字段可锁定,保持核心设定稳定。 示例结构如下所示: ```plaintext 基础信息 姓名:张三 职业:工程师 居住地:杭州 兴趣爱好 爱好:露营、独立游戏 喜欢的音乐:民谣 性格标签 三个关键词:开朗、好奇、爱较真 ``` 适用于个人助理、情感陪伴 / 虚拟角色等场景,用于增强对话一致性、稳定性,让 AI 长期记住用户是谁,详见 [属性记忆](/memos_cloud/features/profile)。 ## 4. 事件记忆 事件记忆(Event)从对话中抽取结构化事件,保留时间、地点、参与者等关键要素。 常见例子: - 6月14日,张三和朋友去西湖边露营,晚上一起看了星星,聊了人生规划。 - 6月10日,客户李四提交退换货申请,客服小二审核通过,6月13日完成签收。 事件记忆是对一段对话的总结与归纳,保留了关键的时间线、发生地点和参与者,详见 [事件记忆](/memos_cloud/features/event_memory)。 ## 5. 记忆自进化 Skills MemOS 从历史消息中自动提炼技能,实现记忆的自进化,也可以直接上传已有技能包到知识库。旅行规划、报销审核、客户问题排查这类有稳定步骤的任务,都适合沉淀为技能,详见 [记忆自进化](/cn/memos_cloud/features/self-evolving)。 ## 6. 工具记忆 工具记忆记录的是“工具怎么用”。它会从 Tool Schema、工具调用参数、工具返回结果和调用轨迹中沉淀经验,帮助 Agent 更稳定地选择工具、填写参数和使用返回结果,详见 [工具记忆](/cn/memos_cloud/features/tool_calling)。 ## 7. 知识库记忆 知识库记忆来自项目级文档、制度、手册、FAQ、流程文件或 Skill 文件。它不属于某个用户的个人历史,更适合被多个用户或 Agent 共享。 常见例子: - 公司财务报销制度。 - 产品使用手册。 - 售后退换货政策。 知识库记忆可以和用户记忆一起参与召回。员工询问【内网代理打不开了,我该重新装哪个版本?】时,知识库提供【安装说明】,用户事实记忆补充【这个员工的设备是 Intel 版本 MacBook Pro】,两者结合后回答会更准确,详见 [知识库](/cn/memos_cloud/features/knowledge_base)。 ## 8. 如何生成并使用 ### 生成记忆 当前,MemOS 默认生成所有类型的记忆,可通过 `allow_memory_view` 控制允许生成的记忆种类: - 事实、偏好、事件、技能记忆在添加消息后自动抽取并更新记忆; - 属性记忆需要先创建模板并绑定用户,添加消息时自动抽取更新; - 工具记忆需要在添加消息时传入 `"role":"tool"` 的工具调用信息; - 知识库记忆需要创建知识库并上传文档。 ### 使用记忆 检索记忆时,可通过 `include_memory_view` 控制允许检索的记忆种类。不传时默认召回事实记忆和偏好记忆。与传入值的对应关系如下所示: | 记忆种类 | 取值 | | --- | --- | | 事实记忆 | `detail_factual` | | 偏好记忆 | `preference` | | 属性记忆 | `profile` | | 事件记忆 | `event` | | 技能记忆 | `skill` | | 工具记忆 | `tool_memory` | 其中,知识库记忆需要在检索记忆时,传入 `knowledgebase_ids` 指定参与召回的知识库记忆。使用方式参考如下所示: ```json { "user_id": "memos_user_123", "query": "最近有什么安排?", "knowledgebase_ids": ["memos_kb_001"] } ``` > **Note**: 需要查看完整字段、请求格式和响应格式,详见 [Search Memory 接口文档](/cn/memos_cloud/mem_operations/search_memory)。 ## 9. 直接开始使用 - [Add Message](/cn/memos_cloud/mem_operations/add_message): 写入用户对话、文件和工具调用轨迹 - [Search Memory](/cn/memos_cloud/mem_operations/search_memory): 检索不同种类的记忆 --- # 多用户 / 多 Agent 隔离 (/cn/memos_cloud/introduction/isolation_filters) 如果你的产品同时被多个用户、Agent、项目或业务场景使用,记忆需要有清楚的边界。 - 项目边界划分了不同产品或业务空间; - 用户边界划分了同一项目下,不同用户的个人记忆; - Agent / 应用边界划分了同一用户在多个 Agent / 应用中产生的不同记忆; - 会话上下文标记每条记忆来自哪一次对话或任务; - 项目中共享的知识可以放入知识库或公共记忆,供有权限的用户使用。 ## 1. 项目边界:创建项目并使用 API Key 如果你还未注册云服务,可以先登录 [MemOS 控制台](https://memos-dashboard.openmem.net/cn/quickstart),新用户会有一个默认项目;如果你需要隔离不同的产品或业务空间,请在控制台创建新项目。 每个项目都有自己的 API Key 列表,启用项目时,传入对应的 API Key,即可使用该项目下的记忆内容。前往 [API Key 页面](https://memos-dashboard.openmem.net/cn/apikeys),快速获取接口密钥。 > **Note**: 关于项目创建、切换和接口密钥管理,详见 [项目配置](/cn/api_docs/start/configuration)。 ## 2. 不同用户记忆:使用不同的`user_id` 每个用户都需要对应唯一的 `user_id`,同一个用户在不同的入口或应用中,可以继续使用相同的 `user_id`,这样 MemOS 才能形成连续的长期记忆。 写入用户 A 的记忆: ```json { "user_id": "memos_user_A", "messages": [ { "role": "user", "content": "我喜欢吃辣。" } ] } ``` 检索用户 B 的记忆: ```json { "user_id": "memos_user_B", "query": "帮我推荐美食" } ``` 这次检索只会在用户 B 的个人记忆中查找,不会检索到用户 A 的记忆。即使两个用户来自同一个项目,与同一个 Agent 对话,使用不同的 `user_id` 时,记忆边界依旧保持清晰。 ### 群聊中的多用户记忆:传入 `user_id` 列表 NEW 当多个用户在同一会话中对话时,`user_id` 支持传入 list,MemOS 会为每个参与者抽取和维护记忆。 ```json { "user_id": ["memos_user_1", "memos_user_2"], "agent_id": "memos_agent", "messages": [ { "role": "user", "role_id": "memos_user_1", "role_name": "张三", "content": "下周二的方案评审,大家时间合适吗?" }, { "role": "user", "role_id": "memos_user_2", "role_name": "李四", "content": "我可以,下午两点怎么样?" }, { "role": "assistant", "role_id": "memos_agent", "content": "已记录,下周二下午两点方案评审。" } ] } ``` 通过 `role_id` 和 `role_name` 标识每条消息的发言人,记忆文本中可区分谁说了什么。 > **Note**: 更多群聊使用方法,详见[群聊](/cn/memos_cloud/features/group_chat)。 ## 3. 多 Agent 隔离:使用 `agent_id` 如果同一个用户使用多个 Agent,例如客服助手、健康助手、代码助手,你需要为不同 Agent 设置不同的 `agent_id`。 添加与健康助手的对话消息时,传入`"agent_id": "health_assistant"`: ```json { "user_id": "memos_user_123", "agent_id": "health_assistant", "messages": [ { "role": "user", "content": "我今天跑了 5 公里,膝盖有点酸。" } ] } ``` 检索记忆时,使用`filter`过滤对应 Agent 的记忆内容: ```json { "user_id": "memos_user_123", "query": "根据我最近的运动情况给些建议", "filter": { "and": [ { "agent_id": "health_assistant" } ] } } ``` 这样做的好处是:用户的长期记忆仍然属于同一个人,不会被拆散;同时,不同 Agent 产生的记忆也可以在检索时按需筛选。 > **Note**: 更多记忆过滤的方法,详见[记忆过滤器(filter)](/cn/memos_cloud/features/filters)。 ### 为 Agent 创建独立记忆 NEW 在控制台创建或修改项目时开启「为 Agent 创建独立记忆」开关,可以让每个 Agent 拥有自己的记忆。 - 更好地维护 AI 角色的经历、认知和状态; - 支持多个用户共用同一 Agent 的场景,例如:家庭共用智能助手、企业群聊助手等。 开启该功能后: - 添加消息时,MemOS 会分别抽取并更新用户和 Agent 的记忆; - 检索记忆时,支持以 `agent_id` 为主体,检索 Agent 的独立记忆; - Agent 可积累自己的长期记忆,在不同用户、不同会话中,保持角色的连续性。 该功能默认关闭,此时 `agent_id` 仍可用于过滤和标记,但不会为 Agent 创建独立的记忆实例。 ## 4. 当前会话:使用 `conversation_id` 为了让 MemOS 更好地理解上下文内容,添加用户消息时可传入会话标识 `conversation_id`,表示这条消息属于哪一次对话或任务;不传时系统自动生成。 ```json { "user_id": "memos_user_123", "conversation_id": "order_refund_001", "messages": [ { "role": "user", "content": "我想咨询退款进度。" }, {"role": "assistant", "content": "退款仍在处理中,预计24小时内到账。"} ] } ``` 检索记忆时,`conversation_id` 不是强制过滤条件。传入它可以明确当前所在会话,让本会话相关记忆获得更高权重;不传时,系统仍会在该用户的历史记忆中检索。 ## 5. 共享知识:放入知识库或公共记忆 不是所有内容都应该写入某个用户的个人记忆,项目文档、制度、产品手册、SOP 等公共知识,更适合放入知识库或公共记忆。 ### **知识库** 对于项目文档、制度和产品手册,通常需要创建知识库并上传文档(完整操作见 [知识库](/cn/memos_cloud/features/knowledge_base));检索时,在用户记忆之外传入 `knowledgebase_ids`,让回答同时参考项目级知识。 ```json { "user_id": "memos_user_123", "query": "结合我的情况和公司制度,判断这笔费用能不能报销", "knowledgebase_ids": ["kb_finance_policy"] } ``` ### **公共记忆** 公共记忆适合保存项目公告、团队经验、通用规则等轻量信息。如果一条消息需要被项目下所有用户共享,可以在写入时开启 `allow_public`,让它进入项目级公共记忆。 ```json { "user_id": "memos_user_123", "allow_public": true, "messages": [ { "role": "user", "content": "本季度报销截止时间是 6 月 25 日。" } ] } ``` 检索记忆时,用户个人记忆与公共记忆会被共同检索并召回相关内容。 --- # 时间感知 (/cn/memos_cloud/introduction/time_awareness) 我们将记忆视为会随时间演化的对象,而不是一段静态文本。用户的偏好、状态和事实可能变化;一次发生的事件也需要保留发生时间。拥有时间感知,MemOS 能知道什么时候应该使用当前最新认知,什么时候应该回溯历史版本。 ## 1. 解决了什么问题 ### 新旧信息冲突 - 用户先说“我喜欢吃苹果”,后来又说“我不喜欢吃苹果了”。 - **MemOS 处理方式**:自动识别前后变化,检索时只返回当前有效认知“不喜欢”。历史版本不会被删除,需要时仍可回溯。 ### 问“现在”和“以前”应该得到不同答案 - 用户之前住在北京,后来搬到上海。 - **MemOS 处理方式**:理解问题中的时间线索,当用户问“我现在住在哪”,能够检索到上海;问“我以前住在哪”,能够检索到北京。 ### 事件不应该被强行合并 - 去年国庆去了西安,今年五一去了杭州。 - **MemOS 处理方式**:保留每次事件的完整信息,不只是合并成“用户喜欢旅游”。问“我最近去哪旅游了”,能够优先召回去了杭州。 ## 2. 处理流程 ### 写入时:用 `chat_time` 锚定历史时间 实时对话通常不需要传时间,MemOS 会使用消息传入时间。如果你需要导入历史数据,建议传入 `chat_time`,让记忆锚定到事件真正发生的时间。 ```json { "user_id": "memos_user_123", "messages": [ { "role": "user", "content": "我喜欢吃辣。", "chat_time": "2025-09-12 08:00:00" }, { "role": "user", "content": "我现在不太能吃重油重辣了,更喜欢清爽一点。", "chat_time": "2025-09-25 12:00:00" } ] } ``` ### 两类记忆的时间处理 MemOS 对记忆做不同的处理: - **可能会变化的状态**,例如住在哪、喜欢什么、当前阶段目标,保留不同时间版本,便于检索时技能召回现在,又能召回历史。 - **一次发生的事件**,例如何时去了哪、做了什么,保留每次事件细节,便于检索时召回完整信息。 ### 检索时:理解问题中的时间指向 - **如果没有明确时间指向**:正常检索,优先返回当前有效记忆。 - **如果带有时间线索**:理解时间指向,选择对应版本或事件。 如果你已经知道明确时间范围,也可以配合 [记忆过滤器](/cn/memos_cloud/features/filters) 使用 `create_time` 缩小候选记忆: ```json { "user_id": "memos_user_123", "query": "整理我 2025 年 12 月和阅读相关的记录", "filter": { "and": [ { "create_time": { "gte": "2025-12-01" } } ] } } ``` ## 3. 示例体验 你可以尝试写入一组带有时间信息的事件: ```json { "user_id": "test_user", "messages": [ { "role": "user", "content": "我住在北京。", "chat_time": "2025-01-10 10:00:00" }, { "role": "user", "content": "我搬到上海了。", "chat_time": "2025-06-01 10:00:00" }, { "role": "user", "content": "去年国庆我去西安旅游了。", "chat_time": "2025-10-08 10:00:00" }, { "role": "user", "content": "今年五一我去杭州旅游了。", "chat_time": "2026-05-02 10:00:00" } ] } ``` | 类型 | 搜索 query | 期望结果 | | --- | --- | --- | | 当前状态 | "我现在住在哪?" | 上海,使用当前最新状态 | | 历史状态 | "我以前住在哪?" | 北京,回溯历史版本 | | 截止当下 | "我去哪旅游过?" | 西安和杭州,杭州排前 | ## 4. 使用建议 - 导入历史数据时传入准确的 `chat_time`,否则历史事件可能被误认为刚发生。 - 对"当前状态"类信息,让用户新表达自然写入即可,系统会自动更新当前认知。 ## 5. 下一步 - [Add Message](/cn/memos_cloud/mem_operations/add_message): 写入带时间的历史消息 - [Search Memory](/cn/memos_cloud/mem_operations/search_memory): 检索和验证时间相关记忆 --- # 常见问题 (/cn/memos_cloud/introduction/faq) 这篇页面回答 MemOS 产品和记忆机制相关的问题。如果你已经在使用 MemOS Cloud,并遇到项目、API Key、额度或接口调用问题,请查看 [云服务 FAQs](/cn/memos_cloud/support/faq) 和 [配额与限制](/cn/memos_cloud/support/limit)。 ## MemOS 和普通 RAG 框架有什么区别? | 对比维度 | RAG | MemOS | | --- | --- | --- | | 管理对象 | 静态知识片段或文档段落 | 随用户、任务和时间变化的记忆 | | 内容形态 | 通常直接召回原文片段 | 将原始输入加工为事实、偏好等记忆单元 | | 更新方式 | 依赖外部文档更新或重新索引 | 支持持续写入、更新、反馈修正和生命周期管理 | | 召回目标 | 让模型知道外部知识 | 让模型理解用户状态、偏好和上下文 | RAG 更适合管理稳定的外部知识;MemOS 更适合管理会在对话和业务过程中持续变化的用户记忆。两者可以配合使用。 ## MemOS 可以和已有 RAG 或知识图谱结合吗? 可以。RAG 负责事实检索和知识增强,MemOS 负责连续记忆和状态管理。 在业务中,你可以把企业制度、产品说明等稳定内容放在知识库或 RAG 系统中,把用户历史对话、偏好、任务进展等动态信息交给 MemOS 管理。回答时同时召回外部知识和用户记忆,让模型既能参考业务知识,也能理解当前用户。 ## MemOS 如何工作? MemOS 的基本流程是: 1. 通过 `add/message`、知识库、反馈等方式写入原始信息。 2. 系统把原始输入加工为可检索、可更新的记忆。 3. 后续通过 `search/memory`、`chat` 或 Agent 集成召回相关记忆。 4. 记忆会随着新输入、反馈和生命周期策略持续更新。 如果你只想快速接入云服务,请从 [在应用中集成](/cn/memos_cloud/getting_started/quick_start) 开始。 ## MemOS 核心能力有哪些? - **用户 / Agent 记忆管理**:保存用户与 AI 的交互内容,并支持多用户、多 Agent 的记忆隔离。 - **记忆生产与更新**:从原始对话、行为事件、知识内容中生成可复用记忆。 - **记忆召回与调度**:按相关性、时效性和上下文选择合适记忆。 - **记忆生命周期管理**:通过更新、合并、归档等方式控制记忆质量和规模。 - **云服务与开源方案**:可以使用托管云服务,也可以基于开源项目自部署和二次开发。 ## 云服务和开源方案怎么选? 如果你希望快速验证、减少运维成本、直接使用控制台、API Key、知识库和额度管理,优先使用 [MemOS Cloud](/cn/memos_cloud/getting_started/quick_start)。 如果你需要自主管理部署环境、修改底层实现、接入自有推理后端或深度二次开发,可以看 [开源项目](/cn/open_source/getting_started/installation)。 更完整的对比请看 [云服务与开源方案](/cn/memos_cloud/getting_started/cloud_and_opensource)。 ## MemOS 是否支持私有化部署? 支持。需要私有化部署、商业化定制或更深的业务场景适配时,可以联系 MemOS 团队确认部署方式、数据边界和功能范围。 如果你的团队希望自行研究和改造,也可以从开源项目开始。 ## 生命周期和调度有什么关系? 生命周期管理负责记忆单元的状态变化,例如更新、合并、沉淀或归档。调度负责在一次请求中选择哪些记忆进入当前上下文。 简单说:生命周期决定记忆如何长期维护,调度决定当前请求该用哪些记忆。 ## MemOS 如何避免记忆膨胀? MemOS 不会把所有原始内容都原样拼接进模型上下文。系统会把原始输入加工为更短的记忆单元,并通过更新、合并、归档等机制控制记忆规模。 后续召回时,MemOS 只选择和当前请求相关的记忆,减少无关内容进入模型。 ## KV-Cache 和激活记忆是一回事吗? 不是。KV-Cache 是模型推理层的计算缓存;激活记忆是 MemOS 中用于描述近期可快速复用记忆状态的产品概念。 在具体实现上,激活记忆可以利用底层缓存能力提升近期上下文复用效率,但两者不等价。 ## MemOS 会不会拖慢推理? MemOS 的目标是通过记忆加工和召回减少无关上下文,而不是把所有历史内容都塞进模型。实际延迟取决于写入量、召回范围、过滤条件、模型调用方式和业务并发。 如果你在云服务调用中遇到额度或延迟问题,请先查看 [配额与限制](/cn/memos_cloud/support/limit) 和 [云服务 FAQs](/cn/memos_cloud/support/faq)。 ## 很近的信息,比如“昨天做的事”,还需要调度吗? 需要。时间近不代表一定相关,也不代表可以直接完整塞入上下文。调度会结合当前问题、会话、用户记忆和相关性,选择更适合本轮回答的记忆。 ## MemOS 适合哪些业务场景? MemOS 适合需要长期记忆和持续个性化的 AI 应用,例如陪伴、游戏、旅游、客服、知识管理、智能投顾、生产运维和 AI 伴学等场景。 如果你需要评估具体业务场景,可以先用 Cloud API 快速验证,再决定是否做更深的集成或私有化部署。 --- # 记忆生产 (/cn/memos_cloud/introduction/mem_production) ## 1. 什么是记忆生产 记忆生产是 MemOS 全流程的写入和加工阶段。开发者提交原始信息后,MemOS 会从中抽取事实、偏好、工具使用过程、技能线索和知识内容,并生成后续可以被检索、过滤、调度和更新的记忆单元。 原始信息可以先被完整保存,但真正进入后续推理链路的通常不是整段原文,而是经过抽取、去噪、结构化和版本治理后的记忆。 ## 2. 为什么不能只保存原文 如果把所有原始信息直接保存,并在下次请求时整段塞给大模型,会遇到三个问题: - **上下文成本高**:原始对话、日志和文件通常包含寒暄、重复内容和无关细节,直接拼接会浪费 Token。 - **检索质量不稳定**:未经抽取的长文本缺少清晰主题和结构,容易召回“看起来相关但帮不上忙”的片段。 - **长期一致性难维护**:用户偏好、居住地、状态会变化,只保存原文无法清楚表达“当前应该相信什么”。 记忆生产的目标就是把“发生过什么”加工成“以后可用什么”。 ## 3. 记忆加工的关键环节 从原始输入到可用记忆,中间不是一次简单的文本保存,而是一个持续整理、形成长期可用认知的过程,通常包括以下几个关键环节: | 环节 | 作用 | | --- | --- | | 抽取 | 从原始对话、事件或文档里识别值得长期保留的信息 | | 结构化 | 将信息整理成事实、偏好、工具、技能、知识等可区分的记忆类型 | | 去噪 | 过滤寒暄、重复内容、临时上下文和低价值流水信息 | | 合并 | 将相同或相近的信息归并,减少重复记忆 | | 演化 | 当用户状态或偏好变化或有冲突时,更新当前可信记忆,并保留必要历史轨迹 | ## 4. 例子:从对话到记忆 原始对话: ```text User: 我暑假定好去广州旅游,住宿的话有哪些连锁酒店可选? Assistant: 您可以考虑【七天、全季、希尔顿】等等 User: 我选七天 Assistant: 好的,有其他问题再问我。 ``` 可能生成的记忆如下所示: - 事实记忆来自原文明确表述; - 偏好记忆结合了上下文推理,总结用户偏好。 ```text - 事实记忆:用户计划在暑假期间前往广州旅游。 - 事实记忆:用户在广州住宿选项中选择了七天连锁酒店。 - 隐式偏好:用户可能偏好经济实用型酒店。<推理依据:用户在七天、全季、希尔顿等选项中选择七天,但原始对话没有明确说明预算原因。> ``` ## 6. 下一步 - [原始输入内容](/cn/memos_cloud/introduction/raw_inputs): 确认哪些内容可以写入 - [记忆类型](/cn/memos_cloud/introduction/memory_types): 了解事实、偏好、工具、技能等记忆类型 - [Add Message](/cn/memos_cloud/mem_operations/add_message): 查看消息写入和记忆生产的接入方式 --- # 记忆调度 (/cn/memos_cloud/introduction/mem_schedule) ## 1. 什么是记忆调度 记忆调度是 MemOS 在运行时管理记忆可用性的能力。它不只是“搜到哪条记忆”,而是根据当前任务、用户状态、历史主题和记忆热度,决定哪些记忆应该更靠近模型上下文,哪些记忆可以留在低频存储中。 可以把记忆调度理解为记忆系统里的注意力管理:当用户进入某个任务场景时,系统优先准备最可能用到的记忆,减少无关历史对模型的干扰。 ## 2. 为什么需要调度 如果每次请求都只做全量检索,系统会遇到三个问题: - **响应变慢**:等用户提问后再从全部历史里搜索,会增加首 Token 延迟。 - **上下文过载**:召回太多历史内容,反而会淹没当前任务真正需要的信息。 - **主题切换不自然**:用户近期关注点变化时,系统需要及时把新主题调到更高优先级,把旧主题降级。 调度的目标不是保存更多内容,而是在合适的时刻让合适的记忆处于可用状态。 ## 3. 调度关注什么 | 判断维度 | 作用 | | --- | --- | | 当前任务 | 判断用户正在处理的问题属于哪个主题或场景 | | 记忆相关性 | 识别哪些记忆与当前输入、会话和业务目标更接近 | | 时效性 | 优先使用近期仍然有效的信息,降低过时内容的影响 | | 使用频率 | 高频使用的记忆更容易被提前准备或保持活跃 | | 权限范围 | 确保调度结果符合用户、Agent、租户和业务隔离规则 | 调度结果会影响后续召回和上下文注入:相关、活跃、可信的记忆更容易被优先使用;低频、过时或不适合当前场景的记忆会被延后处理。 ## 4. 例子:从买房到装修 **前一阶段:买房是核心主题** **用户输入**: “帮我查一下滨江那边的二手房均价。” “提醒我周六去看房。” “记录一下房贷利率的最新变化。” **调度结果**: 生成小区、看房安排、房贷利率的记忆。 判断“买房”是近期高频主题。 让买房相关记忆保持较高优先级。 **最近:装修变成新的活跃主题** **用户输入**: “周末要去看瓷砖。” “提醒我和装修公司确认水电改造。” “记一下下周家具送货时间。” **调度结果**: 继续生成装修相关记忆。 判断“装修”已经成为新的高频主题。 将装修相关记忆调到更高优先级。 买房相关记忆仍然保留,但逐渐降级。 用户随口说:“我感觉好多事堆在一起,你帮我理一下。” **没有调度:全量临时检索**: 需要从全量记忆里临时检索。 可能混入查房价、看房、买菜、看电影等低相关内容。 回答更慢,也更容易偏离当前任务。 **有调度:优先准备当前主题**: 优先准备看瓷砖、确认水电改造、家具送货等装修记忆。 不需要每次都从全部历史里重新判断。 响应更快,结果也更接近用户当前真正挂念的事。 ## 5. 和召回的关系 调度和召回不是同一件事: | 能力 | 关注点 | | --- | --- | | 记忆调度 | 哪些记忆应该在当前阶段更活跃、更靠近模型上下文 | | 记忆召回 | 在一次具体请求中,检索哪些记忆作为回答依据 | 调度更像运行时的准备和优先级管理;召回更像一次请求里的检索和筛选。调度做得好,召回通常会更快、更准,也更不容易被无关历史干扰。 --- # 记忆召回 (/cn/memos_cloud/introduction/mem_recall) ## 1. 什么是记忆召回 记忆召回是 MemOS 在读记忆时的核心能力。用户发起新请求后,系统会结合输入内容、会话上下文、过滤条件和记忆状态,找出可以帮助模型完成当前任务的记忆。 召回的目标不是把历史全部拿出来,而是在有限上下文里放入最有用的事实、偏好、工具经验、技能线索或知识内容。 ## 2. 为什么不能只靠上下文 如果模型只依赖当前对话窗口,会遇到三个问题: - **用户需要反复说明**:偏好、背景和长期事项无法自然延续。 - **历史信息容易丢失**:早期对话、跨会话行为和工具结果不会自动出现在当前上下文里。 - **输入容易过载**:把所有历史原文拼进去成本高,也会降低回答稳定性。 记忆召回的价值,是在需要时把长期记忆转化为当前任务可用的输入。 ## 3. 召回会返回什么 | 记忆类型 | 典型用途 | | --- | --- | | 事实记忆 | 补充用户身份、长期事项、业务状态等明确事实 | | 偏好记忆 | 让模型延续用户偏好的语气、风格、选择习惯或约束 | | 工具记忆 | 帮助 Agent 在相似任务中选择合适工具和调用方式 | | 技能记忆 | 复用多轮任务中沉淀出的执行步骤和约束 | | 知识内容 | 为回答提供文档、图片、多模态内容或知识库依据 | 召回结果通常会带有来源、时间、类型、标签、置信度和状态等信息,开发者可以继续过滤、排序或决定是否注入下游模型。 ## 4. 召回的关键环节 | 环节 | 作用 | | --- | --- | | 理解请求 | 判断当前输入需要哪些背景、偏好或知识 | | 过滤范围 | 根据用户、会话、时间、标签、类型等条件限定候选记忆 | | 检索候选 | 从记忆库中找到语义相关或条件匹配的记忆 | | 排序筛选 | 结合相关性、置信度、时效性和状态选择更可靠的结果 | | 注入治理 | 控制哪些记忆进入模型上下文,避免过多、过旧或不合规内容 | 这些环节共同决定召回结果是否真正有用。召回太少会让模型缺少背景;召回太多会增加噪音和成本。 ## 5. 下一步 - [记忆过滤](/cn/memos_cloud/features/filters): 使用过滤条件控制召回范围,减少无关记忆 - [Search Memory](/cn/memos_cloud/mem_operations/search_memory): 查看记忆召回的具体接入方式 --- # 记忆生命周期管理 (/cn/memos_cloud/introduction/mem_lifecycle) ## 1. 什么是记忆生命周期管理 记忆不是一次写入后永久不变的记录。随着用户状态、任务阶段和业务事实变化,同一类记忆可能需要被更新、合并、降级、归档或清理。 记忆生命周期管理关注的是记忆在存储层面的长期演化:哪些记忆仍然可信,哪些记忆已经过时,哪些记忆需要保留历史轨迹,哪些记忆可以从活跃索引中移除。 ## 2. 为什么需要生命周期管理 如果记忆只增加、不治理,会出现三个问题: - **重复记忆变多**:相似事实和偏好反复写入,召回时噪音增加。 - **过时信息干扰**:旧住址、旧偏好、已完成任务仍然被当成当前事实。 - **冲突难以判断**:当新旧信息矛盾时,系统需要知道当前应该相信哪一条。 生命周期管理的目标,是让记忆既能长期保留,又不会把过时、重复或低价值信息持续带入推理。 ## 3. 生命周期关键状态 | 状态 | 含义 | 常见处理 | | --- | --- | --- | | 生成 | 新记忆被写入,带有来源、时间、类型和置信度等信息 | 进入记忆库,等待后续使用 | | 激活 | 记忆在近期任务中频繁被使用或被调度到更高优先级 | 更容易被召回和注入上下文 | | 合并 | 多条相似或互补记忆被整合为更稳定的表述 | 减少重复,形成更新后的可信记忆 | | 归档 | 长期低频或暂时不适合当前任务的记忆被降级 | 默认减少参与推理,但保留回溯能力 | | 过期 | 记忆超出有效期或被策略判定为不再可用 | 从活跃索引中移除,必要时保留最小审计信息 | | 冻结 | 合规、审计或业务关键记忆不允许被自动改写 | 保留完整历史,限制更新和删除 | 具体状态名和策略可能随接入方式变化,但核心思想是一致的:记忆需要随着时间和使用情况持续治理。 ## 4. 例子:学习偏好的变化 假设你正在用 MemOS 构建一个在线教育助手,帮助学生解答数学题。 #### 生成(Generated) 学生第一次使用时说:“我总是把二次函数和一次函数搞混。” 系统抽取出记忆: ```json { "content": "学生常混淆二次函数与一次函数", "confidence": 0.99, "create_time": "2025-09-11" } ``` 状态:`Generated` 行为:被存储进记忆库,等待后续使用。 #### 激活(Activated) 在接下来的多次答题中,系统频繁调用这条记忆来辅助解题。 状态:`Activated` 行为:被调度机制优先使用,提高后续检索和上下文注入的效率。 #### 合并(Merged) 随着更多交互,系统发现学生不仅混淆一次函数和二次函数,还对指数函数也容易混淆。 系统将多条相似记忆合并为一条新的内容: ```json { "content": "该学生在函数知识点上存在混淆,尤其是一次函数、二次函数和指数函数", "history": "学生常混淆二次函数与一次函数", "version": "v1" } ``` 状态:`Merged` 行为:旧条目被压缩,形成更完整的新版本,减少冗余。 #### 归档(Archived) 三个月后,学生已掌握函数相关知识点,系统很久没有再调度到这条记忆。 状态:`Archived` 行为:被降级到低频状态,默认不参与推理,但可在“学习轨迹回溯”中被调用。 #### 过期(Expired) 又过了一年,该学生升级到新的学段,旧的“初中函数混淆”记忆被策略判定为无效。 状态:`Expired` 行为:从索引中清理,仅保留最小审计信息。 ```json { "deleted_fact_id": "12345", "deleted_at": "2026-09-11" } ``` #### 冻结(Frozen,特殊状态) 与此同时,该学生的“期末成绩评估报告”属于合规性文件,不允许自动修改。 状态:`Frozen` 行为:被锁定,禁止自动更新,仅保留完整修改历史,便于审计与合规检查。 ## 5. 和生产、调度、召回的关系 | 能力 | 关注点 | | --- | --- | | 记忆生产 | 如何把原始输入加工成可用记忆 | | 生命周期管理 | 记忆写入后如何更新、合并、归档和清理 | | 记忆调度 | 当前阶段哪些记忆应该更活跃 | | 记忆召回 | 一次请求中哪些记忆应该被检索和使用 | 生命周期管理为调度和召回提供记忆状态。活跃、可信、未过期的记忆更适合参与当前推理;归档、过期或冻结记忆则需要按策略谨慎处理。 --- # MemOS算法原理概述 (/cn/memos_cloud/introduction/algorithm) > **Note**: 提示 论文地址:https://arxiv.org/abs/2507.03724 ## 1. 什么是 MemOS? 当下的大语言模型(LLM)已经展现出强大的生成和推理能力,但它们普遍缺乏真正的「记忆」。 * 在多轮对话中,它们常常遗忘早期信息; * 在应用场景中,它们无法沉淀用户的个性化偏好; * 在知识迭代时,它们更新缓慢,无法灵活应对新需求。 这使得 LLM 虽然“聪明”,却难以成为真正的 **老师、同事或助手**。 **MemOS(Memory Operating System)** 正是为了解决这一根本性缺陷而提出。 它把「记忆」从一个零散的功能,提升为与算力同等重要的 **系统资源**,为 LLM 提供: * **统一的记忆层**:跨越单一对话,支撑长期知识沉淀和上下文管理; * **持久化与结构化能力**:让记忆能够被保存、追溯和复用; * **记忆增强推理**:在推理时调用历史经验和偏好,生成更符合用户需求的答案。 相比传统的做法(如单纯依赖参数记忆或临时 KV 缓存),MemOS 的价值在于: * 它让 AI 不再是“看过就忘”,而是能持续进化和学习; * 它不仅能回答当下的问题,更能利用过去的积累改善未来的表现; * 它为开发者提供了统一接口,把“记忆”从复杂的自研逻辑变成标准化能力。 简而言之,MemOS 的目标是: **让大模型从一次性对话工具,进化为真正具有长期记忆和自适应能力的智能体。** ## 2. MemOS架构设计 MemOS 的设计核心,是把「记忆」作为一个独立系统层,和计算、存储一样,成为 AI 应用的基础能力。它的整体架构可以概括为 **三层结构**: **API 与应用接口层、记忆调度与管理层、记忆存储与基础设施层** ![art.gif](https://statics.memtensor.com.cn/memos/art.gif) * 在 **API 与应用接口层**,MemOS 提供了标准化的 Memory API,开发者可以通过简单的接口实现**记忆创建、删除、更新**等操作,让大模型具备易于调用和扩展的持久记忆能力,支持多轮对话、长期任务和跨会话个性化等复杂应用场景。 > 这里的 `API 层` 指的是框架内部的标准化接口设计,用于阐述系统原理与能力边界。**不同于云服务对外提供的开发接口** (如 `add`、`search` 等简化封装),后者是基于 MemOS 能力在后端抽象后的统一入口。 * 在记忆调度与管理层,MemOS 提出了**记忆调度(Memory Scheduling)**的全新范式,支持基于上下文的 **“下一场景预测”(Next-Scene Prediction),**可以在模型生成时提前加载潜在需要的记忆片段,显著降低响应延迟、提升推理效率。 * 而在**记忆存储与基础设施层,**MemOS 通过标准化的 **MemCube** 封装,将明文记忆、激活记忆和参数记忆三种形态有机整合。它支持多种持久化存储方式,包括 Graph 数据库、向量数据库等,并具备**跨模型的记忆迁移与复用能力。**
标准化 MemCube(记忆立方体)的基础构成
标准化 MemCube(记忆立方体)的基础构成
## 3. MemOS为什么高效? > **Note**: 从Next-Token Prediction到Next-Scene Prediction * 在传统的大模型问答系统中,生成流程依然遵循**同步的Next-Token机制**:模型接收用户问题→实时检索外部片段→按token逐字生成答案。 * 检索或计算产生的任何停顿,都会直接拉长整条推理链路,知识注入与生成紧密耦合,导致GPU容易出现空等,用户端响应时延明显。 * 与这种传统范式不同,MemOS 从记忆建模的视角出发,提出了**记忆调度范式**,通过设计异步调度框架,提前预测模型可能需要的记忆信息,显著降低实时生成中的效率损耗。 * MemOS 实现了针对MemCube中的三种核心记忆类型(参数记忆、激活记忆、明文记忆),以及外部知识库(包括互联网检索与超大规模本地知识)等多元知识的**联合调度**。 * 依托对对话轮次与时间差的精准感知,系统能够智能预测下一个场景中可能被调用的记忆内容,并动态路由与预加载所需的明文、参数和激活记忆,从而在生成阶段即刻命中,最大化信息引入的效率和推理的流畅性。 ![640.gif](https://statics.memtensor.com.cn/memos/ani.gif)
记忆调度的核心思路
记忆调度的核心思路
## 4. MemOS-Preview 版本性能详细评估结果 ### 4.1 LoCoMo记忆评测 * 为系统性验证MemOS在真实应用场景下的表现,MemOS团队基于**LoCoMo数据集**进行了全面评测。 * 作为当前业界广泛认可的记忆管理基准,LoCoMo已被多种主流框架采用,用于检验模型的记忆存取能力与多轮对话一致性。 * 从官方公开的评测数据来看,**MemOS在准确率和计算效率上均实现了显著提升**,相较于OpenAI的全局记忆方案,在关键指标上展现出更优的性能表现,进一步验证了其在记忆调度、管理与推理融合方面的技术领先性。 ![image.png](https://cdn.memtensor.com.cn/img/1758687655761_blkqnr_compressed.png) ### 4.2 KV Cache记忆评测 * 除了通用的记忆能力评估,研究团队还重点考察了MemOS所提出的KV Cache记忆机制在推理加速方面的实际效果。 * 通过在不同上下文长度(Short/Medium/Long)以及不同模型规模(8B/32B/72B)下进行对比测试,系统性评估了缓存构建时间(Build)、**首Token响应时间(TTFT)以及整体加速比(Speedup)**等关键指标。 * 实验结果(见图10)表明,**MemOS在多种配置下均显著优化了KV Cache的构建与复用效率**,使推理过程更加高效流畅,有效缩短了用户的等待时延,并在大规模模型场景中实现了可观的性能加速。 ![image.png](https://cdn.memtensor.com.cn/img/1758687596553_iptom0_compressed.png) ## 5. 下一步行动 * 了解[云服务与开源方案](/memos_cloud/getting_started/cloud_and_opensource),体验MemOS的强大之处吧! --- # Add Message (/cn/memos_cloud/mem_operations/add_message) > **Note**: ** 为什么记忆很重要?** > > * 长期不丢失:能够实现跨会话的长期记忆,避免对话结束后信息丢失; > * 把握用户偏好:随着交互不断积累,让 AI 越来越“**懂用户**”; > * 随时间演进:会话过程中,持续动态更新用户记忆; > * 跨产品体验:在您的多个应用或产品之间,共享同一用户的记忆,实现一致的用户体验。 ## 1. 关键参数 * **用户标识(user\_id)**:用于标识消息所属的用户,你添加的消息必须关联到唯一的用户标识符。 * **会话标识(conversation\_id)**:用于标识消息所属的会话;传入后,相同 conversation_id 下的多轮消息会被识别为同一上下文。 * **消息(messages)**:用于添加到 MemOS 的用户与 AI 对话内容的有序消息列表。 ## 2. 工作原理 * **信息提取**:MemOS 从消息中提取并处理为记忆,包括事实、偏好、[属性记忆](/cn/memos_cloud/features/profile)、[事件记忆](/cn/memos_cloud/features/event_memory)、工具记忆等。 * **冲突解决**:现有记忆会被检查是否有重复或矛盾,完成更新。 * **记忆储存**:最终产生的记忆使用向量数据库与图数据库储存,便于后续检索时快速召回。 以上所有流程,仅需调用 `add/message` 接口即可触发,无需您对用户的记忆手动操作。 ## 3. 快速上手 ```python [Python (HTTP)] import requests API_KEY = "YOUR_API_KEY" BASE_URL = "https://memos.memtensor.cn/api/openmem/v1" data = { "user_id": "memos_user_123", "conversation_id": "0610", "messages": [ {"role": "user", "content": "我暑假定好去广州旅游,住宿的话有哪些连锁酒店可选?"}, {"role": "assistant", "content": "您可以考虑【七天、全季、希尔顿】等等"}, {"role": "user", "content": "我选七天"}, {"role": "assistant", "content": "好的,有其他问题再问我。"} ] } res = requests.post( f"{BASE_URL}/add/message", headers={"Authorization": f"Token {API_KEY}"}, json=data ) print(res.json()) ``` ```python [Python (SDK)] from memos.api.client import MemOSClient client = MemOSClient(api_key="YOUR_API_KEY") messages = [ {"role": "user", "content": "我暑假定好去广州旅游,住宿的话有哪些连锁酒店可选?"}, {"role": "assistant", "content": "您可以考虑【七天、全季、希尔顿】等等"}, {"role": "user", "content": "我选七天"}, {"role": "assistant", "content": "好的,有其他问题再问我。"} ] res = client.add_message( messages=messages, user_id="memos_user_123", conversation_id="0610" ) print(res) ``` ```bash [Curl] export MEMOS_API_KEY="YOUR_API_KEY" export MEMOS_BASE_URL="https://memos.memtensor.cn/api/openmem/v1" curl "$MEMOS_BASE_URL/add/message" \ -H "Authorization: Token $MEMOS_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "user_id": "memos_user_123", "conversation_id": "0610", "messages": [ {"role": "user", "content": "我暑假定好去广州旅游,住宿的话有哪些连锁酒店可选?"}, {"role": "assistant", "content": "您可以考虑【七天、全季、希尔顿】等等"}, {"role": "user", "content": "我选七天"}, {"role": "assistant", "content": "好的,有其他问题再问我。"} ] }' ``` > **Note**: 想知道生成了哪些记忆?一键复制上述代码并运行,添加好记忆后,前往[**检索记忆**](/cn/memos_cloud/mem_operations/search_memory)。 需要查看完整字段、请求格式和响应格式?详见 [Add Message 接口文档](/cn/api_docs/core/add_message)。 ## 4. 何时添加消息? 记忆的基础来源于原始消息内容。MemOS 会将您添加的消息统一加工为记忆,用于后续的检索与使用。您可以根据实际场景选择合适的添加时机: * **一次性导入**:将已有的用户历史对话一键导入 MemOS,快速建立初始记忆; * **实时添加**:在用户每次发送消息时,实时将消息添加至 MemOS; * **按轮次添加**:根据业务需要,设置每隔若干轮对话再将用户消息添加至 MemOS。 ## 5. 更多使用方法 下面这些字段用于在添加消息时补充时间、分类、隔离和业务上下文。你可以按场景单独使用,也可以组合使用。 ### 写入用户偏好或行为数据 除了对话内容,用户的个人偏好、行为等一切文本数据信息,都可以作为原始信息,添加到 MemOS。 ```python data = { "user_id": "memos_user_123", "conversation_id": "0901", "messages": [ { "role": "user", "content": """ 喜欢的电影类型: 科幻, 动作, 喜剧 喜欢的电视剧类型: 悬疑, 历史剧 喜欢的书籍类型: 科普, 技术, 自我成长 喜欢的聊天风格: 幽默, 温暖, 轻松闲聊 想让AI提供的帮助类型: 建议, 信息查询, 灵感 我最感兴趣的话题: 人工智能, 未来科技, 电影评论 我希望AI帮助的事情: 规划日常学习计划, 推荐电影和书籍, 提供心情陪伴 """ } ] } ``` ### 写入多模态内容 除了文本信息,MemOS 还支持抽取多模态记忆。当消息包含多模态内容时,MemOS 会提取文本、视觉信息等,处理为用户记忆。 ```python data = { "user_id": "memos_user_123", "conversation_id": "1211", "messages": [ { "role": "user", "content": [ { "type": "text", "text": "我正在研究MemOS。" }, { "type": "image_url", "image_url": { "url": "https://cdn.memtensor.com.cn/img/1758706201390_iluj1c_compressed.png" } } ] }, {"role": "assistant", "content": "好的,需要我为您解答吗?"} ] } ``` ### `chat_time`:指定对话发生时间 MemOS 默认以消息传入时的北京时间作为记忆时间。如果你在批量导入历史对话,可以为每条消息传入 `chat_time`,让生成的记忆保留更准确的时间线。 ```python data = { "user_id": "memos_user_123", "conversation_id": "0930", "messages": [ {"role": "user", "content": "我喜欢吃辣。", "chat_time": "2025-09-12 08:00:00"}, {"role": "assistant", "content": "已记住你喜欢辣味。", "chat_time": "2025-09-12 08:01:00"}, {"role": "user", "content": "我不喜欢重油。", "chat_time": "2025-09-25 12:00:00"}, {"role": "assistant", "content": "记住了,你偏好清爽的辣味。", "chat_time": "2025-09-25 12:01:00"} ] } ``` ### `agent_id`:按 Agent 隔离记忆 添加消息时传入 `agent_id`,可以标识当前对话关联的 Agent,用来区分同一用户在不同 Agent 下产生的记忆。 ```python data = { "user_id": "memos_user_123", "conversation_id": "0610", "agent_id": "health_assistant", "messages": [ {"role": "user", "content": "我今天跑了5公里,膝盖有点酸。"}, {"role": "assistant", "content": "明天建议降低强度。"} ] } ``` > **Note**: 后续检索时,可以通过 `filter` 参数传入 `"agent_id":"health_assistant"`,检索用户与该助手聊天的记忆。详细见[记忆过滤器(filter)](/memos_cloud/features/filters)。 #### 为 Agent 创建记忆 如果开启[为 Agent 创建独立记忆](/memos_cloud/introduction/isolation_filters#为-agent-创建独立记忆-new)功能,MemOS 不仅会为用户抽取记忆,还会以该 `agent_id` 为主体单独生成一份 Agent 记忆,使 Agent 具备自己的长期记忆能力,同时支持与多个用户同时对话并记忆。 ### `tags`:对记忆进行语义分类 MemOS 会为每条记忆自动生成标签。如果你的业务已有标签体系,也可以在添加消息时传入自定义 `tags`,让记忆更贴合业务分类。更多说明见[自定义标签](/memos_cloud/features/custom_tags)。 ```python data = { "user_id": "memos_user_123", "conversation_id": "0610", "tags": ["运动建议", "健身规划"], "messages": [ {"role": "user", "content": "我今天跑了5公里,膝盖有点酸。"}, {"role": "assistant", "content": "明天建议降低强度。"} ] } ``` > **Note**: 后续检索时,可以通过 `filter` 参数传入 `"tags":"运动建议"`,检索围绕该标签的用户记忆。详细见[记忆过滤器(filter)](/memos_cloud/features/filters)。 ### `info`:传入自定义信息 添加消息时带上 `info`,可以把业务场景、来源、状态等结构化信息一并写入,后续检索时用于精确过滤。 常用字段如下: | 字段 | 用途 | | --- | --- | | `business_type` | 业务类型 | | `biz_id` | 业务唯一标识 | | `scene` | 业务或对话场景 | | `custom_status` | 自定义状态 | 你也可以传入其他自定义键值对,所有字段都可以正常存储和检索。 ```python data = { "user_id": "memos_user_123", "conversation_id": "0610", "messages": [ {"role": "user", "content": "帮我查找时间合适的机票。"}, {"role": "assistant", "content": "已找到几班北京到上海的航班。"} ], "info": { "scene": "机票" } } ``` > **Note**: 后续检索时,可以通过 `filter` 参数传入 `"scene":"机票"`,检索围绕该场景的用户记忆。详细见[记忆过滤器(filter)](/memos_cloud/features/filters)。 ### `allow_memory_view`:控制生成的记忆种类 通过 `allow_memory_view` 指定本次添加消息后允许生成的[记忆种类](/memos_cloud/introduction/memory_types),不传时默认生成所有种类。 如下所示,仅生成事件记忆和属性记忆,不会生成事实记忆、偏好记忆等。 ```python data = { "user_id": "memos_user_123", "conversation_id": "0624", "allow_memory_view": ["event", "profile"], "messages": [ {"role": "user", "content": "上周二下午和李四做了方案评审,客户对第二版比较满意。"}, {"role": "assistant", "content": "收到,需要我整理评审结论吗?"} ] } ``` ### `custom_extract_prompt`:自定义抽取提示词 MemOS 默认使用内置策略从消息中抽取记忆。如果默认策略不符合业务需要,可以通过 `custom_extract_prompt` 传入自定义抽取提示词,指定某个环节“要抽取什么”。该配置仅对本次请求生效,不会被保存。 支持的 key 分为两类: | 类别 | 取值 | 作用环节 | | --- | --- | --- | | 记忆种类 | `detail_factual`、`preference`、`skill`、`profile`、`event`、`tool_memory` | 对应[记忆种类](/cn/memos_cloud/introduction/memory_types)的抽取 | | 输入模态 | `image`、`document` | 图片内容、文件内容的抽取 | 使用时注意以下几点: * 自定义提示词仅替换对应环节的默认抽取策略,输出格式等协议约束仍由服务端保留,记忆仍按默认结构返回。 * 未配置 `document` 时,文件内容沿用 `detail_factual` 的自定义提示词。 * 记忆种类的 key 仅在对应种类被 `allow_memory_view` 允许时生效,`image` 和 `document` 不受 `allow_memory_view` 影响。 如下所示,本次添加只抽取与出行安排相关的事实,并要求图片只提取可见的文字信息: ```python data = { "user_id": "memos_user_123", "conversation_id": "0827", "custom_extract_prompt": { "detail_factual": "仅抽取与出行安排相关的事实,忽略寒暄与闲聊内容。", "image": "仅提取图片中可见的文字与票据信息。" }, "messages": [ { "role": "user", "content": [ {"type": "text", "text": "帮我看看这张机票行程单。"}, {"type": "image_url", "image_url": {"url": "https://example.com/itinerary.png"}} ] } ] } ``` ### 群聊:`user_id` 传入列表 多个用户在同一会话中对话时,`user_id` 支持传入列表,表示记忆所属的主体。使用 `role_id` 和 `role_name` 标识每条消息的发言人。详见[群聊](/cn/memos_cloud/features/group_chat)。 ```python data = { "user_id": ["memos_user_1", "memos_user_2"], "agent_id": "memos_agent", "conversation_id": "group_conv_001", "messages": [ {"role": "user", "role_id": "memos_user_1", "role_name": "张三", "content": "下周二方案评审,时间合适吗?"}, {"role": "user", "role_id": "memos_user_2", "role_name": "李四", "content": "我可以,下午两点。"}, {"role": "assistant", "role_id": "memos_agent", "content": "已记录,下周二下午两点方案评审。"} ] } ``` ## 6. 常见错误与排查 | 错误码 | 常见原因 | 处理方式 | | --- | --- | --- | | `40000` | 请求 JSON 结构不符合要求,或字段类型错误 | 检查 `messages` 是否为数组,`role` / `content` 是否放在每条消息对象中 | | `40002` | 必填字段为空 | 检查 `user_id`、`conversation_id`、`messages` 是否都已传入且非空 | | `40011` | `conversation_id` 过长 | 使用短 ID,不要把完整对话、用户输入或 JSON 放进 `conversation_id` | | `40013` | `messages` 总长度超限 | 拆分历史对话,分多次调用写入 | | `40305` | 单次输入超过 token 上限 | 缩短单次写入内容,优先保留用户关键事实和偏好 | | `40309` | 单位时间输入 token 超限 | 降低并发和批量导入速度,分批重试 | | `50143` / `50144` | 记忆或消息写入失败 | 检查请求内容后稍后重试;如果持续出现,请联系支持 | ## 7. 更多功能 如果你需要更复杂的写入方式,可以继续了解这些扩展能力。 - [多模态消息](/cn/memos_cloud/features/multimodal): 支持文本、图片、文档等多种输入内容 - [异步模式](/cn/memos_cloud/features/async_mode): 控制消息写入后的处理方式 - [群聊](/cn/memos_cloud/features/group_chat): 多用户同一会话,为每个参与者抽取记忆 --- # Search Memory (/cn/memos_cloud/mem_operations/search_memory) ## 1. 什么是检索记忆? 检索记忆是指 MemOS 在用户提出问题时,结合开发者预先定义的过滤条件,从记忆库中召回最相关、最重要的记忆内容。模型在生成回答时,会参考这些已召回的记忆,从而给出更加准确、贴切且符合用户上下文的回复。 > **Note**: ** 为什么需要检索记忆?** > > * 无需从头构建上下文,直接获取正确且可靠的记忆; > * 通过过滤条件等方式,确保召回的记忆始终与当前问题高度相关。 ## 2. 关键参数 * **查询内容(query)**:用户的提问内容,用于检索的自然语言问题或陈述,系统将基于语义匹配相关记忆。 * **检索记忆种类(include_memory_view)**:控制允许检索的[记忆种类](/cn/memos_cloud/introduction/memory_types)。 * **召回上限(memory_limit_number)**:所有记忆按照相关性排序后,召回的条数上限。 * **记忆过滤(filter)**:基于 JSON 的逻辑条件,用于过滤 agent、create_time、tags、info 等字段,缩小记忆检索的范围;也可以分别对用户/Agent 记忆、公共记忆和知识库记忆设置过滤条件。 * **相关性阈值(relativity)**:召回的记忆与用户提问内容的语义匹配程度。相关性分数越高,该记忆与当前用户提问越相关。相关性阈值用于约束召回记忆的匹配程度,低于该值的记忆将被过滤。 ## 3. 工作原理 * **查询内容重写**:MemOS 会对输入的自然语言查询进行清理与语义增强,自动补全关键信息与检索意图,以提升后续检索的准确性。 * **记忆召回** * **混合检索与排序**:系统基于重写后的查询生成嵌入向量,结合关键词检索与向量语义检索的混合策略召回候选记忆,对候选记忆进行相关性排序。 * **记忆过滤与筛选**:基于逻辑条件与比较运算符对记忆进行结构化过滤,缩小记忆检索的范围;按开发者设定的相关性阈值筛选排序后的记忆,控制召回结果质量。 * **结果去重**:对召回的候选记忆进行跨源去重与语义聚合处理。 * **输出记忆**:最终结果根据设定的记忆条数上限返回,600ms 内响应并返回,用于后续推理与回答生成。 以上所有流程,仅需调用`search/memory`接口即可触发,无需您对用户的记忆手动操作。 ## 4. 快速上手 ```python [Python (HTTP)] import requests API_KEY = "YOUR_API_KEY" BASE_URL = "https://memos.memtensor.cn/api/openmem/v1" data = { "query": "我国庆想出去玩,帮我推荐个没去过的城市,以及没住过的酒店品牌", "user_id": "memos_user_123", "conversation_id": "0928" } res = requests.post( f"{BASE_URL}/search/memory", headers={"Authorization": f"Token {API_KEY}"}, json=data ) print(res.json()) ``` ```python [Python (SDK)] from memos.api.client import MemOSClient client = MemOSClient(api_key="YOUR_API_KEY") res = client.search_memory( query="我国庆想出去玩,帮我推荐个没去过的城市,以及没住过的酒店品牌", user_id="memos_user_123", conversation_id="0928" ) print(res) ``` ```bash [Curl] curl --request POST \ --url https://memos.memtensor.cn/api/openmem/v1/search/memory \ --header 'Authorization: Token YOUR_API_KEY' \ --header 'Content-Type: application/json' \ --data '{ "query": "我国庆想出去玩,帮我推荐个没去过的城市,以及没住过的酒店品牌", "user_id": "memos_user_123", "conversation_id": "0928" }' ``` > **Note**: 开启[为 Agent 创建独立记忆](/cn/memos_cloud/introduction/isolation_filters#为-agent-创建独立记忆-new),可单独传入 `agent_id`,检索该 Agent 记忆。其他情况下,`user_id` 为必填项。 需要查看完整字段、请求格式和响应格式?详见 [Search Memory 接口文档](/cn/api_docs/core/search_memory)。 ## 5. 带记忆的 Prompt 模版 召回的记忆可以直接添加到你开发 AI 应用的 Prompt 中。如下所示,MemOS 为你提供了实践参考。 **展开查看完整 Prompt 模板** ```text # Role 你是一个拥有长期记忆能力的智能助手 (MemOS Assistant)。你的目标是结合检索到的记忆片段,为用户提供高度个性化、准确且逻辑严密的回答。 # System Context - 当前时间: 2026-01-06 15:05 (请以此作为判断记忆时效性的基准) # Memory Data 以下是 MemOS 检索到的相关信息,分为“事实”和“偏好”。 - **事实 (Facts)**:可能包含用户属性、历史对话记录或第三方信息。 - **特别注意**:其中标记为 '[assistant观点]'、'[模型总结]' 的内容代表 **AI 过去的推断**,**并非**用户的原话。 - **偏好 (Preferences)**:用户对回答风格、格式或逻辑的显式/隐式要求。 -[2025-12-26 21:45] 用户计划在暑假期间前往广州旅游,并选择了七天连锁酒店作为住宿选项。 -[2025-12-26 14:26] 用户的名字是Grace。 -[2026-01-04 20:41] [显式偏好] 用户喜欢去南方旅游 -[2025-12-26 21:45] [隐式偏好] 用户可能偏好性价比较高的酒店选择。 # Critical Protocol: Memory Safety (记忆安全协议) 检索到的记忆可能包含**AI 自身的推测**、**无关噪音**或**主体错误**。你必须严格执行以下**“四步判决”**,只要有一步不通过,就**丢弃**该条记忆: 1. **来源真值检查 (Source Verification)**: - **核心**:区分“用户原话”与“AI 推测”。 - 如果记忆带有 '[assistant观点]' 等标签,这仅代表AI过去的**假设**,**不可**将其视为用户的绝对事实。 - *反例*:记忆显示 '[assistant观点] 用户酷爱芒果'。如果用户没提,不要主动假设用户喜欢芒果,防止循环幻觉。 - **原则:AI 的总结仅供参考,权重大幅低于用户的直接陈述。** 2. **主语归因检查 (Attribution Check)**: - 记忆中的行为主体是“用户本人”吗? - 如果记忆描述的是**第三方**(如“候选人”、“面试者”、“虚构角色”、“案例数据”),**严禁**将其属性归因于用户。 3. **强相关性检查 (Relevance Check)**: - 记忆是否直接有助于回答当前的 'Original Query'? - 如果记忆仅仅是关键词匹配(如:都提到了“代码”)但语境完全不同,**必须忽略**。 4. **时效性检查 (Freshness Check)**: - 记忆内容是否与用户的最新意图冲突?以当前的 'Original Query' 为最高事实标准。 # Instructions 1. **审视**:先阅读 '',执行“四步判决”,剔除噪音和不可靠的 AI 观点。 2. **执行**: - 仅使用通过筛选的记忆补充背景。 - 严格遵守 '' 中的风格要求。 3. **输出**:直接回答问题,**严禁**提及“记忆库”、“检索”或“AI 观点”等系统内部术语。 # Original Query 我国庆想出去玩,帮我推荐个没去过的城市,以及没住过的酒店品牌 ``` ## 6. 更多使用方法 ### `conversation_id`:优先召回当前会话记忆 检索记忆时,你可以传入指定的`conversation_id`,MemOS 会优先召回与当前会话内容相关的记忆;不传则全局检索用户的长期记忆,适合在你需要直接检索用户全局画像时使用。 ```python data = { "user_id": "memos_user_123", "query": "帮我继续规划国庆旅行。", "conversation_id": "0928" } ``` ### `include_memory_view`:指定检索的记忆种类 支持通过 `include_memory_view` 控制本次检索允许返回的[记忆种类](/cn/memos_cloud/introduction/memory_types)。不传时默认召回事实记忆和偏好记忆。 ```python data = { "user_id": "memos_user_123", "query": "上周发生了什么?", "include_memory_view": ["event", "profile"] #表示只检索事件记忆和属性记忆 } ``` > **Warning**: 传入该字段时,`include_preference`、`include_skill`、`include_tool_memory`等旧参数不再生效;此时,`memory_limit_number` 表示所有记忆混排后的总返回条数上限。 ### `filter`:精确过滤检索范围 MemOS 支持通过 `filter` 按标签、时间、业务字段等条件缩小检索范围,也支持分别对用户记忆、知识库记忆和公共记忆设置过滤条件。 示例一:检索 2025 年内所有和“阅读”相关的对话记忆 ```python data = { "user_id": "memos_user_123", "query": "整理我今年和阅读相关的要点", "filter": { "and": [ {"tags": {"contains": "阅读"}}, {"create_time": {"gte": "2025-01-01"}}, {"create_time": {"lte": "2025-12-31"}}, {"scene": "chat"}, ], }, } ``` 示例二:对知识库、用户记忆、公共记忆分别过滤 ```python data = { "user_id": "memos_user_123", "query": "结合已有知识库中的制度、我的对话记录和项目公告,整理一份合规要点", "knowledgebase_ids": ["kb_xxx"], "filter": { "knowledgebase": { "and": [ {"tags": {"contains": "制度"}}, {"create_time": {"gte": "2025-01-01"}}, {"create_time": {"lte": "2025-12-31"}}, ] }, "user": { "and": [ {"agent_id": "compliance_assistant"}, {"scene": "chat"}, {"create_time": {"gte": "2025-06-01"}}, ] }, "public": { "and": [ {"tags": {"contains": "公告"}}, ] }, }, } ``` > **Note**: 更多过滤条件和嵌套写法,详见[记忆过滤](/cn/memos_cloud/features/filters)。 ### `relativity` / `memory_limit_number`:控制召回质量和数量 * 传入 `relativity` ,用于提高召回相关性门槛; * 传入 `memory_limit_number` ,限制所有记忆混排后的总返回条数。 ```python data = { "user_id": "memos_user_123", "query": "为我规划5天的成都游。", "relativity": 0.8, # 默认 0.45,范围 0-1 "memory_limit_number": 9 #默认 9,最大 25 } ``` ## 7. 常见错误与排查 | 错误码 | 常见原因 | 处理方式 | | --- | --- | --- | | `40000` | 请求体结构错误,或字段类型不符合要求 | 检查 `query` 是否为字符串,`knowledgebase_ids` 是否为字符串数组 | | `40002` | 缺少必填字段 | 检查 `user_id` 和 `query` 是否都已传入且非空 | | `40011` | `conversation_id` 过长 | 使用短 ID,不要把完整问题或历史对话放进 `conversation_id` | | `40012` | `relativity` 非法 | 传入 0 到 1 之间的数字 | | `40305` | 单次输入超过 token 上限 | 缩短 `query`,不要把长文档直接放进检索查询 | | `50123` | 知识库未关联当前项目 | 回到 [项目配置](/cn/api_docs/start/configuration) 确认知识库已关联到当前 API Key 所属项目 | | `50005` | 搜索服务暂时不可用 | 稍后重试;如果持续出现,请联系支持 | ## 8. 更多功能 - [删除记忆](/memos_cloud/mem_operations/delete_memory): 删除指定的记忆条目或用户记忆 - [记忆过滤](/memos_cloud/features/filters): 按标签、时间等条件过滤召回的记忆结果 - [知识库](/memos_cloud/features/knowledge_base): 指定检索可访问的知识库范围 --- # 删除记忆 (/cn/memos_cloud/mem_operations/delete_memory) ## 1. 选择删除方式 当前支持 3 种以下三种不同的删除方式,请按照你的使用场景选择其中一种传入。 | 删除方式 | 传入字段 | 适用场景 | | :--- | :--- | :--- | | 精确删除 | `memory_ids[]` | 删除至少一条记忆,memory_id 是 search 或 get/memory 返回结果中的 id | | 删除用户记忆 | `user_id` | 清除当前项目下,某用户的全部记忆 | | 删除 Agent 记忆 | `agent_id` | 清除当前项目下,某 Agent 的全部记忆 | > **Warning**: 注意 > > - 三个参数互斥,不可同时传入,每次调用只能选择其中一种删除方式。 > > - 删除只会作用在当前 API Key 所属的项目,请先确认 API Key、项目和待删除记忆属于同一个项目。 > > - 请勿传入 `conversation_id`、`knowledgebase_id` 等参数,当前不支持按照这些维度删除记忆。 ## 2. 精确删除记忆 精确删除适合处理误写入、过期、错误归因或用户主动要求删除的单条记忆。 ### 2.1 定位要删除的记忆 [检索记忆](/cn/memos_cloud/mem_operations/search_memory) 或获取记忆时,如果你发现了需要删除的记忆,每条返回的记忆都有自己的 `memory_id`,删除时复制这条记忆对应的 `id` 即可。 ```json { "memory_detail_list": [ { "id": "e2a7c194-7062-4fa5-a6c0-bbe554d05d60", # 要删除的 memory_id "memory_key": "用户对冰淇淋的喜好", "memory_value": "[user观点]用户喜欢吃冰淇淋。", "memory_type": "WorkingMemory", "memory_time": null, "conversation_id": "0610", "status": "activated", "confidence": 0, "tags": [ "饮食", "喜好", "冰淇淋" ], "update_time": 1761315278665, "relativity": 0.7524414 } ] } ``` ### 2.2 调用删除接口 ```python [Python (HTTP)] import requests API_KEY = "YOUR_API_KEY" BASE_URL = "https://memos.memtensor.cn/api/openmem/v1" data = { "memory_ids": ["6b23b583-f4c4-4a8f-b345-58d0c48fea04"] } res = requests.post( f"{BASE_URL}/delete/memory", headers={"Authorization": f"Token {API_KEY}"}, json=data ) print(res.json()) ``` ```python [Python (SDK)] from memos.api.client import MemOSClient client = MemOSClient(api_key="YOUR_API_KEY") res = client.delete_memory( memory_ids=["6b23b583-f4c4-4a8f-b345-58d0c48fea04"] ) print(res) ``` ```bash [Curl] curl --request POST \ --url https://memos.memtensor.cn/api/openmem/v1/delete/memory \ --header 'Authorization: Token YOUR_API_KEY' \ --header 'Content-Type: application/json' \ --data '{ "memory_ids": ["6b23b583-f4c4-4a8f-b345-58d0c48fea04"] }' ``` ### 2.3 验证删除结果 接口返回 `data.success: true` 表示删除请求成功,删除后可通过再次 [检索记忆](/cn/memos_cloud/mem_operations/search_memory) 验证该条记忆已被删除。 ```json { "code": 0, "data": { "success": true }, "message": "ok" } ``` ## 3. 删除用户全部记忆 当需要清空某个用户在当前项目下的全部记忆时,传入 `user_id`。 > **Warning**: 执行前请确认: > > - `user_id` 是你要清除记忆的用户 ID。 > - API Key 属于该用户所在的项目。 > - 不再需要该用户在当前项目下的事实、偏好、属性、事件、技能、工具记忆。 ```python [Python (HTTP)] import requests API_KEY = "YOUR_API_KEY" BASE_URL = "https://memos.memtensor.cn/api/openmem/v1" data = { "user_id": "memos_user_123" } res = requests.post( f"{BASE_URL}/delete/memory", headers={"Authorization": f"Token {API_KEY}"}, json=data ) print(res.json()) ``` ```python [Python (SDK)] from memos.api.client import MemOSClient client = MemOSClient(api_key="YOUR_API_KEY") res = client.delete_memory(user_id="memos_user_123") print(res) ``` ```bash [Curl] curl --request POST \ --url https://memos.memtensor.cn/api/openmem/v1/delete/memory \ --header 'Authorization: Token YOUR_API_KEY' \ --header 'Content-Type: application/json' \ --data '{ "user_id": "memos_user_123" }' ``` 全量删除后,使用同一个 `user_id` 再次搜索该用户的历史偏好或事实,确认不再返回旧记忆。 ## 4. 删除 Agent 全部记忆 当需要清空某个 Agent 在当前项目下的全部记忆时,传入 `agent_id`。 > **Warning**: 执行前请确认: > > - 该 Agent 已开启[独立记忆功能](/cn/memos_cloud/introduction/isolation_filters#为-agent-创建独立记忆-new)。 > - `agent_id` 是你要清除记忆的 Agent ID。 > - API Key 属于该 Agent 所在的项目。 > - 不再需要该 Agent 在当前项目下的事实、偏好、属性、事件、技能、工具记忆。 ```python [Python (HTTP)] import requests API_KEY = "YOUR_API_KEY" BASE_URL = "https://memos.memtensor.cn/api/openmem/v1" data = { "agent_id": "memos_agent" } res = requests.post( f"{BASE_URL}/delete/memory", headers={"Authorization": f"Token {API_KEY}"}, json=data ) print(res.json()) ``` ```python [Python (SDK)] from memos.api.client import MemOSClient client = MemOSClient(api_key="YOUR_API_KEY") res = client.delete_memory(agent_id="memos_agent") print(res) ``` ```bash [Curl] curl --request POST \ --url https://memos.memtensor.cn/api/openmem/v1/delete/memory \ --header 'Authorization: Token YOUR_API_KEY' \ --header 'Content-Type: application/json' \ --data '{ "agent_id": "memos_agent" }' ``` 全量删除后,使用同一个 `agent_id` 再次搜索该 Agent 的记忆,确认不再返回旧记忆。 ## 5. 在控制台删除记忆 如果只是临时删除一条或少量记忆,可以直接在控制台操作: 1. 登录 [MemOS 控制台](https://memos-dashboard.openmem.net/cn/memoryList),确认当前项目是要操作的项目。 2. 进入「记忆列表」,通过搜索框、主体 ID、主体类型或时间范围找到目标记忆。 3. 点击「查看详情」,核对 记忆 ID 和 记忆内容,确认不是同一用户下的相似记忆。 4. 点击「删除」并二次确认;如果要删除多条记忆,可先勾选多条记录,再点击「批量删除」。 5. 删除后刷新列表,或用相同条件重新搜索,确认该记忆不再出现。 > **Note**: 如果需要在业务系统中自动删除,或需要从日志、检索结果中复制 `memory_id` 后批量处理,请调用 delete/memory 接口实现。 ![控制台删除记忆](https://cdn.memtensor.com.cn/img/1781505876499_qclb2m_compressed.png) ## 6. 常见错误与排查 | 错误码 | 常见原因 | 处理方式 | | :--- | :--- | :--- | | `40000` | 请求体结构错误,或传入了不支持的字段组合 | 确认只传 `memory_ids`、`user_id`、`agent_id` 其中一种(三者互斥);`memory_ids` 必须是非空字符串数组 | | `40002` | 必填字段为空 | 检查是否漏传 `memory_ids` / `user_id` / `agent_id`,或传了空字符串、空数组 | | `40103` / `40132` | API Key 无效、过期或无权访问当前项目 | 回到 [项目配置](/cn/api_docs/start/configuration) 确认当前项目和 API Key 是否匹配 | | `40306` | 删除记忆鉴权失败 | 确认该记忆属于当前 API Key 所属项目,且你有权限删除 | | `40307` | `memory_id` 不存在 | 重新通过 `search/memory` 或 `get/memory` 获取最新 `id`,不要使用 `conversation_id`、`user_id` 或知识库 ID | | `40308` | `user_id` 或 `agent_id` 不存在 | 确认该用户/Agent 是否在当前项目下写入过记忆;若传 `agent_id`,确认该 Agent 已开启独立记忆并写入过记忆 | 更多错误码说明,请查看 [错误码](/cn/api_docs/help/error_codes)。 需要查看完整字段、请求格式和响应格式?详见 [Delete Memory 接口文档](/cn/api_docs/core/delete_memory)。 --- # 修改记忆 (/cn/memos_cloud/mem_operations/update_memory) ## 1. 功能说明 本接口用于手动修改已有的记忆,支持用户主动修正记忆内容、归档过时记忆等。 ## 2. 关键参数 | 字段 | 类型 | 必填 | 说明 | | :--- | :--- | :--- | :--- | | `memory_id` | string | 是 | 记忆 ID,来自 `search/memory` 或 `get/memory` 返回结果中的 `id` | | `content` | string | 否 | 更新后的记忆内容 | | `title` | string | 否 | 更新后的记忆标题 | | `status` | string | 否 | 记忆状态 | ## 3. 使用示例 ### 3.1 定位要修改的记忆 [检索记忆](/cn/memos_cloud/mem_operations/search_memory)或获取记忆时,每条返回的记忆都有自己的 `id`,修改时使用该 `id` 作为 `memory_id`。 ### 3.2 调用修改接口 ```python [Python (HTTP)] import requests API_KEY = "YOUR_API_KEY" BASE_URL = "https://memos.memtensor.cn/api/openmem/v1" data = { "memory_id": "mem_event_001", "title": "和陈默去西湖露营看星星", "content": "上周六和好友陈默去西湖边露营,天气很好,晚上一起看了星星。" } res = requests.post( f"{BASE_URL}/update/memory", headers={"Authorization": f"Token {API_KEY}"}, json=data ) print(res.json()) ``` ```python [Python (SDK)] # 请确保已安装 MemOS(pip install MemoryOS -U) from memos.api.client import MemOSClient client = MemOSClient(api_key="YOUR_API_KEY") res = client.update_memory( memory_id="mem_event_001", title="和陈默去西湖露营看星星", content="上周六和好友陈默去西湖边露营,天气很好,晚上一起看了星星。" ) print(res) ``` ```bash [Curl] curl --request POST \ --url https://memos.memtensor.cn/api/openmem/v1/update/memory \ --header 'Authorization: Token YOUR_API_KEY' \ --header 'Content-Type: application/json' \ --data '{ "memory_id": "mem_event_001", "title": "和陈默去西湖露营看星星", "content": "上周六和好友陈默去西湖边露营,天气很好,晚上一起看了星星。" }' ``` ## 4. 响应说明 接口返回 `code: 0` 表示修改成功。修改后可通过 [检索记忆](/cn/memos_cloud/mem_operations/search_memory) 或 `get/memory/{memory_id}` 验证更新结果。 ```json { "code": 0, "message": "ok", "data": { "success": true } } ``` > **Note**: 如果需要彻底删除记忆,请使用 [删除记忆](/cn/memos_cloud/mem_operations/delete_memory) 接口。 ## 5. 常见错误与排查 | 错误码 | 常见原因 | 处理方式 | | :--- | :--- | :--- | | `40000` | 请求体结构错误,或字段类型不符 | 确认 `memory_id` 为字符串,`status` 为允许的枚举值 | | `40002` | 必填字段为空 | 检查是否传入了 `memory_id` | | `40103` / `40132` | API Key 无效、过期或无权访问当前项目 | 回到 [项目配置](/cn/api_docs/start/configuration) 确认 API Key 与项目匹配 | | `40307` | `memory_id` 不存在 | 重新通过 `search/memory` 或 `get/memory` 获取最新 `id` | 更多错误码说明,请查看 [错误码](/cn/api_docs/help/error_codes)。 --- # Add Feedback (/cn/memos_cloud/mem_operations/add_feedback) ## 1. 何时添加反馈? MemOS 反馈机制用于接收用户对模型回答、知识内容或历史记忆的自然语言反馈,并自动完成记忆校正与更新。你不需要手动定位具体记忆条目,只需要把用户反馈传入 `add/feedback`。 | 对比维度 | 自然语言反馈 | 定点修改记忆 | | --- | --- | --- | | 使用方式 | 用自然语言描述问题或修正信息 | 直接指定某条 memory 进行编辑 | | 用户门槛 | 低,适合非技术用户 | 较高,通常由开发者或管理员操作 | | 系统参与度 | 系统自动解析、定位、关联更新 | 人工主导更新 | | 适用场景 | 对话纠错、知识过期、业务规则变更 | 精确修订、结构化维护 | ## 2. 关键参数 * **反馈内容(feedback_content)**:用户对模型回答、知识内容或记忆结果的自然语言反馈。 * **用户标识(user_id)**:反馈内容所关联的用户唯一标识符。 * **会话标识(conversation_id)**:反馈内容所关联的会话唯一标识符,用于补充上下文。 * **知识库范围(allow_knowledgebase_ids)**:反馈产生的新记忆允许写入的知识库列表。 ## 3. 工作原理 以 Chatbot 场景为例,用户可以在模型回答下方点击“反馈错漏”,填写对本次回答的反馈并提交。 ![image.png](https://cdn.memtensor.com.cn/img/1770716602140_1z3yi5_compressed.png) 根据反馈内容,后端完成一次 MemOS `add/feedback` 接口调用,触发记忆更新。 - **有效性分析**:结合当前会话上下文解析反馈内容,判断是否为有效信息、是否与对话内容相关。 - **更新类型识别**:将反馈更新请求分类为关键词替换或语义更新。 - **更新记忆**:写入新记忆,并对存在冲突、过时或被纠正的已有记忆进行更新或覆盖。 ## 4. 快速上手 ### 语义更新知识库记忆 当企业政策、知识库内容或业务规则发生变化时,可以直接把用户的自然语言反馈传入 MemOS,让系统生成新的高权重记忆。 #### 提交自然语言反馈 财务主管在会话中反馈:办公类软件的采购上限应为 600 元,而不是 800 元。 ```python [Python (HTTP)] import requests API_KEY = "YOUR_API_KEY" BASE_URL = "https://memos.memtensor.cn/api/openmem/v1" data = { "user_id": "memos_user_123", "conversation_id": "memos_feedback_conv", "feedback_content": "办公类软件的采购上限是600元,而不是800元。", "allow_knowledgebase_ids": ["basee5ec9050-c964-484f-abf1-ce3e8e2aa5b7"] } res = requests.post( f"{BASE_URL}/add/feedback", headers={"Authorization": f"Token {API_KEY}"}, json=data ) print(res.json()) ``` ```python [Python (SDK)] from memos.api.client import MemOSClient client = MemOSClient(api_key="YOUR_API_KEY") res = client.add_feedback( user_id="memos_user_123", conversation_id="memos_feedback_conv", feedback_content="办公类软件的采购上限是600元,而不是800元。", allow_knowledgebase_ids=["basee5ec9050-c964-484f-abf1-ce3e8e2aa5b7"] ) print(res) ``` ```bash [Curl] curl --request POST \ --url https://memos.memtensor.cn/api/openmem/v1/add/feedback \ --header 'Authorization: Token YOUR_API_KEY' \ --header 'Content-Type: application/json' \ --data '{ "user_id": "memos_user_123", "conversation_id": "memos_feedback_conv", "feedback_content": "办公类软件的采购上限是600元,而不是800元。", "allow_knowledgebase_ids": ["basee5ec9050-c964-484f-abf1-ce3e8e2aa5b7"] }' ``` #### 检索验证更新结果 反馈处理完成后,任意其他用户搜索【软件报销制度】时,获取一条新增高权重记忆【办公类软件的采购上限为600元,而不是800元】。 ```python [Python (HTTP)] import requests API_KEY = "YOUR_API_KEY" BASE_URL = "https://memos.memtensor.cn/api/openmem/v1" data = { "user_id": "memos_user_123", "conversation_id": "memos_feedback_check", "query": "帮我查一下软件采购报销额度。", "knowledgebase_ids": ["basee5ec9050-c964-484f-abf1-ce3e8e2aa5b7"] } res = requests.post( f"{BASE_URL}/search/memory", headers={"Authorization": f"Token {API_KEY}"}, json=data ) print(res.json()) ``` ```python [Python (SDK)] from memos.api.client import MemOSClient client = MemOSClient(api_key="YOUR_API_KEY") res = client.search_memory( user_id="memos_user_123", conversation_id="memos_feedback_check", query="帮我查一下软件采购报销额度。", knowledgebase_ids=["basee5ec9050-c964-484f-abf1-ce3e8e2aa5b7"] ) print(res) ``` ```bash [Curl] curl --request POST \ --url https://memos.memtensor.cn/api/openmem/v1/search/memory \ --header 'Authorization: Token YOUR_API_KEY' \ --header 'Content-Type: application/json' \ --data '{ "user_id": "memos_user_123", "conversation_id": "memos_feedback_check", "query": "帮我查一下软件采购报销额度。", "knowledgebase_ids": ["basee5ec9050-c964-484f-abf1-ce3e8e2aa5b7"] }' ``` ##### **输出结果** ```python "memory_detail_list": [ { "id": "8a4f3d2e-c417-4e53-bc25-54451abd5ac8", "memory_key": "软件采购报销制度(试行版)", "memory_value": "该制度要求办公类软件的采购上限为800元,适用于文档编辑和表格处理。", "memory_type": "LongTermMemory", "conversation_id": "default_session", "relativity": 0.8931847 }, { "id": "a72a04d1-d7ba-4ebd-9410-0097bfa6c20d", "memory_key": "办公软件采购上限", "memory_value": "用户确认办公类软件的采购上限是600元,而不是800元。", "memory_type": "WorkingMemory", "conversation_id": "memos_feedback_conv", "relativity": 0.7196722 } ] ``` [控制台-知识库](https://memos-dashboard.openmem.net/cn/knowledgeBase/)中也会展示通过自然语言交互更正或补全的知识库记忆。 ![image.png](https://cdn.memtensor.com.cn/img/1765970178683_5tuxe4_compressed.png) ### 关键词替换记忆 如果用户明确指出某个名称、规则或字段需要整体替换,也可以直接用自然语言描述替换意图。 ```python data = { "user_id": "memos_user_123", "conversation_id": "memos_feedback_conv", "feedback_content": "从现在开始我改名了,把用户1号统一替换为用户2号", "allow_knowledgebase_ids": ["basee5ec9050-c964-484f-abf1-ce3e8e2aa5b7"] } ``` ## 5. 常见错误与排查 | 错误码 | 常见原因 | 处理方式 | | --- | --- | --- | | `40000` | 请求 JSON 结构不符合要求,或字段类型错误 | 检查 `feedback_content` 是否为字符串,`allow_knowledgebase_ids` 是否为字符串数组 | | `40002` | 必填字段为空 | 检查 `user_id`、`conversation_id`、`feedback_content` 是否都已传入且非空 | | `40011` | `conversation_id` 过长 | 使用短 ID,不要把完整对话、用户输入或 JSON 放进 `conversation_id` | | `40305` | 单次输入超过 token 上限 | 缩短反馈内容,保留需要修正的关键信息 | | `40309` | 单位时间输入 token 超限 | 降低反馈写入并发,分批重试 | | `50123` | 知识库未关联当前项目 | 回到 [项目配置](/cn/api_docs/start/configuration),确认知识库已关联到当前 API Key 所属项目 | | `50145` | 保存反馈并写入记忆失败 | 检查请求内容后稍后重试;如果持续出现,请联系支持 | 需要查看完整字段、请求格式和响应格式?详见 [Add Feedback 接口文档](/cn/api_docs/message/add_feedback)。 --- # 持续对话 Chat (/cn/memos_cloud/mem_operations/chat) ## 1. 何时使用 Chat 接口 Chat 接口适合用于快速搭建带长期记忆能力的 AI 对话应用。你只需要传入用户本轮消息,MemOS 会自动完成记忆召回、Prompt 拼装、模型回答和对话写入。 - **一体化对话式 AI**:一个接口即可完成对话生成,无需自建复杂链路。 - **记忆自动处理**:自动提取、更新并检索记忆,减少手动维护成本。 - **持续上下文**:在跨轮次、跨天甚至跨会话中保持连贯理解。 ## 2. 对比记忆操作接口 **使用 Chat**: 适合通用 AI 对话、业务 PoC 和快速验证 **使用记忆操作接口**: 适合复杂 Agent 和业务系统深度集成 | 对比维度 | Chat 接口 | 记忆操作接口 | | --- | --- | --- | | 接入复杂度 | 低,开箱即用 | 中等,需要自行编排 | | 记忆管理 | 自动处理 | 手动添加、检索、拼装 | | 模型回答 | MemOS 内置模型生成 | 自行调用外部模型 | | 控制能力 | 适合常规配置 | 适合复杂链路和精细控制 | ## 3. 工作原理 ![chat接口流程.png](https://cdn.memtensor.com.cn/img/1765973438090_tskx7x_compressed.png) 1. 如存在用户历史消息,可先调用 `add/message` 写入 MemOS。 2. 当终端用户发送消息时,你的 AI 应用调用 `chat` 接口,并传入用户消息及相关参数。 3. MemOS 召回与当前用户消息相关的历史记忆,并拼装自定义指令、当前会话上下文和用户记忆。 4. MemOS 调用模型生成回答,并将结果返回给你的 AI 应用。 5. 默认情况下,MemOS 会在后台异步处理用户消息和模型回复,并加工写入记忆。 ## 4. 快速上手 ### 可选:添加历史消息 如果你已有历史对话,可以先调用 `add/message` 写入 MemOS;如果是全新用户或全新会话,可以跳过这一步,直接调用 Chat。 ```python [Python (HTTP)] import requests API_KEY = "YOUR_API_KEY" BASE_URL = "https://memos.memtensor.cn/api/openmem/v1" data = { "user_id": "memos_user_123", "conversation_id": "0610", "messages": [ {"role": "user", "content": "我暑假定好去广州旅游,住宿的话有哪些连锁酒店可选?"}, {"role": "assistant", "content": "您可以考虑【七天、全季、希尔顿】等等"}, {"role": "user", "content": "我选七天"}, {"role": "assistant", "content": "好的,有其他问题再问我。"} ] } res = requests.post( f"{BASE_URL}/add/message", headers={"Authorization": f"Token {API_KEY}"}, json=data ) print(res.json()) ``` ```python [Python (SDK)] from memos.api.client import MemOSClient client = MemOSClient(api_key="YOUR_API_KEY") messages = [ {"role": "user", "content": "我暑假定好去广州旅游,住宿的话有哪些连锁酒店可选?"}, {"role": "assistant", "content": "您可以考虑【七天、全季、希尔顿】等等"}, {"role": "user", "content": "我选七天"}, {"role": "assistant", "content": "好的,有其他问题再问我。"} ] res = client.add_message( messages=messages, user_id="memos_user_123", conversation_id="0610" ) print(res) ``` ```bash [Curl] curl --request POST \ --url https://memos.memtensor.cn/api/openmem/v1/add/message \ --header 'Authorization: Token YOUR_API_KEY' \ --header 'Content-Type: application/json' \ --data '{ "user_id": "memos_user_123", "conversation_id": "0610", "messages": [ {"role": "user", "content": "我暑假定好去广州旅游,住宿的话有哪些连锁酒店可选?"}, {"role": "assistant", "content": "您可以考虑【七天、全季、希尔顿】等等"}, {"role": "user", "content": "我选七天"}, {"role": "assistant", "content": "好的,有其他问题再问我。"} ] }' ``` ### 调用 Chat 发起对话 调用 `chat` 时,MemOS 会自动检索相关记忆并生成回答。 ```python [Python (HTTP)] import requests API_KEY = "YOUR_API_KEY" BASE_URL = "https://memos.memtensor.cn/api/openmem/v1" data = { "user_id": "memos_user_123", "conversation_id": "0928", "query": "我国庆想出去玩,帮我推荐个没去过的城市,以及没住过的酒店品牌" } res = requests.post( f"{BASE_URL}/chat", headers={"Authorization": f"Token {API_KEY}"}, json=data ) print(res.json()) ``` ```python [Python (SDK)] from memos.api.client import MemOSClient client = MemOSClient(api_key="YOUR_API_KEY") res = client.chat( user_id="memos_user_123", conversation_id="0928", query="我国庆想出去玩,帮我推荐个没去过的城市,以及没住过的酒店品牌" ) print(res) ``` ```bash [Curl] curl --request POST \ --url https://memos.memtensor.cn/api/openmem/v1/chat \ --header 'Authorization: Token YOUR_API_KEY' \ --header 'Content-Type: application/json' \ --data '{ "user_id": "memos_user_123", "conversation_id": "0928", "query": "我国庆想出去玩,帮我推荐个没去过的城市,以及没住过的酒店品牌" }' ``` 需要查看完整字段、请求格式和响应格式?详见 [Chat 接口文档](/cn/api_docs/chat/chat)。 ## 5. 使用限制 - 输入上限:8,000 tokens。 - 输出上限:事实记忆最多召回 25 条,偏好记忆最多召回 25 条。 ## 6. 更多使用方法 Chat 接口开箱即可使用,下面这些都是可选参数。只有当你需要控制记忆召回、模型回答或记忆写入方式时,再按场景传入对应字段。 ### 控制记忆召回范围 如果希望回答时只参考特定范围内的记忆,可以通过以下几个字段控制召回范围与数量: - `filter`:按标签、时间、业务字段等条件精确筛选记忆 - `knowledgebase_ids`:指定本次 Chat 可以检索哪些知识库 - `relativity`:控制召回记忆的相关性门槛 - `memory_limit_number`:限制返回给模型的事实记忆数量 ```python data = { "user_id": "memos_user_123", "conversation_id": "0928", "query": "结合知识库,帮我整理差旅报销规则。", "knowledgebase_ids": ["kb_xxx"], "filter": { "and": [ {"tags": {"contains": "差旅"}}, {"create_time": {"gte": "2025-01-01"}} ] }, "relativity": 0.8, "memory_limit_number": 9 } ``` ### 控制模型回答方式 如果你需要指定模型、开启流式返回,或调整生成参数,可以传入以下字段: - `model_name`:指定对话模型 - `stream`:控制是否流式返回 - `temperature`:控制生成内容的随机性 - `top_p`:控制生成时可选择的候选词范围 - `max_tokens`:限制模型最多生成的内容长度 ```python data = { "user_id": "memos_user_123", "conversation_id": "0928", "query": "用简洁的语气总结我的旅行偏好。", "model_name": "qwen2.5-72b-instruct", "stream": False, "temperature": 0.7, "top_p": 0.95, "max_tokens": 1024 } ``` 如果要完全自定义模型行为,可以传入: - `system_prompt`:覆盖默认系统提示词,适合需要自定义角色、规则或输出格式时使用 **展开查看默认 system_prompt 参考** ```text # Role 你是一个拥有长期记忆能力的智能助手 (MemOS Assistant)。你的目标是结合检索到的记忆片段,为用户提供高度个性化、准确且逻辑严密的回答。 # Memory Data 以下是 MemOS 检索到的相关信息,分为“事实”和“偏好”。 - **事实 (Facts)**:可能包含用户属性、历史对话记录或第三方信息。 - **特别注意**:其中标记为 `[assistant观点]`、`[模型总结]` 的内容代表 **AI 过去的推断**,**并非**用户的原话。 - **偏好 (Preferences)**:用户对回答风格、格式或逻辑的显式/隐式要求。 {memories} # Critical Protocol: Memory Safety 检索到的记忆可能包含 AI 自身的推测、无关噪音或主体错误。使用前请先判断来源、主体、相关性和时效性。 # Instructions 1. 先筛选可用记忆,丢弃噪音和不可靠推断。 2. 仅使用通过筛选的记忆补充背景。 3. 直接回答用户问题,不要提及“记忆库”“检索”或系统内部术语。 ``` ### 控制是否自动写入新记忆 默认情况下,Chat 接口会把本轮用户消息和模型回复写入记忆。如果你只想生成回答,不希望本轮对话进入记忆处理,可以传入: - `add_message_on_answer`:控制是否把本轮用户消息和模型回复写入记忆 ```python data = { "user_id": "memos_user_123", "conversation_id": "0928", "query": "只回答这一次,不要把这轮对话写入记忆。", "add_message_on_answer": False } ``` 如果你只需要普通对话,可以忽略这些字段。当你希望 Chat 生成的新记忆带上业务归属,或控制它写入哪里时,再使用下面这些字段: - `agent_id`:标记当前对话属于哪个 Agent - `app_id`:标记当前对话来自哪个应用 - `tags`:给新记忆打标签,便于后续检索和过滤 - `info`:写入自定义业务信息,例如场景、订单 ID、状态 - `allow_public`:是否允许写入项目级公共记忆 - `allow_knowledgebase_ids`:允许写入哪些知识库 ## 7. 常见错误与排查 | 错误码 | 常见原因 | 处理方式 | | --- | --- | --- | | `40000` | 请求 JSON 结构不符合要求,或字段类型错误 | 检查 `query` 是否为字符串,`filter` 是否为对象,`knowledgebase_ids` / `allow_knowledgebase_ids` 是否为字符串数组 | | `40002` | 必填字段为空 | 检查 `user_id`、`conversation_id`、`query` 是否都已传入且非空 | | `40010` | `user_id` 过长 | 使用稳定且较短的终端用户 ID,长度不要超过 100 字符 | | `40011` | `conversation_id` 过长 | 使用短会话 ID,不要把完整对话、用户输入或 JSON 放进 `conversation_id` | | `40301` / `40305` | 输入内容或请求 Token 超过上限 | 缩短 `query`、`system_prompt` 和过滤条件,不要把长文档直接放进 Chat 请求 | | `40302` / `40303` | 生成内容或对话长度超过模型限制 | 降低 `max_tokens`,缩短预期输出或拆分为多轮提问 | | `50123` | 知识库未关联当前项目 | 回到 [项目配置](/cn/api_docs/start/configuration),确认知识库已关联到当前 API Key 所属项目 | | `50144` | Chat 回答后的消息写入失败 | 如果开启 `add_message_on_answer`,检查请求内容后稍后重试;如果持续出现,请联系支持 | 更多错误码说明,请查看 [错误码](/cn/api_docs/help/error_codes)。 需要查看完整字段、请求格式和响应格式?详见 [Chat 接口文档](/cn/api_docs/chat/chat)。 --- # 记忆过滤器 Filter (/cn/memos_cloud/features/filters) > **Warning**: 注意 > > 需要先在 [Add Message 接口](/cn/api_docs/core/add_message)中传入相关字段,才能在 [Search Memory 接口](/cn/api_docs/core/search_memory)中使用过滤条件。 > > 本文聚焦于功能说明,详细接口字段及限制请查看上方 API 文档。 ## 1. 何时使用记忆过滤器 当记忆规模变大,或一次检索会同时访问用户记忆、公共记忆、知识库记忆时,你通常需要先限定候选范围,再让 MemOS 做语义召回。记忆过滤器(Filter)就是用于在检索前做这一步精确筛选。 常见场景包括: - 只检索某个 Agent、某个 App 产生的记忆。 - 只检索某个时间段内创建或更新的记忆。 - 只检索包含指定标签的记忆。 - 根据添加消息时写入的业务字段筛选,例如 `scene`、`biz_id`、`business_type`。 - 对用户记忆、公共记忆、知识库记忆分别设置不同过滤条件。 ## 2. 工作原理 1. **先过滤范围**:MemOS 根据 `filter` 中的条件,对候选记忆做强过滤。 2. **再语义召回**:在过滤后的候选记忆中,执行[记忆检索](/cn/memos_cloud/mem_operations/search_memory),返回与 `query` 最相关的记忆片段。 这意味着 Filter 不是关键词搜索,而是检索前的范围控制。过滤条件越严格,进入语义召回的候选记忆越少。 ## 3. 两种过滤方式 ### 全局过滤 如果你不需要区分记忆来源,可以直接在 `filter` 根节点写逻辑条件。该条件会作用于本次检索涉及的所有记忆范围(包括用户记忆、公共记忆和通过 `knowledgebase_ids` 传入的知识库记忆)。 ```json "filter": { "and": [ {"tags": {"contains": "阅读"}}, {"create_time": {"gte": "2025-01-01"}}, {"create_time": {"lte": "2025-12-31"}}, {"scene": "chat"} ] } ``` ### 分来源过滤 如果一次检索会同时访问多类记忆,可以在 `filter` 中分别设置各来源的过滤条件。 | 来源 | 说明 | | --- | --- | | `user` | 用户个人记忆,来自该用户历史对话沉淀 | | `agent` | 开启[为 Agent 创建独立记忆](/cn/memos_cloud/introduction/isolation_filters#为-agent-创建独立记忆-new)时,可检索 Agent 的记忆 | | `public` | 项目级公共记忆,可供项目下多个用户共享 | | `knowledgebase` | 知识库记忆,来自上传到知识库的文档或技能 | 分来源过滤适合"用户记忆按最近时间筛,知识库记忆按标签筛,公共记忆不参与"等更精细的检索策略。未 传入的来源不会额外附加该来源的过滤条件。 #### 示例:分条件检索用户、知识库、公共记忆 如下所示,检索用户与 Agent 从 2025 年 6 月 1 日以来的记忆,同时检索知识库、公共记忆中包含了【制度】的记忆内容。 ```json "filter": { "user": { "and": [ {"agent_id": "memos_agent"}, {"create_time": {"gte": "2025-06-01"}} ] }, "knowledgebase": { "and": [ {"tags": {"contains": "制度"}} ] }, "public": { "and": [ {"tags": {"contains": "制度"}} ] } } ``` > **Note**: 全局过滤和分来源过滤选择一种即可。若需要对不同来源使用不同条件,优先使用分来源过滤。 ## 4. 可用字段与运算符 每一组过滤条件的根节点必须是 `and` 或 `or`,并组合一系列字段条件。 ### 实例字段 | 字段名 | 数据类型 | 操作符 | 示例 | | --- | --- | --- | --- | | `agent_id` | string | `=` | `{"agent_id":"memos_agent"}` | | `app_id` | string | `=` | `{"app_id":"app_123"}` | | `related_id` | list | `=` | `{"related_id": ["memos_user_1", "memos_user_2"]}` | > **Note**: `related_id` 补充说明: > > - 支持同时传入多个 `agent_id` 与 `user_id`,用于筛选检索的对象,与指定 Agent 或用户相关联的记忆。 > - 数组内多个 ID 之间为或关系,匹配任意一个即命中。 > - 该字段在全局过滤和分来源过滤中均可使用。 ### 元信息字段 在添加消息时,你可以通过 `info` 写入业务元信息。检索时,这些字段在 `filter` 中直接按字段名使用,不需要再包一层 `info`。 | 字段名 | 数据类型 | 操作符 | 示例 | | --- | --- | --- | --- | | `business_type` | string | `=` | `{"business_type":"购物"}` | | `biz_id` | string | `=` | `{"biz_id":"order_123456"}` | | `scene` | string | `=` | `{"scene":"支付"}` | | `custom_status` | string | `=` | `{"custom_status":"VIP3"}` | ```json // 推荐写法 {"scene": "chat"} // 不要写成这样 {"info": {"scene": "chat"}} ``` ### 标签字段 | 字段名 | 数据类型 | 操作符 | 示例 | | --- | --- | --- | --- | | `tags` | list | `contains` | `{"tags": {"contains": "finance"}}` | ### 时间字段 | 字段名 | 数据类型 | 操作符 | 示例 | | --- | --- | --- | --- | | `create_time` | string | `lt`, `gt`, `lte`, `gte` | `{"create_time": {"gte": "2025-12-10"}}` `{"create_time": {"gt": "2025-12-10 15:00:00"}}` | | `update_time` | string | `lt`, `gt`, `lte`, `gte` | `{"update_time": {"lte": "2025-12-10"}}` `{"update_time": {"lt": "2025-12-10 23:00:00"}}` | ## 5. 使用示例 使用以下记忆过滤器可满足常见的过滤需求,无需重新构建过滤逻辑。 --- - **智能体** ```json // 过滤与以下任意智能体相关的记忆 "filter" : { "or": [ {"agent_id": "agent_123"}, {"agent_id": "agent_456"} ] } ``` - **元信息** ```json // 过滤自定义元信息 info 中的属性(filter 中直接写字段名,不包 info) "filter" : { "and": [ {"business_type":"旅行"}, {"biz_id":"travel_001"}, {"scene":"支付"}, {"custom_status":"v1"} ] } ``` - **标签** ```json // 过滤包含指定标签的记忆 "filter" : { "and": [ {"tags": {"contains": "天气"}} ] } ``` - **日期范围** ```json // 过滤 2025 年 12 月的记忆 "filter" : { "and": [ {"create_time": {"gt": "2025-12-01"}}, {"create_time": {"lt": "2026-01-01"}} ] } // 过滤最近一段时间更新的记忆 "filter" : { "and": [ {"update_time": {"gt": "2025-12-10"}} ] } ``` - **多维度** ```json // 过滤某用户在 Q4 与客服助手关于账单的记忆 "filter" : { "and": [ {"agent_id": "customer_service"}, {"scene":"账单"}, {"create_time": {"gt": "2025-10-01"}}, {"create_time": {"lt": "2026-01-01"}} ] } ``` - **检索与多个 Agent 或用户有关的记忆** ```json "filter" : { "and": [ {"related_id": ["memos_agent_1", "memos_agent_2"]} ] } ``` --- # 异步模式AsyncMode (/cn/memos_cloud/features/async_mode) > **Warning**: **[本文是对【添加记忆-addMessage接口】里的异步模式做展开介绍,可点此直接查看详细 API 文档](/api_docs/core/add_message)** > **Note**: `async_mode`参数当前默认为`true`,记忆添加操作默认将异步处理,排队等待后台执行,而不是等待处理完成再返回响应。 ## 1. 使用异步模式 ### 处理流程 `async_mode`参数设置为`true`时,API 会立即返回响应,并在后台排队处理记忆: ```json { "code": 0, "data": { "success": true, "task_id": "c464e17e-f2ff-4e9a-a2c2-41cc55ab43b9", "status": "running" }, "message": "ok" } ``` 在异步模式下,记忆写入将分为“粗加工”和“精加工”两个阶段:系统会先对本轮消息进行毫秒级的粗加工,使其在下一轮对话时即可被快速检索到; 随后在后台继续进行秒级及以上的精加工以提升记忆质量。处理进度可通过 [get/status](/api_docs/message/get_status) 接口查询:粗加工阶段任务状态为 `running`,精加工完成后状态更新为 `completed`。任务完成后,响应中的 `memory_views` 会汇总本轮任务的新增/更新/删除数量,以及各记忆种类下触达的记忆 ID。 ```python import os import requests import json os.environ["MEMOS_API_KEY"] = "YOUR_API_KEY" os.environ["MEMOS_BASE_URL"] = "https://memos.memtensor.cn/api/openmem/v1" data = { "task_id": "c464e17e-f2ff-4e9a-a2c2-41cc55ab43b9" } headers = { "Content-Type": "application/json", "Authorization": f"Token {os.environ['MEMOS_API_KEY']}" } url = f"{os.environ['MEMOS_BASE_URL']}/get/status" res = requests.post(url=url, headers=headers, data=json.dumps(data)) print(f"result: {res.json()}") ``` ```json { "code": 0, "message": "ok", "data": { "task_id": "c464e17e-f2ff-4e9a-a2c2-41cc55ab43b9", "status": "completed", "memory_views": { "added": 1, "updated": 1, "deleted": 0, "detail_factual": { "memory_ids": ["memos_mem_001"] }, "preference": { "memory_ids": ["memos_mem_002"] } } } } ``` ### 何时使用异步模式 * **降低接口响应延迟**:用户无需等待,持续在应用内使用记忆; * **批量添加记忆**:同时处理大量数据,避免阻塞应用; * **后台任务处理**:将耗时的记忆处理操作放入后台,提高系统并发能力。 > **Note**: 注意 > 当消息包含多模态内容时,由于文件记忆的加工时间较长,您传入的`async_mode`字段失效,此时默认使用“异步模式”。您可通过`get/status`接口查询文件记忆的处理进度。 ## 2. 使用同步模式 ### 处理流程 `async_mode`参数设置为`false`时,API 会在记忆处理完成后返回结果: ```json { "code": 0, "data": { "success": true, "task_id": "c464e17e-f2ff-4e9a-a2c2-41cc55ab43b9", "status": "completed" }, "message": "ok" } ``` 此时检索记忆,能够检索到已经完全处理好的记忆: ```json "memory_detail_list":[ { "memory_key": "暑假广州旅游计划", "memory_value": "用户计划在暑假期间前往广州旅游,并选择了七天连锁酒店作为住宿选项。", "conversation_id": "0610", "tags": [ "旅游", "广州", "住宿", "酒店" ] } ], "preference_detail_list":[ { "preference_type": "implicit_preference", "preference": "用户可能偏好性价比较高的酒店选择。", "reasoning": "七天酒店通常以经济实惠著称,而用户选择七天酒店可能表明其在住宿方面倾向于选择性价比较高的选项。虽然用户没有明确提到预算限制或具体酒店偏好,但在提供的选项中选择七天可能反映了对价格和实用性的重视。", "conversation_id": "0610" } ] ``` ### 何时使用同步模式 * **调试与开发阶段**:直接查看记忆处理后的结果,便于调试记忆检索; * **即时查询**:需要在API调用返回时确认记忆已被创建或更新,例如性能测试、功能验证等 * **小规模操作**:数据量较小、延迟影响不大时,可使用同步模式。 ### 重要说明 * 异步处理的默认行为现在为 `async_mode=true`。 * 如果你需要同步模式,请在添加消息时设置 `async_mode=false`。 --- # 自定义标签Tags (/cn/memos_cloud/features/custom_tags) > **Warning**: 注意 > > > > **[需要先在addMessage的时候传入tag list(点此查看详细 API 文档)](/api_docs/core/add_message)** > > > **[才能在searchMemory的时候使用标签进行过滤(点此查看详细 API 文档)](/api_docs/core/search_memory)** > > > > **本文聚焦于功能说明,详细接口字段及限制请点击上方文字链接查看** MemOS 会为每条记忆自动生成标签,但这些标签可能与您业务中所使用的标签不完全一致。您可以在添加消息时传入自定义标签列表,MemOS 将基于您提供的标签含义,对记忆内容自动应用相关标签。 > **Note**: 何时使用自定义标签? > > 您希望 MemOS 能使用产品团队现有的标签体系来标注记忆内容。 > > 您需要应用这些标签,生成结构化内容。 ## 1. 标签运行机制 * **自动生成标签**:MemOS 在处理记忆时会分析语义,自动生成相关标签,用于后续检索、过滤使用。 * **自定义标签**:在添加消息时,您可以通过`tags`字段传入一组自定义的标签,作为候选标签集合。 * **基于语义的匹配**:MemOS 会根据记忆内容与开发者提供的标签列表进行语义相似度判断,从中选择匹配的标签,与系统自动生成的标签一同写入记忆的`tags`字段。 ## 2. 使用示例 > **Note**: 提示 > * 标签内容应保持简洁,同时能够清楚区分不同类别的含义,便于识别和匹配。 > > * 在同一项目维度下使用统一的列表,不轻易替换,以确保检索和过滤的一致性。 ## 3. 添加消息 ```python import os import json import requests # 替换成你的 MemOS API Key os.environ["MEMOS_API_KEY"] = "YOUR_API_KEY" os.environ["MEMOS_BASE_URL"] = "https://memos.memtensor.cn/api/openmem/v1" data = { "user_id": "memos_user_123", "conversation_id": "1210", "messages": [ {"role": "user","content": "今天天气如何?"}, {"role": "assistant","content": "上海,12月10日,阴天,气温为8-12度。"} ], "tags":["天气","阴天"], "async_mode":False } headers = { "Content-Type": "application/json", "Authorization": f"Token {os.environ['MEMOS_API_KEY']}" } url = f"{os.environ['MEMOS_BASE_URL']}/add/message" res = requests.post(url=url, headers=headers, data=json.dumps(data)) print(f"result: {res.json()}") ``` ### 检索记忆 ```python import os import json import requests # 替换成你的 MemOS API Key os.environ["MEMOS_API_KEY"] = "YOUR_API_KEY" os.environ["MEMOS_BASE_URL"] = "https://memos.memtensor.cn/api/openmem/v1" data = { "user_id": "memos_user_123", "query": "上海 天气" } headers = { "Content-Type": "application/json", "Authorization": f"Token {os.environ['MEMOS_API_KEY']}" } url = f"{os.environ['MEMOS_BASE_URL']}/search/memory" res = requests.post(url=url, headers=headers, data=json.dumps(data)) print(f"result: {res.json()}") ``` ### 输出结果 ```json "memory_detail_list": [ { "id": "9bc102cb-76d8-4a59-86d7-8fd1c4542407", "memory_key": "天气情况", "memory_value": "2025年12月10日,上海的天气为阴天,气温在8到12度之间。", "memory_type": "WorkingMemory", "create_time": 1765376340736, "conversation_id": "1210", "status": "activated", "confidence": 0.99, "tags": [ "天气", "阴天", "气温" ], "update_time": 1765376340737, "relativity": 0.82587826 } ] ``` --- # 知识库Knowledgebase (/cn/memos_cloud/features/knowledge_base) > **Warning**: **[本文是对【MemOS知识库】功能做展开介绍,可点此直接查看详细 API 文档](/api_docs/knowledge/create_kb)** ## 1. MemOS vs RAG 基于 RAG(检索增强生成)的应用,擅长查询与问题语义相似的信息,因此在几万字的知识中,能够快速查询到相关且正确的内容。然而,知识本身无状态,每一次查询都是“一次性”的,缺乏对具体用户和上下文的理解。 MemOS 能够利用“记忆+知识库”,将当前问题与历史记忆关联起来,在“带着背景”的前提下查找和使用知识,让 AI 应用不仅能更准确地查询资料,还能更了解背景与懂用户,并在交互过程中,自动沉淀为新的记忆,持续补全和完善知识体系。 > **Note**: **“记忆+知识库”,MemOS 可以做什么?** > * **跨境电商客服**——专属邮件回复每一位客户 > * **私域卖家推送**——结合过往记忆,打动高粘性客户 > * **独立站 AI 导购 (Chatbot)**——接入网站右下角,主动发起推荐 > * **企业助理**——了解企业知识,同时参与你的个人工作 > * **...** > > 👉 如果你想动手实践:[使用 n8n + MemOS,给SHEIN 搭销售Agent](https://mp.weixin.qq.com/s/qm4Av7KiLudaKfxNTC3Eng)。 以下是两个真实的场景,对比 MemOS 和 RAG 两种解决方案: **购物客服机器人** **背景** ```python DAY 1 用户询问:我家有只三个月大的金毛,买哪款狗粮比较好?对了,它不吃鸡肉口味的。 DAY 1 用户在助手推荐下购买了 A 羊肉幼犬狗粮。 DAY 10 用户询问:狗狗吃这款狗粮会拉稀,我想换一款狗粮。 ``` **RAG 方案** ```python # 根据用户发言检索“幼犬狗粮推荐”“拉稀”相关片段,但无法召回“用户的狗不吃鸡肉口味”。检索到知识: 1. 狗粮拉稀常见原因说明:可以更换低敏狗粮。 2. 低敏幼犬狗粮推荐:B(鸡肉)、C(三文鱼)。 # 🤦 购物助手:如果现在出现拉稀,可以试一试 B(鸡肉味)、C(三文鱼)。 ``` **MemOS 方案** ```python # 根据用户发言检索相关记忆,感知到用户家的狗狗是三个月的金毛幼犬,不喜欢吃鸡肉,需要推荐不会拉稀的幼犬狗粮。检索到记忆: 1. 用户家中有一只三个月大的金毛犬,体重约12斤。 2. 用户家的狗狗不吃鸡肉口味狗粮。 3. 用户之前购买的是羊肉幼犬狗粮。 4. 狗粮拉稀常见原因说明:可以更换低敏狗粮。 5. 低敏幼犬狗粮推荐:B(鸡肉)、C(三文鱼)。 # ✅ 购物助手:你之前提到狗狗是 3 个月大的金毛,而且不能吃鸡肉口味,所以我已帮你排除了所有鸡肉口味的幼犬粮。你之前买过羊肉 + 三文鱼幼犬粮,如果现在出现拉稀,可以尝试更温和的 C(三文鱼幼犬低敏)。 ``` **企业知识库助手** **背景** ```python DAY 1 员工询问:我的电脑是 MacBook Pro 13寸,Intel 芯片。我怎么安装公司内网代理? DAY 1 助手提供了 Intel 版本的安装步骤。 DAY 20 员工询问:内网代理打不开了,我该重新装哪个版本? ``` **RAG 方案** ```python # 根据用户发言检索“内网代理”“打不开”相关内容,但无法召回“用户的设备型号”。检索到知识: 1. 内网代理常见故障排查 2. M1/M2(ARM)版本的内网代理安装说明 3. Windows 内网代理客户端安装说明 4. 网络连接与证书问题 5. 通用 FAQ # 🤦 知识库助手:请尝试重新下载安装最新的Mac M1/M2(ARM)版本或Windows的内网代理客户端。以下是安装步骤:... ``` **MemOS 方案** ```python # 根据员工问题检索“内网代理”“打不开”相关记忆, 自动识别该员工的设备型号, 检索到记忆: 1. 用户在20天前安装了公司内网代理,他的设备是 MacBook Pro 13(Intel) 2. 内网代理常见故障排查 3. Intel 版本的内网代理安装说明 # ✅ 知识库助手:你使用的是 Intel 芯片的 MacBook Pro,建议重新安装 Intel 版本 的内网代理客户端。以下是 Intel 版的下载链接和安装步骤:... ``` ## 2. 工作原理 上图展示了终端用户、您构建的 AI Agent 与 MemOS 的完整交互流程: 1. 调用`create/knowledgebase`接口 / 在控制台点击“添加知识库”,创建 MemOS 知识库。 2. 调用`add/knowledgebase-file`接口 / 在控制台点击“上传文档”,将知识库文档上传到对应的 MemOS 知识库。 3. MemOS 接收到请求后,会依次完成以下处理,生成知识库记忆: a. 文档校验:完成鉴权,并对文档的格式、大小等进行合规性校验; b. 文档存储:文档上传成功后由 MemOS 保存,并进入处理队列; c. 文档解析:按不同文件类型解析文档原文内容; d. 智能分段:根据标题、结构与语义将文档拆分为更细粒度的内容片段; e. 生成知识库记忆:为了不丢失内容细节,MemOS 会智能生成记忆,包含文档分片后的原文与处理好的记忆。 f. 嵌入与索引:以上的所有记忆内容写入数据库,并建立嵌入索引以支持毫秒级检索。 4. 调用`search/memory`接口检索记忆,MemOS 会统一返回与上下文相关的用户事实、偏好、工具记忆和知识库记忆。 5. 将上述记忆拼接在完整指令中,传给您自己部署的大模型,获得回答,返还给用户。 > **Note**: **知识库记忆为什么没有单独的检索接口?** > 这是 MemOS 有意为之的设计,我们希望 MemOS 让开发者在一次检索中,同时获得「知识库+用户」记忆,无需关注或区分来源,显著提升回答的实际可用性和用户体感。 ## 3. 知识库要求 ### 容量限制 MemOS 云服务目前为所有开发者提供了从免费版到企业版的多种定价方案,不同版本对应的知识库容量与数量限制不同。目前,所有版本限时免费,欢迎前往[官网-价格](https://memos.openmem.net/cn/pricing),申请符合你需求的版本。 | **版本** | **知识库存储限制** | | ---------- | ----------------------------------------- | | **免费版** | 知识库个数:10个;单知识库存储空间:1G | | **入门版** | 知识库个数:30个;单知识库存储空间:10G | | **专业版** | 知识库个数:100个;单知识库存储空间:100G | > **Warning**: 注意 > 当你的服务等级发生降级时,若现有知识库已超出当前版本的容量限制,MemOS 不会清空已有知识库数据,但将限制以下操作: > > - 无法创建新的知识库 > - 无法继续上传新文档 > > 需将使用量调整至当前版本的容量范围内后,相关功能可恢复。 ### 知识文档限制 1. 支持上传的文档类型:PDF、DOCX、DOC、TXT、JSON、MD、XML 2. 单文件大小上限:不超过 100 MB、500页 3. 单次上传的文件数量上限:不超过20个 > **Warning**: 注意 > 当单次上传的文件数量、单文件大小或页数超过上述限制时,该次上传任务将被判定为**处理失败**。 请根据限制要求调整文件后,重新发起上传请求。 ### 技能文档限制 除了普通知识文档,知识库也支持上传自定义技能(Skill)文档。技能文档用于沉淀可复用的任务处理流程,检索时可与其他记忆一起返回给 Agent。格式要求如下所示: 1. **单文件 `.md`** * 大小限制:≤ 100KB * 文件内容:必须包含 `name` 和 `description` 2. **技能压缩包 `.zip`** | 约束 | 要求 | | --- | --- | | 格式 | 标准 ZIP,不支持 rar/7z | | zip 大小 | ≤ 20MB | | 解压后文件数 | ≤ 200 | | 解压后单文件 | ≤ 10MB | | SKILL.md | ≤ 100KB,`name`/`description` 必填,须在压缩包第一层 | ## 4. 使用示例 以下是一个完整的知识库使用示例,帮助您快速上手使用构建专属您的「知识库助手」。 ### 创建知识库:财务报销知识库 ```python [Python (HTTP)] import os import requests import json # 替换成你的 MemOS API Key os.environ["MEMOS_API_KEY"] = "YOUR_API_KEY" os.environ["MEMOS_BASE_URL"] = "https://memos.memtensor.cn/api/openmem/v1" data = { "knowledgebase_name": "财务报销知识库", "knowledgebase_description": "本公司所有财务报销相关的知识汇总" } headers = { "Content-Type": "application/json", "Authorization": f"Token {os.environ['MEMOS_API_KEY']}" } url = f"{os.environ['MEMOS_BASE_URL']}/create/knowledgebase" res = requests.post(url=url, headers=headers, data=json.dumps(data)) print(f"result: {res.json()}") ``` ```python [输出] "result": { "code": 0, "data": { "id": "idxxxxx" # 替换成上方创建的知识库ID }, "message": "ok" } ``` ### 上传文档:软件采购报销制度 ```python [Python (HTTP)] import os import requests import json # 替换成你的 MemOS API Key os.environ["MEMOS_API_KEY"] = "YOUR_API_KEY" os.environ["MEMOS_BASE_URL"] = "https://memos.memtensor.cn/api/openmem/v1" data = { "knowledgebase_id": "idxxxxx", # 替换成上方创建的知识库ID "file": [ {"content": "https://cdn.memtensor.com.cn/file/软件采购报销制度.pdf"} ] } headers = { "Content-Type": "application/json", "Authorization": f"Token {os.environ['MEMOS_API_KEY']}" } url = f"{os.environ['MEMOS_BASE_URL']}/add/knowledgebase-file" res = requests.post(url=url, headers=headers, data=json.dumps(data)) print(f"result: {res.json()}") ``` ```python [输出] "result": { "code": 0, "data": [ { "id": "1f35642253606ed1e9dd8cd8113a8998", "name": "软件采购报销制度.pdf", "sizeMB": 0.06331157684326172, "status": "running" } ], "message": "ok" } ``` ### 更新或下载文档 文档更新与下载都沿用同一个文件 ID:提交新内容即可生成新版本,下载可获取当前版本的原始内容用于预览或编辑。 | 操作 | 接口 | 说明 | | --- | --- | --- | | 更新文档 | [更新知识库文件](/api_docs/knowledge/update_kb_doc) | 为已有文件生成下一个版本。仅当前版本处理完成的文件可以更新,且不能修改文件类型。 | | 下载文档 | [下载知识库文件](/api_docs/knowledge/download_kb_doc) | 返回当前版本的原始文件内容,文件名通过 `Content-Disposition` 响应头返回。 | > **Note**: 更新成功后,文件列表会立即显示新的文件名、大小和版本号,解析与索引在后台继续执行。可先用返回的 `task_id` 调用 `POST /get/status`,或调用 `POST /get/knowledgebase-file` 查看进度,再进行下一次更新。 ### 添加用户对话 > **Note**:  会话 A:2025-06-10 发生 > > 设计师在聊天中表明了自己是【创意平台部门的设计师】的岗位。 > ```python import os import requests import json # 替换成你的 MemOS API Key os.environ["MEMOS_API_KEY"] = "YOUR_API_KEY" os.environ["MEMOS_BASE_URL"] = "https://memos.memtensor.cn/api/openmem/v1" data = { "user_id": "memos_user_123", "conversation_id": "0610", "messages": [ { "role": "user", "content": "我是创意平台部门的设计师。" }, { "role": "assistant", "content": "好的,我记住了。" } ] } headers = { "Content-Type": "application/json", "Authorization": f"Token {os.environ['MEMOS_API_KEY']}" } url = f"{os.environ['MEMOS_BASE_URL']}/add/message" res = requests.post(url=url, headers=headers, data=json.dumps(data)) print(f"result: {res.json()}") ``` ### 检索知识库记忆 > **Note**:  会话 A:2025-12-12 发生 > > 用户在一个新的会话中,询问【软件报销制度】,MemOS 会自动召回【知识库记忆:软件报销制度内容】【用户记忆:创意平台设计师】,从而回答更加明确且“懂用户”的软件报销内容。 > ```python [Python (HTTP)] import os import requests import json # 替换成你的 MemOS API Key os.environ["MEMOS_API_KEY"] = "YOUR_API_KEY" os.environ["MEMOS_BASE_URL"] = "https://memos.memtensor.cn/api/openmem/v1" data = { "user_id": "memos_user_123", "conversation_id": "1211", "query": "帮我查一下软件采购报销额度。", "knowledgebase_ids":["idxxxxx"] # 替换成上方创建的知识库ID } headers = { "Content-Type": "application/json", "Authorization": f"Token {os.environ['MEMOS_API_KEY']}" } url = f"{os.environ['MEMOS_BASE_URL']}/search/memory" res = requests.post(url=url, headers=headers, data=json.dumps(data)) # 美化 JSON 输出 json_res = res.json() print(json.dumps(json_res, indent=2, ensure_ascii=False)) ``` ```python [输出] "memory_detail_list": [ { "id": "2c760355-de4b-4a8f-b98d-b92851d23fa7", "memory_key": "软件采购报销制度(试行版)", "memory_value": "该制度旨在规范公司各类软件的采购与报销流程,要求所有软件采购遵循特定品类的采购金额上限。设计类软件的采购上限为1000元,适用于平面设计、视频编辑和原型设计,示例包括Photoshop和Premiere。代码/开发类软件的采购上限为1500元,适用范围包括IDE和开发框架,示例有PyCharm和Visual Studio。办公类软件的采购上限为800元,适用于文档编辑和表格处理,示例包括Office套件和WPS。数据分析类软件的采购上限为1200元,适用范围为数据统计和可视化,示例包括Tableau和Power BI。安全与防护类软件的采购上限为1000元,适用于杀毒和防火墙。协作/项目管理类软件的采购上限为900元,示例包括Jira和Slack。特殊行业软件的采购上限为2000元,需专项审批。所有采购必须符合公司预算与信息安全要求,超出限额的软件需提供业务说明并提交专项审批。", "memory_type": "WorkingMemory", "create_time": 1765525947718, "conversation_id": "default_session", "status": "activated", "confidence": 0.99, "tags": [ "软件采购", "报销制度", "审批流程", "预算", "信息安全", "mode:fine", "multimodal:file" ], "update_time": 1765525947720, "relativity": 0.89308184 }, { "id": "81fd1e79-65be-4d4e-81e0-8f76ba697c55", "memory_key": "职位信息", "memory_value": "用户是创意平台部门的设计师。", "memory_type": "WorkingMemory", "create_time": 1765526247112, "conversation_id": "0610", "status": "activated", "confidence": 0.99, "tags": [ "职位", "部门", "设计" ], "update_time": 1765526247113, "relativity": 1.6319022e-05 } ] ``` ### 反馈优化知识库 在企业中,常会出现企业政策/知识已更新,而知识库更新不及时的问题。目前,MemOS 支持通过**自然语言对话**对知识库的记忆反馈,用于快速更新知识库记忆,从而提高准确性与时效性。 尝试一下,用最简单的交互方式驱动知识库始终保持最新。 > **Note**:  会话 A:2025-12-12 发生 > > 财务主管在另一个新的会话中,反馈【办公类软件的采购上限为600元,而不是800元】。 > ```python import os import requests import json # 替换成你的 MemOS API Key os.environ["MEMOS_API_KEY"] = "YOUR_API_KEY" os.environ["MEMOS_BASE_URL"] = "https://memos.memtensor.cn/api/openmem/v1" data = { "user_id": "memos_user_123", "conversation_id": "1212", "feedback_content": "办公类软件的采购上限是600元,而不是800元。", "allow_knowledgebase_ids":["idxxxxx"] # 替换成上方创建的知识库ID } headers = { "Content-Type": "application/json", "Authorization": f"Token {os.environ['MEMOS_API_KEY']}" } url = f"{os.environ['MEMOS_BASE_URL']}/add/feedback" res = requests.post(url=url, headers=headers, data=json.dumps(data)) print(f"result: {res.json()}") ``` > **Note**:  会话 A:2025-12-12 发生 > > 任意其他用户搜索【软件报销制度】时,获取一条新增高权重记忆【办公类软件的采购上限为600元,而不是800元】。 > ```python import os import requests import json # 替换成你的 MemOS API Key os.environ["MEMOS_API_KEY"] = "YOUR_API_KEY" os.environ["MEMOS_BASE_URL"] = "https://memos.memtensor.cn/api/openmem/v1" data = { "user_id": "memos_user_123", "conversation_id": "1211", "query": "帮我查一下软件采购报销额度。", "knowledgebase_ids":["idxxxxx"] # 替换成上方创建的知识库ID } headers = { "Content-Type": "application/json", "Authorization": f"Token {os.environ['MEMOS_API_KEY']}" } url = f"{os.environ['MEMOS_BASE_URL']}/search/memory" res = requests.post(url=url, headers=headers, data=json.dumps(data)) # 美化 JSON 输出 json_res = res.json() print(json.dumps(json_res, indent=2, ensure_ascii=False)) ``` 输出结果如下(简化版): ```python "memory_detail_list": [ { "id": "8a4f3d2e-c417-4e53-bc25-54451abd5ac8", "memory_key": "软件采购报销制度(试行版)", "memory_value": "该制度旨在规范公司各类软件的采购与报销流程,要求所有软件采购遵循特定品类的采购金额上限。设计类软件的采购上限为1000元,适用于平面设计、视频编辑和原型设计,示例包括Photoshop和Premiere。代码/开发类软件的采购上限为1500元,适用范围包括IDE和开发框架,示例有PyCharm和Visual Studio。办公类软件的采购上限为800元,适用于文档编辑和表格处理,示例包括Office套件和WPS。数据分析类软件的采购上限为1200元,适用范围为数据统计和可视化,示例包括Tableau和Power BI。安全与防护类软件的采购上限为1000元,适用于杀毒和防火墙。协作/项目管理类软件的采购上限为900元,示例包括Jira和Slack。特殊行业软件的采购上限为2000元,需专项审批。所有采购必须符合公司预算与信息安全要求,超出限额的软件需提供业务说明并提交专项审批。", "memory_type": "LongTermMemory", "create_time": 1765525947718, "conversation_id": "default_session", "status": "activated", "confidence": 0.99, "tags": [ "软件采购", "报销制度", "审批流程", "预算", "信息安全", "mode:fine", "multimodal:file" ], "update_time": 1765525947720, "relativity": 0.8931847 }, { "id": "a72a04d1-d7ba-4ebd-9410-0097bfa6c20d", "memory_key": "办公软件采购上限", "memory_value": "用户确认办公类软件的采购上限是600元,而不是800元。", "memory_type": "WorkingMemory", "create_time": 1765531700539, "conversation_id": "1212", "status": "activated", "confidence": 0.99, "tags": [ "采购", "办公软件", "预算" ], "update_time": 1765531700540, "relativity": 0.7196722 } ] ``` [控制台-知识库](https://memos-dashboard.openmem.net/knowledgeBase/)中展示了知识库中所有通过自然语言交互,更正或补全知识库记忆的详情。 ![image.png](https://cdn.memtensor.com.cn/img/1765970178683_5tuxe4_compressed.png) > **Note**: 有关反馈 API 字段、格式等信息的完整列表,详见[Add Feedback 接口文档](/api_docs/message/add_feedback)。 ## 5. 更多功能:上传技能文档 如果你希望知识库不仅返回知识内容,还能返回可复用的任务处理流程,可以在知识库中上传技能(Skill)文档。与普通文档不同,上传技能文档时需要将文件类型标记为 `skill`。 上传成功后,检索时可同时召回知识库记忆和匹配的技能。 > **Note**: 技能文件的详细工作原理与使用示例,请查看 [记忆自进化](/memos_cloud/features/self-evolving) 中的完整示例。 ```python [Python (HTTP)] import os import requests import json # 替换成你的 MemOS API Key os.environ["MEMOS_API_KEY"] = "YOUR_API_KEY" os.environ["MEMOS_BASE_URL"] = "https://memos.memtensor.cn/api/openmem/v1" data = { "knowledgebase_id": "idxxxxx", # 替换成你的知识库ID "file": [ { "type": "skill", "content": "https://cdn.memtensor.com.cn/file/SKILL.md" } ] } headers = { "Content-Type": "application/json", "Authorization": f"Token {os.environ['MEMOS_API_KEY']}" } url = f"{os.environ['MEMOS_BASE_URL']}/add/knowledgebase-file" res = requests.post(url=url, headers=headers, data=json.dumps(data)) print(f"result: {res.json()}") ``` ## 6. 常见错误与排查 | 错误码 | 常见原因 | 处理方式 | | --- | --- | --- | | `40002` / `40003` | 缺少 `knowledgebase_id`、`file`,或文件列表为空 | 检查请求体字段是否完整,`file` 必须是非空数组 | | `40007` / `50107` | 文件类型不支持 | 更换为 PDF、DOCX、DOC、TXT、JSON、MD、XML;Skill 文件请使用 `.md` 或 `.zip` | | `40008` / `40009` | Base64 内容非法或格式错误 | 确认 Base64 未被截断,不要混入非法字符或错误前缀 | | `40305` | 单次输入超过 token 上限 | 拆分大文件,减少单次上传内容 | | `40309` | 单位时间输入 token 超限 | 降低上传并发,分批重试 | | `50123` | 知识库未关联当前项目 | 回到 [项目配置](/cn/api_docs/start/configuration),确认知识库已关联到当前 API Key 所属项目 | --- # 属性记忆 Profile (/cn/memos_cloud/features/profile) ## 1. 属性记忆是什么? AI 应用通常通过 Prompt 传入的固定角色设定,并根据提前设定的标签分类,对不同用户推送不同的回复内容实现“有记忆、个性化”。然而,随着对话的深入,用户会不断变化,人工维护的分类标签跟不上,用户的“专属感”也就无法凸显。 属性记忆(Profile)可用于构建结构化的画像,对话中的零散信息被抽取并映射到预先定义好的属性字段,并随对话深入自动更新、补全。核心特点包括: - **结构化**:画像由预先定义的字段构成,统一存储、可直接取用,不分散在零散的记忆中; - **持续更新**:随对话深入,MemOS 自动更新属性字段,让画像不断补全、始终贴合用户的最新状态,无需手写或手动维护; - **字段级可控**:支持自定义每个字段是否允许自动更新,开放的字段随对话演进,关键字段可锁定,保持核心设定稳定、不随对话噪声偏移。 适用于 智能家居、品牌客服、金融投顾 等场景,用于增强对话一致性、稳定性,让 AI 长期记住用户是谁。 示例结构如下所示: ```plaintext 基础信息 姓名:张三 职业:工程师 居住地:杭州 兴趣爱好 爱好:露营、独立游戏 喜欢的音乐:民谣 性格标签 三个关键词:开朗、好奇、爱较真 ``` > **Note**: 可以同时绑定到 AI 角色(Agent)上,维护该角色的稳定人设。开启[为 Agent 创建独立记忆](/cn/memos_cloud/introduction/isolation_filters#为-agent-创建独立记忆-new)后,每个 Agent 拥有各自独立的属性记忆。 ## 2. 关键参数 - **模板(profile_template)**:用于定义属性记忆的字段结构,包括字段名称、层级、 默认值、是否允许算法更新等。一个模板可以重复绑定到多个用户或 AI 角色。 - **实例(profile)**:用户或 AI 角色绑定模板后生成的属性记忆,用于存放各自的字段值。 - **属性**:实例中的具体字段项,如关系、兴趣、说话风格、纪念日等。 - **属性值(value)**:实例的字段值。添加消息时,MemOS 根据消息内容更新对应字段值。 - **算法更新标记(algorithm_updatable)**:用于控制字段是否允许被算法自动更新。 - **主体(user_id/agent_id)**:每个用户拥有各自独立的属性记忆实例;开启[为 Agent 创建独立记忆](/cn/memos_cloud/introduction/isolation_filters#为-agent-创建独立记忆-new)后,也可为 Agent(AI 角色)创建属性记忆实例。 ## 3. 工作原理 ```mermaid sequenceDiagram autonumber participant Dev as 开发者 participant User as 终端用户 participant App as AI 产品 participant Mem as MemOS participant LLM as AI 产品接入大模型 Dev->>Mem: 创建模板,定义属性记忆结构 Dev->>Mem: 为用户绑定模板,生成实例 User->>App: 发送消息 / 产生对话 App->>Mem: 检索记忆 searchMemory Mem-->>App: 召回属性记忆 + 其他记忆 App->>LLM: 拼接上下文,生成更懂该用户的回复 LLM-->>App: 返回回复 App-->>User: 展示回复 App->>Mem: 添加消息 addMessage Mem->>Mem: 从对话抽取信息,更新属性值 ``` 上图展示了开发者、终端用户、AI 产品 与 MemOS 的完整交互流程: 1. **准备模板**:在控制台或通过 API 创建属性记忆模板,定义字段结构; 2. **绑定到主体**:为 用户/ AI 角色 绑定模板,生成属于 TA 的属性记忆实例; 3. **检索使用**:召回与当前问题相关的记忆,包含属性记忆,拼接到大模型上下文中,生成更懂用户的回复; 4. **自动更新**:后续添加消息时,MemOS 从对话中抽取信息,更新实例中对应的属性字段值。 > **Note**: 当前,绑定模板**不会**自动回溯历史对话来填充属性值,建议从创建用户时就绑定模板。 ## 4. 使用示例 > **Note**: 有关 API 字段、格式等信息的完整列表,详见 [属性树操作](/api_docs/core/bind_profile_template)接口文档。 ### 创建模板 属性记忆模板可以在 [MemOS 控制台](https://memos-dashboard.openmem.net) 中创建和维护,也可以通过 API 创建。模板使用 JSON 描述,**最多三层**嵌套: ```json { "基础信息": { "姓名": { "value": "", "algorithm_updatable": false }, "职业": { "value": "", "algorithm_updatable": true }, "居住地": { "value": "", "algorithm_updatable": true } }, "性格标签": { "三个关键词": { "value": "", "algorithm_updatable": true } } } ``` - `value`:属性字段值,可以留空或填入默认值; - `algorithm_updatable`:标记该属性是否允许算法从对话中自动更新。 通过 API 创建模板: ```python [Python (HTTP)] import requests API_KEY = "YOUR_API_KEY" BASE_URL = "https://memos.memtensor.cn/api/openmem/v1" data = { "name": "用户画像", "metadata": { "基础信息": { "姓名": {"value": "", "algorithm_updatable": False}, "职业": {"value": "", "algorithm_updatable": True}, "居住地": {"value": "", "algorithm_updatable": True} }, "性格标签": { "三个关键词": {"value": "", "algorithm_updatable": True} } } } res = requests.post( f"{BASE_URL}/add/profile_template", headers={"Authorization": f"Token {API_KEY}"}, json=data ) print(res.json()) ``` ```bash [Curl] curl --request POST \ --url https://memos.memtensor.cn/api/openmem/v1/add/profile_template \ --header 'Authorization: Token YOUR_API_KEY' \ --header 'Content-Type: application/json' \ --data '{ "name": "用户画像", "metadata": { "基础信息": { "姓名": {"value": "", "algorithm_updatable": false}, "职业": {"value": "", "algorithm_updatable": true}, "居住地": {"value": "", "algorithm_updatable": true} }, "性格标签": { "三个关键词": {"value": "", "algorithm_updatable": true} } } }' ``` 响应示例: ```json { "code": 0, "data": { "profile_template_id": "tpl_user_001" }, "message": "ok" } ``` 创建成功后,使用返回的模板 ID 进行绑定、查询、修改和删除。模板管理的完整 API 如下: | 操作 | 接口 | 说明 | | --- | --- | --- | | 创建模板 | [Add Profile Template](/api_docs/core/add_profile_template) | 创建属性结构,设置字段默认值和是否允许自动更新 | | 获取模板列表 | [List Profile Templates](/api_docs/core/list_profile_template) | 分页查看项目内的模板 | | 获取模板详情 | [Get Profile Template](/api_docs/core/get_profile_template) | 查看模板完整结构和绑定数量 | | 修改模板 | [Update Profile Template](/api_docs/core/update_profile_template) | 修改名称或属性结构,与控制台更新行为一致 | | 删除模板 | [Delete Profile Template](/api_docs/core/delete_profile_template) | 删除模板,同时删除全部绑定实例 | > **Note**: Python SDK 的模板管理方法正在开发中,请暂时通过 HTTP 方式调用模板管理接口;绑定、编辑、删除实例等接口的 SDK 示例见下文。 > **Warning**: 修改或删除模板中的字段,会影响所有绑定过该模板的属性记忆实例字段,请谨慎修改已绑定实例的属性树模板。删除模板会同时删除该模板的全部绑定实例;只需删除某个用户或 Agent 的实例时,请使用 [Delete Profile](/api_docs/core/delete_profile)。 ### 绑定用户到模板 为用户绑定模板后,MemOS 会为该用户创建属性记忆实例。后续添加消息时 MemOS 自动更新对应字段值,动态维护用户画像。 ```python [Python (HTTP)] import requests API_KEY = "YOUR_API_KEY" BASE_URL = "https://memos.memtensor.cn/api/openmem/v1" data = { "bind_list": [ {"user_id": "memos_user_123", "profile_template_id": "tpl_user_001"} ] } res = requests.post( f"{BASE_URL}/bind/profile_template", headers={"Authorization": f"Token {API_KEY}"}, json=data ) print(res.json()) ``` ```python [Python (SDK)] # 请确保已安装 MemOS (pip install MemoryOS -U) from memos.api.client import MemOSClient client = MemOSClient(api_key="YOUR_API_KEY") res = client.bind_profile_template( bind_list=[{"user_id": "memos_user_123", "profile_template_id": "tpl_user_001"}] ) print(res) ``` ```bash [Curl] curl --request POST \ --url https://memos.memtensor.cn/api/openmem/v1/bind/profile_template \ --header 'Authorization: Token YOUR_API_KEY' \ --header 'Content-Type: application/json' \ --data '{ "bind_list": [ { "user_id": "memos_user_123", "profile_template_id": "tpl_user_001" } ] }' ``` ### 添加对话 用户在对话中提到自己的职业和爱好,MemOS 自动抽取信息并更新属性记忆。 ```python [Python (HTTP)] import requests API_KEY = "YOUR_API_KEY" BASE_URL = "https://memos.memtensor.cn/api/openmem/v1" data = { "user_id": "memos_user_123", "conversation_id": "conv_0624", "allow_memory_view": ["profile", "detail_factual", "preference"], "messages": [ {"role": "user", "content": "我在杭州做产品经理,平时喜欢看科幻小说和露营。"}, {"role": "assistant", "content": "了解了,杭州是个好地方,周边露营地很多。"} ] } res = requests.post( f"{BASE_URL}/add/message", headers={"Authorization": f"Token {API_KEY}"}, json=data ) print(res.json()) ``` ```python [Python (SDK)] # 请确保已安装 MemOS (pip install MemoryOS -U) from memos.api.client import MemOSClient client = MemOSClient(api_key="YOUR_API_KEY") res = client.add_message( user_id="memos_user_123", conversation_id="conv_0624", allow_memory_view=["profile", "detail_factual", "preference"], messages=[ {"role": "user", "content": "我在杭州做产品经理,平时喜欢看科幻小说和露营。"}, {"role": "assistant", "content": "了解了,杭州是个好地方,周边露营地很多。"} ] ) print(res) ``` ```bash [Curl] curl --request POST \ --url https://memos.memtensor.cn/api/openmem/v1/add/message \ --header 'Authorization: Token YOUR_API_KEY' \ --header 'Content-Type: application/json' \ --data '{ "user_id": "memos_user_123", "conversation_id": "conv_0624", "allow_memory_view": ["profile", "detail_factual", "preference"], "messages": [ {"role": "user", "content": "我在杭州做产品经理,平时喜欢看科幻小说和露营。"}, {"role": "assistant", "content": "了解了,杭州是个好地方,周边露营地很多。"} ] }' ``` ### 检索属性记忆 在新会话中询问用户信息时,调用检索记忆接口,在 `include_memory_view` 中传入 `"profile"` 即可召回属性记忆。 ```python [Python (HTTP)] import requests API_KEY = "YOUR_API_KEY" BASE_URL = "https://memos.memtensor.cn/api/openmem/v1" data = { "user_id": "memos_user_123", "query": "这个用户的基本情况是什么?", "include_memory_view": ["profile"] } res = requests.post( f"{BASE_URL}/search/memory", headers={"Authorization": f"Token {API_KEY}"}, json=data ) print(res.json()) ``` ```python [Python (SDK)] # 请确保已安装 MemOS (pip install MemoryOS -U) from memos.api.client import MemOSClient client = MemOSClient(api_key="YOUR_API_KEY") res = client.search_memory( user_id="memos_user_123", query="这个用户的基本情况是什么?", include_memory_view=["profile"] ) print(res) ``` ```bash [Curl] curl --request POST \ --url https://memos.memtensor.cn/api/openmem/v1/search/memory \ --header 'Authorization: Token YOUR_API_KEY' \ --header 'Content-Type: application/json' \ --data '{ "user_id": "memos_user_123", "query": "这个用户的基本情况是什么?", "include_memory_view": ["profile"] }' ``` 响应示例: ```json { "code": 0, "message": "ok", "data": { "profile_detail_list": [ { "id": "memos97701df652bb42cf8fe276b0da1441f3_tpl_bb0948b22fe7_e6a0dbfb3d47", "memory": "基础信息.职业: 产品经理", "memory_type": "ProfileMemory", "template_id": "tpl_bb0948b22fe7", "profile_category": "基础信息", "profile_field": "职业", "profile_path": "基础信息.职业", "status": "activated", "confidence": 0.99, "relativity": 0.6782, "algorithm_updatable": true }, { "id": "memos97701df652bb42cf8fe276b0da1441f3_tpl_bb0948b22fe7_2785203c3b81", "memory": "基础信息.居住地: 杭州", "memory_type": "ProfileMemory", "template_id": "tpl_bb0948b22fe7", "profile_category": "基础信息", "profile_field": "居住地", "profile_path": "基础信息.居住地", "status": "activated", "confidence": 0.99, "relativity": 0.6808, "algorithm_updatable": true } ] } } ``` ### 编辑属性值 用户搬家到了上海,手动更新“居住地”并锁定该字段,防止后续对话中被自动覆盖。 ```python [Python (HTTP)] import requests API_KEY = "YOUR_API_KEY" BASE_URL = "https://memos.memtensor.cn/api/openmem/v1" data = { "user_id": "memos_user_123", "profile_template_id": "tpl_user_001", "metadata": { "基础信息": { "居住地": { "value": "上海", "algorithm_updatable": False } } } } res = requests.post( f"{BASE_URL}/edit/profile", headers={"Authorization": f"Token {API_KEY}"}, json=data ) print(res.json()) ``` ```python [Python (SDK)] # 请确保已安装 MemOS (pip install MemoryOS -U) from memos.api.client import MemOSClient client = MemOSClient(api_key="YOUR_API_KEY") res = client.edit_profile( user_id="memos_user_123", profile_template_id="tpl_user_001", metadata={ "基础信息": { "居住地": { "value": "上海", "algorithm_updatable": False } } } ) print(res) ``` ```bash [Curl] curl --request POST \ --url https://memos.memtensor.cn/api/openmem/v1/edit/profile \ --header 'Authorization: Token YOUR_API_KEY' \ --header 'Content-Type: application/json' \ --data '{ "user_id": "memos_user_123", "profile_template_id": "tpl_user_001", "metadata": { "基础信息": { "居住地": { "value": "上海", "algorithm_updatable": false } } } }' ``` ### 删除实例 不再需要某个用户的属性记忆时,可删除实例,绑定关系和所有字段值一并清除。 ```python [Python (HTTP)] import requests API_KEY = "YOUR_API_KEY" BASE_URL = "https://memos.memtensor.cn/api/openmem/v1" data = { "user_id": "memos_user_123", "profile_template_id": "tpl_user_001" } res = requests.post( f"{BASE_URL}/delete/profile", headers={"Authorization": f"Token {API_KEY}"}, json=data ) print(res.json()) ``` ```python [Python (SDK)] # 请确保已安装 MemOS (pip install MemoryOS -U) from memos.api.client import MemOSClient client = MemOSClient(api_key="YOUR_API_KEY") res = client.delete_profile( user_id="memos_user_123", profile_template_id="tpl_user_001" ) print(res) ``` ```bash [Curl] curl --request POST \ --url https://memos.memtensor.cn/api/openmem/v1/delete/profile \ --header 'Authorization: Token YOUR_API_KEY' \ --header 'Content-Type: application/json' \ --data '{ "user_id": "memos_user_123", "profile_template_id": "tpl_user_001" }' ``` ## 5. 相关功能 - [记忆种类](/cn/memos_cloud/introduction/memory_types): 了解属性记忆与其他记忆种类的区别 - [事件记忆](/cn/memos_cloud/features/event_memory): 从对话中抽取带时间、地点、参与者的结构化事件 --- # 事件记忆 Event (/cn/memos_cloud/features/event_memory) ## 1. 事件记忆是什么? 事件记忆(Event)从对话中自动抽取结构化事件,保留时间、地点、参与者等关键要素,让 AI 能够准确、完整地回忆和引用过去的经历,使对话更有连续感。 > **Note**: 适用场景 > > - 日程管理:记住"上周完成了哪个项目"、"下个月要参加的考试"; > - 客户服务历史:追溯客户的投诉、咨询、退换货等关键事件; > - 游戏 / 角色扮演中的剧情记忆:保留角色经历过的关键剧情节点。 > > 事件记忆与[属性记忆](/cn/memos_cloud/features/profile)互补——属性记忆维护"TA 是谁"的稳定画像,事件记忆记录"TA 经历了什么"的动态过程。 ## 2. 关键参数 - **事件(event)**:从对话中抽取的一条结构化事件,是事件记忆的基本单元。 - **标题(title)**:事件的简短描述,如"和朋友去西湖露营"。 - **内容(content)**:事件的详细摘要,包含关键信息。 - **事件时间**:事件发生的时间,优先使用消息中传入的 `chat_time`。 - **参与者**:事件涉及的人物,从对话上下文中自动识别。 - **自定义抽取配置**:支持自定义事件记忆的抽取 Prompt,控制从对话中抽取事件的方式和关注维度。 ## 3. 使用流程 ```mermaid sequenceDiagram autonumber participant User as 用户 participant App as AI 产品 participant Mem as MemOS participant LLM as AI 产品接入大模型 User->>App: 发送消息 / 产生对话 App->>Mem: 检索记忆 searchMemory Mem-->>App: 召回事件记忆 + 其他记忆 App->>LLM: 拼接上下文,生成回复 LLM-->>App: 返回回复 App-->>User: 展示回复 App->>Mem: 添加消息 addMessage Mem->>Mem: 从对话中抽取结构化事件 ``` 上图展示了事件记忆的完整交互流程: 1. **检索使用**:用户对话时,检索召回与当前问题相关的事件记忆及其他[记忆种类](/cn/memos_cloud/introduction/memory_types),拼接到大模型上下文中; 2. **生成回复**:大模型结合召回的事件记忆生成回复; 3. **自动抽取**:添加消息后,MemOS 自动从对话中抽取结构化事件并存储。 ## 4. 使用示例 ### 添加对话 添加消息时,在 `allow_memory_view` 中包含 `"event"` 即可触发事件记忆抽取。 ```python [Python (HTTP)] import requests API_KEY = "YOUR_API_KEY" BASE_URL = "https://memos.memtensor.cn/api/openmem/v1" data = { "user_id": "memos_user_123", "conversation_id": "conv_0624", "allow_memory_view": ["event", "detail_factual", "preference"], "messages": [ {"role": "user", "content": "上周二下午和李四一起做了方案评审,客户对第二版方案比较满意,但希望把交付时间提前到七月底。"}, {"role": "assistant", "content": "收到,需要我帮你整理一下评审中的关键结论吗?"} ] } res = requests.post( f"{BASE_URL}/add/message", headers={"Authorization": f"Token {API_KEY}"}, json=data ) print(res.json()) ``` ```python [Python (SDK)] # 请确保已安装 MemOS(pip install MemoryOS -U) from memos.api.client import MemOSClient client = MemOSClient(api_key="YOUR_API_KEY") res = client.add_message( user_id="memos_user_123", conversation_id="conv_0624", allow_memory_view=["event", "detail_factual", "preference"], messages=[ {"role": "user", "content": "上周二下午和李四一起做了方案评审,客户对第二版方案比较满意,但希望把交付时间提前到七月底。"}, {"role": "assistant", "content": "收到,需要我帮你整理一下评审中的关键结论吗?"} ] ) print(res) ``` ```bash [Curl] curl --request POST \ --url https://memos.memtensor.cn/api/openmem/v1/add/message \ --header 'Authorization: Token YOUR_API_KEY' \ --header 'Content-Type: application/json' \ --data '{ "user_id": "memos_user_123", "conversation_id": "conv_0624", "allow_memory_view": ["event", "detail_factual", "preference"], "messages": [ {"role": "user", "content": "上周二下午和李四一起做了方案评审,客户对第二版方案比较满意,但希望把交付时间提前到七月底。"}, {"role": "assistant", "content": "收到,需要我帮你整理一下评审中的关键结论吗?"} ] }' ``` ### 检索事件记忆 调用 searchMemory 时,在 `include_memory_view` 中传入 `"event"` 即可召回事件记忆。 ```python [Python (HTTP)] import requests API_KEY = "YOUR_API_KEY" BASE_URL = "https://memos.memtensor.cn/api/openmem/v1" data = { "user_id": "memos_user_123", "query": "最近有什么评审或会议?", "include_memory_view": ["event"] } res = requests.post( f"{BASE_URL}/search/memory", headers={"Authorization": f"Token {API_KEY}"}, json=data ) print(res.json()) ``` ```python [Python (SDK)] # 请确保已安装 MemOS(pip install MemoryOS -U) from memos.api.client import MemOSClient client = MemOSClient(api_key="YOUR_API_KEY") res = client.search_memory( user_id="memos_user_123", query="最近有什么评审或会议?", include_memory_view=["event"] ) print(res) ``` ```bash [Curl] curl --request POST \ --url https://memos.memtensor.cn/api/openmem/v1/search/memory \ --header 'Authorization: Token YOUR_API_KEY' \ --header 'Content-Type: application/json' \ --data '{ "user_id": "memos_user_123", "query": "最近有什么评审或会议?", "include_memory_view": ["event"] }' ``` 响应示例: ```json { "code": 0, "message": "ok", "data": { "event_detail_list": [ { "id": "d7785b39-1374-4738-b449-3e86ab1f8b2f", "event_key": "方案评审与交付调整", "event_value": "用户与李四于上周二下午完成方案评审,客户对第二版方案表示满意,并希望将交付时间提前至七月底。", "event_type": "EventMemory", "create_time": 1783929751765, "conversation_id": "conv_event_verify_001", "status": "activated", "update_time": 1783929757755, "relativity": 0.6364, "event_time": ["上周二下午", "七月底"], "event_location": [], "event_roles": ["用户", "李四", "客户"] } ] } } ``` ### 获取事件详情 通过 `get/memory/{memory_id}` 查询单条事件记忆。 ```python [Python (HTTP)] import requests API_KEY = "YOUR_API_KEY" BASE_URL = "https://memos.memtensor.cn/api/openmem/v1" memory_id = "d7785b39-1374-4738-b449-3e86ab1f8b2f" res = requests.get( f"{BASE_URL}/get/memory/{memory_id}", headers={"Authorization": f"Token {API_KEY}"} ) print(res.json()) ``` ```python [Python (SDK)] # 请确保已安装 MemOS(pip install MemoryOS -U) from memos.api.client import MemOSClient client = MemOSClient(api_key="YOUR_API_KEY") res = client.get_memory_by_id(memory_id="d7785b39-1374-4738-b449-3e86ab1f8b2f") print(res) ``` ```bash [Curl] curl --request GET \ --url https://memos.memtensor.cn/api/openmem/v1/get/memory/d7785b39-1374-4738-b449-3e86ab1f8b2f \ --header 'Authorization: Token YOUR_API_KEY' ``` ### 自定义抽取配置 事件记忆支持在控制台自定义抽取 Prompt,适用于需要调整抽取粒度或关注方向的场景: 1. 登录 [MemOS 控制台](https://memos-dashboard.openmem.net/cn/quickstart),进入项目,找到「自定义抽取」; 2. 编辑事件记忆的抽取 Prompt,支持手动修改或 AI 辅助生成; 3. 使用「快速调试」验证抽取效果:输入样例对话,点击「运行抽取」,查看抽取的记忆是否符合预期; 4. 确认后保存修改。 ![自定义抽取:编辑事件记忆 Prompt 与快速调试](https://cdn.memtensor.com.cn/img/1783930331092_hk236a_compressed.png) ## 5. 相关功能 - [属性记忆](/cn/memos_cloud/features/profile): 维护用户或 AI 角色的结构化画像,与事件记忆互补 - [记忆种类](/cn/memos_cloud/introduction/memory_types): 了解事件记忆与其他记忆种类的区别 --- # 记忆自进化 Self-Evolving (/cn/memos_cloud/features/self-evolving) ## 什么是记忆自进化(Self-Evolving)? 在 AI Agent 的语境中,**Skill** 是一套可复用的任务处理方法。它告诉 Agent「遇到某类任务该怎么做」,例如: - 如何规划一次旅行 - 如何处理一笔退货工单 - 如何按公司规范生成周报 技能可以弥补大模型在长期运行中经验难以沉淀的问题,主要体现在: - 可维护:把真实任务中的稳定流程沉淀为结构化方法,方便持续迭代。 - 按需调用:由 Agent 根据当前任务召回相关技能,而不是把所有流程都放进上下文。 - 个性化:将不同用户的偏好、习惯和禁忌转化为可复用的执行方式。 通过在对话中提炼可复用的Skill,MemOS可以实现记忆的自进化,持续增强Agent的能力。 --- ## MemOS 如何为 Agent 提供记忆自进化能力? ### 1. 自动生成个性化技能 MemOS 主张“记忆即资产”,在真实对话中沉淀下来的解决路径与用户偏好,就是最宝贵的技能素材。 你不需要准备任何文件,只要添加用户与 Agent 的对话原文,MemOS **会从用户记忆中自动提炼技能**——将零散的交互历史固化为可复用、个性化的专业能力。 ### 2. 上传自定义技能 现在,MemOS 也支持直接上传你已有的技能文件,上传 Markdown 文件或 ZIP 包到知识库,MemOS 就能在检索时返回相关的技能给 Agent。 --- ## 自动生成个性化技能 ### 工作原理 ![image.png](https://cdn.memtensor.com.cn/img/1769653199709_6ol3n7_compressed.png) 上图展示了终端用户、你构建的 AI Agent 与 MemOS 的完整交互流程: 1. 调用 `add/message` 接口将用户的对话消息传入 MemOS。 2. MemOS 接收到请求后,会依次完成以下处理,生成技能(Skill)文件: a. **智能切片**:识别历史对话中的任务边界,切分成任务文本块; b. **聚类提取**:将同类型的任务文本块聚类,结合用户的历史记忆,提取出结构化的技能文本。 c. **技能转化**:将技能转化为可运行、可被识别的技能(Skill)文件。 3. 调用 `search/memory` 接口检索记忆,MemOS 会统一返回与上下文相关的用户事实、偏好、工具记忆与匹配的技能(Skill)文件。 4. 下载技能文件,将记忆和技能文件统一传给你自己部署的大模型,从而实现对长期经验与自动生成技能的有效利用。 整个过程无需手动上传任何技能文件。 ### 旅行规划示例 以「旅行规划」为例,展示同一个任务如何为不同用户生成不同技能。 #### 1. 添加对话 用户在对话中表达了自己的旅行规划偏好:不走回头路、行程紧凑、偏好文化景点、需要提前检查天气。 ```python import os import json import requests os.environ["MEMOS_API_KEY"] = "YOUR_API_KEY" os.environ["MEMOS_BASE_URL"] = "https://memos.memtensor.cn/api/openmem/v1" data = { "user_id": "memos_user_j", "conversation_id": "travel_0127", "messages": [ { "role": "user", "content": "下周我要去成都玩,帮我规划一个5天的出行计划。我喜欢不走回头路的特种兵出行,也帮我标注路途中值得品尝的美食。" }, {"role": "assistant", "content": "...此处省略..."}, { "role": "user", "content": "我比较喜欢逛文化景点,商场什么的不太感兴趣。" }, {"role": "assistant", "content": "...此处省略..."}, { "role": "user", "content": "帮我在规划的时候提前确认天气和温度,方便我准备行李。" }, {"role": "assistant", "content": "...此处省略..."} ] } headers = { "Content-Type": "application/json", "Authorization": f"Token {os.environ['MEMOS_API_KEY']}" } url = f"{os.environ['MEMOS_BASE_URL']}/add/message" res = requests.post(url=url, headers=headers, data=json.dumps(data)) print(f"result: {res.json()}") ``` #### 2. 检索技能 当同一用户下次提出类似需求时,传入 `include_skill=true`: ```python data = { "query": "清明节我打算去云南,帮我规划7天的行程。", "user_id": "memos_user_j", "conversation_id": "travel_0301", "include_skill": True } res = requests.post( url=f"{os.environ['MEMOS_BASE_URL']}/search/memory", headers=headers, data=json.dumps(data) ) print(f"result: {res.json()}") ``` #### 3. MemOS 生成技能 同样是「旅行规划」,不是所有用户套同一个模板,而是把每个用户长期对话中的偏好沉淀为专属、可复用的能力。 如下所示,MemOS 为这位高能量 J 人生成的技能可能如下: ```markdown --- name: 旅行行程规划 description: 为高能量旅行者设计多日行程,包括高效动线、文化景点、美食与天气适配建议。 --- ## Procedure 1. 确定旅行天数、目的地和用户偏好 2. 收集目的地文化景点、美食点位和交通信息 3. 按区域规划每日路线,避免来回折返 4. 将美食点位穿插进交通动线中 5. 检查天气预报,调整每日路线和行李建议 ## Experience - 优先安排文化景点,减少购物商场类行程 - 路线要紧凑,适合高能量、特种兵式旅行 - 每日行程尽量按地理位置顺路推进 ## User Preferences - 不走回头路 - 偏好文化景点 - 希望提前确认天气和温度 ``` 如果另一个用户是「低能量 P 人」,在对话中表达了"夜猫子、早上起不来、不想去太远、喜欢小众景点",MemOS 生成的技能会明显不同: ```markdown --- name: 旅行行程规划 description: 帮助低能量旅行者规划轻松、灵活、偏下午和夜间体验的旅行行程。 --- ## Procedure 1. 确认用户当天精力、起床时间和不可接受的通勤距离 2. 优先筛选距离近、交通简单、不需要赶早的景点 3. 将行程重心放在下午、傍晚和夜间活动 4. 穿插小众景点,避免过度热门和拥挤路线 5. 保留弹性时间,允许用户临时调整 ## Experience - 避免安排早起项目 - 避免长距离奔波和过密行程 - 优先推荐地铁直达或短途打车可达的地点 ## User Preferences - 夜猫子,早上起不来 - 不喜欢赶路 - 喜欢小众、不走寻常路的体验 ``` --- ## 上传自定义技能 ### 客服退货示例 当你已有明确的标准流程,可以直接上传技能文件到知识库,MemOS 将统一检索并返回相关的技能。下述示例以「客服 Agent 退货处理流程」举例,讲解从技能上传到检索使用的全流程。 #### 1. 通过 API 上传到知识库 通过上传知识库文件,上传一份指导客服 Agent 协助用户完成退货的技能文件。 ```python [URL 上传] import os import json import requests os.environ["MEMOS_API_KEY"] = "YOUR_API_KEY" os.environ["MEMOS_BASE_URL"] = "https://memos.memtensor.cn/api/openmem/v1" headers = { "Content-Type": "application/json", "Authorization": f"Token {os.environ['MEMOS_API_KEY']}" } data = { "knowledgebase_id": "kb_xxx", # 替换为你的知识库 ID "file": [ { "type": "skill", "content": "https://cdn.memtensor.com.cn/file/SKILL.md" # 替换为你要上传的文件地址 } ] } url = f"{os.environ['MEMOS_BASE_URL']}/add/knowledgebase-file" res = requests.post(url=url, headers=headers, data=json.dumps(data)) print(f"result: {res.json()}") ``` ```python [Base64 上传] import os import json import base64 import requests os.environ["MEMOS_API_KEY"] = "YOUR_API_KEY" os.environ["MEMOS_BASE_URL"] = "https://memos.memtensor.cn/api/openmem/v1" skill_markdown = """--- name: 客服退货处理流程 description: 指导客服按标准流程处理用户退货请求 --- ## Procedure 1. 确认用户身份和订单号 2. 核实退货原因是否符合政策 3. 引导用户选择退货方式(上门取件/自行寄回) 4. 生成退货单号并告知用户 5. 跟踪物流状态,退款到账后通知用户 ## Experience - 签收 7 天内可无理由退货 - 生鲜类商品不支持退货,需走售后补偿流程 - 高价值商品(>500 元)需主管审批 ## User Preferences - 优先推荐上门取件,减少用户操作成本 - 退款方式默认原路退回 ## Examples ### Example 1: 普通商品退货 用户:我三天前买的耳机想退货。 助手:好的,已确认您的订单在 7 天无理由退货范围内。请问您希望上门取件还是自行寄回? """ encoded_skill = base64.b64encode(skill_markdown.encode("utf-8")).decode("utf-8") data = { "knowledgebase_id": "kb_xxx", # 替换为你的知识库 ID "file": [ { "type": "skill", "name": "customer-return-sop.md", "content": f"data:text/markdown;base64,{encoded_skill}" } ] } headers = { "Content-Type": "application/json", "Authorization": f"Token {os.environ['MEMOS_API_KEY']}" } url = f"{os.environ['MEMOS_BASE_URL']}/add/knowledgebase-file" res = requests.post(url=url, headers=headers, data=json.dumps(data)) print(f"result: {res.json()}") ``` #### 2. 通过控制台上传技能文件 前往 [控制台 - 知识库](https://memos-dashboard.openmem.net/knowledgeBase/),选择目标知识库,点击「上传文档」,将 `.md` 或 `.zip` 文件拖入即可。上传时选择文件类型为「技能文件」。 ![image](https://cdn.memtensor.com.cn/img/1778148120408_c3xk8d_compressed.png) #### 3. 检索技能 上传成功后,检索时传入 `knowledgebase_ids` 并开启 `include_skill`,MemOS 会返回与查询内容相关的技能。如下所示,Agent 可按「客服退货处理流程」引导用户完成退货。 ```python data = { "query": "用户想退一件三天前买的耳机", "user_id": "memos_user_123", "conversation_id": "session_001", "knowledgebase_ids": ["kb_xxx"], "include_skill": True } res = requests.post( url=f"{os.environ['MEMOS_BASE_URL']}/search/memory", headers=headers, data=json.dumps(data) ) print(f"result: {res.json()}") ``` ### Skill 文件规范 #### 1. 单文件 `.md` - 约束条件如下: - 大小限制:≤ 100KB - 文件内容:必须包含 `name` 和 `description` - 推荐按以下格式组织正文: ```text --- name: (技能名称) description: (一句话描述技能的用途和适用场景) --- ## Procedure 1. 步骤一 2. 步骤二 3. 步骤三 ## Experience - 经验或注意事项一 - 经验或注意事项二 ## User Preferences - 偏好设定一 - 偏好设定二 ## Examples ### Example 1: (场景描述) (完整的输入输出示例) ## Additional Information (补充说明,如参考链接、特殊规则等) ``` #### 2. 技能压缩包 `.zip` - 约束条件如下: | 约束 | 要求 | | --- | --- | | 格式 | 标准 ZIP,不支持 rar/7z | | zip 大小 | ≤ 20MB | | 解压后文件数 | ≤ 200 | | 解压后单文件 | ≤ 10MB | | SKILL.md | ≤ 100KB,`name`/`description` 必填,须在压缩包第一层 | - 推荐按以下格式组织正文: ```text refund-sop-v1.zip ├── SKILL.md ├── references/ │ └── 退货政策摘要.md ├── scripts/ │ └── check_order.py └── assets/ └── flowchart.png ``` --- ## 如何使用召回的技能 无论技能来源是自动生成还是知识库上传,检索返回的 `skill_detail_list` 中每个技能包含两个字段: | 字段 | 说明 | | --- | --- | | `skill_value` | 技能的结构化内容,可直接转为字符串注入 Agent 的 prompt | | `skill_url` | 技能文件的下载链接;如果是 zip 技能包,Agent 可下载后获取脚本、参考资料等附件 | ### 用法参考 根据你调用的 Agent 是否具备使用 Skill 的能力,可参考以下两种用法: #### 1. Agent 支持 Skill 将 `skill_url` 提供给 Agent,让它下载链接中的文件,可以把它写进 prompt: ```python skill_detail = result["skill_detail_list"][0] skill_url = skill_detail.get("skill_url") system_prompt = f"""你是一个客服助手。遇到用户退货,可使用以下 Skill 文件完成任务: {skill_url} """ ``` #### 2. Agent 不支持 Skill 将 `skill_value` 转成字符串,添加到 prompt 中: ```python skill_detail = result["skill_detail_list"][0] skill = str(skill_detail["skill_value"]) system_prompt = f"""你是一个客服助手。请参考以下技能执行任务: {skill} """ ``` > **Tip**: 检索时,MemOS 会同时搜索个人对话生成的技能和知识库中上传的技能,统一排序返回。你无需区分来源。 --- **现在就开始探索 MemOS 记忆自进化能力吧!** - 前往 [控制台 - 技能页面](https://memos-dashboard.openmem.net/cn/skill/),查看自动生成的技能。 - 还没有技能?[添加消息](/memos_cloud/mem_operations/add_message)即可触发生成。 - 想上传自定义技能?前往 [控制台 - 知识库](https://memos-dashboard.openmem.net/knowledgeBase/)上传。 --- # 群聊 (/cn/memos_cloud/features/group_chat) ## 1. 群聊是什么? 群聊场景下,多个用户和/或 Agent 在同一会话中对话,MemOS 为每个参与者独立抽取和维护记忆。传入发言人的标识和名称后,记忆抽取会自动区分“谁说了什么”,生成以具体人名为主语的记忆,让每个参与者的画像更精准。 > **Note**: 适用场景 > > - 项目群、周会、方案评审等多人同场讨论; > - 家庭 / 团队共用助手:一次群聊写入后,各成员记忆中都保留这份讨论; > - 多 Agent 参与:`agent_id` 同样支持数组,多个 AI 角色可一起参与。 ## 2. 关键参数 - **用户标识(user_id)**:支持字符串(单用户)或字符串数组(群聊多用户)。 - **Agent 标识(agent_id)**:同样支持字符串或字符串数组;多 Agent 可同时参与群聊。 - **发言人标识(role_id)**:群聊时建议传入,标识每条消息由谁发送,建议对应顶层 `user_id` / `agent_id` 中的某个值。 - **发言人名称(role_name)**:与 `role_id` 同时传入后,记忆文本中可带上人名,便于区分发言人。 - **会话标识(conversation_id)**:群聊会话的唯一标识。 ### 限制说明 | 限制项 | 说明 | | --- | --- | | `user_id` / `agent_id` 列表上限 | 单次最多传入 20 个 ID | | QPS 折算 | 按参与人数折算;例如传入 20 个 ID 时 ×20 折算,即每秒最多 2 次请求 | 更多通用配额说明见[配额与限制](/cn/memos_cloud/support/limit)。 ## 3. 使用流程 ```mermaid sequenceDiagram autonumber participant UserA as 用户A participant UserB as 用户B participant App as AI 产品 participant Mem as MemOS participant LLM as AI 产品接入大模型 UserA->>App: 在群聊中发言 UserB->>App: 在群聊中发言 App->>Mem: searchMemory(user_id=用户A) Mem-->>App: 从用户 A 的记忆中召回 App->>LLM: 拼接上下文 LLM->>UserA:展示回复 App->>Mem: addMessage(user_id 列表 + role_id + role_name) Mem->>Mem: 将群聊记录写入用户A的记忆 Mem->>Mem: 将群聊记录写入用户B的记忆 ``` 1. **多人对话**:多个用户在同一会话中发言; 2. **按人检索**:用某个 `user_id` 调用 searchMemory,在该用户的记忆空间中检索; 3. **一次写入**:`user_id` 传为列表,每条消息标注 `role_id` / `role_name`; 4. **各自抽取**:列表中每位参与者都会抽取关于这份群聊的记忆。 ## 4. 使用示例 ### 添加群聊消息 例如张三、李四与助手在同一会话里对齐方案评审时间: ```python [Python (HTTP)] import requests API_KEY = "YOUR_API_KEY" BASE_URL = "https://memos.memtensor.cn/api/openmem/v1" data = { "user_id": ["memos_user_1", "memos_user_2"], "agent_id": "memos_agent", "conversation_id": "group_conv_001", "messages": [ {"role": "user", "role_id": "memos_user_1", "role_name": "张三", "content": "下周二的方案评审,大家时间合适吗?"}, {"role": "user", "role_id": "memos_user_2", "role_name": "李四", "content": "我可以,下午两点怎么样?"}, {"role": "assistant", "role_id": "memos_agent", "content": "已记录,下周二下午两点方案评审。需要我帮忙准备会议议程吗?"} ] } res = requests.post( f"{BASE_URL}/add/message", headers={"Authorization": f"Token {API_KEY}"}, json=data ) print(res.json()) ``` ```python [Python (SDK)] # 请确保已安装 MemOS(pip install MemoryOS -U) from memos.api.client import MemOSClient client = MemOSClient(api_key="YOUR_API_KEY") res = client.add_message( user_id=["memos_user_1", "memos_user_2"], agent_id="memos_agent", conversation_id="group_conv_001", messages=[ {"role": "user", "role_id": "memos_user_1", "role_name": "张三", "content": "下周二的方案评审,大家时间合适吗?"}, {"role": "user", "role_id": "memos_user_2", "role_name": "李四", "content": "我可以,下午两点怎么样?"}, {"role": "assistant", "role_id": "memos_agent", "content": "已记录,下周二下午两点方案评审。需要我帮忙准备会议议程吗?"} ] ) print(res) ``` ```bash [Curl] curl --request POST \ --url https://memos.memtensor.cn/api/openmem/v1/add/message \ --header 'Authorization: Token YOUR_API_KEY' \ --header 'Content-Type: application/json' \ --data '{ "user_id": ["memos_user_1", "memos_user_2"], "agent_id": "memos_agent", "conversation_id": "group_conv_001", "messages": [ {"role": "user", "role_id": "memos_user_1", "role_name": "张三", "content": "下周二的方案评审,大家时间合适吗?"}, {"role": "user", "role_id": "memos_user_2", "role_name": "李四", "content": "我可以,下午两点怎么样?"}, {"role": "assistant", "role_id": "memos_agent", "content": "已记录,下周二下午两点方案评审。需要我帮忙准备会议议程吗?"} ] }' ``` 写入后,记忆文本里可通过 `role_name` 区分发言人。 ### 检索群聊相关记忆 之后任一参与者继续对话时,用该用户的 `user_id` 检索即可召回这份群聊上下文。例如张三询问会议安排: ```python [Python (HTTP)] import requests API_KEY = "YOUR_API_KEY" BASE_URL = "https://memos.memtensor.cn/api/openmem/v1" data = { "user_id": "memos_user_1", "query": "最近有什么会议安排?" } res = requests.post( f"{BASE_URL}/search/memory", headers={"Authorization": f"Token {API_KEY}"}, json=data ) print(res.json()) ``` ```python [Python (SDK)] # 请确保已安装 MemOS(pip install MemoryOS -U) from memos.api.client import MemOSClient client = MemOSClient(api_key="YOUR_API_KEY") res = client.search_memory( user_id="memos_user_1", query="最近有什么会议安排?" ) print(res) ``` ```bash [Curl] curl --request POST \ --url https://memos.memtensor.cn/api/openmem/v1/search/memory \ --header 'Authorization: Token YOUR_API_KEY' \ --header 'Content-Type: application/json' \ --data '{ "user_id": "memos_user_1", "query": "最近有什么会议安排?" }' ``` > **Note**: 若仍需缩小检索范围,可在 `filter` 中使用 `related_id` 等条件。详见[记忆过滤](/cn/memos_cloud/features/filters)。 ## 5. 相关功能 - [多用户 / 多 Agent 隔离](/cn/memos_cloud/introduction/isolation_filters): 了解 user_id、agent_id 与会话隔离机制 - [配额与限制](/cn/memos_cloud/support/limit): 群聊列表上限与 QPS 折算说明 --- # 工具调用ToolCall (/cn/memos_cloud/features/tool_calling) > **Warning**: 注意 > > > > **[需要先在addMessage的时候传入工具记忆(点此查看详细 API 文档)](/api_docs/core/add_message)** > > > **[才能在searchMemory的时候搜索到工具记忆(点此查看详细 API 文档)](/api_docs/core/search_memory)** > > > > **本文聚焦于功能说明,详细接口字段及限制请点击上方文字链接查看** ## 1. 何时使用 当您的 Agent 需要通过工具(function / tool)获取外部信息,并希望这些「工具调用的上下文与结果」能够被 MemOS 一并理解、关联和沉淀为可检索记忆时,适合使用这种消息结构。 ## 2. 工作原理 Step1:添加工具调用信息 `assistant` 消息: `tool_calls` 描述模型决定调用某个工具的行为及其参数。 `tool` 消息:携带真实的工具返回结果,并通过 `tool_call_id` 与对应的 `tool_calls` 精确关联。 Step2:MemOS 处理工具相关记忆 * **工具信息(Tool Schema)**:MemOS 支持对工具信息的结构化管理与动态更新,统一不同工具的描述方式,使模型能够高效地进行工具检索、理解与发现,而无需在提示词中硬编码工具细节。 * **轨迹记忆(Tool Trajectory Memory)**:MemOS 会对工具使用过程中的关键轨迹进行抽取与存储,包括“在什么上下文下调用了什么工具、使用了哪些参数、返回了什么结果”。这些轨迹可在后续对话中被检索和复用,帮助模型更稳定地重现工具使用模式,减少重复试探和调用错误。 ## 3.使用示例 有关 API 字段、格式等信息的完整列表,详见[Add Message 接口文档](/api_docs/core/add_message)查看如何添加工具调用信息。 ### 添加工具调用信息 > **Note**:  会话 A:用户在对话中询问【北京天气如何】,助手调用【天气工具】,天气工具得出结果【北京,温度7°C,阴天】。 ```python import os import requests import json # 替换成你的 MemOS API Key os.environ["MEMOS_API_KEY"] = "YOUR_API_KEY" os.environ["MEMOS_BASE_URL"] = "https://memos.memtensor.cn/api/openmem/v1" # 带 tool_call 的消息序列 tool_schema = [{ "name": "get_weather", "description": "Get current weather information for a given location", "parameters": { "type": "object", "properties": { "location": { "type": "string", "description": "City name, e.g. Beijing" } }, "required": [ "location" ] } }] data = { "user_id": "memos_user_123", "conversation_id": "demo-conv-id", "messages": [ { "role": "system", "content": f"""You are an assistant that can call tools. When a user's request can be fulfilled by a tool, you MUST call the appropriate tool. {json.dumps(tool_schema, indent=2, ensure_ascii=False)} """ }, {"role": "user", "content": "What's the weather like in Beijing right now?"}, { "role": "assistant", "tool_calls": [ { "id": "call_123", "type": "function", "function": { "name": "get_weather", "arguments": json.dumps({"location": "Beijing"}), }, } ], }, { "role": "tool", "tool_call_id": "call_123", "content": [ { "type": "text", "text": json.dumps( {"location": "Beijing", "temperature": "7°C", "condition": "Cloudy"} ), } ], }, ], } headers = { "Content-Type": "application/json", "Authorization": f"Token {os.environ['MEMOS_API_KEY']}" } url = f"{os.environ['MEMOS_BASE_URL']}/add/message" res = requests.post(url=url, headers=headers, data=json.dumps(data)) print(json.dumps(res.json(), indent=2, ensure_ascii=False)) ``` ### 检索工具记忆 > **Note**:  会话 B:在新会话中,用户询问【北京适合穿什么衣服】,MemOS能够召回过往【天气工具调用】的相关工具记忆,模型可在后续使用工具记忆,提升工具使用的准确率、有效性。 ```python import os import requests import json os.environ["MEMOS_API_KEY"] = "YOUR_API_KEY" os.environ["MEMOS_BASE_URL"] = "https://memos.memtensor.cn/api/openmem/v1" data = { "user_id": "memos_user_123", "conversation_id": "0928", "query": "北京适合穿什么衣服", "include_memory_view": ["tool_memory"], "memory_limit_number": 10 } headers = { "Content-Type": "application/json", "Authorization": f"Token {os.environ['MEMOS_API_KEY']}" } url = f"{os.environ['MEMOS_BASE_URL']}/search/memory" res = requests.post(url=url, headers=headers, data=json.dumps(data)) print(json.dumps(res.json(), indent=2, ensure_ascii=False)) ``` ### 输出结果 ```python "tool_memory_detail_list": [ { "id": "7ec50fd8-19ec-42a2-a7c7-ce3cebdb70cf", "tool_type": "ToolSchemaMemory", "tool_value": {"name": "get_weather", "description": "Get current weather information for a given location", "parameters": {"type": "object", "properties": {"location": {"type": "string", "description": "City name, e.g. Beijing"}}, "required": ["location"]}}, "create_time": 1766494806624, "conversation_id": "demo-conv-id", "status": "activated", "update_time": 1766494806625, "relativity": 0.44700349055540967 }, { "id": "4b208707-991a-481c-9dd6-c7f0577ff371", "tool_type": "ToolTrajectoryMemory", "tool_value": "User asked about the current weather in Beijing -> Tool 'get_weather' was called with the parameter 'location' set to 'Beijing' -> The tool returned the weather information: temperature is 7°C and condition is Cloudy.", "tool_used_status": [ { "used_tool": "get_weather", "error_type": "", "success_rate": 1.0, "tool_experience": "The 'get_weather' tool requires a valid location parameter and provides current weather information for that location." #新增:当前轨迹中该工具的经验。 } ], "create_time": 1768390489180, "conversation_id": "demo-conv-id", "status": "activated", "update_time": 1768390489181, "relativity": 0.47883897395535013, "experience": "when encountering weather inquiry tasks, then ensure to call the 'get_weather' tool with the correct location parameter." #新增:整个轨迹的程序性经验,作为指导任务完成的总体经验。 } ] ``` --- # 多模态消息 (/cn/memos_cloud/features/multimodal) > **Warning**: **[本文是对【添加记忆-addMessage接口】里的如何添加多模态数据做展开介绍,可点此直接查看详细 API 文档](/api_docs/core/add_message)** MemOS 不仅支持文本,还支持多模态数据,包括文档和图片。用户可以将文本、文档和图片无缝整合到与 MemOS 的交互中,使系统能够从多种媒体类型提取相关信息,丰富记忆内容,并增强记忆系统的能力。 ## 1. 如何添加多模态消息 > **Note**: 注意 > 当消息包含多模态内容时,由于文件记忆的加工时间较长,您传入的`async_mode`字段失效,此时默认使用“异步模式”。您可通过`get/status`接口查询文件记忆的处理进度。 当用户上传文档或图片时,MemOS 会提取文本、视觉信息和其他相关细节,并处理为用户记忆。 > **Note**: **多模态消息与工具记忆** > > 除了处理文档和图片内容外,MemOS 还支持处理工具调用信息。当您在消息中添加工具调用信息时,系统会将其处理为工具记忆,包括工具信息(Tool Schema)和轨迹记忆(Tool Trajectory Memory)。详见[工具调用](/cn/memos_cloud/features/tool_calling)。 ### 添加消息 ```python import os import requests import json # 替换成你的 MemOS API Key os.environ["MEMOS_API_KEY"] = "YOUR_API_KEY" os.environ["MEMOS_BASE_URL"] = "https://memos.memtensor.cn/api/openmem/v1" data = { "user_id": "memos_user_123", "conversation_id": "1211", "messages": [ { "role": "user", "content": [ { "type": "text", "text": "我正在研究MemOS。" }, { "type": "image_url", "image_url": { "url": "https://cdn.memtensor.com.cn/img/1758706201390_iluj1c_compressed.png" } } ] }, {"role": "assistant", "content": "好的,需要我为您解答吗?"} ] } headers = { "Content-Type": "application/json", "Authorization": f"Token {os.environ['MEMOS_API_KEY']}" } url = f"{os.environ['MEMOS_BASE_URL']}/add/message" res = requests.post(url=url, headers=headers, data=json.dumps(data)) print(json.dumps(res.json(), indent=2, ensure_ascii=False)) ``` ### 检索记忆 ```python import os import requests import json # 替换成你的 MemOS API Key os.environ["MEMOS_API_KEY"] = "YOUR_API_KEY" os.environ["MEMOS_BASE_URL"] = "https://memos.memtensor.cn/api/openmem/v1" data = { "query": "帮我总结一下这张图", "user_id": "memos_user_123", "conversation_id": "1214" } headers = { "Content-Type": "application/json", "Authorization": f"Token {os.environ['MEMOS_API_KEY']}" } url = f"{os.environ['MEMOS_BASE_URL']}/search/memory" res = requests.post(url=url, headers=headers, data=json.dumps(data)) # 替换打印部分 print("结果:") print(json.dumps(res.json(), indent=2, ensure_ascii=False)) ``` ### 输出结果 ```python { "code": 0, "data": { "memory_detail_list": [ { "id": "a5136287-de10-4df2-afc5-e412cdb8b649", "memory_key": "研究MemOS", "memory_value": "用户正在研究MemOS,并分享了一张相关的图片,时间为2025年12月18日早上7:07(UTC)。", "memory_type": "WorkingMemory", "create_time": 1766041646311, "conversation_id": "1211", "status": "activated", "confidence": 0.99, "tags": [ "研究", "MemOS", "图片分享" ], "update_time": 1766041689234, "relativity": 0.5170716 }, { "id": "4a1d42f4-c9fa-41bf-805d-2ea985bba984", "memory_key": "MemOS功能概述", "memory_value": "MemOS是一个智能记忆系统,能够通过添加路径进行信息存储,并通过查询功能进行信息检索。系统支持多种文档格式,如PDF和DOC,并利用AI进行智能响应和处理。", "memory_type": "WorkingMemory", "create_time": 1766041689091, "conversation_id": "1211", "status": "activated", "confidence": 0.99, "tags": [ "MemOS", "智能记忆", "信息存储", "查询功能", "image", "visual" ], "update_time": 1766041689234, "relativity": 0.38406307 } ], "preference_detail_list": [], "tool_memory_detail_list": [], "preference_note": "" }, "message": "ok" } ``` ## 2. 媒体类型 MemOS 目前支持以下的媒体类型: 1. **图片** - JPG、PNG 及其他常见图片格式 2. **文档** - PDF、DOCX、DOC、TXT、JSON、MD、XML ## 3. 文件上传限制 1. 添加消息时,每次请求上传的文件不超过20个,单文件大小不超过 100 MB、500页。注意:`add/message`接口的输入上限为 20,000 Token 数。 2. 当文件数量、单文件大小或页数超出上述限制时,本次任务将被判定为“处理失败”。您需根据限制要求调整后,重新发起请求。 ## 4. 使用示例 ### 上传图片消息 **使用图片网址** 添加消息时,可以直接上传图片的网址。 ```python import os import requests import json # 替换成你的 MemOS API Key os.environ["MEMOS_API_KEY"] = "YOUR_API_KEY" os.environ["MEMOS_BASE_URL"] = "https://memos.memtensor.cn/api/openmem/v1" data = { "user_id": "memos_user_123", "conversation_id": "1211", "messages": [ { "role": "user", "content": [ { "type": "image_url", "image_url": { "url": "https://cdn.memtensor.com.cn/img/1758706201390_iluj1c_compressed.png" } } ] } ] } headers = { "Content-Type": "application/json", "Authorization": f"Token {os.environ['MEMOS_API_KEY']}" } url = f"{os.environ['MEMOS_BASE_URL']}/add/message" res = requests.post(url=url, headers=headers, data=json.dumps(data)) print(json.dumps(res.json(), indent=2, ensure_ascii=False)) ``` **使用 Base64 图像编码上传本地图片** 上传本地图像或者直接嵌入图像,可以使用 Base64 图像编码。 ```python import os import requests import json import base64 # 替换成你的 MemOS API Key os.environ["MEMOS_API_KEY"] = "YOUR_API_KEY" os.environ["MEMOS_BASE_URL"] = "https://memos.memtensor.cn/api/openmem/v1" # 图像文件的路径地址 image_path = "path/to/your/image.jpg" # 使用 Base64 为图像编码 with open(image_path, "rb") as image_file: base64_image = base64.b64encode(image_file.read()).decode("utf-8") data = { "user_id": "memos_user_123", "conversation_id": "1211", "messages": [ { "role": "user", "content": [ { "type": "image_url", "image_url": {"url": f"data:image/jpeg;base64,{base64_image}"} } ] } ] } headers = { "Content-Type": "application/json", "Authorization": f"Token {os.environ['MEMOS_API_KEY']}" } url = f"{os.environ['MEMOS_BASE_URL']}/add/message" res = requests.post(url=url, headers=headers, data=json.dumps(data)) print(json.dumps(res.json(), indent=2, ensure_ascii=False)) ``` ### 上传文档消息 **使用文档网址** ```python import os import requests import json # 替换成你的 MemOS API Key os.environ["MEMOS_API_KEY"] = "YOUR_API_KEY" os.environ["MEMOS_BASE_URL"] = "https://memos.memtensor.cn/api/openmem/v1" data = { "user_id": "memos_user_123", "conversation_id": "1211", "messages": [ { "role": "user", "content": [ { "type": "file", "file": { "file_data": "https://cdn.memtensor.com.cn/file/MemOS 2.pdf" } } ] } ] } headers = { "Content-Type": "application/json", "Authorization": f"Token {os.environ['MEMOS_API_KEY']}" } url = f"{os.environ['MEMOS_BASE_URL']}/add/message" res = requests.post(url=url, headers=headers, data=json.dumps(data)) print(json.dumps(res.json(), indent=2, ensure_ascii=False)) ``` **使用 Base64 图像编码上传本地文档** ```python import os import requests import json import base64 # 替换成你的 MemOS API Key os.environ["MEMOS_API_KEY"] = "YOUR_API_KEY" os.environ["MEMOS_BASE_URL"] = "https://memos.memtensor.cn/api/openmem/v1" # 文档文件的路径地址 document_path = "path/to/your/document.pdf" # 将文件转换为 Base64 字符串的函数 def file_to_base64(file_path): with open(file_path, "rb") as file: return base64.b64encode(file.read()).decode('utf-8') # 使用 Base64 为文档编码 base64_document = file_to_base64(document_path) data = { "user_id": "memos_user_123", "conversation_id": "1211", "messages": [ { "role": "user", "content": [ { "type": "file", "file": {"file_data": base64_document} } ] } ] } headers = { "Content-Type": "application/json", "Authorization": f"Token {os.environ['MEMOS_API_KEY']}" } url = f"{os.environ['MEMOS_BASE_URL']}/add/message" res = requests.post(url=url, headers=headers, data=json.dumps(data)) print("结果:") print(json.dumps(res.json(), indent=2, ensure_ascii=False)) ``` ### 完整示例 以下是一个完整的示例,展示如何添加用户与助手包含了不同媒体类型的对话消息: ```python import os import json import requests # 替换成你的 MemOS API Key os.environ["MEMOS_API_KEY"] = "YOUR_API_KEY" os.environ["MEMOS_BASE_URL"] = "https://memos.memtensor.cn/api/openmem/v1" data = { "user_id": "memos_user_123", "conversation_id": "1211", "messages": [ { "role": "user", "content": [ { "type": "text", "text": "我在研究MemOS。" } # 文本消息 ] }, { "role": "user", "content": [ { "type": "image_url", "image_url": { "url": "https://cdn.memtensor.com.cn/img/1758706201390_iluj1c_compressed.png" } } # 上传图片 ] }, { "role": "user", "content": [ { "type": "file", "file": { "file_data": "https://cdn.memtensor.com.cn/file/MemOS 2.pdf" } } # 上传文档 ] } ] } headers = { "Content-Type": "application/json", "Authorization": f"Token {os.environ['MEMOS_API_KEY']}" } url = f"{os.environ['MEMOS_BASE_URL']}/add/message" res = requests.post(url=url, headers=headers, data=json.dumps(data)) print(json.dumps(res.json(), indent=2, ensure_ascii=False)) ``` --- # 云服务 FAQs (/cn/memos_cloud/support/faq) 这篇页面回答 MemOS Cloud 使用过程中的常见问题。如果你想了解 MemOS 和 RAG、开源方案、私有化部署或记忆调度的关系,请查看 [常见问题](/cn/memos_cloud/introduction/faq)。 ## 新用户应该先看哪篇文档? 如果你还没有登录过控制台,先按使用场景选择: - 想让 Claude Code、Cursor 等 Agent 工具帮你接入,先看 [在 Agent 中使用](/cn/memos_cloud/getting_started/agent_usage)。 - 想自己在应用里调用 Cloud API,先看 [在应用中集成](/cn/memos_cloud/getting_started/quick_start)。 [项目配置](/cn/api_docs/start/configuration) 更适合在你需要管理多个项目、修改项目、删除项目,或理解知识库如何绑定到项目时阅读。 ## API Key 和项目是什么关系? 每个项目都有自己的 API Key。使用某个 API Key 调用接口时,只能访问这个项目下的记忆、消息、知识库和配置。 如果出现“控制台看得到,但 API 查不到”的情况,先确认: - 当前控制台项目是否和 API Key 所属项目一致。 - 请求中使用的是不是同一个 `user_id`。 - 检索时是否传了过窄的 `filter`、`knowledgebase_ids`,或过高的 `relativity`。 ## 认证或权限错误怎么排查? 先检查请求头: ```text Authorization: Token YOUR_API_KEY ``` 常见问题包括: - 漏传 `Authorization`。 - 少了 `Token` 前缀。 - API Key 复制不完整。 - API Key 属于另一个项目。 - API Key 已失效,或没有当前资源权限。 如果返回 `40100`、`40130`、`40132`,先回到 [项目配置](/cn/api_docs/start/configuration) 检查 API Key 和项目。 ## 为什么 Search Memory 或 Chat 没有召回知识库内容? 先确认知识库是否已经绑定到当前项目,并且文件已经完成处理。调用接口时还需要注意: - 不传 `knowledgebase_ids` 时,默认不检索知识库。 - 传 `knowledgebase_ids` 时,确认 ID 属于当前项目可访问的知识库。 - 如果设置了 `filter` 或较高的 `relativity`,可能会过滤掉本来相关的内容。 知识库的上传、绑定和处理状态说明,请查看 [知识库](/cn/memos_cloud/features/knowledge_base)。 ## 遇到额度或限流错误怎么办? 先判断是哪类限制: - 单次输入或输出过长:减少本次输入、历史上下文或期望输出。 - 调用次数达到上限:等待额度恢复,或按文档申请更多额度。 - 并发或短时间请求过多:降低请求频率,避免重试风暴。 具体额度说明请查看 [配额与限制](/cn/memos_cloud/support/limit)。 ## 写入成功后,为什么马上检索不到? 记忆写入后需要经过抽取、加工和索引。刚写入后立刻检索,可能还没有完成处理。 建议先确认: - 写入和检索使用的是同一个 `user_id`。 - 没有使用过窄的 `conversation_id`、`filter` 或 `knowledgebase_ids`。 - 如果是异步写入,等任务完成后再检索。 ## Delete Memory 删除失败怎么办? 删除单条记忆时,优先使用 `memory_ids`。不要把 `conversation_id`、`user_id` 或知识库 ID 当成 `memory_id` 使用。 如果需要删除某个用户在当前项目下的全部记忆,才传 `user_id`。这是高风险操作,执行前需要确认 API Key、项目和用户 ID 都正确。 ## 控制台和 API 的数据范围为什么不一致? 控制台和 API 都按项目隔离数据。出现范围不一致时,通常是因为: - 控制台当前选中的项目和 API Key 所属项目不同。 - API 请求使用了另一个 `user_id`。 - 接口里传了额外过滤条件。 - 知识库没有授权给当前项目。 如果接口返回具体 `code`,可以查看 [错误码](/cn/api_docs/help/error_codes)。 --- # 配额和限制 (/cn/memos_cloud/support/limit) ## 1. 额度说明 ![image.png](https://cdn.memtensor.com.cn/img/1766481509513_5d4x8o_compressed.png) MemOS 云服务目前为所有开发者提供了从免费版到企业版的多种定价方案,满足不同规模团队的需求。目前,所有版本限时免费,欢迎前往[MemOS 官网-价格](https://memos.openmem.net/cn/pricing),申请符合你需求的版本。 立即行动,享受 MemOS 云服务带来的无限可能,助力你的项目快速成长! > **Note**: 注意 > > - 使用额度由每个开发者账号下的所有项目共同累计。 > - 请求失败(鉴权失败、参数错误、超额限制等)**不消耗额度**,系统直接返回对应错误码。 > - 如有更高阶或特殊需求,请联系项目组沟通。 ## 2. 资源限制 为保证服务稳定与安全,MemOS 云服务对核心资源有如下限制,按照账号维度计算。 ### 接口调用限制 | **接口名称** | **单次输入上限** | **单次输出上限** | | --- | --- | --- | | addMessage | 40,000 token | - | | searchMemory | 40,000 token | 召回总上限:25 条(含事实、偏好、属性、事件、工具、技能) | ### 请求频率限制(QPS) | 限制项 | 说明 | | --- | --- | | 建议最大 QPS | ≤ 40(每秒最多 40 次请求);非严格限制,但高并发可能受平台处理能力影响 | | 每分钟输入 token 总量 | 不超过 400,000 token,超出后请求将被限流 | ### 群聊场景 | 限制项 | 说明 | | --- | --- | | `user_id` / `agent_id` 列表上限 | 单次最多传入 20 个 ID | | QPS 折算 | 按参与人数折算;例如传入 20 个 ID 时 ×20 折算,即每秒最多 2 次请求 | ### 知识库文档上传 | 限制项 | 说明 | | --- | --- | | 支持的文档类型 | PDF、DOCX、DOC、TXT、JSON、MD、XML | | 单文件大小上限 | 100 MB、500 页 | | 单次上传文件数量 | 不超过 20 个 | > **Note**: 知识库还支持上传 Skill 文件,详细限制见 [知识库](/cn/memos_cloud/features/knowledge_base)。 ## 3. 用量监控 您可通过**API 控制台**查看各接口的剩余额度,并支持按项目、接口密钥和日期进行筛选,方便跟踪和管理调用情况。 ![image.png](https://cdn.memtensor.com.cn/img/1766632358212_mxan3a_compressed.png) --- # Search memories **POST** `/product/search` Search memories for a specific user. - operationId: `search_memories_product_search_post` ## Request Body ## Response Successful Response URL: /cn/api-reference/search-memories --- # Add memories **POST** `/product/add` Add memories for a specific user. - operationId: `add_memories_product_add_post` ## Request Body ## Response Successful Response URL: /cn/api-reference/add-memories --- # Get all memories for user **POST** `/product/get_all` Get all memories or subgraph for a specific user. If search_query is provided, returns a subgraph based on the query. Otherwise, returns all memories of the specified type. - operationId: `get_all_memories_product_get_all_post` ## Request Body ## Response Successful Response URL: /cn/api-reference/get-all-memories-for-user --- # Get memories for user **POST** `/product/get_memory` Get memories for user with pagination support. - operationId: `get_memories_product_get_memory_post` ## Request Body | Parameter | Type | Required | Description | |---|---|---|---| | `user_id` | string | No | 获取的记忆所关联用户的唯一标识符。 | | `agent_id` | string | No | 获取的记忆所关联 Agent 的唯一标识符。仅开启「为 Agent 创建独立记忆」时可用,与 user_id 二选一。 | | `page` | integer | No | 分页页码,用于在返回结果较多时进行分页控制。 | | `size` | integer | No | 指定每一类记忆在当前页返回的条目数量,最大值为50。 | | `filter` | object | No | 记忆过滤的条件,用于在获取记忆前精确限定记忆范围。可用字段包括:"agent_id", "app_id", "create_time", "update_time"以及"info"中的字段。支持逻辑运算符(and,or)和比较运算符(gte、lte、gt、lt)。对于"info"字段,支持过滤传入的"business_type", "biz_id", "scene"和其他自定义字段。 | | `include_memory_view` | array | No | 允许获取的记忆种类,不传时默认获取所有种类的记忆。全部种类及取值说明见 记忆种类。 | ## Response Successful Response | Parameter | Type | Required | Description | |---|---|---|---| | `code` | number | Yes | 接口状态码,更多内容可查阅错误码列表了解详情。 | | `data` | object | No | | | `message` | string | Yes | 接口提示信息。 | #### `data` object | Parameter | Type | Required | Description | |---|---|---|---| | `memory_detail_list` | array | No | 返回的事实记忆片段详情列表。 | | `preference_detail_list` | array | No | 返回的偏好记忆片段详情列表。 | | `profile_detail_list` | array | No | 返回的属性记忆片段详情列表。 | | `event_detail_list` | array | No | 返回的事件记忆片段详情列表。 | | `tool_memory_detail_list` | array | No | 返回的工具记忆片段详情列表。 | | `skill_detail_list` | array | No | 返回的技能 Skill 详情列表。 | | `total` | integer | No | 获取的各类记忆总数中的最大值,用于判断是否存在下一页。 | | `size` | integer | No | 每一类记忆在当前页返回的条目数量。 | | `current` | integer | No | 当前获取的记忆所在页数。 | | `pages` | integer | No | 获取记忆的总页数。 | #### `memory_detail_list` object | Parameter | Type | Required | Description | |---|---|---|---| | `id` | string | No | 事实记忆的唯一标识符。 | | `memory_key` | string | No | 事实记忆的标题或关键词。 | | `memory_value` | string | No | 事实记忆的具体内容。 | | `memory_type` | string (enum: WorkingMemory, LongTermMemory, UserMemory) | No | 事实记忆类型。 | | `create_time` | string | No | 事实记忆创建时间,ISO 8601 格式。 | | `conversation_id` | string | No | 与该事实记忆关联的会话唯一标识符。 | | `status` | string (enum: activated) | No | 事实记忆状态,当前仅返回 activated。 | | `confidence` | number | No | 事实记忆的置信度分数,范围 0~1。 | | `tags` | array | No | 与事实记忆相关的标签列表。 | | `update_time` | string | No | 事实记忆最后一次更新时间,ISO 8601 格式。 | | `relativity` | number | No | 事实记忆的相关性分数,范围 0~1。 | | `sources` | array | No | 事实记忆的来源消息列表。 | | `info` | object | No | 添加消息时自定义的元信息字段。 | #### `preference_detail_list` object | Parameter | Type | Required | Description | |---|---|---|---| | `id` | string | No | 偏好记忆的唯一标识符。 | | `preference_type` | string (enum: explicit_preference, implicit_preference) | No | 偏好记忆类型。 | | `preference` | string | No | 偏好记忆的具体内容。 | | `reasoning` | string | No | 偏好记忆提取的原因。 | | `create_time` | string | No | 偏好记忆创建时间,ISO 8601 格式。 | | `conversation_id` | string | No | 与该偏好记忆关联的会话唯一标识符。 | | `status` | string (enum: activated) | No | 偏好记忆状态,当前仅返回 activated。 | | `update_time` | string | No | 偏好记忆最后一次更新时间,ISO 8601 格式。 | | `relativity` | number | No | 偏好记忆的相关性分数,范围 0~1。 | | `sources` | array | No | 偏好记忆的来源消息列表。 | | `info` | object | No | 添加消息时自定义的元信息字段。 | #### `profile_detail_list` object | Parameter | Type | Required | Description | |---|---|---|---| | `id` | string | No | 属性记忆实例的唯一标识符。 | | `project_id` | string | No | 项目 ID。 | | `profile_template_id` | string | No | 属性模板 ID。 | | `properties` | object | No | 属性记忆的结构化字段树。 | | `status` | string (enum: activated) | No | 属性记忆状态,当前仅返回 activated。 | | `created_at` | string | No | 属性记忆创建时间,ISO 8601 格式。 | | `updated_at` | string | No | 属性记忆最后一次更新时间,ISO 8601 格式。 | #### `event_detail_list` object | Parameter | Type | Required | Description | |---|---|---|---| | `id` | string | No | 事件记忆的唯一标识符。 | | `event_key` | string | No | 事件记忆的标题或关键词。 | | `event_value` | string | No | 事件记忆的具体内容。 | | `event_type` | string | No | 事件记忆类型,通常为 EventMemory。 | | `create_time` | string | No | 事件记忆创建时间,ISO 8601 格式。 | | `conversation_id` | string | No | 与该事件记忆关联的会话唯一标识符。 | | `status` | string (enum: activated) | No | 事件记忆状态,当前仅返回 activated。 | | `update_time` | string | No | 事件记忆最后一次更新时间,ISO 8601 格式。 | | `info` | object | No | 事件记忆的扩展信息。 | | `sources` | array | No | 事件记忆的来源消息列表。 | | `event_time` | array | No | 事件时间列表。 | | `event_location` | array | No | 事件地点列表。 | | `event_roles` | array | No | 事件参与者列表。 | #### `tool_memory_detail_list` object | Parameter | Type | Required | Description | |---|---|---|---| | `id` | string | No | 工具记忆片段的唯一标识符。 | | `tool_type` | string (enum: ToolTrajectoryMemory, ToolSchema) | No | 工具记忆类型。ToolTrajectoryMemory 表示工具轨迹记忆;ToolSchema 表示工具信息记忆。 | | `tool_value` | string | No | 工具记忆的具体内容。 | | `tool_used_status` | array | No | 工具轨迹记忆列表,每条记录包含使用的工具及经验信息。 | | `create_time` | string | No | 工具记忆创建时间,ISO 8601 格式。 | | `conversation_id` | string | No | 与该工具记忆关联的会话唯一标识符。 | | `status` | string (enum: activated) | No | 工具记忆状态,当前为 activated。 | | `update_time` | string | No | 工具记忆最后一次更新时间,ISO 8601 格式。 | | `relativity` | number | No | 工具记忆的相关性分数,范围 0~1。 | | `source` | string | No | 工具记忆的来源信息。 | | `experience` | string | No | 整个轨迹的程序性经验,作为指导任务完成的总体经验。 | | `info` | object | No | 添加消息时自定义的元信息字段。 | #### `skill_detail_list` object | Parameter | Type | Required | Description | |---|---|---|---| | `id` | string | No | 技能 Skill 的唯一标识符,系统内部用于区分不同的记忆条目。 | | `skill_value` | object | No | 技能 Skill 的结构化内容,可直接转为字符串后注入 Agent 的 prompt。 | | `skill_url` | string | No | 技能 Skill 的下载链接。Markdown Skill 可下载为 SKILL.md;ZIP 技能包可下载后获取 SKILL.md、脚本、参考资料等附件。 | | `skill_type` | string | No | 技能 Skill 的类型。 | | `create_time` | string | No | 技能 Skill 内容创建的时间,通常为 ISO 8601 格式。 | | `conversation_id` | string | No | 与该技能 Skill 关联的会话的唯一标识符。 | | `status` | string (enum: activated) | No | 技能 Skill 的状态,当前所有检索到的技能 Skill 都是 activated。activated:激活状态,当前可检索和使用的技能 Skill 。 | | `confidence` | number | No | 技能 Skill 的置信度分数,范围 0~1,数值越接近 1 表示该技能 Skill 越准确可靠。 置信度分数会随着模型对该技能 Skill 的推理次数增加而逐渐衰减,用于反映技能 Skill 随着时间或使用频率可能产生的不确定性。 | | `tags` | array | No | 与技能 Skill 相关的标签列表,用于分类、检索或主题标记。数组中的每个元素都是string,例如 ["人物", "事件", "工作"]。 | | `update_time` | string | No | 技能 Skill 最后一次被修改或更新的时间,通常为 ISO 8601 格式 | | `relativity` | string | No | 查询内容与该技能 Skill 的相关性分数,范围 0~1,数值越接近 1 表示越相关。 | ### Response Example ```json { "data": { "memory_detail_list": [ { "memory_type": "WorkingMemory", "status": "activated" } ], "preference_detail_list": [ { "preference_type": "explicit_preference", "status": "activated" } ], "profile_detail_list": [ { "status": "activated" } ], "event_detail_list": [ { "status": "activated" } ], "tool_memory_detail_list": [ { "tool_type": "ToolTrajectoryMemory", "status": "activated" } ], "skill_detail_list": [ { "status": "activated" } ] } } ``` URL: /cn/api-reference/get-memories-for-user --- # Get memory by id **GET** `/product/get_memory/{memory_id}` Get a specific memory by its ID. - operationId: `get_memory_by_id_product_get_memory__memory_id__get` ## Response Successful Response | Parameter | Type | Required | Description | |---|---|---|---| | `code` | number | Yes | 接口状态码,更多内容可查阅错误码列表了解详情。 | | `data` | object | No | | | `message` | string | Yes | 接口提示信息。 | #### `data` object | Parameter | Type | Required | Description | |---|---|---|---| | `memory_detail_list` | array | No | 返回的事实记忆片段详情列表。 | | `preference_detail_list` | array | No | 返回的偏好记忆片段详情列表。 | | `profile_detail_list` | array | No | 返回的属性记忆片段详情列表。 | | `event_detail_list` | array | No | 返回的事件记忆片段详情列表。 | | `tool_memory_detail_list` | array | No | 返回的工具记忆片段详情列表。 | | `skill_detail_list` | array | No | 返回的技能 Skill 详情列表。 | | `total` | integer | No | 获取的各类记忆总数中的最大值,用于判断是否存在下一页。 | | `size` | integer | No | 每一类记忆在当前页返回的条目数量。 | | `current` | integer | No | 当前获取的记忆所在页数。 | | `pages` | integer | No | 获取记忆的总页数。 | #### `memory_detail_list` object | Parameter | Type | Required | Description | |---|---|---|---| | `id` | string | No | 事实记忆的唯一标识符。 | | `memory_key` | string | No | 事实记忆的标题或关键词。 | | `memory_value` | string | No | 事实记忆的具体内容。 | | `memory_type` | string (enum: WorkingMemory, LongTermMemory, UserMemory) | No | 事实记忆类型。 | | `create_time` | string | No | 事实记忆创建时间,ISO 8601 格式。 | | `conversation_id` | string | No | 与该事实记忆关联的会话唯一标识符。 | | `status` | string (enum: activated) | No | 事实记忆状态,当前仅返回 activated。 | | `confidence` | number | No | 事实记忆的置信度分数,范围 0~1。 | | `tags` | array | No | 与事实记忆相关的标签列表。 | | `update_time` | string | No | 事实记忆最后一次更新时间,ISO 8601 格式。 | | `relativity` | number | No | 事实记忆的相关性分数,范围 0~1。 | | `sources` | array | No | 事实记忆的来源消息列表。 | | `info` | object | No | 添加消息时自定义的元信息字段。 | #### `preference_detail_list` object | Parameter | Type | Required | Description | |---|---|---|---| | `id` | string | No | 偏好记忆的唯一标识符。 | | `preference_type` | string (enum: explicit_preference, implicit_preference) | No | 偏好记忆类型。 | | `preference` | string | No | 偏好记忆的具体内容。 | | `reasoning` | string | No | 偏好记忆提取的原因。 | | `create_time` | string | No | 偏好记忆创建时间,ISO 8601 格式。 | | `conversation_id` | string | No | 与该偏好记忆关联的会话唯一标识符。 | | `status` | string (enum: activated) | No | 偏好记忆状态,当前仅返回 activated。 | | `update_time` | string | No | 偏好记忆最后一次更新时间,ISO 8601 格式。 | | `relativity` | number | No | 偏好记忆的相关性分数,范围 0~1。 | | `sources` | array | No | 偏好记忆的来源消息列表。 | | `info` | object | No | 添加消息时自定义的元信息字段。 | #### `profile_detail_list` object | Parameter | Type | Required | Description | |---|---|---|---| | `id` | string | No | 属性记忆实例的唯一标识符。 | | `project_id` | string | No | 项目 ID。 | | `profile_template_id` | string | No | 属性模板 ID。 | | `properties` | object | No | 属性记忆的结构化字段树。 | | `status` | string (enum: activated) | No | 属性记忆状态,当前仅返回 activated。 | | `created_at` | string | No | 属性记忆创建时间,ISO 8601 格式。 | | `updated_at` | string | No | 属性记忆最后一次更新时间,ISO 8601 格式。 | #### `event_detail_list` object | Parameter | Type | Required | Description | |---|---|---|---| | `id` | string | No | 事件记忆的唯一标识符。 | | `event_key` | string | No | 事件记忆的标题或关键词。 | | `event_value` | string | No | 事件记忆的具体内容。 | | `event_type` | string | No | 事件记忆类型,通常为 EventMemory。 | | `create_time` | string | No | 事件记忆创建时间,ISO 8601 格式。 | | `conversation_id` | string | No | 与该事件记忆关联的会话唯一标识符。 | | `status` | string (enum: activated) | No | 事件记忆状态,当前仅返回 activated。 | | `update_time` | string | No | 事件记忆最后一次更新时间,ISO 8601 格式。 | | `info` | object | No | 事件记忆的扩展信息。 | | `sources` | array | No | 事件记忆的来源消息列表。 | | `event_time` | array | No | 事件时间列表。 | | `event_location` | array | No | 事件地点列表。 | | `event_roles` | array | No | 事件参与者列表。 | #### `tool_memory_detail_list` object | Parameter | Type | Required | Description | |---|---|---|---| | `id` | string | No | 工具记忆片段的唯一标识符。 | | `tool_type` | string (enum: ToolTrajectoryMemory, ToolSchema) | No | 工具记忆类型。ToolTrajectoryMemory 表示工具轨迹记忆;ToolSchema 表示工具信息记忆。 | | `tool_value` | string | No | 工具记忆的具体内容。 | | `tool_used_status` | array | No | 工具轨迹记忆列表,每条记录包含使用的工具及经验信息。 | | `create_time` | string | No | 工具记忆创建时间,ISO 8601 格式。 | | `conversation_id` | string | No | 与该工具记忆关联的会话唯一标识符。 | | `status` | string (enum: activated) | No | 工具记忆状态,当前为 activated。 | | `update_time` | string | No | 工具记忆最后一次更新时间,ISO 8601 格式。 | | `relativity` | number | No | 工具记忆的相关性分数,范围 0~1。 | | `source` | string | No | 工具记忆的来源信息。 | | `experience` | string | No | 整个轨迹的程序性经验,作为指导任务完成的总体经验。 | | `info` | object | No | 添加消息时自定义的元信息字段。 | #### `skill_detail_list` object | Parameter | Type | Required | Description | |---|---|---|---| | `id` | string | No | 技能 Skill 的唯一标识符,系统内部用于区分不同的记忆条目。 | | `skill_value` | object | No | 技能 Skill 的结构化内容,可直接转为字符串后注入 Agent 的 prompt。 | | `skill_url` | string | No | 技能 Skill 的下载链接。Markdown Skill 可下载为 SKILL.md;ZIP 技能包可下载后获取 SKILL.md、脚本、参考资料等附件。 | | `skill_type` | string | No | 技能 Skill 的类型。 | | `create_time` | string | No | 技能 Skill 内容创建的时间,通常为 ISO 8601 格式。 | | `conversation_id` | string | No | 与该技能 Skill 关联的会话的唯一标识符。 | | `status` | string (enum: activated) | No | 技能 Skill 的状态,当前所有检索到的技能 Skill 都是 activated。activated:激活状态,当前可检索和使用的技能 Skill 。 | | `confidence` | number | No | 技能 Skill 的置信度分数,范围 0~1,数值越接近 1 表示该技能 Skill 越准确可靠。 置信度分数会随着模型对该技能 Skill 的推理次数增加而逐渐衰减,用于反映技能 Skill 随着时间或使用频率可能产生的不确定性。 | | `tags` | array | No | 与技能 Skill 相关的标签列表,用于分类、检索或主题标记。数组中的每个元素都是string,例如 ["人物", "事件", "工作"]。 | | `update_time` | string | No | 技能 Skill 最后一次被修改或更新的时间,通常为 ISO 8601 格式 | | `relativity` | string | No | 查询内容与该技能 Skill 的相关性分数,范围 0~1,数值越接近 1 表示越相关。 | ### Response Example ```json { "data": { "memory_detail_list": [ { "memory_type": "WorkingMemory", "status": "activated" } ], "preference_detail_list": [ { "preference_type": "explicit_preference", "status": "activated" } ], "profile_detail_list": [ { "status": "activated" } ], "event_detail_list": [ { "status": "activated" } ], "tool_memory_detail_list": [ { "tool_type": "ToolTrajectoryMemory", "status": "activated" } ], "skill_detail_list": [ { "status": "activated" } ] } } ``` URL: /cn/api-reference/get-memory-by-id --- # Delete memories for user **POST** `/product/delete_memory` Delete memories for a specific user. - operationId: `delete_memories_product_delete_memory_post` ## Request Body | Parameter | Type | Required | Description | |---|---|---|---| | `memory_ids` | array | No | 需要删除的记忆 ID 列表。 | | `user_id` | string | No | 删除该用户在当前项目下的全部记忆。与 memory_ids、agent_id 互斥。 | | `agent_id` | string | No | 删除该 Agent 在当前项目下的全部记忆。仅开启「为 Agent 创建独立记忆」时可用。与 memory_ids、user_id 互斥。 | ## Response Successful Response | Parameter | Type | Required | Description | |---|---|---|---| | `code` | integer | No | 接口状态码,更多内容可查阅错误码列表了解详情。 | | `data` | object | No | 返回删除信息 | | `message` | string | No | 删除提示信息 | #### `data` object | Parameter | Type | Required | Description | |---|---|---|---| | `success` | boolean | No | 是否删除成功。true 表示成功,false 表示失败。 | ### Response Example ```json { "data": { "success": true } } ``` URL: /cn/api-reference/delete-memories-for-user --- # Chat with MemOS (Complete Response) **POST** `/product/chat/complete` Chat with MemOS for a specific user. Returns complete response (non-streaming). - operationId: `chat_complete_product_chat_complete_post` ## Request Body ## Response Successful Response URL: /cn/api-reference/chat-with-memos-(complete-response) --- # Chat with MemOS **POST** `/product/chat/stream` Chat with MemOS for a specific user. Returns SSE stream. - operationId: `chat_stream_product_chat_stream_post` ## Request Body | Parameter | Type | Required | Description | |---|---|---|---| | `user_id` | string | Yes | 对话内容所关联的用户唯一标识符。 | | `conversation_id` | string | Yes | 对话内容所在会话的唯一标识符,传入可明确当前会话,本会话的记忆应当比其他历史会话的权重高;不传可跨会话检索相关记忆,得到相关性更高的模型回答。 | | `query` | string | Yes | 用户输入的对话内容。 | | `filter` | object | No | 记忆过滤的条件,用于在检索记忆前精确限定记忆范围。可用字段包括:"agent_id", "app_id", "create_time", "update_time"与"info"中的字段。支持逻辑运算符(and,or)和比较运算符(gte、lte、gt、lt)。对于"info"字段,支持过滤传入的"business_type", "biz_id", "scene"和其他自定义字段。 | | `knowledgebase_ids` | array | No | 该字段用于限制当次搜索可访问的知识库范围,默认为空(即不检索任何知识库)。传入具体知识库 ID,则可检索指定知识库中的普通文档和已上传的 Skill;传入 all,则可检索该项目下所有关联知识库。 | | `memory_limit_number` | integer | No | 召回的事实记忆条数上限,在满足相关性阈值(relativity)的前提下最多返回该数量的记忆,不保证返回固定条数。默认值 9,最大值 25。 | | `include_preference` | boolean | No | 是否要召回偏好记忆,开启后系统会根据查询内容智能召回与用户偏好相关的记忆。默认 =true | | `preference_limit_number` | integer | No | 召回的偏好记忆条数上限,在满足相关性阈值(relativity)的前提下最多返回该数量的记忆,不保证返回固定条数。默认值 9,最大值 25。 | | `relativity` | number | No | 召回记忆的相关性阈值(0~1)。用于过滤低相关记忆,并与限定返回的事实、偏好记忆最大条数,共同约束最终返回结果。不传时使用系统默认阈值,取值为0时表示不进行相关性过滤。 | | `model_name` | string (enum: qwen3-32b, deepseek-r1, qwen2.5-72b-instruct) | No | 指定具体对话模型。 | | `system_prompt` | string | No | 自定义系统指令。 | | `stream` | boolean | No | 是否启用流式返回。 | | `max_tokens` | integer | No | 表示最大生成 token 数。 | | `temperature` | number | No | 控制生成随机性。取值范围:0 ≤ x ≤ 2 | | `top_p` | number | No | Nucleus 采样参数。取值范围:0 ≤ x ≤ 1 | | `add_message_on_answer` | boolean | No | 是否自动将用户与助手的会话内容写入记忆。启用后,开发者无需再调用add/message接口添加消息为记忆。 | | `app_id` | string | No | 对话内容所关联的应用唯一标识符。 | | `agent_id` | string | No | 对话内容所关联的Agent唯一标识符。 | | `tags` | array | No | 自定义标签列表,用于标记对话内容的主题或分类。 | | `info` | object | No | 自定义元信息字段,能够存储任意与对话内容相关的结构化数据,例如位置、来源、版本等,主要用于在检索时精确过滤或追踪来源。 | | `allow_public` | boolean | No | 是否允许加入公共记忆。 | | `allow_knowledgebase_ids` | array | No | 添加的消息产生的记忆允许被写入的知识库列表。 | ## Response Successful Response URL: /cn/api-reference/chat-with-memos --- # Chat with MemOS playground **POST** `/product/chat/stream/playground` Chat with MemOS for a specific user in playground. Returns SSE stream. - operationId: `chat_stream_playground_product_chat_stream_playground_post` ## Request Body ## Response Successful Response URL: /cn/api-reference/chat-with-memos-playground --- # Get suggestion queries **POST** `/product/suggestions` Get suggestion queries for a specific user with language preference. - operationId: `get_suggestion_queries_product_suggestions_post` ## Request Body ## Response Successful Response URL: /cn/api-reference/get-suggestion-queries --- # Feedback memories **POST** `/product/feedback` Feedback memories for a specific user. - operationId: `feedback_memories_product_feedback_post` ## Request Body ## Response Successful Response URL: /cn/api-reference/feedback-memories --- # Get detailed scheduler status **GET** `/product/scheduler/allstatus` Get detailed scheduler status including running tasks and queue metrics. - operationId: `scheduler_allstatus_product_scheduler_allstatus_get` ## Response Successful Response URL: /cn/api-reference/get-detailed-scheduler-status --- # Get scheduler running status **GET** `/product/scheduler/status` Get scheduler running status. - operationId: `scheduler_status_product_scheduler_status_get` ## Response Successful Response URL: /cn/api-reference/get-scheduler-running-status --- # Get scheduler task queue status **GET** `/product/scheduler/task_queue_status` Get scheduler task queue backlog/pending status for a user. - operationId: `scheduler_task_queue_status_product_scheduler_task_queue_status_get` ## Response Successful Response URL: /cn/api-reference/get-scheduler-task-queue-status --- # Wait until scheduler is idle for a specific user **POST** `/product/scheduler/wait` Wait until scheduler is idle for a specific user. - operationId: `scheduler_wait_product_scheduler_wait_post` ## Response Successful Response URL: /cn/api-reference/wait-until-scheduler-is-idle-for-a-specific-user --- # Stream scheduler progress for a user **GET** `/product/scheduler/wait/stream` Stream scheduler progress via Server-Sent Events (SSE). - operationId: `scheduler_wait_stream_product_scheduler_wait_stream_get` ## Response Successful Response URL: /cn/api-reference/stream-scheduler-progress-for-a-user --- # Get user names by memory ids **POST** `/product/get_user_names_by_memory_ids` Get user names by memory ids. - operationId: `get_user_names_by_memory_ids_product_get_user_names_by_memory_ids_post` ## Request Body ## Response Successful Response URL: /cn/api-reference/get-user-names-by-memory-ids --- # Check if mem cube id exists **POST** `/product/exist_mem_cube_id` Check if mem cube id exists. - operationId: `exist_mem_cube_id_product_exist_mem_cube_id_post` ## Request Body ## Response Successful Response URL: /cn/api-reference/check-if-mem-cube-id-exists --- # 安装指南 (/cn/open_source/getting_started/installation) - [通过Docker安装](/cn/open_source/getting_started/installation#通过docker安装): 适合快速部署:一键启动服务与依赖组件。 - [从源码安装](/cn/open_source/getting_started/installation#从源码安装): 适合二次开发与贡献:可编辑安装、可跑测试、可本地调试。 - [通过pip安装](/cn/open_source/getting_started/installation#通过pip安装): 最简单的安装方式:快速开始使用 MemOS。 ## 通过Docker安装 ```bash git clone https://github.com/MemTensor/MemOS.git cd MemOS ``` #### 创建 .env 配置文件 > **Note**: **请注意** > .env 文件配置需要放在MemOS 项目根目录下 #### 1. 新建 .env ```bash cd MemOS touch .env ``` #### 2. .env 内容 .env 快速配置如下 ```bash # OpenAI API 密钥 (需自定义配置) OPENAI_API_KEY=sk-xxx # OpenAI API 基础 URL OPENAI_API_BASE=http://xxx:3000/v1 # 默认模型名称 MOS_CHAT_MODEL=qwen3-max # Memory Reader LLM 模型 MEMRADER_MODEL=qwen3-max # Memory Reader API 密钥 MEMRADER_API_KEY=sk-xxx # Memory Reader API 基础 URL MEMRADER_API_BASE=http://xxx:3000/v1 # Embedder 模型名称 MOS_EMBEDDER_MODEL=text-embedding-v4 # 配置embedding backend 两种选择 ollama | universal_api MOS_EMBEDDER_BACKEND=universal_api # Embedder API 基础 URL MOS_EMBEDDER_API_BASE=http://xxx:8081/v1 # Embedder API 密钥 MOS_EMBEDDER_API_KEY=xxx # Embedding 向量维度 EMBEDDING_DIMENSION=1024 # Reranker 后端 (http_bge | etc.) MOS_RERANKER_BACKEND=cosine_local # Neo4j 连接 URI # 可选值: neo4j-community | neo4j | nebular | polardb NEO4J_BACKEND=neo4j-community # 当 backend=neo4j* 时必须 NEO4J_URI=bolt://localhost:7687 NEO4J_USER=neo4j NEO4J_PASSWORD=12345678 NEO4J_DB_NAME=neo4j MOS_NEO4J_SHARED_DB=false # 是否使用 redis 的调度器 DEFAULT_USE_REDIS_QUEUE=false # 启用聊天 API ENABLE_CHAT_API=true # 聊天模型列表 可以通过百炼申请. 模型可自选 CHAT_MODEL_LIST=[{"backend": "qwen", "api_base": "https://xxx/v1", "api_key": "sk-xxx", "model_name_or_path": "qwen3-max", "extra_body": {"enable_thinking": true} ,"support_models": ["qwen3-max"]}] ``` #### .env 以百炼为示例配置如下 ```bash # 可通过百炼平台申请 # https://bailian.console.aliyun.com/?spm=a2c4g.11186623.0.0.2f2165b08fRk4l&tab=api#/api # 申请成功后,获取API_KEY和BASE_URL,示例配置如下 # OpenAI API 密钥 (用百炼的API_KEY) OPENAI_API_KEY=you_bailian_api_key # OpenAI API 基础 URL OPENAI_API_BASE=https://dashscope.aliyuncs.com/compatible-mode/v1 # 默认模型名称 MOS_CHAT_MODEL=qwen3-max # Memory Reader LLM 模型 MEMRADER_MODEL=qwen3-max # Memory Reader API 密钥 (用百炼的API_KEY) MEMRADER_API_KEY=you_bailian_api_key # Memory Reader API 基础 URL MEMRADER_API_BASE=https://dashscope.aliyuncs.com/compatible-mode/v1 # Embedder模型名称可以参考下面链接 # https://bailian.console.aliyun.com/?spm=a2c4g.11186623.0.0.2f2165b08fRk4l&tab=api#/api/?type=model&url=2846066 MOS_EMBEDDER_MODEL=text-embedding-v4 # 配置embedding backend 两种选择 ollama | universal_api MOS_EMBEDDER_BACKEND=universal_api # Embedder API 基础 URL MOS_EMBEDDER_API_BASE=https://dashscope.aliyuncs.com/compatible-mode/v1 # Embedder API 密钥 (用百炼的API_KEY) MOS_EMBEDDER_API_KEY=you_bailian_api_key # Embedding 向量维度 EMBEDDING_DIMENSION=1024 # Reranker 后端 (http_bge | etc.) MOS_RERANKER_BACKEND=cosine_local # Neo4j 连接 URI # 可选值: neo4j-community | neo4j | nebular | polardb NEO4J_BACKEND=neo4j-community # 当 backend=neo4j* 时必须 NEO4J_URI=bolt://localhost:7687 NEO4J_USER=neo4j NEO4J_PASSWORD=12345678 NEO4J_DB_NAME=neo4j MOS_NEO4J_SHARED_DB=false # 是否使用 redis 的调度器 DEFAULT_USE_REDIS_QUEUE=false # 启用聊天 API ENABLE_CHAT_API=true CHAT_MODEL_LIST=[{"backend": "qwen", "api_base": "https://dashscope.aliyuncs.com/compatible-mode/v1", "api_key": "you_bailian_api_key", "model_name_or_path": "qwen3-max-preview", "extra_body": {"enable_thinking": true} ,"support_models": ["qwen3-max-preview"]}] ``` ![MemOS bailian](https://cdn.memtensor.com.cn/img/get_key_url_by_bailian_compressed.png)
百炼申请 API_KEY和 BASE_URL 示例 #### 配置Dockerfile文件 > **Note**: **请注意** > Dockerfile 文件在 docker 目录下 ```bash #进入docker目录下 cd docker ``` 包含快速模式和完整模式,可区分使用精简包(区分arm和x86)和全量包(区分arm和x86) ```bash ● 精简包:简化体量过大的 nvidia相关等依赖,对镜像实现轻量化,使本地部署更加轻量快速。 url: registry.cn-shanghai.aliyuncs.com/memtensor/memos-base:v1.0 url: registry.cn-shanghai.aliyuncs.com/memtensor/memos-base-arm:v1.0 ● 全量包:将 MemOS 全部依赖包打为镜像,可体验完整功能,通过配置 Dockerfile可直接构建启动。 url: registry.cn-shanghai.aliyuncs.com/memtensor/memos-full-base:v1.0.0 url: registry.cn-shanghai.aliyuncs.com/memtensor/memos-full-base-arm:v1.0.0 ``` ```bash # 当前示例使用精简包 url FROM registry.cn-shanghai.aliyuncs.com/memtensor/memos-base-arm:v1.0 WORKDIR /app ENV HF_ENDPOINT=https://hf-mirror.com ENV PYTHONPATH=/app/src COPY src/ ./src/ EXPOSE 8000 CMD ["uvicorn", "memos.api.server_api:app", "--host", "0.0.0.0", "--port", "8000", "--reload"] ``` #### 启动docker客户端 ```bash # 如果没有安装docker,请安装对应版本,下载地址如下: https://www.docker.com/ # 安装完成之后,可通过客户端启动docker,或者通过命令行启动docker # 通过命令行启动docker sudo systemctl start docker # 安装完成后,查看docker状态 docker ps # 查看docker镜像 (可不用) docker images ``` #### 构建并启动服务 : > **Note**: **请注意** > 构建命令同样在 docker 目录下 ```bash # 在docker目录下 docker compose up ``` ![MemOS buildComposeupSuccess](https://cdn.memtensor.com.cn/img/memos_build_composeup_success_compressed.png)
示例图片,端口按 docker 自定义的配置 #### 通过 [http://localhost:8000/docs](http://localhost:8000/docs) 访问 API。 ![MemOS Architecture](https://cdn.memtensor.com.cn/img/memos_run_server_success_compressed.png) #### ADD Memory ```bash curl --location --request POST 'http://127.0.0.1:8000/product/add' \ --header 'Content-Type: application/json' \ --data-raw '{ "messages": [{ "role": "user", "content": "我喜欢吃草莓" }], "user_id": "8736b16e-1d20-4163-980b-a5063c3facdc", "writable_cube_ids":["b32d0977-435d-4828-a86f-4f47f8b55bca"] }' # 响应 { "code": 200, "message": "Memory created successfully", "data": null } ``` #### Search Memory ```bash curl --location --request POST 'http://127.0.0.1:8000/product/search' \ --header 'Content-Type: application/json' \ --data-raw '{ "query": "我喜欢吃什么", "user_id": "8736b16e-1d20-4163-980b-a5063c3facdc", "readable_cube_ids": ["b32d0977-435d-4828-a86f-4f47f8b55bca"], "top_k":20 }' # 响应 { "code": 200, "message": "Search completed successfully", "data": { "text_mem": [ { "cube_id": "7231eda8-6c57-4f6e-97ce-98b699eebb98", "memories": [ { "id": "2f40be8f-736c-4a5f-aada-9489037769e0", "memory": "[user观点]用户喜欢草莓。", "metadata": { "user_id": "de8215e3-3beb-4afc-9b64-ae594d62f1ea", "session_id": "root_session", "status": "activated", "type": "fact", "key": "用户对草莓的喜好", "confidence": 0.99, "source": null, "tags": [ "喜好", "草莓" ], "visibility": null, "updated_at": "2025-09-18T08:23:44.625479000+00:00", "memory_type": "UserMemory", "sources": [], "embedding": [], "created_at": "2025-09-18T08:23:44.625511000+00:00", "usage": [ "{ "time": "2025-09-18T08:24:17.759748", "info": { "user_id": "de8215e3-3beb-4afc-9b64-ae594d62f1ea", "session_id": "root_session" } }" ], "background": "用户表达了对草莓的喜好,显示出他们在饮食偏好上的倾向。", "relativity": 0.6349761312470591, "vector_sync": "success", "ref_id": "[2f40be8f]", "id": "2f40be8f-736c-4a5f-aada-9489037769e0", "memory": "[user观点]用户喜欢草莓。" }, "ref_id": "[2f40be8f]" }, ... } } ], "act_mem": [], "para_mem": [] } } ``` ## 从源码安装 ```bash git clone https://github.com/MemTensor/MemOS.git cd MemOS ``` #### 创建 .env 配置文件 MemOS 的 server_api 依赖环境变量启动,因此需要在启动目录下创建 .env 文件。 1. 新建 .env ```bash cd MemOS touch .env ``` 2. .env 内容,快速配置请见 docker 安装下的[env 配置](/open_source/getting_started/installation#2.-.env-内容) .env详细配置请见[env配置](/open_source/getting_started/rest_api_server/#本地运行) > **Note**: **请注意** > .env 文件配置需要放在MemOS 项目根目录下 #### 安装依赖 ```bash # 执行安装命令 pip install -e . pip install --no-cache-dir -r ./docker/requirements.txt -i https://mirrors.aliyun.com/pypi/simple/ # 配置PYTHONPATH 当前项目文件的绝对目录下的 src export PYTHONPATH=/******/MemOS/src ``` #### 安装图数据库 Memos的记忆底层是通过图数据库进行存储的,在开源项目中,推荐使用Neo4j运行您的第一个项目。社区同时支持Neo4j企业版/社区版与PolarDB。 > **Note**: **PC开发者的最快选择:Neo4j Desktop** 如果您计划使用 Neo4j 作为图记忆,Neo4j Desktop可能是最方便的安装方式。 > 另外,您需要在 .env 文件中设置 **NEO4J_BACKEND=neo4j** #### 启动 MemOS Server。 ```bash # 项目根目录下 uvicorn memos.api.server_api:app --host 0.0.0.0 --port 8000 --workers 1 ``` #### ADD Memory ```bash curl --location --request POST 'http://127.0.0.1:8000/product/add' \ --header 'Content-Type: application/json' \ --data-raw '{ "messages": [{ "role": "user", "content": "我喜欢吃草莓" }], "user_id": "8736b16e-1d20-4163-980b-a5063c3facdc", "writable_cube_ids":["b32d0977-435d-4828-a86f-4f47f8b55bca"] }' # 响应 { "code": 200, "message": "Memory created successfully", "data": null } ``` #### Search Memory ```bash curl --location --request POST 'http://127.0.0.1:8000/product/search' \ --header 'Content-Type: application/json' \ --data-raw '{ "query": "我喜欢吃什么", "user_id": "8736b16e-1d20-4163-980b-a5063c3facdc", "readable_cube_ids": ["b32d0977-435d-4828-a86f-4f47f8b55bca"], "top_k":20 }' # 响应 { "code": 200, "message": "Search completed successfully", "data": { "text_mem": [ { "cube_id": "7231eda8-6c57-4f6e-97ce-98b699eebb98", "memories": [ { "id": "2f40be8f-736c-4a5f-aada-9489037769e0", "memory": "[user观点]用户喜欢草莓。", "metadata": { "user_id": "de8215e3-3beb-4afc-9b64-ae594d62f1ea", "session_id": "root_session", "status": "activated", "type": "fact", "key": "用户对草莓的喜好", "confidence": 0.99, "source": null, "tags": [ "喜好", "草莓" ], "visibility": null, "updated_at": "2025-09-18T08:23:44.625479000+00:00", "memory_type": "UserMemory", "sources": [], "embedding": [], "created_at": "2025-09-18T08:23:44.625511000+00:00", "usage": [ "{ "time": "2025-09-18T08:24:17.759748", "info": { "user_id": "de8215e3-3beb-4afc-9b64-ae594d62f1ea", "session_id": "root_session" } }" ], "background": "用户表达了对草莓的喜好,显示出他们在饮食偏好上的倾向。", "relativity": 0.6349761312470591, "vector_sync": "success", "ref_id": "[2f40be8f]", "id": "2f40be8f-736c-4a5f-aada-9489037769e0", "memory": "[user观点]用户喜欢草莓。" }, "ref_id": "[2f40be8f]" }, ... } } ], "act_mem": [], "para_mem": [] } } ``` ## 通过pip安装 安装 MemOS 最简单的方法是使用 pip。 #### 创建并激活 Conda 环境(推荐) 为避免依赖冲突,强烈建议使用独立的 Conda 环境。 ```bash conda create -n memos python=3.11 conda activate memos ``` #### 从 PyPI 安装 MemOS 安装 MemOS 及其全部可选组件: ```bash pip install -U "MemoryOS[all]" ``` #### 安装图数据库 Memos的记忆底层是通过图数据库进行存储的,在开源项目中,推荐使用Neo4j运行您的第一个项目。社区同时支持Neo4j企业版/社区版与PolarDB。 > **Note**: **PC开发者的最快选择:Neo4j Desktop** 如果您计划使用 Neo4j 作为图记忆,Neo4j Desktop可能是最方便的安装方式。 #### 创建 .env 配置文件 MemOS 的 server_api 依赖环境变量启动,因此需要在启动目录下创建 .env 文件。 1. 新建 .env ```bash touch .env ``` 2. 示例 .env 内容 .env详细配置请见[env配置](/open_source/getting_started/rest_api_server) 有关详细的开发环境设置、工作流程指南和贡献最佳实践,请参阅我们的 [贡献指南](/open_source/contribution/overview)。 #### 启动 MemOS Server MemOS 不会自动加载 .env 文件,请使用 python-dotenv 方式启动。 ```bash python -m dotenv run -- \ uvicorn memos.api.server_api:app \ --host 0.0.0.0 \ --port 8000 ``` 启动成功后,你将看到类似输出: ```text INFO: Uvicorn running on http://0.0.0.0:8000 INFO: Application startup complete. ``` #### 开始您的记忆操作吧 添加记忆(调用方式和从源码部署是一致哒,这次我们试试**同步**方式来添加记忆): ```text curl --location --request POST 'http://127.0.0.1:8000/product/add' \ --header 'Content-Type: application/json' \ --data-raw '{ "messages": [{ "role": "user", "content": "我喜欢吃草莓" }], "user_id": "8736b16e-1d20-4163-980b-a5063c3facdc", "writable_cube_ids":["b32d0977-435d-4828-a86f-4f47f8b55bca"], "async_mode": "sync", "mode": "fine" }' ``` > **Note**: **期望的输出** > ```json > { > "code": 200, > "message": "Memory added successfully", > "data": [ > { > "memory": "用户喜欢吃草莓。", > "memory_id": "d01a354e-e5f6-4e2a-bd89-c57ae", > "memory_type": "UserMemory", > "cube_id": "b32d0977-435d-4828-a86f-4f47f8b55bca" > } > ] > } > ``` 检索记忆(调用方式和从源码部署是一致哒): ```text curl --location --request POST 'http://127.0.0.1:8000/product/search' \ --header 'Content-Type: application/json' \ --data-raw '{ "query": "我喜欢吃什么", "user_id": "8736b16e-1d20-4163-980b-a5063c3facdc", "readable_cube_ids": ["b32d0977-435d-4828-a86f-4f47f8b55bca"], "top_k":20 }' ``` > **Note**: **期望的输出** > ```json > { > "code": 200, > "message": "Search completed successfully", > "data": { > "text_mem": [ > { > "cube_id": "b32d0977-435d-4828-a86f-4f47f8b55bca", > "memories": [ > { > "id": "f18cbe36-4cd9-456f-9b9f-6be89c35b2bf", > "memory": "用户喜欢吃草莓。", > "metadata": { > "user_id": "8736b16e-1d20-4163-980b-a5dc", > "session_id": "default_session", > "status": "activated", > "type": "fact", > "key": "草莓喜好", > "confidence": 0.99, > "source": null, > "tags": ["饮喜好", "草莓"], > "visibility": null, > "updated_at": "2025-12-26T20:35:08.178564000+00:00", > "info": null, > "covered_history": null, > "memory_type": "WorkingMemory", > "sources": [], > "embedding": [], > "created_at": "2025-12-26T20:35:08.177484000+00:00", > "usage": [], > "background": "用户表达了好,表明他们喜欢这种水果,可能在饮食选择中倾向于包含草莓。", > "file_ids": [], > "relativity": 0.0, > "ref_id": "[f18cbe36]" > }, > "ref_id": "[f18cbe36]" > } > ] > } > ], > "act_mem": [], > "para_mem": [], > "pref_mem": [ > { > "cube_id": "b32d0977-435d-4828-a86f-4f47f8b55bca", > "memories": [] > } > ], > "pref_note": "", > "tool_mem": [ > { > "cube_id": "b32d0977-435d-4828-a86f-4f47f8b55bca", > "memories": [] > } > ], > "pref_string": "" > } > } > ``` > **Note**: **下载示例代码** 恭喜您🎉已完成从pip安装MemOS,并跑通最小验证用例!您还可以基于以下命令下载示例代码,从而了解每个memos > 内部模块的调用方式: > ```bash > memos download_examples > ``` --- # 创建你的第一个记忆 (/cn/open_source/getting_started/your_first_memory) ## 学习目标 本教程将引导您完成 MemOS 的核心工作流,掌握以下能力: 1. **读 (Read)**:怎么用 `SimpleStructMemReader` 把乱七八糟的聊天记录变成结构化的记忆。 2. **存 (Add)**:怎么把提取出来的记忆存进 `TreeTextMemory`(图数据库)。 3. **搜 (Search)**:怎么用自然语言把存进去的记忆搜出来。 --- ## 核心组件简介 在开始实战前,先了解我们将要使用的两个关键组件: ### SimpleStructMemReader(结构化记忆提取器) 这是一个基于 LLM 的智能信息提取模块,能够: - 自动分析对话、文档等非结构化数据 - 识别用户偏好、事实陈述、行为模式等关键信息 - 输出标准化的结构化记忆单元 ### TreeTextMemory(树状文本记忆库) 这是一个基于图数据库的记忆管理系统,能够: - 以树状结构组织记忆,支持层级关系 - 建立记忆间的语义关联 - 支持高效的语义检索和图遍历 - 底层兼容 Neo4j 等图数据库 ## 动手试试 我们将通过一个具体案例演示:如何从用户关于"网球状态不佳"的对话中提取关键信息,建立可检索的记忆系统。 ### 1. 导入模块 ```python from memos import log from memos.configs.mem_reader import SimpleStructMemReaderConfig from memos.configs.memory import TreeTextMemoryConfig from memos.mem_reader.simple_struct import SimpleStructMemReader from memos.memories.textual.tree import TreeTextMemory logger = log.get_logger(__name__) ``` ### 2. 初始化核心组件 ```python # 1. 初始化 TreeTextMemory(记忆仓库) tree_config = TreeTextMemoryConfig.from_json_file( "examples/data/config/tree_config_shared_database.json" ) my_tree_textual_memory = TreeTextMemory(tree_config) # ⚠️ 注意:这里为了演示方便清空了旧数据。生产环境千万别这么干! my_tree_textual_memory.delete_all() # 2. 初始化 SimpleStructMemReader(信息提取器) reader_config = SimpleStructMemReaderConfig.from_json_file( "examples/data/config/simple_struct_reader_config.json" ) reader = SimpleStructMemReader(reader_config) ``` ### 3. 准备一段对话 以下是一段用户与 AI 的对话,用户表达了打网球时的状态问题: ```python scene_data = [ [ { "role": "user", "chat_time": "3 May 2025", "content": "This week I’ve been feeling a bit off, especially when playing tennis. My body just doesn’t feel right.", }, { "role": "assistant", "chat_time": "3 May 2025", "content": "It sounds like you've been having some physical discomfort lately...", }, # ... (中间省略了几轮吐槽) ... { "role": "user", "chat_time": "3 May 2025", "content": "I think it might be due to stress and lack of sleep recently...", }, ] ] ``` ### 4. 提取并存储 **SimpleStructMemReader** 会自动分析对话,提取出“用户最近压力大”、“睡眠不足”、“网球表现下降”等关键记忆点,然后存入数据库。 ```python # 1. 提取 (Extract) # Reader 会调用 LLM 分析对话,返回一个记忆列表 memory = reader.get_memory( scene_data, type="chat", info={"user_id": "1234", "session_id": "2222"} ) # 2. 存储 (Add) for m_list in memory: added_ids = my_tree_textual_memory.add(m_list) # 看看存进去了啥 for i, id in enumerate(added_ids): print(f"存入第 {i} 条记忆: " + my_tree_textual_memory.get(id).memory) # 等待后台整理完成(建立索引需要一点时间) my_tree_textual_memory.memory_manager.wait_reorganizer() ``` ### 5. 检索记忆 **基础搜索 (Search):** 就像用搜索引擎一样,直接问它。 ```python # 稍微等一下索引构建 import time time.sleep(2) init_time = time.time() # 试着搜一下关于“童年”的事(假设之前的对话里包含相关内容) # 或者搜 "Why is the user feeling bad?" 试试 results = my_tree_textual_memory.search( "Talk about the user's childhood story?", top_k=10, info={ "query": "Talk about the user's childhood story?", "user_id": "111", "session_id": "2234", }, ) for i, r in enumerate(results): print(f"搜到的第 {i} 条结果: {r.memory}") print(f"搜索耗时: {round(time.time() - init_time)}s") ``` **高级搜索 (Fine Mode):** 如果您想要更聪明一点的搜索结果(比如让 LLM 帮您总结一下搜到的内容),可以开启 `mode="fine"`。 ```python # 开启 Fine 模式 results_fine_search = my_tree_textual_memory.search( "Recent news in the first city you've mentioned.", top_k=10, mode="fine", # 关键在这里 info={ "query": "Recent news in NewYork", "user_id": "111", "session_id": "2234", "chat_history": [ {"role": "user", "content": "I want to know three beautiful cities"}, {"role": "assistant", "content": "New York, London, and Shanghai"}, ], }, ) for i, r in enumerate(results_fine_search): print(f"Fine Search 结果: {r.memory}") ``` ### 6. 进阶:多模态与工具 (Modality & Tools) MemOS 的能力不仅限于文本对话处理,还支持多模态输入和高级功能。 #### 1. 读取文档 (Documents) 可直接读取本地文档并转化为记忆: ```python # 构造文档数据 doc_data = [ { "type": "file", "file": { "filename": "tennis_rule.txt", "path": "./tennis_rule.txt", # 确保文件存在 # 或者直接提供 content: "file_data": "..." } } ] # 告诉 Reader 这是 "doc" 类型 doc_memories = reader.get_memory( doc_data, type="doc", info={"user_id": "1234", "session_id": "docs_import"} ) # 存入记忆 for m in doc_memories: my_tree_textual_memory.add(m) ``` #### 2. 工具调用 (Tools) 当 Agent 使用工具(如搜索、计算器)时,MemOS 能解析工具的输入输出,记录下“用户查询了天气”、“计算结果是50”等事实。 ```python tool_scene = [ [ {"role": "user", "content": "What's the weather in Beijing?"}, { "role": "assistant", "content": "", "tool_calls": [{"id": "call_1", "function": {"name": "get_weather", "arguments": "{'city': 'Beijing'}"}}] }, { "role": "tool", "tool_call_id": "call_1", "content": "Sunny, 25°C" } ] ] # Reader 会自动理解这是工具交互 tool_memories = reader.get_memory(tool_scene, type="chat", info={"user_id": "1234"}) ``` ### 7. 用户偏好 (Preferences) 除了事实性记忆(TreeTextMemory),MemOS 还有专门的 **PreferenceTextMemory** 来管理用户喜好(如“喜欢吃辣”、“讨厌下雨”)。它使用向量数据库(如 Milvus/Qdrant)来存储,方便快速检索用户的个性化设置。 ```python from memos.memories.textual.simple_preference import SimplePreferenceTextMemory # 注意:初始化需要配置 VectorDB, Embedder 等,这里仅作示意 # pref_memory = SimplePreferenceTextMemory(...) # 从对话中自动提取偏好 pref_memories = pref_memory.get_memory(chat_data, type="chat", info=...) # 存入偏好 pref_memory.add(pref_memories) # 搜索偏好 prefs = pref_memory.search("What is the user's UI preference?", top_k=1) print(prefs[0].memory) # 输出: "User prefers dark mode" ``` ### 8. 记忆反馈 (Feedback) 记忆不是一成不变的。用户可能会纠正 AI:“我不喜欢红色,我改主意了,我喜欢蓝色”。**MemFeedback** 模块就是用来处理这种“修正”的。 它可以: 1. **修改**错误的记忆。 2. **删除**过时的记忆。 3. **合并**冲突的记忆。 ```python from memos.mem_feedback.simple_feedback import SimpleMemFeedback # 初始化反馈模块 # feedback_module = SimpleMemFeedback(...) # 处理用户反馈 # 假设用户说:"Actually, I started playing tennis in 2020, not 2018." feedback_module.process_feedback({ "user_id": "1234", "feedback_content": "Actually, I started playing tennis in 2020, not 2018.", "chat_history": [...], # 提供上下文 "feedback_time": "Now" }) # 反馈模块会自动在后台更新 Graph 数据库中的节点和关系 ``` ### 总结 通过本教程,您已经掌握了 MemOS 的核心工作流: 1. **信息提取**: 使用 Reader 从各种数据源提取结构化信息 2. **记忆存储**: 使用 TreeTextMemory 管理事实记忆,PreferenceMemory 管理用户偏好 3. **智能检索**: 通过自然语言查询获取相关记忆 4. **持续优化**: 通过反馈机制保持记忆的准确性和时效性 下一步,您可以尝试运行 `examples/mem_os/simple_memos.py`,体验一个整合了所有这些功能的完整 Agent! ### 7. 收尾 测试完成后,建议进行以下清理操作: ```python # 关闭后台线程 my_tree_textual_memory.memory_manager.close() # 备份一下记忆 my_tree_textual_memory.dump("tmp/my_tree_textual_memory") # 删库跑路(仅限测试环境!) my_tree_textual_memory.drop() ``` --- ## 下一步? - **尝试自己的 LLM 后端:** 切换到 OpenAI、HuggingFace 或 Ollama。 - **探索 [TreeTextMemory](/open_source/modules/memories/tree_textual_memory):** 构建基于图的层级记忆。 - **添加 [Activation Memory](/open_source/modules/memories/kv_cache_memory):** 缓存键值状态,加速推理。 - **深入学习:** 查看 [API Reference](/api-reference/search-memories) 和 [Examples](/open_source/getting_started/examples) 了解高级工作流程。 接下来,您可以去看看更高级的玩法: - **[MemReader](/open_source/modules/mem_reader)**:其实它还能读图片和 PDF。 - **[MemFeedback](/open_source/modules/mem_feedback)**:如果有记忆记错了,怎么让 AI 自动修正? - **[MemCube](/open_source/modules/mem_cube)**:怎么把各种记忆能力打包在一起,做一个真正的全能大脑。 --- # 核心概念 (/cn/open_source/home/core_concepts) ## 概述 * [MOS (记忆操作系统)](#mos-记忆操作系统) * [MemCube](#memcube) * [记忆类型](#记忆类型) * [横切概念](#横切概念) ## MOS (记忆操作系统) **定义** MOS 是 MemOS 的编排调度层,负责协调多个 MemCube 与各类记忆操作。它作为中间件,将 LLM 与结构化、可解释的记忆系统连接起来,以支持复杂的推理与规划任务。 **使用场景** 当您需要在用户、会话或智能体之间建立一致、可审计且可追溯的记忆工作流时,应使用 MOS 进行统一调度。 ## MemCube **定义** MemCube 是 MemOS 中的可插拔、可扩展记忆容器。每个用户、会话或任务均可分配独立的 MemCube,其中可承载一种或多种类型的记忆。 **使用场景** 随着系统规模增长,可通过配置不同的 MemCube 实现记忆的隔离、复用与水平扩展。 ## 记忆类型 MemOS 将记忆视为动态演化的知识系统,而非静态数据存储。其核心记忆类型如下: | 记忆类型 | 描述 | 何时使用 | |----------------|----------------------------------------------|---------------------------------------------| | **参数记忆** | 内化至模型权重的知识 | 常青技能、稳定领域专业知识 | | **激活记忆** | 可复用的 KV 缓存与隐藏状态 | 对话中的快速重用、多轮会话 | | **明文记忆** | 文本、文档、图节点、工具或偏好等 | 可搜索、可检查、演进知识 | ### 参数记忆 **定义** 参数记忆指固化在模型权重中的知识,可视为模型的“长期记忆”。它始终在线,为推理任务提供零延迟的知识支持。 **使用场景** 适用于稳定的领域知识、经过提炼的通用问题解法以及不易变化的操作技能。 ### 激活记忆 **定义** 激活记忆是模型可复用的“工作记忆”,包括预先计算的键值缓存(KV Cache)与隐藏状态,可直接注入注意力机制中,避免对重复内容的重复编码。 **为什么重要:** 将稳定的上下文信息(如产品说明、操作指南)以 KV Cache 形式存储,可大幅降低首词元延迟(TTFT),并提升多轮对话与检索增强生成(RAG)的吞吐效率。 **何时使用:** - 在连续查询中复用背景知识 - 加速基于固定上下文的对话系统 - 配合 MemScheduler 将高频明文记忆自动转换为 KV 缓存 ### 明文记忆 **定义** 结构化或非结构化的知识单元,具有用户可见性和可解释性。除了传统的文档、聊天日志、图节点和向量嵌入外,MemOS 还将以下内容视为明文记忆: - **工具记忆 (Tool Memory)**:包括工具的定义 (Schema) 和使用轨迹 (Trajectory),用于增强智能体(Agent)的工具调用能力。 - **偏好记忆 (Preference Memory)**:显式或隐式的用户偏好,用于个性化推荐和响应。 **使用场景** 适用于语义搜索、个性化体验构建、复杂任务的工具增强以及随时间演进的可追溯事实。支持标签、来源追踪和完整的生命周期管理。 ## 它们如何协同工作 MemOS 让您在生命周期循环中调度所有三种记忆类型: - 提炼过程:高频使用的明文记忆可被蒸馏为参数记忆,提升推理效率。 - 缓存优化:常见推理路径可固化为可复用的 KV 模板,减少重复计算。 - 降级归档:使用频率降低的参数或激活记忆可降级为明文存储,便于审计与再训练。 借助 MemOS,您的 AI 系统不仅能存储信息,更能实现持续**记忆**、**深度理解**和**自主进化**。 > **Note**: **系统洞察** > - 随着时间的推移,频繁使用的明文记忆可以提炼为参数记忆。 > - 低频参数或缓存则可归档为明文,形成可审计、可再训练的知识闭环。 ## 横切概念 ### 混合检索 结合向量相似性检索和图遍历算法,实现稳健且具有上下文感知能力的混合搜索。 ### 治理与生命周期 每个记忆单元都具备完整的生命周期状态(激活、合并、归档),并支持来源跟踪和细粒度访问控制,这对满足审计和数据合规性要求至关重要。 > **Note**: **合规提示** > 请确保对每个记忆单元的来源与状态变更进行完整记录,以符合数据治理与审计规范。 ## 关键要点 MemOS 为您的 LLM 应用提供结构化、可演进、可治理的记忆系统,使智能体能够进行长远规划、复杂推理与持续自适应,释放下一代 AI 应用的真正潜力。 --- # 架构设计 (/cn/open_source/home/architecture) ## 核心模块 ### MOS (Memory Operating System,记忆操作系统) MemOS 的编排层——管理跨多种记忆类型(纯文本、激活、参数化)的预测性、异步调度,并编排**多用户、多会话**记忆工作流。 **核心功能** - **统一 API 网关**:为所有记忆操作(添加、搜索、更新、传输、回滚)提供一致接口 - **工作流编排**:协调 MemCube、MemReader、MemScheduler 等组件的执行流程 - **互操作性支持**:通过记忆交换协议 (MIP) 实现跨模型、跨设备的记忆迁移 - **资源调度**:智能分配计算资源,平衡实时响应与后台处理需求 ### MemCube (记忆容器) MemCube 是 MemOS 的**模块化记忆存储单元**,可视为一个独立且可移植的“记忆卡”。每个 MemCube 可专门服务于特定用户、智能体或会话,容纳一种或多种记忆类型。 **多 Cube 支持 (Multi-Cube):** MemOS 支持通过**组合视图 (Composite View)** 同时操作多个 MemCube,实现灵活的记忆隔离与共享: | 操作类型 | 策略 | 应用场景 | |---------|------|---------| | **写入** | 扇出写入 (Fan-out Write) | 将记忆同时写入用户个人 Cube 和项目共享 Cube | | **读取** | 并行搜索 (Parallel Search) | 同时查询多个 Cube,聚合结果提供全局视图 | **动态管理能力:** - **热插拔支持**:可在运行时动态注册、更新或移除 MemCube - **容器化存储**:支持记忆在会话、模型和设备间的安全传输 - **隔离保障**:确保不同用户或应用间的记忆数据相互隔离 ### 异步添加机制 (Asynchronous Addition) 为了在高并发场景下保持低延迟,MemOS 提供了异步记忆添加模式 (`async_mode`),利用 **MemScheduler** 进行后台调度: | 记忆类型 | 处理策略 | 优势 | |---------|---------|------| | **文本记忆** | 快速提取 + 异步处理 | API 立即返回基础结果,复杂处理后台执行 | | **偏好记忆** | 全异步处理 | 最大化减少 API 响应延迟 | **MemScheduler 角色:** 作为异步任务调度器,负责: - 管理后台处理任务的优先级队列 - 协调重索引、图推理等计算密集型操作 - 监控任务状态,确保处理一致性 ### 记忆类型体系 MemOS 支持几种专门的记忆类型以满足不同需求: #### 1. 参数化记忆(**即将推出**) - **特性**: 知识固化于模型权重中,推理零延迟 - **应用场景**:稳定的领域知识、核心技能 - **生命周期**:长期持久,更新成本较高 #### 2. 激活记忆 - **特性**:运行时 KV 缓存与隐藏状态,快速复用 - **应用场景**:多轮对话上下文、频繁访问的背景信息 - **生命周期**:短期有效,会话级保持 #### 3. 明文记忆 结构化或非结构化知识块;可编辑、可追溯,适合快速更新、个性化和多代理共享。 | 记忆子类 | 存储结构 | 核心优势 | 典型应用 | |---------|---------|---------|---------| | **GeneralTextMemory** | 向量存储 | 语义检索灵活,支持元数据过滤 | 非结构化文档、聊天记录 | | **TreeTextMemory** | 图结构存储 | 层次化组织,支持多跳推理 | 结构化知识库、用户画像 | > **Note**: **起步建议** :从 `GeneralTextMemory` 开始快速验证概念 > **演进路径** :随着业务复杂度提升,逐步引入 `TreeTextMemory` 处理结构化知识 #### 基础支撑组件 MemOS 的基础模块提供标准化能力,确保系统的可扩展性与一致性: | 组件类别 | 核心功能 | 实现示例 | |---------|---------|---------| | **文本处理** | 智能分块、记忆提取 | Chunkers, MemReaders | | **向量化** | 文本嵌入生成 | Embedders (bge-m3, text-embedding-3-large) | | **存储接口** | 多数据库适配 | GraphDBs (Neo4j, Qdrant, PolarDB) | | **模型连接** | 统一 LLM 接口 | LLMs (OpenAI, Ollama) | | **质量优化** | 检索结果重排 | Rerankers (bge-reranker-v2-m3) | ## 代码组织架构 MemOS 项目组织清晰,支持即插即用: ``` src/memos/ api/ # API 定义 chunkers/ # 文本分块工具 configs/ # 配置模式 context/ # 日志上下文 embedders/ # 嵌入模型 graph_dbs/ # 图数据库后端 (例如,Neo4j) vec_dbs/ # 向量数据库后端 (例如,Qdrant) llms/ # LLM 连接器 mem_agent/ # 深度检索 mem_chat/ # 记忆增强聊天逻辑 mem_cube/ # MemCube 管理 mem_feedback # 记忆反馈 mem_os/ # MOS 编排 mem_reader/ # 记忆读取器 mem_scheduler/ # 记忆调度模块 memories/ # 记忆类型实现 multi_mem_cube/# 多视图cube parsers/ # 解析工具 reranker/ # 重排模块 templates/ # 提示词模板 types/ # 类型定义 ``` > **Note**: **专业提示** > - **快速实验**:使用 `examples/` 目录中的示例快速验证功能 > - **深度定制**:参考 `src/` 中的模块实现进行二次开发 > - **配置管理**:所有组件均支持通过 `configs/` 进行灵活配置 ## 可扩展性 MemOS 是**模块化设计的**。 添加您自己的记忆类型、存储后端或 LLM 连接器,只需最少的更改——这要归功于其**统一配置和工厂模式**。 > **Note**: **专业提示** > [贡献](/open_source/contribution/overview) 一个新的后端或分享您的自定义记忆类型——这很容易插入。 --- # REST API 服务 (/cn/open_source/getting_started/rest_api_server) ![MemOS Architecture](https://cdn.memtensor.com.cn/img/memos_run_server_success_compressed.png)
MemOS REST API 服务支持的 API ### 功能特点 - 添加新记忆:为指定用户创建一条新的记忆。 - 搜索记忆:为指定用户搜索其记忆内容。 - 获取用户所有记忆:获取某个用户的所有记忆内容。 - 记忆反馈:为指定用户反馈记忆内容。 - 与 MemOS 对话:与 MemOS 进行对话,返回 SSE 流式响应。 ## 本地运行 ### 1、本地下载 ```bash # 将代码下载到本地文件夹下 git clone https://github.com/MemTensor/MemOS ``` ### 2、配置环境变量 ```bash # 进入文件夹目录下 cd MemOS ``` #### 在根目录中创建一个 `.env` 文件并设置你的环境变量。 ##### .env 快速模式配置如下,完整模式参考 [.env.example](https://github.com/MemTensor/MemOS/blob/main/docker/.env.example)。 ```bash # OpenAI API 密钥 (需自定义配置) OPENAI_API_KEY=sk-xxx # OpenAI API 基础 URL OPENAI_API_BASE=http://xxx:3000/v1 # 默认模型名称 MOS_CHAT_MODEL=qwen3-max # Memory Reader LLM 模型 MEMRADER_MODEL=qwen3-max # Memory Reader API 密钥 MEMRADER_API_KEY=sk-xxx # Memory Reader API 基础 URL MEMRADER_API_BASE=http://xxx:3000/v1 # Embedder 模型名称 MOS_EMBEDDER_MODEL=text-embedding-v4 # 配置embedding backend 两种选择 ollama | universal_api MOS_EMBEDDER_BACKEND=universal_api # Embedder API 基础 URL MOS_EMBEDDER_API_BASE=http://xxx:8081/v1 # Embedder API 密钥 MOS_EMBEDDER_API_KEY=xxx # Embedding 向量维度 EMBEDDING_DIMENSION=1024 # Reranker 后端 (http_bge | etc.) MOS_RERANKER_BACKEND=cosine_local # Neo4j 连接 URI # 可选值: neo4j-community | neo4j | nebular | polardb NEO4J_BACKEND=neo4j-community # 当 backend=neo4j* 时必须 NEO4J_URI=bolt://localhost:7687 NEO4J_USER=neo4j NEO4J_PASSWORD=12345678 NEO4J_DB_NAME=neo4j MOS_NEO4J_SHARED_DB=false # 是否使用 redis 的调度器 DEFAULT_USE_REDIS_QUEUE=false # 启用聊天 API ENABLE_CHAT_API=true # 聊天模型列表 可以通过百炼申请. 模型可自选 CHAT_MODEL_LIST=[{"backend": "qwen", "api_base": "https://xxx/v1", "api_key": "sk-xxx", "model_name_or_path": "qwen3-max", "extra_body": {"enable_thinking": true} ,"support_models": ["qwen3-max"]}] ``` ### 3、以百炼为例自定义配置 ```bash # 可通过百炼平台申请 # https://bailian.console.aliyun.com/?spm=a2c4g.11186623.0.0.2f2165b08fRk4l&tab=api#/api # 申请成功后,获取API_KEY和BASE_URL,示例配置如下 # OpenAI API 密钥 (用百炼的API_KEY) OPENAI_API_KEY=you_bailian_api_key # OpenAI API 基础 URL OPENAI_API_BASE=https://dashscope.aliyuncs.com/compatible-mode/v1 # 默认模型名称 MOS_CHAT_MODEL=qwen3-max # Memory Reader LLM 模型 MEMRADER_MODEL=qwen3-max # Memory Reader API 密钥 (用百炼的API_KEY) MEMRADER_API_KEY=you_bailian_api_key # Memory Reader API 基础 URL MEMRADER_API_BASE=https://dashscope.aliyuncs.com/compatible-mode/v1 # Embedder模型名称可以参考下面链接 # https://bailian.console.aliyun.com/?spm=a2c4g.11186623.0.0.2f2165b08fRk4l&tab=api#/api/?type=model&url=2846066 MOS_EMBEDDER_MODEL=text-embedding-v4 # 配置embedding backend 两种选择 ollama | universal_api MOS_EMBEDDER_BACKEND=universal_api # Embedder API 基础 URL MOS_EMBEDDER_API_BASE=https://dashscope.aliyuncs.com/compatible-mode/v1 # Embedder API 密钥 (用百炼的API_KEY) MOS_EMBEDDER_API_KEY=you_bailian_api_key # Embedding 向量维度 EMBEDDING_DIMENSION=1024 # Reranker 后端 (http_bge | etc.) MOS_RERANKER_BACKEND=cosine_local # Neo4j 连接 URI # 可选值: neo4j-community | neo4j | nebular | polardb NEO4J_BACKEND=neo4j-community # 当 backend=neo4j* 时必须 NEO4J_URI=bolt://localhost:7687 NEO4J_USER=neo4j NEO4J_PASSWORD=12345678 NEO4J_DB_NAME=neo4j MOS_NEO4J_SHARED_DB=false # 是否使用 redis 的调度器 DEFAULT_USE_REDIS_QUEUE=false # 启用聊天 API ENABLE_CHAT_API=true CHAT_MODEL_LIST=[{"backend": "qwen", "api_base": "https://dashscope.aliyuncs.com/compatible-mode/v1", "api_key": "you_bailian_api_key", "model_name_or_path": "qwen3-max-preview", "extra_body": {"enable_thinking": true} ,"support_models": ["qwen3-max-preview"]}] ``` ![MemOS bailian](https://cdn.memtensor.com.cn/img/get_key_url_by_bailian_compressed.png)
百炼申请 API_KEY和 BASE_URL 示例 配置docker/requirement.txt中依赖包的版本等(可忽略)。完整版可参考 [requirements.txt](https://github.com/MemTensor/MemOS/blob/main/docker/requirements.txt)。 ### 4、启动docker ```bash # 如果没有安装docker,请安装对应版本,下载地址如下: https://www.docker.com/ # 安装完成之后,可通过客户端启动docker,或者通过命令行启动docker # 通过命令行启动docker sudo systemctl start docker # 安装完成后,查看docker状态 docker ps # 查看docker镜像 (可不用) docker images ``` ### 方式一:Docker 使用仓库依赖包镜像启动(推荐使用) ```bash #进入docker目录下 cd docker ``` #### 镜像包使用确认 包含快速模式和完整模式,可区分使用精简包(区分arm和x86)和全量包(区分arm和x86) ```bash ● 精简包:简化体量过大的 nvidia相关等依赖,对镜像实现轻量化,使本地部署更加轻量快速。 url: registry.cn-shanghai.aliyuncs.com/memtensor/memos-base:v1.0 url: registry.cn-shanghai.aliyuncs.com/memtensor/memos-base-arm:v1.0 ● 全量包:将 MemOS 全部依赖包打为镜像,可体验完整功能,通过配置 Dockerfile可直接构建启动。 url: registry.cn-shanghai.aliyuncs.com/memtensor/memos-full-base:v1.0.0 url: registry.cn-shanghai.aliyuncs.com/memtensor/memos-full-base-arm:v1.0.0 ``` #### 配置Dockerfile文件 ```bash # 当前示例使用精简包 url FROM registry.cn-shanghai.aliyuncs.com/memtensor/memos-base-arm:v1.0 WORKDIR /app ENV HF_ENDPOINT=https://hf-mirror.com ENV PYTHONPATH=/app/src COPY src/ ./src/ EXPOSE 8000 CMD ["uvicorn", "memos.api.server_api:app", "--host", "0.0.0.0", "--port", "8000", "--reload"] ``` #### 构建并启动服务 : ```bash # 在docker目录下 docker compose up ``` ![MemOS buildComposeupSuccess](https://cdn.memtensor.com.cn/img/memos_build_composeup_success_compressed.png)
示例图片,端口按 docker 自定义的配置 #### 通过 [http://localhost:8000/docs](http://localhost:8000/docs) 访问 API。 ![MemOS Architecture](https://cdn.memtensor.com.cn/img/memos_run_server_success_compressed.png) #### 测试用例 (添加用户记忆->查询用户记忆) 参考Docker Compose up测试用例 ### 方式二:客户端install Docker Compose up 开发环境的 Docker Compose up 已预配置了 qdrant、neo4j。 运行服务器需要环境变量 `OPENAI_API_KEY`。 #### 进入docker文件夹 ```bash # 当前文件夹下进入docker文件夹 cd docker ``` #### 安装对应依赖模块 ```bash pip install --upgrade pip && pip install --no-cache-dir -r requirements.txt # 使用阿里云源安装依赖 pip install --upgrade pip && pip install --no-cache-dir -r requirements.txt -i https://mirrors.aliyun.com/pypi/simple/ # command not found: pip 使用pip3 ``` #### 在docker目录下使用 Docker Compose Up启动容器(保证vpn正常连接): ```bash # 首次运行需要build docker compose up --build # 再次运行则不需要 docker compose up ``` #### 通过 [http://localhost:8000/docs](http://localhost:8000/docs) 访问 API。 #### 示例流程 ##### (查询用户记忆(没有继续往后)->添加用户记忆->查询用户记忆) ##### 添加用户记忆 http://localhost:8000/product/add (POST) ```bash # 请求参数 { "user_id": "8736b16e-1d20-4163-980b-a5063c3facdc", "mem_cube_id": "b32d0977-435d-4828-a86f-4f47f8b55bca", "async_mode": "async", "messages": [ { "role": "user", "content": "我喜欢草莓" } ] } # 响应 { "code": 200, "message": "Memory created successfully", "data": null } ``` ##### 查询用户记忆 http://localhost:8000/product/search (POST) ```bash # 请求参数 { "query": "我喜欢什么", "user_id": "8736b16e-1d20-4163-980b-a5063c3facdc", "mem_cube_id": "b32d0977-435d-4828-a86f-4f47f8b55bca" } # 响应 { "code": 200, "message": "Search completed successfully", "data": { "text_mem": [ { "cube_id": "7231eda8-6c57-4f6e-97ce-98b699eebb98", "memories": [ { "id": "2f40be8f-736c-4a5f-aada-9489037769e0", "memory": "[user观点]用户喜欢草莓。", "metadata": { "user_id": "de8215e3-3beb-4afc-9b64-ae594d62f1ea", "session_id": "root_session", "status": "activated", "type": "fact", "key": "用户对草莓的喜好", "confidence": 0.99, "source": null, "tags": [ "喜好", "草莓" ], "visibility": null, "updated_at": "2025-09-18T08:23:44.625479000+00:00", "memory_type": "UserMemory", "sources": [], "embedding": [], "created_at": "2025-09-18T08:23:44.625511000+00:00", "usage": [ "{ "time": "2025-09-18T08:24:17.759748", "info": { "user_id": "de8215e3-3beb-4afc-9b64-ae594d62f1ea", "session_id": "root_session" } }" ], "background": "用户表达了对草莓的喜好,显示出他们在饮食偏好上的倾向。", "relativity": 0.6349761312470591, "vector_sync": "success", "ref_id": "[2f40be8f]", "id": "2f40be8f-736c-4a5f-aada-9489037769e0", "memory": "[user观点]用户喜欢草莓。" }, "ref_id": "[2f40be8f]" }, ... } } ], "act_mem": [], "para_mem": [] } } # 响应失败,原因排查 # src/memos/api/config.py # 检查get_neo4j_community_config方法中配置的"neo4j_vec_db"和"EMBEDDING_DIMENSION" ``` #### 对服务器代码或库代码进行修改将自动重新加载服务器。 ### 方式三:客户端install 使用 CLI 命令 #### 安装依赖 ```bash # pip install --upgrade pip && pip install --no-cache-dir -r ./docker/requirements.txt # 使用阿里云源安装依赖 pip install --no-cache-dir -r ./docker/requirements.txt -i https://mirrors.aliyun.com/pypi/simple/ ``` #### 在终端中打开运行以下命令进行安装: ```bash # 目前可能需要手动安装的包 这两个包需要找资源 # neo4j.5.26.4.tar qdrant.v1.15.3.tar docker load -i neo4j.5.26.4.tar docker load -i qdrant.v1.15.3.tar # 查看是否安装成功 docker images # 查看是否跑起来了 docker ps -a # 若启动时出现ModuleNotFoundError: No module named 'memos',是因为路径匹配有问题,请执行 export PYTHONPATH=/you-file-absolute-path/MemOS/src # 根目录 uvicorn memos.api.server_api:app --host 0.0.0.0 --port 8000 --workers 1 ``` #### 访问 API 启动完成后,通过 [http://localhost:8000/docs](http://localhost:8000/docs) 访问 API。 ### 方式四:不使用 Docker #### 参考上方配置环境变量,已经好配置.env文件 #### 安装 Poetry 用于依赖管理: ```bash curl -sSL https://install.python-poetry.org | python3 - ``` #### Poetry 环境变量配置: ```bash #要开始使用,您需要在“PATH”中找到Poetry的bin目录(/Users/jinyunyuan/.local/bin)`环境变量 # 现代 macOS 系统默认的 Shell 是 zsh。你可以通过以下命令确认 1. 确定你使用的 Shell echo $SHELL # 如果输出是 /bin/zsh 或 /usr/bin/env zsh,那么你就是 zsh。 # (如果你的系统版本较老,可能还在使用 bash,输出会是 /bin/bash) 2. 打开对应的 Shell 配置文件 # 如果使用的是 zsh (绝大多数情况): # 使用 nano 编辑器(推荐新手) nano ~/.zshrc # 或者使用 vim 编辑器 # vim ~/.zshrc # 如果使用的是 bash: nano ~/.bash_profile # 或者 nano ~/.bashrc 3. 添加 PATH 环境变量 # 在打开的文件的最末尾,新起一行,粘贴安装提示给你的那行命令: export PATH="/you-path/.local/bin:$PATH" 4. 保存并退出编辑器 # 如果你用的是 nano: # 按 Ctrl + O 来写入(保存),按 Enter 确认文件名。 # 然后按 Ctrl + X 退出编辑器。 # 如果你用的是 vim: # 按 i 进入插入模式,粘贴代码后,按 ESC 键退出插入模式。 # 输入 :wq,然后按 Enter 来保存并退出。 5. 使配置立刻生效 # 刚刚修改的配置文件不会自动在当前已打开的终端窗口生效,你需要运行以下命令之一来重新加载它: # 对于 zsh: source ~/.zshrc # 对于 bash: source ~/.bash_profile 6. 验证安装是否成功 # 现在,你可以执行提示中的测试命令来检查一切是否就绪: poetry --version # 成功后将显示版本号 Poetry (version 2.2.0) ``` #### 安装所有项目依赖和开发工具: ```bash make install ``` #### 先在docker中启动 neo4j 和 qdrant #### 启动 FastAPI 服务器(在MomOS目录下): ```bash uvicorn memos.api.product_api:app --host 0.0.0.0 --port 8000 --reload ``` #### 服务器运行后,您可以使用OpenAPI文档测试API,网址为 [http://localhost:8000/docs](http://localhost:8000/docs) 或者 [http://127.0.0.1:8000/docs](http://127.0.0.1:8000/docs) #### 测试用例 (注册用户->添加用户记忆->查询用户记忆) 参考Docker Compose up测试用例 ### 方式五:使用 PyCharm 启动 #### 运行 server_api ```bash 1、进入MemOS/docker/Dockerfile文件,修改运行配置 # Start the docker CMD ["uvicorn", "memos.api.server_api:app", "--host", "0.0.0.0", "--port", "8000", "--reload"] 2、进入目录MemOS/src/memos/api 直接运行server_api.py ``` --- # MemOS 示例 (/cn/open_source/getting_started/examples) - [最简Pipeline](/cn/open_source/getting_started/examples#示例-1最简pipeline): 最小的可用Pipeline — 添加、搜索明文记忆。 - [多信息源的添加与检索](/cn/open_source/getting_started/examples#示例-2多信息源记忆的添加与检索): 添加文本、图片、文件、工具调用的多信息源messages到记忆,并能够检索它们。 - [多Cube添加和检索](/cn/open_source/getting_started/examples#示例-3多cube添加和检索): 添加不同记忆到不同的Cube,在检索时同时召回它们。 - [仅 KVCacheMemory](/cn/open_source/getting_started/examples#示例-4仅-kvcachememory): 使用短期 KV cache加速会话,实现快速上下文注入。 - [记忆调度](/cn/open_source/getting_started/examples#示例-5多忆调度): 为多用户、多会话智能体运行动态记忆调用。 ## 示例 1:最简Pipeline ### 何时使用: - 你想要最小的入门可用示例。 - 你只需要将简单的明文记忆存储到数据库中,并能够检索它们。 ### 关键点: - 支持基础的个人用户记忆添加、搜索。 ### 完整示例代码 ```python import json from memos.api.routers.server_router import add_memories, search_memories from memos.api.product_models import APIADDRequest, APISearchRequest user_id = "test_user_1" add_req = APIADDRequest( user_id=user_id, writable_cube_ids=["cube_test_user_1"], messages = [ {"role": "user", "content": "I’ve planned to travel to Guangzhou during the summer vacation. What chain hotels are available for accommodation?"}, {"role": "assistant", "content": "You can consider [7 Days Inn, Ji Hotel, Hilton], etc."}, {"role": "user", "content": "I’ll choose 7 Days Inn."}, {"role": "assistant", "content": "Okay, feel free to ask me if you have any other questions."} ], async_mode="sync", mode="fine", ) add_rsp = add_memories(add_req) print("add_memories rsp: \n\n", add_rsp) search_req = APISearchRequest( user_id=user_id, readable_cube_ids=["cube_test_user_1"], query="Please recommend a hotel that I haven’t stayed at before.", include_preference=True, ) search_rsp = search_memories(search_req).data print("\n\nsearch_rsp: \n\n", json.dumps(search_rsp, indent=2, ensure_ascii=False)) ```` ## 示例 2:多信息源记忆的添加与检索 ### 何时使用: - 除单纯的文本对话外,你需要将文件、图片内容或工具调用历史信息加入记忆 - 同时你想要检索这些多源信息的记忆 ### 关键点: - 多种信息来源的记忆添加 - 需要有可下载的文件、图片url - 添加的信息需要严格符合OpenAI Messages格式 - system prompt中的工具Schema需要包装在 中 ### 完整示例代码 添加文本+文件到记忆中 ```python import json from memos.api.routers.server_router import add_memories, search_memories from memos.api.product_models import APIADDRequest, APISearchRequest user_id = "test_user_2" add_req = APIADDRequest( user_id=user_id, writable_cube_ids=["cube_test_user_2"], messages = [ { "role": "user", "content": [ { "type": "text", "text": "Please read this file, summarize the key points, and provide a final conclusion." }, { "type": "file", "file": { "file_id": "file_123", "filename": "report.md", "file_data": "@http://139.196.232.20:9090/graph-test/algorithm/2025_11_13/1763043889_1763043782_PM1%E8%BD%A6%E9%97%B4PMT%E9%9D%B4%E5%8E%8B%E8%BE%B9%E5%8E%8B%E5%8E%8B%E5%8A%9B%E6%97%A0%E6%B3%95%E5%BB%BA%E7%AB%8B%E6%95%85%E9%9A%9C%E6%8A%A5%E5%91%8A20240720.md" } }, ] }, { "role": "assistant", "content": [ { "type": "text", "text": "Final Summary: During the PMT boot-pressure startup test of the PM1 workshop on July 20, 2024, the drive could not run because the edge pressures on both sides failed to reach the 2.5-bar interlock requirement. After troubleshooting, the PLC output signals, hydraulic pipelines, and valves were all found to be normal. The root cause was ultimately identified as poor contact at the negative terminal of the proportional valve’s DC 24V power supply inside the PLC cabinet, caused by a short-jumpered terminal block. After re-connecting the negative incoming lines in parallel, the equipment returned to normal operation. It is recommended to replace terminal blocks in batches, inspect instruments with uncertain service life, and optimize the troubleshooting process by tracing common-mode issues from shared buses and power supply sources." } ] } ], async_mode="sync", mode="fine", ) add_rsp = add_memories(add_req) print("add_memories rsp: \n\n", add_rsp) search_req = APISearchRequest( user_id=user_id, readable_cube_ids=["cube_test_user_2"], query="Workshop PMT boot pressure startup test", include_preference=False, ) search_rsp = search_memories(search_req).data print("\n\nsearch_rsp: \n\n", json.dumps(search_rsp, indent=2, ensure_ascii=False)) ``` 添加多种混合信息源的messages到记忆中 ```python import json from memos.api.routers.server_router import add_memories, search_memories from memos.api.product_models import APIADDRequest, APISearchRequest user_id = "test_user_2" add_req = APIADDRequest( user_id=user_id, writable_cube_ids=["cube_test_user_2"], messages = [ { "role": "system", "content": [ { "type": "text", "text": "You are a professional industrial fault analysis assistant. Please read the PDF, images, and instructions provided by the user and provide a professional technical summary.\n\n\n[\n {\n \"name\": \"file_reader\",\n \"description\": \"Used to read the content of files uploaded by the user and return the text data (in JSON string format).\",\n \"parameters\": [\n {\"name\": \"file_id\", \"type\": \"string\", \"required\": true, \"description\": \"The file ID to be read\"}\n ],\n \"returns\": {\"type\": \"text\", \"description\": \"Returns the extracted text content of the file\"}\n }\n]\n" } ] }, { "role": "user", "content": [ { "type": "text", "text": "Please read this file and image, summarize the key points, and provide a final conclusion." }, { "type": "file", "file": { "file_id": "file_123", "filename": "report.pdf", "file_data": "@http://139.196.232.20:9090/graph-test/algorithm/2025_11_13/1763043889_1763043782_PM1%E8%BD%A6%E9%97%B4PMT%E9%9D%B4%E5%8E%8B%E8%BE%B9%E5%8E%8B%E5%8E%8B%E5%8A%9B%E6%97%A0%E6%B3%95%E5%BB%BA%E7%AB%8B%E6%95%85%E9%9A%9C%E6%8A%A5%E5%91%8A20240720.md" } }, { "type": "image_url", "image_url": { "url": "https://play-groud-test-1.oss-cn-shanghai.aliyuncs.com/%E5%9B%BE%E7%89%871.jpeg" } } ] }, { "role": "assistant", "tool_calls": [ { "id": "call_file_reader_001", "type": "function", "function": { "name": "file_reader", "arguments": "{\"file_id\": \"file_123\"}" } } ] }, { "role": "tool", "tool_call_id": "call_file_reader_001", "content": [ { "type": "text", "text": "{\"file_id\":\"file_123\",\"extracted_text\":\"PM1 workshop PMT boot pressure startup test record… Final fault cause: poor contact at the negative terminal of the DC 24V power supply circuit due to a short-jumped terminal block.\"}" } ] }, { "role": "assistant", "content": [ { "type": "text", "text": "Final Summary: During the PMT boot-pressure startup test of the PM1 workshop on July 20, 2024, the drive could not run because the edge pressures on both sides failed to reach the 2.5-bar interlock requirement. After troubleshooting, the PLC output signals, hydraulic pipelines, and valves were all found to be normal. The root cause was ultimately identified as poor contact at the negative terminal of the proportional valve’s DC 24V power supply inside the PLC cabinet, caused by a short-jumpered terminal block. After re-connecting the negative incoming lines in parallel, the equipment returned to normal operation. It is recommended to replace terminal blocks in batches, inspect instruments with uncertain service life, and optimize the troubleshooting process by tracing common-mode issues from shared buses and power supply sources." } ] } ], async_mode="sync", mode="fine", ) add_rsp = add_memories(add_req) print("add_memories rsp: \n\n", add_rsp) search_req = APISearchRequest( user_id=user_id, readable_cube_ids=["cube_test_user_2"], query="Workshop PMT boot pressure startup test", include_preference=False, ) search_rsp = search_memories(search_req).data print("\n\nsearch_rsp: \n\n", json.dumps(search_rsp, indent=2, ensure_ascii=False)) ``` ## 示例 3:多Cube添加和检索 ### 何时使用: - 向彼此隔离的不同的Cube空间中添加记忆 - 你希望同时检索不同Cube空间中的记忆 ### 关键点: - 在检索时输入含有多个cube id的readable_cube_ids列表 ### 完整示例代码 ```python import json from memos.api.routers.server_router import add_memories, search_memories from memos.api.product_models import APIADDRequest, APISearchRequest user_id = "test_user_3" add_req = APIADDRequest( user_id=user_id, writable_cube_ids=["cube_test_user_3_1"] , messages = [ {"role": "user", "content": "I’ve planned to travel to Guangzhou during the summer vacation. What chain hotels are available for accommodation?"}, {"role": "assistant", "content": "You can consider [7 Days Inn, Ji Hotel, Hilton], etc."}, {"role": "user", "content": "I’ll choose 7 Days Inn."}, {"role": "assistant", "content": "Okay, feel free to ask me if you have any other questions."} ], async_mode="sync", mode="fine", ) add_rsp = add_memories(add_req) print("add_memories rsp: \n\n", add_rsp) add_req = APIADDRequest( user_id=user_id, writable_cube_ids=["cube_test_user_3_2"] , messages = [ {"role": "user", "content": "I love you, I need you."}, {"role": "assistant", "content": "Wow, I love you too"}, ], async_mode="sync", mode="fine", ) add_rsp = add_memories(add_req) print("add_memories rsp: \n\n", add_rsp) search_req = APISearchRequest( user_id=user_id, readable_cube_ids=["cube_test_user_3_1", "cube_test_user_3_2"], query="Please recommend a hotel, Love u u", include_preference=True, ) search_rsp = search_memories(search_req).data print("\n\nsearch_rsp: \n\n", json.dumps(search_rsp, indent=2, ensure_ascii=False)) ``` ## 示例 4:仅 KVCacheMemory ### 何时使用: - 你想要短期工作记忆以加快多轮对话速度。 - 适合聊天机器人会话加速或提示复用。 - 最适合缓存隐藏状态 / KV 对。 ### 关键点: - 使用 KVCacheMemory,不含显式明文记忆。 - 演示提取 → 添加 → 合并 → 获取 → 删除。 - 展示如何导出/加载 KV cache。 ### 完整示例代码 ```python import json from transformers import DynamicCache from memos.memories.activation.item import KVCacheItem from memos.configs.memory import MemoryConfigFactory from memos.memories.factory import MemoryFactory def get_cache_info(cache): if not cache: return None num_layers = 0 total_size_bytes = 0 if hasattr(cache, "layers"): num_layers = len(cache.layers) for layer in cache.layers: if hasattr(layer, "key_cache") and layer.key_cache is not None: total_size_bytes += layer.key_cache.nelement() * layer.key_cache.element_size() if hasattr(layer, "value_cache") and layer.value_cache is not None: total_size_bytes += layer.value_cache.nelement() * layer.value_cache.element_size() if hasattr(layer, "keys") and layer.keys is not None: total_size_bytes += layer.keys.nelement() * layer.keys.element_size() if hasattr(layer, "values") and layer.values is not None: total_size_bytes += layer.values.nelement() * layer.values.element_size() elif hasattr(cache, "key_cache") and hasattr(cache, "value_cache"): num_layers = len(cache.key_cache) for k, v in zip(cache.key_cache, cache.value_cache, strict=False): if k is not None: total_size_bytes += k.nelement() * k.element_size() if v is not None: total_size_bytes += v.nelement() * v.element_size() return { "num_layers": num_layers, "size_bytes": total_size_bytes, "size_mb": f"{total_size_bytes / (1024 * 1024):.2f} MB", } def serialize_item(obj): if isinstance(obj, list): return [serialize_item(x) for x in obj] if isinstance(obj, KVCacheItem): return { "id": obj.id, "metadata": obj.metadata, "records": obj.records.model_dump() if hasattr(obj.records, "model_dump") else obj.records, "memory": get_cache_info(obj.memory), } if isinstance(obj, DynamicCache): return get_cache_info(obj) return str(obj) # 为 KVCacheMemory(HuggingFace 后端)创建配置 config = MemoryConfigFactory( backend="kv_cache", config={ "extractor_llm": { "backend": "huggingface", "config": { "model_name_or_path": "Qwen/Qwen3-0.6B", "max_tokens": 32, "add_generation_prompt": True, "remove_think_prefix": True, }, }, }, ) # 实例化 KVCacheMemory kv_mem = MemoryFactory.from_config(config) # 提取一个 KVCacheItem(DynamicCache) prompt = [ {"role": "user", "content": "What is MemOS?"}, {"role": "assistant", "content": "MemOS is a memory operating system for LLMs."}, ] print("===== Extract KVCacheItem =====") cache_item = kv_mem.extract(prompt) print(json.dumps(serialize_item(cache_item), indent=2, default=str)) # 将缓存添加到内存中 kv_mem.add([cache_item]) print("All caches:") print(json.dumps(serialize_item(kv_mem.get_all()), indent=2, default=str)) # 通过 ID 获取 retrieved = kv_mem.get(cache_item.id) print("Retrieved:") print(json.dumps(serialize_item(retrieved), indent=2, default=str)) # 合并缓存 item2 = kv_mem.extract([{"role": "user", "content": "Tell me a joke."}]) kv_mem.add([item2]) merged = kv_mem.get_cache([cache_item.id, item2.id]) print("Merged cache:") print(json.dumps(serialize_item(merged), indent=2, default=str)) # 删除其中一个 kv_mem.delete([cache_item.id]) print("After delete:") print(json.dumps(serialize_item(kv_mem.get_all()), indent=2, default=str)) # 导出和加载缓存 kv_mem.dump("tmp/kv_mem") print("Dumped to tmp/kv_mem") kv_mem.delete_all() kv_mem.load("tmp/kv_mem") print("Loaded caches:") print(json.dumps(serialize_item(kv_mem.get_all()), indent=2, default=str)) ``` ## 示例 5:记忆调度 ### 何时使用: - 你希望自定义记忆调度逻辑或扩展后台任务,以异步触发的方式不断对记忆进行管理和优化。 - 适用于 SaaS 智能体或多会轮对话的LLM应用任务。 - 展示 MemScheduler的记忆管理任务设置与运行方式。 ### 关键点: - 通过 `mem_scheduler.register_handlers` 注册自定义回调。 - 使用 `add_handler` 和 `chat_stream_playground` 进行交互。 - 演示了如何获取和使用从环境量初始化完成的MemScheduler实例。 ### 完整示例代码 ```python import asyncio import json import os import sys import time from pathlib import Path # 在依赖路径的导入之前设置路径 FILE_PATH = Path(__file__).absolute() BASE_DIR = FILE_PATH.parent.parent.parent sys.path.insert(0, str(BASE_DIR)) # 启用从任何工作目录执行 # 在导入 server_router 之前设置环境变量,以确保组件正确初始化 os.environ["ENABLE_CHAT_API"] = "true" from memos.api.product_models import APIADDRequest, ChatPlaygroundRequest # noqa: E402 # 从 server_router 导入以进行初始化 from memos.api.routers.server_router import ( # noqa: E402 add_handler, chat_stream_playground, mem_scheduler, ) from memos.log import get_logger # noqa: E402 from memos.mem_scheduler.schemas.message_schemas import ScheduleMessageItem # noqa: E402 from memos.mem_scheduler.schemas.task_schemas import ( # noqa: E402 MEM_UPDATE_TASK_LABEL, QUERY_TASK_LABEL, ) logger = get_logger(__name__) def init_task(): conversations = [ {"role": "user", "content": "I just adopted a golden retriever puppy yesterday."}, {"role": "assistant", "content": "Congratulations! What did you name your new puppy?"}, { "role": "user", "content": "His name is Max. I live near Central Park in New York where we'll walk daily.", }, {"role": "assistant", "content": "Max will love those walks! Any favorite treats for him?"}, { "role": "user", "content": "He loves peanut butter biscuits. Personally, I'm allergic to nuts though.", }, {"role": "assistant", "content": "Good to know about your allergy. I'll note that."}, # 问题 1 (宠物) - 名字 {"role": "user", "content": "What's my dog's name again?"}, {"role": "assistant", "content": "Your dog is named Max."}, # 问题 2 (宠物) - 品种 {"role": "user", "content": "Can you remind me what breed Max is?"}, {"role": "assistant", "content": "Max is a golden retriever."}, # 问题 3 (宠物) - 零食 {"role": "user", "content": "What treats does Max like?"}, {"role": "assistant", "content": "He loves peanut butter biscuits."}, # 问题 4 (地址) {"role": "user", "content": "Where did I say I live?"}, {"role": "assistant", "content": "You live near Central Park in New York."}, # 问题 5 (过敏) {"role": "user", "content": "What food should I avoid due to allergy?"}, {"role": "assistant", "content": "You're allergic to nuts."}, {"role": "user", "content": "Perfect, just wanted to check what you remembered."}, {"role": "assistant", "content": "Happy to help! Let me know if you need anything else."}, ] questions = [ {"question": "What's my dog's name again?", "category": "Pet"}, {"question": "Can you remind me what breed Max is?", "category": "Pet"}, {"question": "What treats does Max like?", "category": "Pet"}, {"question": "Where did I say I live?", "category": "Address"}, {"question": "What food should I avoid due to allergy?", "category": "Allergy"}, ] return conversations, questions working_memories = [] # 定义自定义查询处理函数 def custom_query_handler(messages: list[ScheduleMessageItem]): for msg in messages: # 打印用户输入内容 print(f"\n[scheduler] User input query: {msg.content}") # 手动构造带有 MEM_UPDATE 标签的新消息以触发记忆更新 new_msg = msg.model_copy(update={"label": MEM_UPDATE_TASK_LABEL}) # 提交消息给调度器处理 mem_scheduler.submit_messages([new_msg]) # 定义自定义记忆更新处理函数 def custom_mem_update_handler(messages: list[ScheduleMessageItem]): global working_memories search_args = {} top_k = 2 for msg in messages: # 在文本记忆中搜索与当前内容相关的记忆(返回 top_k=2) results = mem_scheduler.retriever.search( query=msg.content, user_id=msg.user_id, mem_cube_id=msg.mem_cube_id, mem_cube=mem_scheduler.current_mem_cube, top_k=top_k, method=mem_scheduler.search_method, search_args=search_args, ) working_memories.extend(results) working_memories = working_memories[-5:] for mem in results: print(f"\n[scheduler] Retrieved memory: {mem.memory}") async def run_with_scheduler(): print("==== run_with_automatic_scheduler_init ====") conversations, questions = init_task() # 使用 server_router 组件进行初始化 # 配置通过 init_server() 中的环境变量加载 user_id = "user_1" mem_cube_id = "mem_cube_5" print(f"Adding conversations for user {user_id}...") # 使用 add_handler 添加记忆 add_req = APIADDRequest( user_id=user_id, writable_cube_ids=[mem_cube_id], messages=conversations, async_mode="sync", # 在此示例中使用同步模式以便立即添加 ) add_handler.handle_add_memories(add_req) for item in questions: print("===== Chat Start =====") query = item["question"] print(f"Query:\n {query}\n") # 使用 chat_handler 进行聊天 chat_req = ChatPlaygroundRequest( user_id=user_id, query=query, readable_cube_ids=[mem_cube_id], writable_cube_ids=[mem_cube_id], ) response = chat_stream_playground(chat_req) answer = "" buffer = "" async for chunk in response.body_iterator: if isinstance(chunk, bytes): chunk = chunk.decode("utf-8") buffer += chunk while "\n\n" in buffer: msg, buffer = buffer.split("\n\n", 1) for line in msg.split("\n"): if line.startswith("data: "): json_str = line[6:] try: data = json.loads(json_str) if data.get("type") == "text": answer += data["data"] except json.JSONDecodeError: pass print(f"\nAnswer: {answer}") if __name__ == "__main__": mem_scheduler.register_handlers( { QUERY_TASK_LABEL: custom_query_handler, # 查询任务 MEM_UPDATE_TASK_LABEL: custom_mem_update_handler, # 记忆更新任务 } ) asyncio.run(run_with_scheduler()) time.sleep(20) mem_scheduler.stop() ``` > **Note**: **请注意** > 使用 dump() 和 load() 来持久化你的记忆立方体。 > > 务必确保你的向量数据库维度与你的嵌入器匹配。 > > 如使用基于图的明文记忆功能,你需要安装 Neo4j Desktop。 ## 下一步 你才刚刚开始!接下来可以尝试: - 选择与你使用场景匹配的示例。 - 组合模块以构建更智能、更持久的智能体! 还需要更多帮助? 查看 API 文档或贡献你自己的示例吧! --- # API 开发指南 (Component & Handler 架构) (/cn/open_source/modules/mos/overview) 这种架构将“系统的元件”(Components)与“业务逻辑的执行”(Handlers)分离开来,使得系统更易于扩展、测试和维护。 ## 1. 核心概念 ### 1.1 Components (核心组件) Components 是 MemOS 的各个“器官”,它们在服务器启动时被初始化(通过 `init_server()`),并在整个生命周期中复用。 核心组件包括: #### 核心记忆组件 1. **MemCube**: 记忆容器, 用于隔离不同用户/不同应用场景的记忆, 并统一管理多种记忆模块. 2. **MemReader**: 记忆加工器, 把用户输入的各类素材(聊天, 文档, 图片)解析为系统可写入的记忆片段. 3. **MemScheduler**: 后台调度器, 负责管理后台任务队列,将记忆的存储、索引、组织等耗时操作异步处理,支持多任务的并发执行. 4. **MemChat**: 对话控制器, 负责在对话过程中自动进行“记忆检索 -> 上下文管理 -> LLM 调度 -> 记忆更新”的对话闭环. 5. **MemFeedback**: 记忆纠错器,自动理解用户的自然语言反馈,精准定位冲突记忆并执行原子级修正(纠错/补充/替换). ### 1.2 Handlers (业务处理器) Handlers 是 MemOS 的“大脑”,它们封装了具体的业务逻辑(如添加、搜索、对话),通过调用和协调 Components (器官)的各项能力来完成具体的用户任务。 #### 核心 Handler 概览 | Handler | 作用 | 核心方法 | | :--- | :--- | :--- | | **AddHandler** | 添加记忆 (对话/文档/文本) | `handle_add_memories` | | **SearchHandler** | 搜索记忆 (语义检索) | `handle_search_memories` | | **ChatHandler** | 对话 (带记忆增强) | `handle_chat_complete`, `handle_chat_stream` | | **FeedbackHandler** | 反馈 (修正记忆/人工干预) | `handle_feedback_memories` | | **MemoryHandler** | 管理 (获取详情/删除) | `handle_get_memory`, `handle_delete_memories` | | **SchedulerHandler** | 调度 (查询异步任务状态) | `handle_scheduler_status`, `handle_scheduler_wait` | | **SuggestionHandler** | 建议 (生成推荐问题) | `handle_get_suggestion_queries` | ## 2. API 详解 ### 2.1 初始化 (Initialization) 初始化是系统启动的基石。所有 Handler 的运行都依赖于统一的组件注册与依赖注入机制。 - 组件加载 ( init_server ) : 系统启动时会初始化所有核心组件,包括 LLM(大语言模型)、存储层(向量数据库、图数据库)、调度器(Scheduler)以及各类 Memory Cube。 - 依赖注入 ( HandlerDependencies ) : 为了保证代码的解耦与可测试性,所有组件被统一封装到一个依赖容器(`HandlerDependencies`)中。当 Handler 启动时,只需接收这个容器,就能获取所需的 `naive_mem_cube`、`mem_reader`、`feedback_server` 等资源,而无需各自重复创建这些组件。 ### 2.2 添加记忆 (AddHandler) AddHandler 是大脑的"记忆接纳指令",负责将外部信息转化并写入系统记忆。它不仅负责接纳和转化各类信息,还能自动识别反馈并路由到专门的反馈处理流程。 - 核心功能 : - 多模态支持 : 能够处理用户对话、文档、图片等多种输入形式,统一转化为系统内部的记忆对象。 - 同步与异步模式 : 通过 `async_mode` 参数控制处理方式。**同步模式**("sync"):立即处理,调用者阻塞等待结果,适合调试;**异步模式**("async"):任务推入后台队列由 MemScheduler 并发处理,API 立即返回任务 ID,适合生产环境提升响应速度。 - 自动反馈路由 : 如果请求中标记了 `is_feedback=True`,Handler 会自动提取对话中的最后一条用户消息作为反馈内容,将其转发到 MemFeedback 处理,而不是作为普通新记忆添加。 - 多目标写入 : 支持向多个 MemCube 同时写入记忆。当指定多个目标 Cube 时,系统会并行处理所有写入任务;当仅有一个目标时,则使用轻量级的处理方式。 ### 2.3 搜索记忆 (SearchHandler) SearchHandler 是大脑的"记忆检索指令",提供基于语义的智能记忆查询能力,是实现 RAG(检索增强生成)的关键组件。 - 核心功能 : - 语义检索 : 利用向量嵌入(Embedding)技术,根据查询语句的语义相似度召回相关记忆,相比简单的关键词匹配,能更准确地理解用户意图。 - 灵活的搜索范围 : 支持指定检索的目标数据范围。例如,可以仅在特定用户的记忆库中搜索,也可以跨多个用户搜索共享的公开记忆,满足不同的隐私和业务需求。 - 多种检索模式 : 根据应用场景在速度和准确率之间灵活选择。**快速模式**适合实时性要求高的场景,**精细模式**适合追求高记忆精准度的场景,**混合模式**兼顾两者。 - 多步推理检索 : 对于复杂问题,支持引入深度推理能力,通过多轮理解和检索逐步逼近最相关的记忆。 ### 2.4 对话 (ChatHandler) ChatHandler 是大脑的"对话协调指令",负责将用户的对话需求转化为完整的业务流程。它不直接存储数据,而是通过协调其他 Handler 来完成端到端的对话任务。 - 核心功能 : - 流程编排 : 自动执行"记忆检索 → LLM 生成 → 记忆保存"的完整对话闭环。用户每次提问都能基于历史记忆获得更智能的回复,同时每一次对话都被沉淀为新的记忆,实现对话即学习。 - 上下文管理 : 负责处理 history (历史对话)与 query (当前问题)的拼接,确保 LLM 理解完整的对话语境,避免信息丢失。 - 多种交互模式 : 支持标准请求-响应模式( APIChatCompleteRequest )和流式响应(Stream)模式,标准模式适合简单问题,流式模式适合长文本回复,满足不同的前端交互需求。 - 消息推送(可选) : 支持在生成回复后自动将结果推送到第三方平台(如钉钉),实现多渠道集成。 ### 2.5 反馈与修正 (FeedbackHandler) FeedbackHandler 是大脑的"反馈纠正指令",负责理解用户对 AI 表现的自然语言反馈,自动精准定位并修正相关的记忆内容。 - 核心功能 : - 记忆修正 : 当用户指出 AI 的错误(如"会议地点不是北京是上海")时,Handler 会自动更新或标记相关的旧记忆。系统采用版本管理而非直接删除,保持修改历史的可追溯性。 - 正负反馈 : 支持用户通过点赞或点踩的方式标记特定记忆的质量。系统据此调整该记忆的权重和可信度,使后续检索更加准确。 - 精准定位 : 支持两种反馈方式。一种是基于对话历史自动定位冲突信息,另一种是用户直接指定具体的记忆来修正,提高反馈的有效性和准确度。 ### 2.6 记忆管理 (MemoryHandler) MemoryHandler 是大脑的"记忆管理指令",提供了对记忆数据的底层 CRUD(增删改查)能力,主要用于系统管理后台或数据清理等运维场景。 - 核心功能 : - 精细化管理 : 不同于 AddHandler 的业务级写入,此 Handler 允许通过记忆 ID 直接获取单条记忆的详细信息或执行物理删除。这种直接操作方式绕过了业务逻辑的包装,主要用于调试、审计或系统清理。 - 底层直通 : 某些管理操作需要直接与底层的记忆器官(naive_mem_cube)交互,以提供最高效和最低延迟的数据操作能力,满足系统运维的需求。 ### 2.7 任务调度状态 (SchedulerHandler) SchedulerHandler 是大脑的"任务监控指令",负责追踪系统中所有异步任务的实时执行状态,让用户能够了解后台任务的进度和结果。 - 核心功能 : - 状态追踪 : 配合 Redis 后端,追踪任务的实时状态(Queued 排队中, Running 执行中, Completed 已完成, Failed 已失败)。 - 结果获取 : 提供任务结果查询接口。当异步任务完成后,用户可以通过此接口获取最终的执行结果或错误信息,从而了解操作是否成功以及失败的原因。 - 同步等待(调试工具) : 在测试和集成测试时,提供将异步任务强制转为同步等待的工具,使开发者能够像调试同步代码一样调试异步流程,提高开发效率。 ### 2.8 猜你想问 (SuggestionHandler) SuggestionHandler 是大脑的"建议生成指令",通过预测用户的潜在需求,主动推荐相关问题,帮助用户探索系统能力和发现感兴趣的话题。 - 核心功能 : - 双模式生成 : - 基于对话的建议 : 当用户提供了最近的对话记录时,系统分析对话上下文,推断用户可能感兴趣的后续话题,生成 3 个相关的推荐问题。 - 基于用户画像的建议 : 当没有对话上下文时,系统从用户的近期记忆中推断其兴趣和状态,生成与用户最近生活或工作相关的推荐问题。这适合在对话开始或话题转换时使用。 - 多语言支持 : 推荐问题自动适配用户语言设置,支持中英文等多种语言,提升不同用户的体验。 --- # MemCube (/cn/open_source/modules/mem_cube) ## 什么是 MemCube? **MemCube** 是一个容器,包含了三种主要类型的记忆: - **明文记忆** (例如,`GeneralTextMemory`、`TreeTextMemory`): 用于存储和检索非结构化或结构化文本知识。 - **激活记忆** (例如,`KVCacheMemory`): 用于存储键值缓存以加速 LLM 推理和上下文重用。 - **参数化记忆** (例如,`LoRAMemory`): 用于存储模型适应参数(如 LoRA 权重)。 每种记忆都可以独立配置,根据应用需求灵活组合。 ## 结构 MemCube 由配置定义(参见 `GeneralMemCubeConfig`),该配置为每种记忆类型指定后端和配置。典型结构是: ``` MemCube ├── user_id ├── cube_id ├── text_mem: TextualMemory ├── act_mem: ActivationMemory └── para_mem: ParametricMemory ``` 所有记忆模块都可通过 MemCube 接口访问: - `mem_cube.text_mem` - `mem_cube.act_mem` - `mem_cube.para_mem` ## View 架构 从 MemOS 2.0 开始,运行时操作(add/search)应通过 **View 架构**: ### SingleCubeView 用于管理单个 MemCube。当系统只需要一个记忆空间时使用。 ```python from memos.multi_mem_cube.single_cube import SingleCubeView view = SingleCubeView( cube_id="my_cube", naive_mem_cube=naive_mem_cube, mem_reader=mem_reader, mem_scheduler=mem_scheduler, logger=logger, searcher=searcher, feedback_server=feedback_server, # 可选 ) # 添加记忆 view.add_memories(add_request) # 搜索记忆 view.search_memories(search_request) ``` ### CompositeCubeView 用于管理多个 MemCube。当需要跨多个记忆空间进行统一操作时使用。 ```python from memos.multi_mem_cube.composite_cube import CompositeCubeView # 创建多个 SingleCubeView view1 = SingleCubeView(cube_id="cube_1", ...) view2 = SingleCubeView(cube_id="cube_2", ...) # 用于多 cube 操作的组合视图 composite = CompositeCubeView(cube_views=[view1, view2], logger=logger) # 跨所有 cube 搜索 results = composite.search_memories(search_request) # 结果包含 cube_id 字段以标识来源 ``` ### API 请求字段 #### 添加记忆(add模式) | 字段 | 描述 | | --------------------- | ---------------------------------------------------------------- | | `writable_cube_ids` | add 操作的目标 cube | | `async_mode` | `"async"`(启用 scheduler 后台处理)或 `"sync"`(禁用 scheduler 同步处理) | #### 搜索记忆(search模式) | 字段 | 描述 | | --------------------- | ---------------------------------------------------------------- | | `readable_cube_ids` | search 操作的目标 cube | | `async_mode` | `"async"`(启用 scheduler 后台处理)或 `"sync"`(禁用 scheduler 同步处理) | ## 核心方法(GeneralMemCube) GeneralMemCube 是 MemCube 的标准实现,通过统一的接口管理系统的所有记忆。GeneralMemCube 提供以下核心方法来管理记忆数据的生命周期。 ### 初始化 ```python from memos.mem_cube.general import GeneralMemCube mem_cube = GeneralMemCube(config) ``` ### 静态数据操作 | 方法 | 描述 | | ----------------------------------------- | ----------------------------------------- | | `init_from_dir(dir)` | 从本地目录加载 MemCube | | `init_from_remote_repo(repo, base_url)` | 从远程仓库加载 MemCube(如 Hugging Face) | | `load(dir)` | 从目录加载所有记忆到现有实例 | | `dump(dir)` | 将所有记忆保存到目录以持久化 | ## 文件存储 MemCube 保存后的目录包含以下文件,每个文件对应一种记忆类型: - `config.json` (MemCube 配置) - `textual_memory.json` (明文记忆) - `activation_memory.pickle` (激活记忆) - `parametric_memory.adapter` (参数化记忆) ## 使用示例 ### 导出示例 (dump_cube.py) ```python import json import os import shutil from memos.api.handlers import init_server from memos.api.product_models import APIADDRequest from memos.log import get_logger from memos.multi_mem_cube.single_cube import SingleCubeView logger = get_logger(__name__) EXAMPLE_CUBE_ID = "example_dump_cube" EXAMPLE_USER_ID = "example_user" # 1. 初始化服务 components = init_server() naive = components["naive_mem_cube"] # 2. 创建 SingleCubeView view = SingleCubeView( cube_id=EXAMPLE_CUBE_ID, naive_mem_cube=naive, mem_reader=components["mem_reader"], mem_scheduler=components["mem_scheduler"], logger=logger, searcher=components["searcher"], feedback_server=components["feedback_server"], ) # 3. 通过 View 添加记忆 result = view.add_memories(APIADDRequest( user_id=EXAMPLE_USER_ID, writable_cube_ids=[EXAMPLE_CUBE_ID], messages=[ {"role": "user", "content": "This is a test memory"}, {"role": "user", "content": "Another memory to persist"}, ], async_mode="sync", # 使用同步模式确保立即完成 )) print(f"✓ Added {len(result)} memories") # 4. 导出特定 cube_id 的数据 output_dir = "tmp/mem_cube_dump" if os.path.exists(output_dir): shutil.rmtree(output_dir) os.makedirs(output_dir, exist_ok=True) # 导出图数据(仅导出当前 cube_id 的数据) json_data = naive.text_mem.graph_store.export_graph( include_embedding=True, # 包含 embedding 以支持语义搜索 user_name=EXAMPLE_CUBE_ID, # 按 cube_id 过滤 ) # 修复 embedding 格式:将字符串解析为列表以兼容导入 import contextlib for node in json_data.get("nodes", []): metadata = node.get("metadata", {}) if "embedding" in metadata and isinstance(metadata["embedding"], str): with contextlib.suppress(json.JSONDecodeError): metadata["embedding"] = json.loads(metadata["embedding"]) print(f"✓ Exported {len(json_data.get('nodes', []))} nodes") # 保存到文件 memory_file = os.path.join(output_dir, "textual_memory.json") with open(memory_file, "w", encoding="utf-8") as f: json.dump(json_data, f, indent=2, ensure_ascii=False) print(f"✓ Saved to: {memory_file}") ``` ### 导入与搜索示例 (load_cube.py) > **Embedding 兼容性说明**:示例数据使用 **bge-m3** 模型,维度为 **1024**。如果您的环境使用不同的 embedding 模型或维度,导入后的语义搜索可能不准确或失败。请确保您的 `.env` 配置与导出时的 embedding 配置一致。 ```python import json import os from memos.api.handlers import init_server from memos.api.product_models import APISearchRequest from memos.log import get_logger from memos.multi_mem_cube.single_cube import SingleCubeView logger = get_logger(__name__) EXAMPLE_CUBE_ID = "example_dump_cube" EXAMPLE_USER_ID = "example_user" # 1. 初始化服务 components = init_server() naive = components["naive_mem_cube"] # 2. 创建 SingleCubeView view = SingleCubeView( cube_id=EXAMPLE_CUBE_ID, naive_mem_cube=naive, mem_reader=components["mem_reader"], mem_scheduler=components["mem_scheduler"], logger=logger, searcher=components["searcher"], feedback_server=components["feedback_server"], ) # 3. 从文件加载数据到 graph_store load_dir = "examples/data/mem_cube_tree" memory_file = os.path.join(load_dir, "textual_memory.json") with open(memory_file, encoding="utf-8") as f: json_data = json.load(f) naive.text_mem.graph_store.import_graph(json_data, user_name=EXAMPLE_CUBE_ID) nodes = json_data.get("nodes", []) print(f"✓ Imported {len(nodes)} nodes") # 4. 显示加载的数据 print(f"\nLoaded {len(nodes)} memories:") for i, node in enumerate(nodes[:3], 1): # 显示前3条 metadata = node.get("metadata", {}) memory_text = node.get("memory", "N/A") mem_type = metadata.get("memory_type", "unknown") print(f" [{i}] Type: {mem_type}") print(f" Content: {memory_text[:60]}...") # 5. 语义搜索验证 query = "test memory dump persistence demonstration" print(f'\nSearching: "{query}"') search_result = view.search_memories( APISearchRequest( user_id=EXAMPLE_USER_ID, readable_cube_ids=[EXAMPLE_CUBE_ID], query=query, ) ) text_mem_results = search_result.get("text_mem", []) memories = [] for group in text_mem_results: memories.extend(group.get("memories", [])) print(f"✓ Found {len(memories)} relevant memories") for i, mem in enumerate(memories[:2], 1): # 显示前2条 print(f" [{i}] {mem.get('memory', 'N/A')[:60]}...") ``` ### 完整示例 参见代码仓库中的示例: - `MemOS/examples/mem_cube/dump_cube.py` - 导出 MemCube 数据(add + export) - `MemOS/examples/mem_cube/load_cube.py` - 导入 MemCube 数据并进行语义搜索(import + search) ### 旧 API 说明 早期版本中直接调用 `mem_cube.text_mem.get_all()` 的方式已废弃,请使用 View 架构。旧示例已移至 `MemOS/examples/mem_cube/_deprecated/`。 ## 开发者说明 * MemCube 强制执行模式一致性,确保安全的加载/转储 * 每种记忆类型都是可插拔的,支持独立测试 * 参见 `/tests/mem_cube/` 了解集成测试和使用模式 --- # MemReader (/cn/open_source/modules/mem_reader) ## 1. 简介 在构建 AI 应用时,我们经常遇到这样的问题:用户发来的东西千奇百怪——有的是随口的聊天,有的是 PDF 文档,有的是图片。**MemReader** 的作用就是把这些原始数据(Raw Data)“嚼碎”并“消化”,变成带有 Embedding 和元数据的标准记忆块(Memory Item)。 简单来说,它做三件事: 1. **归一化**:不管你发来的是字符串还是 JSON,先统一变成标准格式。 2. **切片 (Chunking)**:把长对话或长文档切成合适的小块,方便后续处理。 3. **精炼 (Extraction)**:调用 LLM 把非结构化的信息提取成结构化的知识点(Fine 模式),或者直接生成快照(Fast 模式)。 --- ## 2. 核心模式 MemReader 设计了两种工作模式,分别对应“快”和“准”两种需求: ### ⚡ Fast 模式(唯快不破) * **特点**:**不调用 LLM**,只做切片和 Embedding。 * **适用场景**: * 用户发消息飞快,系统需要毫秒级响应。 * 只需保留对话的“快照”,不需要深度理解。 * **产物**:原始文本片段 + 向量索引 + 来源追踪 (Sources)。 ### 🧠 Fine 模式(精雕细琢) * **特点**:**调用 LLM** 进行深度分析。 * **适用场景**: * 长时记忆写入(需要提取关键事实)。 * 文档分析(需要总结核心观点)。 * 多模态理解(需要看懂图片里的内容)。 * **产物**:结构化的事实 + 关键信息提取 (Key) + 背景 (Background) + 向量索引 + 来源追踪 (Sources) + 多模态细节。 --- ## 3. 代码结构 MemReader 的代码结构非常清晰,主要由以下几部分组成: * **`base.py`**: 定义了所有 Reader 必须遵守的接口规范。 * **`simple_struct.py`**: **最常用的实现**。专攻纯文本对话和本地文档,轻量高效。 * **`multi_modal_struct.py`**: **全能型选手**。能处理图片、文件 URL、Tool 调用等复杂输入。 * **`read_multi_modal/`**: 存放了各种具体的解析器(Parser),比如专门解析图片的 `ImageParser`,解析文件的 `FileParser` 等。 --- ## 4. 如何选择? | 你的需求 | 推荐选择 | 理由 | | :--- | :--- | :--- | | **只处理纯文本对话** | `SimpleStructMemReader` | 简单、直接、性能好。 | | **需要处理图片、文件链接** | `MultiModalStructMemReader` | 内置了多模态解析能力。 | | **需要从 Fast 升级到 Fine** | 任意 Reader 的 `fine_transfer` 方法 | 支持“先存后优”的渐进式策略。 | --- ## 5. API 概览 ### 统一工厂:`MemReaderFactory` 不要自己去 `new` 对象,使用工厂模式是最佳实践: ```python from memos.configs.mem_reader import MemReaderConfigFactory from memos.mem_reader.factory import MemReaderFactory # 从配置创建 Reader cfg = MemReaderConfigFactory.model_validate({...}) reader = MemReaderFactory.from_config(cfg) ``` ### 核心方法:`get_memory()` 这是你最常调用的方法。 ```python memories = reader.get_memory( scene_data, # 你的输入数据 type="chat", # 类型:chat 或 doc info=user_info, # 用户信息(user_id, session_id) mode="fine" # 模式:fast 或 fine(强烈建议显式指定!) ) ``` **返回结果**:`list[list[TextualMemoryItem]]` > **Note**: 为什么是双层列表? > 因为一个长对话可能会被切成多个窗口(Window),外层列表代表窗口,内层列表代表该窗口提取出的记忆项。 --- ## 6. 开发实战 ### 场景一:处理简单的聊天记录 这是最基础的用法,使用 `SimpleStructMemReader`。 ```python # 1. 准备输入:标准的 OpenAI 格式对话 conversation = [ [ {"role": "user", "content": "我明天下午 3 点有个会"}, {"role": "assistant", "content": "会议主题是什么?"}, {"role": "user", "content": "讨论 Q4 项目截止日期"}, ] ] # 2. 提取记忆 (Fine 模式) memories = reader.get_memory( conversation, type="chat", mode="fine", info={"user_id": "u1", "session_id": "s1"} ) # 3. 结果 # memories 里会包含提取出的事实,例如:"用户明天下午3点有关于Q4项目的会议" ``` ### 场景二:处理多模态输入 当用户发来图片或文件链接时,切换到 `MultiModalStructMemReader`。 ```python # 1. 准备输入:包含文件和图片的复杂消息 scene_data = [ [ { "role": "user", "content": [ {"type": "text", "text": "看看这个文件和图片"}, # 文件支持 URL 自动下载解析 {"type": "file", "file": {"file_data": "https://example.com/readme.md"}}, # 图片支持 URL {"type": "image_url", "image_url": {"url": "https://example.com/chart.png"}}, ] } ] ] # 2. 提取记忆 memories = multimodal_reader.get_memory( scene_data, type="chat", mode="fine", # 只有 Fine 模式才会调用视觉模型解析图片 info={"user_id": "u1", "session_id": "s1"} ) ``` ### 场景三:渐进式优化 (Fine Transfer) 为了用户体验,你可以先用 Fast 模式快速存下对话,等系统空闲时再把它“精炼”成 Fine 记忆。 ```python # 1. 先快速存(毫秒级) fast_memories = reader.get_memory(conversation, mode="fast", ...) # ... 存入数据库 ... # 2. 后台异步精炼 refined_memories = reader.fine_transfer_simple_mem( fast_memories_flat_list, # 注意这里传入的是展平后的 Item 列表 type="chat" ) # 3. 用 refined_memories 替换掉原来的 fast_memories ``` --- ## 7. 配置项说明 在 `.env` 或配置文件中,你可以调整以下关键参数: * **`chat_window_max_tokens`**: **滑窗大小**。默认 1024。决定了多少上下文会被打包在一起处理。设得太小容易丢失语境,设得太大容易超出 LLM 的 Token 限制。 * **`remove_prompt_example`**: **是否移除 Prompt 里的示例**。True = 省 Token 但可能降低提取质量;False = 保留示例提高准确度但消耗更多 Token(保留 Few-shot 示例)。 * **`direct_markdown_hostnames`** (仅多模态): **域名白名单**。列表中的域名(如 `raw.githubusercontent.com`)会被直接当作 Markdown 文本处理,跳过 OCR/格式转换步骤,加速处理。 --- # MemScheduler (/cn/open_source/modules/mem_scheduler) ## 主要特性 - 🚀 **与 MemOS 系统并发操作**:独立线程/进程运行,不阻塞主业务逻辑。 - 🧠 **多记忆协调**:智能管理工作记忆、长时记忆和用户个性化记忆的流转。 - ⚡ **事件驱动调度**:基于消息队列(Redis/Local)的异步任务分发机制。 - 🔍 **高效检索**:集成向量检索与图谱检索,快速定位相关记忆。 - 📊 **全面监控**:实时监控记忆使用率、任务队列状态和调度延迟。 - 📝 **详细日志记录**:全链路追踪记忆操作,便于调试和系统分析。 ## MemScheduler 架构 `MemScheduler` 采用模块化架构,分为三层: ### 调度层(核心) 1. **调度器(路由器)**:智能消息路由器,根据消息类型(`QUERY`, `ANSWER`, `MEM_UPDATE` 等)将任务分发给对应的处理器。 2. **消息处理**:通过带有特定标签(Label)的消息驱动业务逻辑,定义消息格式和处理规则。 ### 执行层(保障) 3. **任务队列**:支持 Redis Stream(生产环境)和 Local Queue(开发测试)两种模式,提供异步任务缓冲和持久化。 4. **记忆管理**:执行三层记忆(Working/Long-term/User)的读写、压缩、遗忘和类型转换。 5. **检索系统**:混合检索模块,结合用户意图、场景管理与关键词匹配,快速定位相关记忆。 ### 支撑层(辅助) 6. **监控**:跟踪任务积压、处理耗时和记忆库健康状态。 7. **日志记录**:维护全链路记忆操作日志,便于调试和分析。 ## MemScheduler 初始化 在 MemOS 的架构中,`MemScheduler` 是作为服务器组件的一部分在启动时被初始化的。 ### 在 Server Router 中初始化 在 `src/memos/api/routers/server_router.py` 中,调度器通过 `init_server()` 函数被自动加载: ```python from memos.api import handlers from memos.api.handlers.base_handler import HandlerDependencies from memos.mem_scheduler.base_scheduler import BaseScheduler from memos.mem_scheduler.utils.status_tracker import TaskStatusTracker # ... 其他导入 ... # 1. 初始化所有服务器组件 (包括 DB, LLM, Memory, Scheduler) # init_server() 会读取环境变量并初始化全局单例组件 components = handlers.init_server() # Create dependency container for handlers dependencies = HandlerDependencies.from_init_server(components) # Initialize handlers... # search_handler = SearchHandler(dependencies) # ... # 2. 从组件字典中获取调度器实例 # 调度器在 init_server 内部已经被初始化并启动(如果启用了的话) mem_scheduler: BaseScheduler = components["mem_scheduler"] # 3. 用户还可以在components中获取其他调度相关组件 (可选,用于自定义任务处理) # redis_client 用于直接操作 Redis 或监控任务状态 redis_client = components["redis_client"] # ... ``` ## 调度任务与数据模型 调度器通过消息驱动的方式分发和执行任务。本节介绍支持的任务类型、消息结构和执行日志。 ### 消息类型与处理器 调度器通过注册特定的任务标签(Label)与处理器(Handler)来分发和执行任务。以下是当前版本(基于 `GeneralScheduler` 和 `OptimizedScheduler`)默认支持的调度任务: | 消息标签 (Label) | 对应常量 | 处理器方法 | 描述 | | :--- | :--- | :--- | :--- | | `query` | `QUERY_TASK_LABEL` | `_query_message_consumer` | 处理用户查询,触发意图识别、记忆检索,并将其转换为记忆更新任务。 | | `answer` | `ANSWER_TASK_LABEL` | `_answer_message_consumer` | 处理 AI 回复,记录对话日志。 | | `mem_update` | `MEM_UPDATE_TASK_LABEL` | `_memory_update_consumer` | 核心任务。执行长时记忆的更新流程,包括提取 Query Keyword、更新 Monitor、检索相关记忆并替换工作记忆(Working Memory)。 | | `add` | `ADD_TASK_LABEL` | `_add_message_consumer` | 处理新记忆的添加日志记录(支持本地和云端日志)。 | | `mem_read` | `MEM_READ_TASK_LABEL` | `_mem_read_message_consumer` | 使用 `MemReader` 深度处理和导入外部记忆内容。 | | `mem_organize` | `MEM_ORGANIZE_TASK_LABEL` | `_mem_reorganize_message_consumer` | 触发记忆的重组和合并(Merge)操作。 | | `pref_add` | `PREF_ADD_TASK_LABEL` | `_pref_add_message_consumer` | 处理用户偏好记忆(Preference Memory)的提取和添加。 | | `mem_feedback` | `MEM_FEEDBACK_TASK_LABEL` | `_mem_feedback_message_consumer` | 处理用户反馈,用于修正记忆或强化偏好。 | | `api_mix_search` | `API_MIX_SEARCH_TASK_LABEL` | `_api_mix_search_message_consumer` | (OptimizedScheduler 特有) 执行异步混合搜索任务,结合快速检索与精细检索。 | ### 消息数据结构 (ScheduleMessageItem) 调度器使用统一的 `ScheduleMessageItem` 结构在队列中传递消息。 > **注意**:`mem_cube` 对象本身不直接包含在消息模型中,而是通过 `mem_cube_id` 在运行时由调度器解析。 | 字段 | 类型 | 描述 | 默认值/备注 | | :--- | :--- | :--- | :--- | | `item_id` | `str` | 消息唯一标识符 (UUID) | 自动生成 | | `user_id` | `str` | 关联的用户 ID | (必需) | | `mem_cube_id` | `str` | 关联的 Memory Cube ID | (必需) | | `label` | `str` | 任务标签 (如 `query`, `mem_update`) | (必需) | | `content` | `str` | 消息载荷 (通常为 JSON 字符串或文本) | (必需) | | `timestamp` | `datetime` | 消息提交时间 | 自动生成 (UTC now) | | `session_id` | `str` | 会话 ID,用于上下文隔离 | `""` | | `trace_id` | `str` | 链路追踪 ID,用于全链路日志关联 | 自动生成 | | `user_name` | `str` | 用户显示名称 | `""` | | `task_id` | `str` | 业务级任务 ID (用于关联多个消息) | `None` | | `info` | `dict` | 额外的自定义上下文信息 | `None` | | `stream_key` | `str` | (内部使用) Redis Stream 的键名 | `""` | ### 执行日志结构 (ScheduleLogForWebItem) 调度器会生成用于前端展示或持久化存储的结构化日志消息。 | 字段 | 类型 | 描述 | 备注 | | :--- | :--- | :--- | :--- | | `item_id` | `str` | 日志条目唯一标识符 | 自动生成 | | `task_id` | `str` | 关联的父任务 ID | 可选 | | `user_id` | `str` | 用户 ID | (必需) | | `mem_cube_id` | `str` | Memory Cube ID | (必需) | | `label` | `str` | 日志类别 (如 `addMessage`, `addMemory`) | (必需) | | `log_content` | `str` | 简短的日志描述文本 | (必需) | | `from_memory_type` | `str` | 源记忆区域 | 如 `UserInput`, `LongTermMemory` | | `to_memory_type` | `str` | 目标记忆区域 | 如 `WorkingMemory` | | `memcube_log_content` | `list[dict]` | 结构化的详细内容 | 包含具体的记忆文本、引用 ID 等 | | `metadata` | `list[dict]` | 记忆项元数据 | 包含置信度、状态、标签等 | | `status` | `str` | 任务状态 | 如 `completed`, `failed` | | `timestamp` | `datetime` | 日志创建时间 | 自动生成 | | `current_memory_sizes` | `MemorySizes` | 当前各区域记忆数量快照 | 用于监控面板展示 | | `memory_capacities` | `MemoryCapacities` | 各区域记忆容量限制 | 用于监控面板展示 | ## 调度功能示例 ### 1. 消息处理与自定义 Handler 调度器最强大的功能是支持注册自定义的消息处理器(Handler)。你可以定义特定类型的消息(如 `MY_CUSTOM_TASK`),并编写函数来处理它。 ```python import uuid from datetime import datetime # 1. 导入必要的类型定义和调度器实例 # 注意:mem_scheduler 需要从 server_router 导入,因为它是一个全局单例 from memos.api.routers.server_router import mem_scheduler from memos.mem_scheduler.schemas.message_schemas import ScheduleMessageItem # 定义一个自定义的任务标签 MY_TASK_LABEL = "MY_CUSTOM_TASK" # 定义处理器函数 def my_task_handler(messages: list[ScheduleMessageItem]): """ 处理自定义任务的函数 """ for msg in messages: print(f"⚡️ [Handler] 收到任务: {msg.item_id}") print(f"📦 内容: {msg.content}") # 在这里执行你的业务逻辑,例如:调用 LLM、写数据库、触发其他任务等 # 2. 注册处理器到调度器 # 这一步将您的自定义逻辑挂载到调度系统中 mem_scheduler.register_handlers({ MY_TASK_LABEL: my_task_handler }) # 3. 提交任务 task = ScheduleMessageItem( item_id=str(uuid.uuid4()), user_id="user_123", mem_cube_id="cube_001", label=MY_TASK_LABEL, content="这是一条测试消息", timestamp=datetime.now() ) # 如果调度器未启动,这里会直接放入队列等待处理(如果是 Redis 队列) # 或者在本地队列模式下可能需要先调用 mem_scheduler.start() mem_scheduler.submit_messages([task]) print(f"Task submitted: {task.item_id}") # 防止调度器主进程提前退出 time.sleep(10) ``` ### 2. Redis 队列 vs 本地队列 - **本地队列 (Local Queue)**: - **适用场景**:单元测试、简单的单机脚本。 - **特点**:速度快,但进程重启后数据丢失,不支持多进程/多实例共享。 - **配置**:`MOS_SCHEDULER_USE_REDIS_QUEUE=false` - **Redis 队列 (Redis Stream)**: - **适用场景**:生产环境、分布式部署。 - **特点**:数据持久化,支持消费者组(Consumer Group),允许多个调度器实例共同处理任务(负载均衡)。 - **配置**:`MOS_SCHEDULER_USE_REDIS_QUEUE=true` - **调试**:可以使用 `show_redis_status.py` 脚本查看队列堆积情况。 ## 综合应用场景 ### 场景 1: 基础对话流与记忆更新 以下是一个完善的示例,展示了如何初始化环境、注册自定义逻辑、模拟对话流以及触发记忆更新。 ```python import asyncio import json import os import sys import time from pathlib import Path # --- 环境准备 --- # 1. 设置项目根目录到 sys.path,确保能导入 memos 模块 FILE_PATH = Path(__file__).absolute() BASE_DIR = FILE_PATH.parent.parent.parent sys.path.insert(0, str(BASE_DIR)) # 2. 设置必要的环境变量 (模拟 .env 配置) os.environ["ENABLE_CHAT_API"] = "true" os.environ["MOS_ENABLE_SCHEDULER"] = "true" # 决定使用 Redis 还是 Local 队列 os.environ["MOS_SCHEDULER_USE_REDIS_QUEUE"] = "false" # --- 导入组件 --- # 注意:导入 server_router 会触发组件初始化,确保环境变量在此之前设置好 from memos.api.product_models import APIADDRequest, ChatPlaygroundRequest from memos.api.routers.server_router import ( add_handler, chat_stream_playground, mem_scheduler, # 这里的 mem_scheduler 已经是初始化好的单例 ) from memos.log import get_logger from memos.mem_scheduler.schemas.message_schemas import ScheduleMessageItem from memos.mem_scheduler.schemas.task_schemas import ( MEM_UPDATE_TASK_LABEL, QUERY_TASK_LABEL, ) logger = get_logger(__name__) # 全局变量用于演示记忆检索结果 working_memories = [] # --- 自定义处理器 --- def custom_query_handler(messages: list[ScheduleMessageItem]): """ 处理用户查询消息: 1. 打印查询内容 2. 将消息转换为 MEM_UPDATE 任务,触发记忆检索/更新流程 """ for msg in messages: print(f"\n[Scheduler 🟢] 收到用户查询: {msg.content}") # 复制消息并将标签改为 MEM_UPDATE,这是一种常见的“任务链”模式 new_msg = msg.model_copy(update={"label": MEM_UPDATE_TASK_LABEL}) # 提交新任务回调度器 mem_scheduler.submit_messages([new_msg]) def custom_mem_update_handler(messages: list[ScheduleMessageItem]): """ 处理记忆更新任务: 1. 使用检索器 (Retriever) 查找相关记忆 2. 更新全局的工作记忆列表 """ global working_memories search_args = {} top_k = 2 for msg in messages: print(f"[Scheduler 🔵] 正在为查询检索记忆...") # 调用核心检索功能 results = mem_scheduler.retriever.search( query=msg.content, user_id=msg.user_id, mem_cube_id=msg.mem_cube_id, mem_cube=mem_scheduler.current_mem_cube, top_k=top_k, method=mem_scheduler.search_method, search_args=search_args, ) # 模拟工作记忆的更新 working_memories.extend(results) working_memories = working_memories[-5:] # 保持最新的5条 for mem in results: # 打印检索到的记忆片段 print(f" ↳ [Memory Found]: {mem.memory[:50]}...") # --- 模拟业务数据 --- def get_mock_data(): """生成模拟对话数据""" conversations = [ {"role": "user", "content": "I just adopted a golden retriever puppy named Max."}, {"role": "assistant", "content": "That's exciting! Max is a great name."}, {"role": "user", "content": "He loves peanut butter treats but I am allergic to nuts."}, {"role": "assistant", "content": "Noted. Peanut butter for Max, no nuts for you."}, ] questions = [ {"question": "What is my dog's name?", "category": "Pet"}, {"question": "What am I allergic to?", "category": "Allergy"}, ] return conversations, questions # --- 主流程 --- async def run_demo(): print("==== MemScheduler Demo Start ====") conversations, questions = get_mock_data() user_id = "demo_user_001" mem_cube_id = "cube_demo_001" print(f"1. 初始化用户记忆库 ({user_id})...") # 使用 API Handler 添加初始记忆 (同步模式) add_req = APIADDRequest( user_id=user_id, writable_cube_ids=[mem_cube_id], messages=conversations, async_mode="sync", ) add_handler.handle_add_memories(add_req) print(" 记忆添加完成。") print("\n2. 开始对话测试 (并在后台触发调度任务)...") for item in questions: query = item["question"] print(f"\n>> User: {query}") # 发起聊天请求 chat_req = ChatPlaygroundRequest( user_id=user_id, query=query, readable_cube_ids=[mem_cube_id], writable_cube_ids=[mem_cube_id], ) # 获取流式响应 response = chat_stream_playground(chat_req) # 处理流式输出 (简化版) full_answer = "" buffer = "" async for chunk in response.body_iterator: if isinstance(chunk, bytes): chunk = chunk.decode("utf-8") buffer += chunk while "\n\n" in buffer: msg, buffer = buffer.split("\n\n", 1) for line in msg.split("\n"): if line.startswith("data: "): try: data = json.loads(line[6:]) if data.get("type") == "text": full_answer += data["data"] except: pass print(f">> AI: {full_answer}") # 等待一小会儿让后台调度器处理任务并打印日志 await asyncio.sleep(1) if __name__ == "__main__": # 1. 注册我们的自定义 Handler # 这会覆盖或添加到默认的调度逻辑中 mem_scheduler.register_handlers( { QUERY_TASK_LABEL: custom_query_handler, MEM_UPDATE_TASK_LABEL: custom_mem_update_handler, } ) # 2. 确保调度器已启动 if not mem_scheduler._running: mem_scheduler.start() try: asyncio.run(run_demo()) except KeyboardInterrupt: pass finally: # 防止调度器主进程提前退出 time.sleep(10) print("\n==== 停止调度器 ====") mem_scheduler.stop() ``` ### 场景 2: 异步任务并发与断点重启 (Redis) 该示例展示了如何使用 Redis 队列实现异步任务的并发处理以及断点重启功能。运行此示例需要配置 Redis 环境。 ```python from pathlib import Path from time import sleep from memos.api.routers.server_router import mem_scheduler from memos.mem_scheduler.schemas.message_schemas import ScheduleMessageItem # 调试:打印调度器配置 print("=== Scheduler Configuration Debug ===") print(f"Scheduler type: {type(mem_scheduler).__name__}") print(f"Config: {mem_scheduler.config}") print(f"use_redis_queue: {mem_scheduler.use_redis_queue}") print(f"Queue type: {type(mem_scheduler.memos_message_queue).__name__}") print(f"Queue maxsize: {getattr(mem_scheduler.memos_message_queue, 'maxsize', 'N/A')}") print("=====================================\n") queue = mem_scheduler.memos_message_queue # 定义处理函数 def my_test_handler(messages: list[ScheduleMessageItem]): print(f"My test handler received {len(messages)} messages: {[one.item_id for one in messages]}") for msg in messages: # 根据 task_id 创建文件(使用 item_id 作为数字 ID 0..99) task_id = str(msg.item_id) file_path = tmp_dir / f"{task_id}.txt" try: sleep(5) file_path.write_text(f"Task {task_id} processed.\n") print(f"writing {file_path} done") except Exception as e: print(f"Failed to write {file_path}: {e}") def submit_tasks(): mem_scheduler.memos_message_queue.clear() # 创建 100 条消息(task_id 0..99) users = ["user_A", "user_B"] messages_to_send = [ ScheduleMessageItem( item_id=str(i), user_id=users[i % 2], mem_cube_id="test_mem_cube", label=TEST_HANDLER_LABEL, content=f"Create file for task {i}", ) for i in range(100) ] # 批量提交消息并打印完成信息 print(f"Submitting {len(messages_to_send)} messages to the scheduler...") mem_scheduler.memos_message_queue.submit_messages(messages_to_send) print(f"Task submission done! tasks in queue: {mem_scheduler.get_tasks_status()}") # 注册处理函数 TEST_HANDLER_LABEL = "test_handler" mem_scheduler.register_handlers({TEST_HANDLER_LABEL: my_test_handler}) # 5秒重启 mem_scheduler.orchestrator.tasks_min_idle_ms[TEST_HANDLER_LABEL] = 5_000 tmp_dir = Path("./tmp") tmp_dir.mkdir(exist_ok=True) # 测试停止并重启:如果 tmp 中已有 >1 个文件,跳过提交并打印信息 existing_count = len(list(Path("tmp").glob("*.txt"))) if Path("tmp").exists() else 0 if existing_count > 1: print(f"Skip submission: found {existing_count} files in tmp (>1), continue processing") else: submit_tasks() # 6. 等待直到 tmp 有 100 个文件或超时 poll_interval = 1 expected = 100 tmp_dir = Path("tmp") tasks_status = mem_scheduler.get_tasks_status() mem_scheduler.print_tasks_status(tasks_status=tasks_status) while ( mem_scheduler.get_tasks_status()["remaining"] != 0 or mem_scheduler.get_tasks_status()["running"] != 0 ): count = len(list(tmp_dir.glob("*.txt"))) if tmp_dir.exists() else 0 tasks_status = mem_scheduler.get_tasks_status() mem_scheduler.print_tasks_status(tasks_status=tasks_status) print(f"[Monitor] Files in tmp: {count}/{expected}") sleep(poll_interval) print(f"[Result] Final files in tmp: {len(list(tmp_dir.glob('*.txt')))})") # 7. 停止调度器 sleep(20) print("Stopping the scheduler...") mem_scheduler.stop() ``` --- # MemChat (/cn/open_source/modules/mem_chat) ## 1. 简介 **MemChat** 是 MemOS 的对话控制中心。 它不仅仅是一个聊天接口,更是连接“即时对话”与“长时记忆”的桥梁。在与用户交流的过程中,MemChat 负责实时地从 MemCube(记忆立方体)中检索相关背景信息,构建上下文,并将新的对话内容沉淀为新的记忆。通过它,你的 Agent 不再是“金鱼记忆”,而是能够真正理解过往、持续成长的智能伙伴。 --- ## 2. 核心能力 ### 记忆增强对话 (Memory-Augmented Chat) 在回答用户问题前,MemChat 会自动从 MemCube 中检索相关的 Textual Memory(文本记忆),将其注入到 Prompt 中。这使得 Agent 能够基于过往的交互历史或知识库来回答问题,而不仅仅依赖于 LLM 的预训练知识。 ### 自动记忆沉淀 (Auto-Memorization) 对话后,MemChat 会利用 Extractor LLM 自动从对话流中提取有价值的信息(如用户偏好、事实知识),并存储到 MemCube 中。无需用户手动干预,整个过程完全自动化。 ### 上下文管理 自动管理对话历史窗口 (`max_turns_window`)。当对话过长时,它会智能裁剪旧的上下文,同时依赖检索到的长期记忆来保持对话的连贯性,有效解决了 LLM Context Window 的限制问题。 ### 灵活配置 支持通过配置开关不同类型的记忆(文本记忆、激活记忆等),适应不同的应用场景。 --- ## 3. 代码结构 核心逻辑位于 `memos/src/memos/mem_chat/` 下。 * **`simple.py`**: **默认实现 (SimpleMemChat)**。这是一个开箱即用的 REPL(Read-Eval-Print Loop)实现,包含了完整的“检索 -> 生成 -> 存储”闭环逻辑。 * **`base.py`**: **接口定义 (BaseMemChat)**。定义了 MemChat 的基本行为,如 `run()` 和 `mem_cube` 属性。 * **`factory.py`**: **工厂类**。负责根据配置 (`MemChatConfig`) 实例化具体的 MemChat 对象。 --- ## 4. 关键接口 主要的交互入口是 `MemChat` 类(通常由 `MemChatFactory` 创建)。 ### 4.1 初始化 你需要先创建一个配置对象,然后通过工厂方法创建实例。创建后,必须将 `MemCube` 实例挂载到 `mem_chat.mem_cube` 上。 ### 4.2 `run()` 启动一个交互式的命令行对话循环。适合开发调试,它会处理用户输入、调用记忆检索、生成回复并打印。 ### 4.3 属性 * **`mem_cube`**: 关联的记忆立方体对象。MemChat 通过它来读写记忆。 * **`chat_llm`**: 用于生成回复的 LLM 实例。 --- ## 5. 工作流程 MemChat 的一轮对话循环通常包含以下步骤: 1. **接收输入 (Input)**: 获取用户的文本输入。 2. **记忆检索 (Recall)**: (如果开启 `enable_textual_memory`) 使用用户输入作为 Query,从 `mem_cube.text_mem` 中检索 Top-K 条相关记忆。 3. **构建提示词 (Prompt Construction)**: 将系统提示词、检索到的记忆、最近的对话历史 (History) 拼接成完整的 Prompt。 4. **生成回复 (Generation)**: 调用 `chat_llm` 生成回复。 5. **记忆提取与存储 (Memorization)**: (如果开启 `enable_textual_memory`) 将本轮对话 (User + Assistant) 发送给 `mem_cube` 的提取器,提取新记忆并存入数据库。 --- ## 6. 开发示例 下面是一个完整的代码示例,展示了如何配置 MemChat,并挂载一个基于 Qdrant 和 OpenAI 的 MemCube。 ### 6.1 代码实现 ```python import os import sys # 确保 src 模块可以被导入 sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "../../../src"))) from memos.configs.mem_chat import MemChatConfigFactory from memos.configs.mem_cube import GeneralMemCubeConfig from memos.mem_chat.factory import MemChatFactory from memos.mem_cube.general import GeneralMemCube def get_mem_chat_config() -> MemChatConfigFactory: """生成 MemChat 配置""" return MemChatConfigFactory.model_validate( { "backend": "simple", "config": { "user_id": "user_123", "chat_llm": { "backend": "openai", "config": { "model_name_or_path": os.getenv("MOS_CHAT_MODEL", "gpt-4o"), "temperature": 0.8, "max_tokens": 1024, "api_key": os.getenv("OPENAI_API_KEY"), "api_base": os.getenv("OPENAI_API_BASE"), }, }, "max_turns_window": 20, "top_k": 5, "enable_textual_memory": True, # 开启显式记忆 }, } ) def get_mem_cube_config() -> GeneralMemCubeConfig: """生成 MemCube 配置""" return GeneralMemCubeConfig.model_validate( { "user_id": "user03alice", "cube_id": "user03alice/mem_cube_tree", "text_mem": { "backend": "general_text", "config": { "cube_id": "user03alice/mem_cube_general", "extractor_llm": { "backend": "openai", "config": { "model_name_or_path": os.getenv("MOS_CHAT_MODEL", "gpt-4o"), "api_key": os.getenv("OPENAI_API_KEY"), "api_base": os.getenv("OPENAI_API_BASE"), }, }, "vector_db": { "backend": "qdrant", "config": { "collection_name": "user03alice_mem_cube_general", "vector_dimension": 1024, }, }, "embedder": { "backend": os.getenv("MOS_EMBEDDER_BACKEND", "universal_api"), "config": { "provider": "openai", "api_key": os.getenv("MOS_EMBEDDER_API_KEY", "EMPTY"), "model_name_or_path": os.getenv("MOS_EMBEDDER_MODEL", "bge-m3"), "base_url": os.getenv("MOS_EMBEDDER_API_BASE"), }, }, }, }, } ) def main(): print("Initializing MemChat...") mem_chat = MemChatFactory.from_config(get_mem_chat_config()) print("Initializing MemCube...") mem_cube = GeneralMemCube(get_mem_cube_config()) # 关键步骤:挂载记忆立方体 mem_chat.mem_cube = mem_cube print("Starting Chat Session...") try: mem_chat.run() finally: print("Saving memory cube...") mem_chat.mem_cube.dump("new_cube_path") if __name__ == "__main__": main() ``` --- ## 7. 配置说明 在配置 `MemChatConfigFactory` 时,以下参数至关重要: * **`user_id`**: 必填。用于标识当前对话的用户,确保记忆的隔离性。 * **`chat_llm`**: 对话模型配置。建议使用能力较强的模型(如 GPT-4o),以获得更好的回复质量和指令遵循能力。 * **`enable_textual_memory`**: `True` / `False`。是否开启文本记忆。如果开启,系统会在对话前进行检索,并在对话后进行存储。 * **`max_turns_window`**: 整数。对话历史保留的轮数。超过此限制的历史记录将被截断,从而依赖长期记忆来补充上下文。 * **`top_k`**: 整数。每次从记忆库中检索多少条最相关的记忆片段注入到 Prompt 中。 --- # MemFeedback (/cn/open_source/modules/mem_feedback) ## 1. 简介 **MemFeedback** 是 MemOS 的“后悔药”。 在长时记忆系统中,最头疼的往往不是“记不住”,而是“记错了改不掉”。当用户说“不,我的生日是明天”或者“把这个项目的代号改成 X”时,简单的 RAG 系统通常无能为力。 MemFeedback 能够听懂这些自然语言指令,自动去数据库里精准定位冲突的记忆,并执行原子级的修正操作(比如把旧记忆归档、写入新记忆)。通过它,你的 Agent 能够像人一样在交流中不断纠错和学习。 --- ## 2. 核心能力 它能处理四种常见的反馈场景: ### 纠错 (Correction) 用户指出事实错误。系统不会粗暴地删除旧数据,而是将其**归档 (Archive)**,并写入新数据。这样既修正了错误,又保留了版本历史(Traceability)。如果是正在进行的对话(WorkingMemory),则直接原地更新,保证上下文连贯。 ### 补充 (Addition) 如果用户只是补充了新信息,且与旧记忆不冲突,那就很简单——直接作为新节点存入记忆库。 ### 全局替换 (Keyword Replacement) 类似于 IDE 里的“全局重构”。比如用户说“把所有文档里的‘张三’都改成‘李四’”,系统会结合 Reranker 自动圈定受影响的文档范围,批量更新所有相关记忆。 ### 偏好进化 (Preference Evolution) 专门处理“我不吃香菜”、“我喜欢 Python”这类偏好。系统会记录下这个偏好产生的场景,不断丰富用户画像,让 Agent 越用越顺手。 --- ## 3. 代码结构 核心逻辑都在 `memos/src/memos/mem_feedback/` 下。 * **`simple_feedback.py`**: **推荐直接看这个**。它是官方封装好的版本,把 LLM、向量数据库、检索器都组装好了,开箱即用。 * **`feedback.py`**: 核心实现类 `MemFeedback`。脏活累活都在这儿:意图识别、冲突比对、安全风控。 * **`base.py`**: 接口定义。 * **`utils.py`**: 工具箱。 --- ## 4. 关键接口 主入口就一个:`process_feedback()`。通常在 RAG 流程结束、用户给出反馈后异步调用。 ### 4.1 输入参数 | 参数 | 说明 | | :--- | :--- | | `user_id` / `user_name` | 用户标识与 Cube ID。 | | `chat_history` | 对话历史,让 LLM 知道你们刚才聊了啥。 | | `feedback_content` | 用户说的那句反馈(比如“不对,是五点”)。 | | **`retrieved_memory_ids`** | **必填项(强烈建议)**。把上一轮 RAG 检索到的记忆 ID 传进来,相当于给了系统一个“靶子”,告诉它要修正哪条记忆。如果不传,系统得自己去海量记忆里重新搜,不仅慢,还容易改错。 | | `corrected_answer` | 是否顺便生成一句修正后的回复。 | ### 4.2 输出结果 返回一个字典,告诉你这次操作改了什么: * **`record`**: 数据库变更明细(比如 `{ "add": [...], "update": [...] }`)。 * **`answer`**: 给用户的自然语言回复。 --- ## 5. 工作流程 MemFeedback 的工作流程像是一个严谨的编辑部: 1. **审稿 (意图识别)**: 先看用户是在纠错、补充信息,还是在改名。 2. **定位 (召回)**: 找到要修改的那条记忆(如果你传了 ID,这步就省了)。 3. **校对 (比对)**: 让 LLM 仔细比对新旧信息,确定是完全新增 (ADD) 还是需要更新 (UPDATE)。 4. **风控 (安全检查)**: 防止 LLM 瞎改。比如 ID 对不对?是不是要把一篇长文档全删了?(会有阈值拦截)。 5. **出版 (写入)**: 最后执行图数据库操作,归档旧的,写入新的。 --- ## 6. 开发示例 这里有一份可运行的代码清单,展示了如何初始化服务、预置一个“错误记忆”,然后通过用户反馈将其修正。 ### 6.1 准备工作 首先,我们需要初始化 `SimpleMemFeedback` 服务。 ```python # 假设 llm, embedder, graph_db 等组件已通过 Factory 初始化完成 # 完整初始化代码请参考 examples/mem_feedback/example_feedback.py from memos.mem_feedback.simple_feedback import SimpleMemFeedback feedback_server = SimpleMemFeedback( llm=llm, embedder=embedder, graph_store=graph_db, memory_manager=memory_manager, mem_reader=mem_reader, searcher=searcher, reranker=mem_reranker, pref_mem=None, ) ``` ### 6.2 模拟场景与执行反馈 场景:系统错误地记住了“你喜欢苹果,不喜欢香蕉”,现在我们要纠正它。 ```python import json from memos.mem_feedback.utils import make_mem_item # 1. 模拟对话历史 # 用户问偏好,助手答错了 history = [ {"role": "user", "content": "我喜欢什么水果,不喜欢什么水果"}, {"role": "assistant", "content": "你喜欢苹果,不喜欢香蕉"}, ] # 2. 预置“错误记忆” # 我们手动往库里塞一条错误的事实 mem_text = "你喜欢苹果,不喜欢香蕉" # ... (省略 make_mem_item 的详细参数,见源码) ... memory_manager.add([make_mem_item(mem_text, ...)], ...) # 3. 用户反馈 feedback_content = "错了,实际上我喜欢的是山竹" print(f"Feedback Input: {feedback_content}") # 4. 执行修正 # MemFeedback 会发现冲突,把旧记忆归档,写入新记忆“喜欢山竹” res = feedback_server.process_feedback( ..., chat_history=history, feedback_content=feedback_content, ... ) # 5. 查看结果 print(json.dumps(res, indent=4)) ``` --- ## 7. 配置说明 要让 MemFeedback 转起来,你需要准备好以下组件的配置(通常在 `.env` 或 YAML 里): * **LLM (`extractor_llm`)**: 脑子要好使,建议用 GPT-4o 级别的模型。Temperature 设低点(比如 0),因为它要干的是逻辑分析,不需要太发散。 * **Embedder (`embedder`)**: 用于把新记忆变成向量。 * **GraphDB (`graph_db`)**: 记忆存在哪、怎么存,这两兄弟负责。 * **MemReader (`mem_reader`)**: 如果是纯新增的记忆,用它来解析。 --- --- # 记忆模块总览 (/cn/open_source/modules/memories/overview) # 为什么需要不同的记忆模块 记忆模块是赋予Agent“长期记忆”能力的核心组件。它不只是像数据库一样死板地存取数据,而是能够像人类一样,对信息进行自动化地提取、分类、关联和动态更新。通过选择不同的记忆模块,你可以让 Agent拥有不同能力。 ## 🎯 快速选择指南 > **Alert**: **不确定选哪个?** 跟随这个决策树: > - 🚀 **快速测试/演示:简单上手,无需额外软件** → [NaiveTextMemory](#naivetextmemory-简单明文记忆) > - 📝 **通用文本记忆:记住聊天内容或大量文档,并能根据语义搜索** → [GeneralTextMemory](#generaltextmemory-通用文本记忆) > - 👤 **用户偏好管理:专门针对用户画像设计** → [PreferenceTextMemory](#preferencetextmemory-偏好记忆) > - 🌳 **结构化知识图谱:数据之间有复杂的逻辑关联** → [TreeTextMemory](#treetextmemory-分层结构记忆) > - ⚡ **推理加速:访问量很大,希望回复能更平稳、响应更快** → [KVCacheMemory](#kvcachememory-激活记忆) --- ## 📚 记忆模块分类 ### 一、文本记忆系列 专注于存储和检索文本形式的记忆,适用于绝大多数应用场景。 #### NaiveTextMemory: 简单明文记忆 **适用场景:** 快速原型、演示、教学、小规模应用 **核心特性:** - ✅ 零依赖,纯内存存储 - ✅ 关键词匹配检索 - ✅ 极简 API,5 分钟上手 - ✅ 支持文件持久化 **局限性:** - ❌ 无向量语义搜索 - ❌ 不适合大规模数据 - ❌ 检索精度有限 📖 [查看文档](./naive_textual_memory) #### GeneralTextMemory: 通用文本记忆 **适用场景:** 会话代理、个人助理、知识管理系统 **核心特性:** - ✅ 基于向量的语义搜索 - ✅ 丰富的元数据支持(类型、时间、来源等) - ✅ 灵活的过滤和查询 - ✅ 适合中大规模应用 **技术要求:** - 需要向量数据库(Qdrant 等) - 需要 Embedding 模型 📖 [查看文档](./general_textual_memory) #### PreferenceTextMemory: 偏好记忆 **适用场景:** 个性化推荐、用户画像、智能助理 **核心特性:** - ✅ 自动识别显式和隐式偏好 - ✅ 偏好去重与冲突检测 - ✅ 按偏好类型、强度筛选 - ✅ 向量语义检索 **专用功能:** - 双重偏好提取(explicit/implicit) - 偏好强度评分 - 时间衰减支持 📖 [查看文档](./preference_textual_memory) #### TreeTextMemory: 分层结构记忆 **适用场景:** 知识图谱、复杂关系推理、多跳查询 **核心特性:** - ✅ 基于图数据库的结构化存储 - ✅ 支持层次关系和因果链 - ✅ 多跳推理能力 - ✅ 去重、冲突检测、记忆调度 **高级功能:** - 支持 MultiModal Reader(图片、URL、文件) - 支持互联网检索(BochaAI、Google、Bing) - 工作记忆替换机制 **技术要求:** - 需要图数据库(Neo4j 等) - 需要向量数据库和 Embedding 模型 📖 [查看文档](./tree_textual_memory) --- ### 二、专用记忆模块 针对特定场景优化的记忆系统。 #### KVCacheMemory: 激活记忆 **适用场景:** LLM 推理加速、高频背景知识复用 **核心特性:** - ⚡ 预计算 KV Cache,跳过重复编码 - ⚡ 大幅减少预填充阶段计算 - ⚡ 适合高吞吐量场景 **典型用例:** - 常见问题(FAQ)缓存 - 对话历史复用 - 领域知识预加载 **工作原理:** 稳定的文本记忆 → 预转换为 KV Cache → 推理时直接注入 📖 [查看文档](./kv_cache_memory) #### ParametricMemory: 参数化记忆 **状态:** 🚧 正在开发中 **设计目标:** - 将知识编码到模型权重(LoRA、专家模块) - 动态加载/卸载能力模块 - 支持多任务、多角色架构 **未来功能:** - 参数模块生成与压缩 - 版本控制与回滚 - 热插拔能力模块 📖 [查看文档](./parametric_memory) --- ### 三、图数据库后端 为 TreeTextMemory 提供图存储能力。 #### Neo4j Graph DB **推荐度:** ⭐⭐⭐⭐⭐ **特性:** - 完整的图数据库功能 - 支持向量增强检索 - 多租户架构(v0.2.1+) - 兼容社区版 📖 [查看文档](./neo4j_graph_db) #### Nebula Graph DB **特性:** - 分布式图数据库 - 高可用性 - 适合大规模部署 📖 [查看文档](./nebula_graph_db) #### PolarDB Graph DB **特性:** - 阿里云 PolarDB 图计算 - 云原生架构 - 企业级可靠性 📖 [查看文档](./polardb_graph_db) --- ## 🛠️ 使用场景推荐 ### 场景 1: 快速原型开发 **推荐:** [NaiveTextMemory](./naive_textual_memory) ```python from memos.memories import NaiveTextMemory memory = NaiveTextMemory() memory.add("用户喜欢喝咖啡") results = memory.search("咖啡") ``` ### 场景 2: 聊天机器人记忆 **推荐:** [GeneralTextMemory](./general_textual_memory) - 支持语义搜索 - 按时间、类型、来源过滤 - 适合对话历史管理 ### 场景 3: 个性化推荐系统 **推荐:** [PreferenceTextMemory](./preference_textual_memory) - 自动提取用户偏好 - 偏好冲突检测 - 强度评分与筛选 ### 场景 4: 知识图谱应用 **推荐:** [TreeTextMemory](./tree_textual_memory) - 多跳关系查询 - 层次结构管理 - 复杂推理场景 ### 场景 5: 高性能 LLM 服务 **推荐:** [KVCacheMemory](./kv_cache_memory) - FAQ 系统 - 客服机器人 - 大批量请求处理 --- ## 🔗 高级功能 ### MultiModal Reader(多模态读取) 在 TreeTextMemory 中支持处理: - 对话中的图片 - 网页 URL - 本地文件(PDF、DOCX、TXT、Markdown) - 混合模式(文本+图片+URL) 👉 [查看示例](./tree_textual_memory#使用-multimodalstructmemreader高级) ### Internet Retrieval(互联网检索) 从网络获取实时信息并添加到记忆: - BochaAI 搜索 - Google 搜索 - Bing 搜索 👉 [查看示例](./tree_textual_memory#从互联网检索记忆可选) --- --- # KVCacheMemory: 激活记忆 (/cn/open_source/modules/memories/kv_cache_memory) ## KV Cache记忆使用案例 在MemOS中,KV Cache最适合存储**语义稳定且经常复用的背景信息**,例如: - 常见问题(FAQs)或特定领域知识 - 先前的对话历史 这些稳定的**明文记忆项**由`MemScheduler`模块自动识别和管理。一旦被选中,它们就会被提前转换成KV格式的表示(`KVCacheItem`)。这个预计算步骤以可复用的格式存储记忆的激活状态(键值对张量),允许它们在推理期间注入到模型的注意力缓存中。 一旦进行转换,这些KV记忆就可以**跨查询复用**,而不需要对原始内容重新编码。这减少了处理和存储大量文本的计算开销,使其成为需要**快速响应时间**和**高吞吐量**的应用程序的理想选择。 ## 为什么是KV Cache记忆 将`MemScheduler`与KV Cache记忆集成可以实现显著的性能优化,特别是在LLM推理的**预填充阶段**。 ### 无KV Cache记忆 - 每个新查询都被添加到完整的提示模板中,包括背景知识。 - 模型必须在整个序列上**重新计算token嵌入和注意力**——即使是未更改的记忆。 ### 有KV Cache记忆 - 背景知识以键值对张量的形式**缓存一次**。 - 对于每个查询,只对新用户输入(查询token)进行编码。 - 之前缓存的KV被直接注入到注意力机制中。 ### 好处 这种分离减少了预填充阶段的冗余计算,从而导致: - 跳过背景知识的重复编码 - 更快的查询token和缓存记忆之间的注意力计算 - **降低首次token时间(Time To First Token, TTFT)** 生成过程中的延迟 这种优化在以下方面特别有价值: - 多回合聊天机器人交互 - 检索增强生成或上下文增强生成(RAG, CAG) - 在固定文档或FAQ风格记忆上操作的助理 ### KV Cache记忆加速评估 为了验证基于KV的记忆注入对性能的影响,我们进行了一组在MemOS中模拟真实记忆复用的对照实验。 #### 实验建立 在典型的使用中,`MemScheduler`模块持续跟踪交互模式,并将高频、稳定的明文记忆提升为KV格式。这些KV记忆作为激活缓存加载到GPU内存中,并在推理过程中重复使用。 评估比较两种记忆策略: 1. **基于提示的注入**: 背景知识被作为原始文本添加 2. **KV Cache注入**: 记忆被直接注入到模型的注意力缓存 我们对这些策略进行了测试: - **三种文本长度**: 短文本, 中等长度文本和长文本 - **三种查询类型**: 短查询, 中等查询和长查询 主要指标是**首次token时间(TTFT)**,这是响应式生成的关键延迟指标。 #### 实验结果 下表显示了跨三个模型的结果(Qwen3-8B, Qwen3-32B, Qwen2.5-72B).KV Cache注入下的TTFT始终低于基于提示的注入,而两种策略的输出token保持一致. > **Note**: `Build (s)`是指将记忆转换为KV格式的一次性预处理成本,分摊到多个查询中. | Model | Ctx | CtxTok | Qry | QryTok | Build (s) | KV TTFT (s) | Dir TTFT (s) | Speedup (%) | | ----------- | ------ | ------ | ------ | ------ | --------- | ----------- | ------------ | ----------- | | Qwen3-8B | long | 6064 | long | 952.7 | 0.92 | 0.50 | 2.37 | 79.1 | | | | | medium | 302.7 | 0.93 | 0.19 | 2.16 | 91.1 | | | | | short | 167 | 0.93 | 0.12 | 2.04 | 94.2 | | | medium | 2773 | long | 952.7 | 0.41 | 0.43 | 1.22 | 64.6 | | | | | medium | 302.7 | 0.41 | 0.16 | 1.08 | 85.1 | | | | | short | 167 | 0.43 | 0.10 | 0.95 | 89.7 | | | short | 583 | long | 952.7 | 0.12 | 0.39 | 0.51 | 23.0 | | | | | medium | 302.7 | 0.12 | 0.14 | 0.32 | 55.6 | | | | | short | 167 | 0.12 | 0.08 | 0.29 | 71.3 | | Qwen3-32B | long | 6064 | long | 952.7 | 0.71 | 0.31 | 1.09 | 71.4 | | | | | medium | 302.7 | 0.71 | 0.15 | 0.98 | 84.3 | | | | | short | 167 | 0.71 | 0.11 | 0.96 | 88.8 | | | medium | 2773 | long | 952.7 | 0.31 | 0.24 | 0.56 | 56.9 | | | | | medium | 302.7 | 0.31 | 0.12 | 0.47 | 75.1 | | | | | short | 167 | 0.31 | 0.08 | 0.44 | 81.2 | | | short | 583 | long | 952.7 | 0.09 | 0.20 | 0.24 | 18.6 | | | | | medium | 302.7 | 0.09 | 0.09 | 0.15 | 39.6 | | | | | short | 167 | 0.09 | 0.07 | 0.14 | 53.5 | | Qwen2.5-72B | long | 6064 | long | 952.7 | 1.26 | 0.48 | 2.04 | 76.4 | | | | | medium | 302.7 | 1.26 | 0.23 | 1.82 | 87.2 | | | | | short | 167 | 1.27 | 0.15 | 1.79 | 91.4 | | | medium | 2773 | long | 952.7 | 0.58 | 0.39 | 1.05 | 62.7 | | | | | medium | 302.7 | 0.58 | 0.18 | 0.89 | 79.2 | | | | | short | 167 | 0.71 | 0.23 | 0.82 | 71.6 | | | short | 583 | long | 952.7 | 0.16 | 0.33 | 0.43 | 23.8 | | | | | medium | 302.7 | 0.16 | 0.15 | 0.27 | 43.2 | | | | | short | 167 | 0.16 | 0.10 | 0.25 | 60.5 | #### 基于 vLLM 的性能表现 MemOS 现在支持使用 vLLM 管理激活内存。为了评估KV Cache预存不同长度的前缀文本带来的影响,我们在一个配备 8 张 `H800 80GB GPU(112 vCPU,1920 GiB 内存)`的系统,以及一个配备 8张 `RTX4090-24G-PCIe(112 vCPU,960 GiB 内存)` 的系统上分别进行了性能测试。评估覆盖了当前两种核心模型:Qwen3-32B 和 Qwen2.5-72B。 基准测试在一系列记忆和上下文长度组合下运行,以模拟各种激活内存场景: - **记忆文本长度(tokens)**:500、1000、2000 - **上下文文本长度(tokens)**:500、1000、2000、4000 下表总结了基准测试结果。 **Qwen2.5-72B** - On 4090(2 Nodes 16 GPUs) | mem tks | prompt tks | TTFT (without cache, ms) | TTFT (With cache, ms) | TTFT Speedup (%) | Abs Dis(ms) | | ------- | ---------- | ------------------------ | --------------------- | ---------------- | ----------- | | 0.5k | 0.5k | 1787.21 | 851.47 | 52.358% | 935.74 | | 0.5k | 1k | 2506.26 | 1290.68 | 48.502% | 1215.58 | | 0.5k | 2k | 3843.48 | 2897.97 | 24.600% | 945.51 | | 0.5k | 4k | 6078.01 | 5200.86 | 14.432% | 877.15 | | 1k | 0.5k | 2274.61 | 920.16 | 59.546% | 1354.45 | | 1k | 1k | 2907.17 | 1407.65 | 51.580% | 1499.52 | | 1k | 2k | 4278.53 | 2916.47 | 31.835% | 1362.06 | | 1k | 4k | 6897.99 | 5218.94 | 24.341% | 1679.05 | | 2k | 0.5k | 3460.12 | 782.73 | 77.379% | 2677.39 | | 2k | 1k | 4443.34 | 1491.24 | 66.439% | 2952.10 | | 2k | 2k | 5733.14 | 2758.48 | 51.885% | 2974.66 | | 2k | 4k | 8152.76 | 5627.41 | 30.975% | 2525.35 | - On H800(4 GPUs) | mem tks | prompt tks | TTFT (without cache, ms) | TTFT (With cache, ms) | TTFT Speedup (%) | Abs Dis(ms) | | ------- | ---------- | ------------------------ | --------------------- | ---------------- | ----------- | | 0.5k | 0.5k | 51.65 | 52.17 | -1.007% | -0.52 | | 0.5k | 1k | 55.70 | 57.03 | -2.388% | -1.33 | | 0.5k | 2k | 74.23 | 78.56 | -5.833% | -4.33 | | 0.5k | 4k | 77.56 | 77.45 | 0.142% | 0.11 | | 1k | 0.5k | 55.90 | 55.73 | 0.304% | 0.17 | | 1k | 1k | 55.35 | 52.89 | 4.444% | 2.46 | | 1k | 2k | 80.14 | 73.82 | 7.886% | 6.32 | | 1k | 4k | 82.83 | 73.51 | 11.252% | 9.32 | | 2k | 0.5k | 75.82 | 71.31 | 5.948% | 4.51 | | 2k | 1k | 80.60 | 78.71 | 2.345% | 1.89 | | 2k | 2k | 83.91 | 78.60 | 6.328% | 5.31 | | 2k | 4k | 99.15 | 80.12 | 19.193% | 19.03 | **Qwen3-32B** - On 4090(1 Nodes 8 GPUs) | mem tks | prompt tks | TTFT (without cache, ms) | TTFT (With cache, ms) | TTFT Speedup (%) | Abs Dis(ms) | | ------- | ---------- | ------------------------ | --------------------- | ---------------- | ----------- | | 0.5k | 0.5k | 288.72 | 139.29 | 51.756% | 149.43 | | 0.5k | 1k | 428.72 | 245.85 | 42.655% | 182.87 | | 0.5k | 2k | 683.65 | 538.59 | 21.218% | 145.06 | | 0.5k | 4k | 1170.48 | 986.94 | 15.681% | 183.54 | | 1k | 0.5k | 409.83 | 137.96 | 66.337% | 271.87 | | 1k | 1k | 507.95 | 262.21 | 48.379% | 245.74 | | 1k | 2k | 743.48 | 539.71 | 27.408% | 203.77 | | 1k | 4k | 1325.34 | 1038.59 | 21.636% | 286.75 | | 2k | 0.5k | 686.01 | 147.34 | 78.522% | 538.67 | | 2k | 1k | 762.96 | 246.22 | 67.728% | 516.74 | | 2k | 2k | 1083.93 | 498.05 | 54.051% | 585.88 | | 2k | 4k | 1435.39 | 1053.31 | 26.619% | 382.08 | - On H800(2 GPUs) | mem tks | prompt tks | TTFT (without cache, ms) | TTFT (With cache, ms) | TTFT Speedup (%) | Abs Dis(ms) | | ------- | ---------- | ------------------------ | --------------------- | ---------------- | ----------- | | 0.5k | 0.5k | 161.18 | 97.61 | 39.440% | 63.57 | | 0.5k | 1k | 164.00 | 121.39 | 25.982% | 42.61 | | 0.5k | 2k | 257.34 | 215.20 | 16.375% | 42.14 | | 0.5k | 4k | 365.14 | 317.95 | 12.924% | 47.19 | | 1k | 0.5k | 169.45 | 100.52 | 40.679% | 68.93 | | 1k | 1k | 180.91 | 128.25 | 29.108% | 52.66 | | 1k | 2k | 271.69 | 210.00 | 22.706% | 61.69 | | 1k | 4k | 389.30 | 314.64 | 19.178% | 74.66 | | 2k | 0.5k | 251.43 | 130.92 | 47.930% | 120.51 | | 2k | 1k | 275.81 | 159.60 | 42.134% | 116.21 | | 2k | 2k | 331.11 | 218.17 | 34.110% | 112.94 | | 2k | 4k | 451.06 | 334.80 | 25.775% | 116.26 | 结果清楚地表明,集成 vLLM 的 KV 缓存重用功能为 MemOS 带来了革命性的性能提升。 ## KV Cache的记忆结构 通过`KVCacheMemory`实现基于KV的记忆复用,在保持相同输出的同时,大大减少了模型大小和查询类型之间的延迟。通过将可复用记忆从明文提示转移到预先计算的KV Cache,MemOS消除了冗余的上下文编码,并实现了更快的响应时间,特别是在实时的、记忆增强的LLM应用程序中。 每个缓存被存储为一个`KVCacheItem`: | 字段 | 类型 | 描述 | | ------------- | -------------- | ------------------------------------------- | | `kv_cache_id` | `str` | 缓存中的唯一ID(UUID) | | `kv_cache` | `DynamicCache` | 实际的KV Cache(transformers) | | `metadata` | `dict` | 元数据 (源, 抽取时间等.) | ## API总结 (`KVCacheMemory`) ### 初始化 ```python KVCacheMemory(config: KVCacheMemoryConfig) ``` ### 核心方法 | 方法 | 描述 | | ------------------------ | -------------------------------------------------------- | | `extract(text)` | 使用LLM从输入文本中提取KV Cache | | `add(memories)` | 添加一个或多个`KVCacheItem`到记忆中 | | `get(memory_id)` | 根据ID获取单个缓存 | | `get_by_ids(ids)` | 根据IDs获取多个缓存 | | `get_all()` | 返回所有存储的缓存 | | `get_cache(cache_ids)` | 从多个IDs合并并返回组合缓存 | | `delete(ids)` | 通过IDs删除缓存 | | `delete_all()` | 删除所有缓存 | | `dump(dir)` | 将所有缓存序列化到目录中的pickle文件 | | `load(dir)` | 从目录中的pickle文件加载缓存 | | `from_textual_memory(mem)` | 将`TextualMemoryItem` 转换为 `KVCacheItem` | 当调用`dump(dir)`, 系统写到: ``` / ``` 该文件包含所有KV Cache的pickle字典,可以使用`load(dir)`重新加载。 ## 如何使用 ### HF KVCache Memory ```python import json from transformers import DynamicCache from memos.configs.memory import MemoryConfigFactory from memos.memories.activation.item import KVCacheItem from memos.memories.factory import MemoryFactory def get_cache_info(cache): if not cache: return None num_layers = 0 total_size_bytes = 0 if hasattr(cache, "layers"): num_layers = len(cache.layers) for layer in cache.layers: if hasattr(layer, "key_cache") and layer.key_cache is not None: total_size_bytes += layer.key_cache.nelement() * layer.key_cache.element_size() if hasattr(layer, "value_cache") and layer.value_cache is not None: total_size_bytes += layer.value_cache.nelement() * layer.value_cache.element_size() if hasattr(layer, "keys") and layer.keys is not None: total_size_bytes += layer.keys.nelement() * layer.keys.element_size() if hasattr(layer, "values") and layer.values is not None: total_size_bytes += layer.values.nelement() * layer.values.element_size() elif hasattr(cache, "key_cache") and hasattr(cache, "value_cache"): num_layers = len(cache.key_cache) for k, v in zip(cache.key_cache, cache.value_cache, strict=False): if k is not None: total_size_bytes += k.nelement() * k.element_size() if v is not None: total_size_bytes += v.nelement() * v.element_size() return { "num_layers": num_layers, "size_bytes": total_size_bytes, "size_mb": f"{total_size_bytes / (1024 * 1024):.2f} MB", } def serialize_item(obj): if isinstance(obj, list): return [serialize_item(x) for x in obj] if isinstance(obj, KVCacheItem): return { "id": obj.id, "metadata": obj.metadata, "records": obj.records.model_dump() if hasattr(obj.records, "model_dump") else obj.records, "memory": get_cache_info(obj.memory), } if isinstance(obj, DynamicCache): return get_cache_info(obj) return str(obj) if __name__ == "__main__": # ===== 示例:使用工厂和 HFLLM 构建及管理 KVCacheMemory ===== # 1. 创建 KVCacheMemory 配置(使用 HuggingFace 后端) config = MemoryConfigFactory( backend="kv_cache", config={ "extractor_llm": { "backend": "huggingface", "config": { "model_name_or_path": "Qwen/Qwen3-0.6B", # 使用有效的 HuggingFace 模型名称 "max_tokens": 32, "add_generation_prompt": True, "remove_think_prefix": True, }, }, }, ) # 2. 使用工厂实例化 KVCacheMemory kv_mem = MemoryFactory.from_config(config) # 3. 从提示中提取 KVCacheItem (DynamicCache)(内部使用 HFLLM.build_kv_cache) prompt = [ {"role": "user", "content": "What is MemOS?"}, {"role": "assistant", "content": "MemOS is a memory operating system for LLMs."}, ] print("===== Extract KVCacheItem =====") cache_item = kv_mem.extract(prompt) print(json.dumps(serialize_item(cache_item), indent=2, default=str)) print() # 4. 添加提取的 KVCacheItem print("===== Add KVCacheItem =====") kv_mem.add([cache_item]) print(json.dumps(serialize_item(kv_mem.get_all()), indent=2, default=str)) print() # 5. 根据 ID 获取 print("===== Get KVCacheItem by id =====") retrieved = kv_mem.get(cache_item.id) print(json.dumps(serialize_item(retrieved), indent=2, default=str)) print() # 6. 合并缓存(使用两个项目进行模拟) print("===== Merge DynamicCache =====") item2 = kv_mem.extract([{"role": "user", "content": "Tell me a joke."}]) kv_mem.add([item2]) merged_cache = kv_mem.get_cache([cache_item.id, item2.id]) print(json.dumps(serialize_item(merged_cache), indent=2, default=str)) print() # 7. 删除一个 print("===== Delete one KVCacheItem =====") kv_mem.delete([cache_item.id]) print(json.dumps(serialize_item(kv_mem.get_all()), indent=2, default=str)) print() # 8. 转储和加载 print("===== Dump and Load KVCacheMemory =====") kv_mem.dump("tmp/kv_mem") print("Memory dumped to 'tmp/kv_mem'.") kv_mem.delete_all() kv_mem.load("tmp/kv_mem") print( "Memory loaded from 'tmp/kv_mem':", json.dumps(serialize_item(kv_mem.get_all()), indent=2, default=str), ) ``` ### VLLM KVCache Memory ```python #!/usr/bin/env python3 """ 演示如何使用带有 vLLM 后端的 VLLMKVCacheMemory 的示例。 此示例展示了如何使用新的兼容 vLLM 的 KV cache 记忆。 """ from memos.configs.memory import MemoryConfigFactory from memos.memories.factory import MemoryFactory def main(): """演示 VLLMKVCacheMemory 用法的主函数。""" print("=== VLLM KV Cache Memory Example ===\n") # 1. 创建 VLLMKVCacheMemory 配置(使用 vLLM 后端) config = MemoryConfigFactory( backend="vllm_kv_cache", # 使用新的 vLLM KV cache 后端 config={ "extractor_llm": { "backend": "vllm", "config": { "model_name_or_path": "Qwen/Qwen3-0.6B", "api_base": "http://localhost:8088/v1", "temperature": 0.7, "max_tokens": 1024, "model_schema": "memos.configs.llm.VLLMLLMConfig", }, }, }, ) # 2. 使用工厂实例化 VLLMKVCacheMemory print("Initializing VLLM KV Cache Memory...") vllm_kv_mem = MemoryFactory.from_config(config) print("✓ VLLM KV Cache Memory initialized successfully.\n") # 3. 从提示中提取 VLLMKVCacheItem print("===== Extract VLLMKVCacheItem =====") system_prompt = [ {"role": "system", "content": "You are a helpful AI assistant."}, {"role": "user", "content": "What is MemOS?"}, {"role": "assistant", "content": "MemOS is a memory operating system for LLMs."}, ] try: cache_item = vllm_kv_mem.extract(system_prompt) print("✓ KV cache item extracted successfully") print(f" ID: {cache_item.id}") print(f" Memory (prompt): {cache_item.memory[:100]}...") print(f" Metadata: {cache_item.metadata}") print() except Exception as e: print(f"✗ Failed to extract KV cache item: {e}") return # 4. 添加提取的 VLLMKVCacheItem print("===== Add VLLMKVCacheItem =====") vllm_kv_mem.add([cache_item]) all_items = vllm_kv_mem.get_all() print(f"✓ Added cache item. Total items: {len(all_items)}") print() # 5. 根据 ID 获取 print("===== Get VLLMKVCacheItem by id =====") retrieved = vllm_kv_mem.get(cache_item.id) if retrieved: print(f"✓ Retrieved cache item: {retrieved.id}") print(f" Memory (prompt): {retrieved.memory[:100]}...") else: print("✗ Failed to retrieve cache item") print() # 6. 获取缓存(返回 vLLM 的提示字符串) print("===== Get Cache (Prompt String) =====") prompt_string = vllm_kv_mem.get_cache([cache_item.id]) if prompt_string: print(f"✓ Retrieved prompt string: {prompt_string[:100]}...") print(" This prompt can be used for vLLM generation with preloaded KV cache") else: print("✗ Failed to retrieve prompt string") print() # 7. 提取另一个缓存项进行演示 print("===== Extract Another VLLMKVCacheItem =====") another_prompt = [ {"role": "system", "content": "You are a coding assistant."}, {"role": "user", "content": "Write a Python function to calculate fibonacci numbers."}, ] try: cache_item2 = vllm_kv_mem.extract(another_prompt) vllm_kv_mem.add([cache_item2]) print(f"✓ Added second cache item. Total items: {len(vllm_kv_mem.get_all())}") print() except Exception as e: print(f"✗ Failed to extract second KV cache item: {e}") print() # 8. 在 vLLM 服务器上预加载 KV cache print("===== Preload KV Cache on vLLM Server =====") try: vllm_kv_mem.preload_kv_cache([cache_item.id, cache_item2.id]) print("✓ KV cache preloaded on vLLM server successfully") print(" The server now has the KV cache ready for fast generation") except Exception as e: print(f"✗ Failed to preload KV cache: {e}") print() # 9. 删除一个项目 print("===== Delete One VLLMKVCacheItem =====") vllm_kv_mem.delete([cache_item.id]) remaining_items = vllm_kv_mem.get_all() print(f"✓ Deleted cache item. Remaining items: {len(remaining_items)}") print() # 10. 转储和加载 print("===== Dump and Load VLLMKVCacheMemory =====") try: vllm_kv_mem.dump("tmp/vllm_kv_mem") print("✓ Memory dumped to 'tmp/vllm_kv_mem'") # 清除记忆并重新加载 vllm_kv_mem.delete_all() vllm_kv_mem.load("tmp/vllm_kv_mem") reloaded_items = vllm_kv_mem.get_all() print(f"✓ Memory loaded from 'tmp/vllm_kv_mem': {len(reloaded_items)} items") except Exception as e: print(f"✗ Failed to dump/load memory: {e}") print() print("=== Example completed successfully ===") if __name__ == "__main__": main() ``` ## 开发者注意事项 * 使用HuggingFace `DynamicCache` 高效的键值存储 * 基于pickle的序列化,用于快速加载/保存 * `/tests`中的集成测试涵盖了所有方法。 --- # 参数记忆 (正在开发中) (/cn/open_source/modules/memories/parametric_memory) > **Note**: **正在开发中** > 该功能仍在积极开发中,敬请期待更新! `参数记忆 (Parametric Memory)` 是 MemOS 架构中核心的**长期知识与能力载体**。与明文记忆或激活记忆不同,参数化记忆将语言结构、世界知识以及通用推理能力的深度表征进行编码,直接嵌入在模型的权重之中。 在 MemOS 的架构设计中,参数化记忆不仅仅局限于静态的预训练权重,它还包含了**LoRA 适配器**和专家插件模块等模块化的权重组件。这使得你能够在无需重新训练整个模型的情况下,逐步扩展或定制 LLM 的能力。 例如,你可以将结构化或固定的知识提炼为参数形式,将其保存为独立的**能力模块 (Capability Blocks)**,并在推理过程中动态加载或卸载。这使得为法律推理、财务分析或特定领域摘要等任务创建“专家子模型”变得轻而易举——而这一切都由 MemOS 统一管理。 ## 设计目标 - **可控性** — 支持按需生成、加载、切换或组合参数模块。 - **可塑性** — 与明文记忆和激活记忆协同演进;支持知识的提炼与回滚。 - **可追溯性** *(开发中)* — 提供参数模块的版本控制与管理功能。 ## 当前状态 `参数化记忆 (Parametric Memory)` 目前仍处于设计和原型验证阶段。我们计划在未来的版本中发布用于生成、压缩以及热插拔参数模块的 API,旨在更好地支持多任务、多角色及多智能体架构。 请持续关注我们的更新! ## 相关模块 虽然参数记忆正在开发中,但今天你已经可以尝试这些: - **[GeneralTextMemory](/open_source/modules/memories/general_textual_memory)**: 基于向量的灵活语义存储 - **[TreeTextMemory](/open_source/modules/memories/tree_textual_memory)**: 结构化、层次化和知识图谱 - **[Activation Memory](/open_source/modules/memories/kv_cache_memory)**: 高效的运行时状态缓存 ## 开发者注意事项 参数化记忆将补全 MemOS 关于统一 **Memory³** 架构的愿景: - **参数化记忆**: 内化与嵌入的隐式知识 - **激活记忆**: 短暂的运行时状态 - **明文记忆**: 结构化、可追溯的显式外部记忆 三者有机结合,将构建出一个适应性强、可持续进化且具备可解释性的智能系统。 --- # NaiveTextMemory: 简单明文记忆 (/cn/open_source/modules/memories/naive_textual_memory) ## 目录 - [你将学到什么](#你将学到什么) - [为什么选择 NaiveTextMemory](#为什么选择-naivetextmemory) - [核心概念](#核心概念) - [记忆结构](#记忆结构) - [元数据字段](#元数据字段-textualmemorymetadata) - [搜索机制](#搜索机制) - [API 参考](#api-参考) - [初始化](#初始化) - [核心方法](#核心方法) - [配置参数](#配置参数) - [动手实践](#动手实践) - [快速开始](#快速开始) - [完整示例](#完整示例) - [文件存储](#文件存储) - [使用场景指南](#使用场景指南) - [与其他记忆模块对比](#与其他记忆模块对比) - [最佳实践](#最佳实践) - [下一步](#下一步) ## 你将学到什么 在本指南的最后,你将能够: - 使用 LLM 从对话中自动提取结构化记忆 - 在内存中存储和管理记忆(无需数据库) - 使用关键词匹配搜索记忆 - 持久化和恢复记忆数据 - 理解何时使用 NaiveTextMemory,何时升级到其他模块 ## 为什么选择 NaiveTextMemory ### 优势特性 - **零依赖**:无需向量数据库或嵌入模型 - **快速启动**:几行代码即可运行 - **轻量高效**:低资源占用,执行速度快 - **简单直观**:关键词匹配,结果可预测 - **易于调试**:所有记忆都在内存中,方便查看 - **完美起点**:学习 MemOS 的最佳入门选择 ### 适用场景 - 快速原型开发和概念验证 - 简单对话代理(记忆数量 < 1000 条) - 测试和演示场景 - 资源受限环境(无法运行嵌入模型) - 关键词搜索场景(查询与记忆直接匹配) > **Note**: **性能提示** > 当记忆数量超过 1000 条时,建议升级到 [GeneralTextMemory](/open_source/modules/memories/general_textual_memory),它使用向量搜索,性能更优。 ## 核心概念 ### 记忆结构 每个记忆表示为一个 `TextualMemoryItem` 对象,包含以下字段: | 字段 | 类型 | 必填 | 描述 | | ---------- | --------------------------- | ---- | ----------------------------- | | `id` | `str` | ✗ | 唯一标识符(自动生成 UUID) | | `memory` | `str` | ✓ | 记忆的主要文本内容 | | `metadata` | `TextualMemoryMetadata` | ✗ | 元数据(用于分类、过滤和检索)| ### 元数据字段 (`TextualMemoryMetadata`) 元数据提供了丰富的上下文信息,用于分类、过滤和组织记忆: | 字段 | 类型 | 默认值 | 描述 | | ------------- | -------------------------------------------------- | ---------- | ------------------------------ | | `type` | `"procedure"` / `"fact"` / `"event"` / `"opinion"` | `"fact"` | 记忆类型分类 | | `memory_time` | `str (YYYY-MM-DD)` | 当前日期 | 记忆关联的时间 | | `source` | `"conversation"` / `"retrieved"` / `"web"` / `"file"` | - | 记忆来源 | | `confidence` | `float (0-100)` | 80.0 | 确定性/可信度评分 | | `entities` | `list[str]` | `[]` | 提及的实体或概念 | | `tags` | `list[str]` | `[]` | 主题标签 | | `visibility` | `"private"` / `"public"` / `"session"` | `"private"` | 访问控制范围 | | `updated_at` | `str` | 自动生成 | 最近更新时间戳(ISO 8601) | ## API 参考 ### 初始化 ```python from memos.memories.textual.naive import NaiveTextMemory from memos.configs.memory import NaiveTextMemoryConfig memory = NaiveTextMemory(config: NaiveTextMemoryConfig) ``` ### 核心方法 | 方法 | 参数 | 返回值 | 描述 | | ------------------------ | ------------------------------------- | ----------------------------- | -------------------------------------- | | `extract(messages)` | `messages: list[dict]` | `list[TextualMemoryItem]` | 使用 LLM 从对话中提取结构化记忆 | | `add(memories)` | `memories: list / dict / Item` | `None` | 添加一个或多个记忆 | | `search(query, top_k)` | `query: str, top_k: int` | `list[TextualMemoryItem]` | 关键词匹配检索 top-k 记忆 | | `get(memory_id)` | `memory_id: str` | `TextualMemoryItem` | 通过 ID 获取单个记忆 | | `get_by_ids(ids)` | `ids: list[str]` | `list[TextualMemoryItem]` | 通过 ID 列表批量获取记忆 | | `get_all()` | - | `list[TextualMemoryItem]` | 返回所有记忆 | | `update(memory_id, new)` | `memory_id: str, new: dict` | `None` | 更新指定记忆的内容或元数据 | | `delete(ids)` | `ids: list[str]` | `None` | 删除一个或多个记忆 | | `delete_all()` | - | `None` | 清空所有记忆 | | `dump(dir)` | `dir: str` | `None` | 将记忆序列化为 JSON 文件保存 | | `load(dir)` | `dir: str` | `None` | 从 JSON 文件加载记忆 | ### 搜索机制 `NaiveTextMemory` 使用**关键词匹配算法**: #### 步骤 1: 分词 将查询和每条记忆内容分解为词汇列表 #### 步骤 2: 计算匹配度 统计查询词汇与记忆词汇的交集数量 #### 步骤 3: 排序 按匹配词数降序排列所有记忆 #### 步骤 4: 返回结果 取前 top-k 条记忆作为搜索结果 > **Note**: **示例对比** > 查询:"猫咪" > - **关键词匹配**:只匹配包含"猫"、"猫咪"的记忆 > - **语义搜索**:还能匹配"宠物"、"小猫"、"喵星人"等相关记忆(稍后我们将在“通用明文记忆”文章中学习) ### 配置参数 **NaiveTextMemoryConfig** | 参数 | 类型 | 必填 | 默认值 | 描述 | | ------------------ | ---------------------- | ---- | ---------------------- | ------------------------------------------ | | `extractor_llm` | `LLMConfigFactory` | ✓ | - | 用于从对话中提取记忆的 LLM 配置 | | `memory_filename` | `str` | ✗ | `textual_memory.json` | 持久化存储的文件名 | **配置示例** ```json { "backend": "naive_text", "config": { "extractor_llm": { "backend": "openai", "config": { "model_name_or_path": "gpt-4o-mini", "temperature": 0.8, "max_tokens": 1024, "api_base": "xxx", "api_key": "sk-xxx" } }, "memory_filename": "my_memories.json" } } ``` ## 动手实践 ### 快速开始 只需 3 步即可开始使用 NaiveTextMemory: #### 步骤 1: 创建配置 ```python from memos.configs.memory import MemoryConfigFactory config = MemoryConfigFactory( backend="naive_text", config={ "extractor_llm": { "backend": "openai", "config": { "model_name_or_path": "gpt-4o-mini", "api_key": "your-api-key", "api_base": "your-api-base" }, }, }, ) ``` #### 步骤 2: 初始化记忆模块 ```python from memos.memories.factory import MemoryFactory memory = MemoryFactory.from_config(config) ``` #### 步骤 3: 提取并添加记忆 ```python # 从对话中自动提取记忆 memories = memory.extract([ {"role": "user", "content": "I love tomatoes."}, {"role": "assistant", "content": "Great! Tomatoes are delicious."}, ]) # 添加到记忆库 memory.add(memories) print(f"✓ 已添加 {len(memories)} 条记忆") ``` > **Alert**: **进阶:使用 MultiModal Reader** > 如果需要处理图片、URL、文件等多模态内容,可以使用 `MultiModalStructMemReader`。 > 查看完整示例:[使用 MultiModalStructMemReader](./tree_textual_memory#使用-multimodalstructmemreader高级) ### 完整示例 以下是一个完整的端到端示例,展示所有核心功能: ```python from memos.configs.memory import MemoryConfigFactory from memos.memories.factory import MemoryFactory # ======================================== # 1. 初始化 # ======================================== config = MemoryConfigFactory( backend="naive_text", config={ "extractor_llm": { "backend": "openai", "config": { "model_name_or_path": "gpt-4o-mini", "api_key": "your-api-key", }, }, }, ) memory = MemoryFactory.from_config(config) # ======================================== # 2. 提取并添加记忆 # ======================================== memories = memory.extract([ {"role": "user", "content": "I love tomatoes."}, {"role": "assistant", "content": "Great! Tomatoes are delicious."}, ]) memory.add(memories) print(f"✓ 已添加 {len(memories)} 条记忆") # ======================================== # 3. 搜索记忆 # ======================================== results = memory.search("tomatoes", top_k=2) print(f"\n🔍 找到 {len(results)} 条相关记忆:") for i, item in enumerate(results, 1): print(f" {i}. {item.memory}") # ======================================== # 4. 获取所有记忆 # ======================================== all_memories = memory.get_all() print(f"\n📊 总共 {len(all_memories)} 条记忆") # ======================================== # 5. 更新记忆 # ======================================== if memories: memory_id = memories[0].id memory.update( memory_id, { "memory": "User loves tomatoes.", "metadata": {"type": "opinion", "confidence": 95.0} } ) print(f"\n✓ 已更新记忆: {memory_id}") # ======================================== # 6. 持久化存储 # ======================================== memory.dump("tmp/mem") print("\n💾 记忆已保存到 tmp/mem/textual_memory.json") # ======================================== # 7. 加载记忆 # ======================================== memory.load("tmp/mem") print("✓ 记忆已从文件加载") # ======================================== # 8. 删除记忆 # ======================================== if memories: memory.delete([memories[0].id]) print(f"\n🗑️ 已删除 1 条记忆") # 删除所有记忆 # memory.delete_all() ``` > **Note**: **扩展:互联网检索** > NaiveTextMemory 专注于本地记忆管理。如需从互联网检索信息并添加到记忆库,请查看: > [从互联网检索记忆](./tree_textual_memory#从互联网检索记忆可选) ### 文件存储 调用 `dump(dir)` 时,系统会将记忆保存到: ``` / ``` 该文件包含所有记忆条目的JSON列表,可以使用`load(dir)`重新加载. **默认文件结构** ```json [ { "id": "550e8400-e29b-41d4-a716-446655440000", "memory": "User loves tomatoes.", "metadata": { "type": "opinion", "confidence": 95.0, "entities": ["user", "tomatoes"], "tags": ["food", "preference"], "updated_at": "2026-01-14T10:30:00Z" } }, ... ] ``` 使用 `load(dir)` 可以完整恢复所有记忆数据。 > **Note**: **重要提示** > 记忆存储在内存中,进程重启后会丢失。请定期调用 `dump()` 保存数据! ## 使用场景指南 ### 最适合的场景 - **快速原型开发**:无需配置向量数据库,几分钟即可启动 - **简单对话代理**:记忆数量 < 1000 条的小规模应用 - **测试和演示**:快速验证记忆提取和检索逻辑 - **资源受限环境**:无法运行嵌入模型或向量数据库的场景 - **关键词搜索**:查询内容与记忆文本直接匹配的场景 - **学习和教学**:了解 MemOS 记忆系统的最佳起点 ### 不推荐的场景 - **大规模应用**:超过 10,000 条记忆(搜索性能退化) - **语义搜索需求**:需要理解同义词(如"猫"和"宠物") - **生产环境**:对性能和准确性有严格要求 - **多语言场景**:需要跨语言语义理解 - **复杂关系推理**:需要理解记忆之间的关联关系 > **Alert**: **升级路径** > 对于上述不推荐的场景,建议升级到: > - [GeneralTextMemory](/open_source/modules/memories/general_textual_memory) - 向量语义搜索,适合 10K-100K 条记忆 > - [TreeTextMemory](/open_source/modules/memories/tree_textual_memory) - 图结构存储,支持关系推理和多跳查询 ## 与其他记忆模块对比 选择合适的记忆模块对于项目成功至关重要。以下对比帮助你做出决策: | 特性 | **NaiveTextMemory** | **GeneralTextMemory** | **TreeTextMemory** | | -------------- | --------------------- | -------------------------- | --------------------------- | | **搜索方式** | 关键词匹配 | 向量语义搜索 | 图结构 + 向量搜索 | | **依赖组件** | 仅 LLM | LLM + 嵌入器 + 向量数据库 | LLM + 嵌入器 + 图数据库 | | **适用规模** | < 1K 条 | 1K - 100K 条 | 10K - 1M 条 | | **查询复杂度** | O(n) 线性扫描 | O(log n) 近似最近邻 | O(log n) + 图遍历 | | **语义理解** | ❌ | ✅ | ✅ | | **关系推理** | ❌ | ❌ | ✅ | | **多跳查询** | ❌ | ❌ | ✅ | | **存储后端** | 内存列表 | 向量数据库(Qdrant 等) | 图数据库(Neo4j/PolarDB) | | **配置复杂度** | 低 ⭐ | 中 ⭐⭐ | 高 ⭐⭐⭐ | | **学习曲线** | 极简 | 中等 | 较陡 | | **生产就绪** | ❌ 仅原型/演示 | ✅ 适合大多数场景 | ✅ 适合复杂应用 | > **Alert**: **选择建议** > - **刚开始学习?** → 从 NaiveTextMemory 开始 > - **需要语义搜索?** → 使用 GeneralTextMemory > - **需要关系推理?** → 选择 TreeTextMemory ## 最佳实践 遵循以下建议,充分发挥 NaiveTextMemory 的优势: ### 1. 定期持久化数据 ```python # 在关键操作后立即保存 memory.add(new_memories) memory.dump("tmp/mem") # ✓ 立即持久化 # 定期自动备份 import schedule schedule.every(10).minutes.do(lambda: memory.dump("tmp/mem")) ``` ### 2. 控制记忆规模 ```python # 定期清理旧记忆 if len(memory.get_all()) > 1000: old_memories = sorted( memory.get_all(), key=lambda m: m.metadata.updated_at )[:100] # 最旧的 100 条 memory.delete([m.id for m in old_memories]) print("✓ 已清理 100 条旧记忆") ``` ### 3. 优化搜索查询 ```python # ❌ 不好:模糊查询 results = memory.search("东西", top_k=5) # ✅ 好:使用具体关键词 results = memory.search("番茄 西红柿", top_k=5) ``` ### 4. 合理使用元数据 ```python # 添加记忆时设置清晰的元数据 memory.add({ "memory": "User prefers dark mode", "metadata": { "type": "opinion", # ✓ 明确分类 "tags": ["UI", "preference"], # ✓ 便于过滤 "confidence": 90.0, # ✓ 标注可信度 "entities": ["user", "dark mode"] # ✓ 实体标注 } }) ``` ### 5. 规划升级路径 ```python # 监控记忆数量,及时升级 memory_count = len(memory.get_all()) if memory_count > 800: print("⚠️ 记忆数量接近上限,建议升级到 GeneralTextMemory") # 迁移代码参考: # 1. 导出现有记忆:memory.dump("backup") # 2. 创建 GeneralTextMemory 配置 # 3. 导入记忆到新模块 ``` ## 下一步 恭喜!你已经掌握了 NaiveTextMemory 的核心用法。接下来可以: - **升级到向量搜索**:学习 [GeneralTextMemory](/open_source/modules/memories/general_textual_memory) 的语义检索能力 - **探索图结构**:了解 [TreeTextMemory](/open_source/modules/memories/tree_textual_memory) 的关系推理功能 - **集成到应用**:查看 [完整 API 文档](/api-reference/search-memories) 构建生产级应用 - **运行示例代码**:浏览 `/examples/` 目录获取更多实战案例 - **了解图数据库**:如果需要高级功能,可以学习 [Neo4j](/open_source/modules/memories/neo4j_graph_db) 或 [PolarDB](/open_source/modules/memories/polardb_graph_db) > **Alert**: **提示** > NaiveTextMemory 是学习 MemOS 的完美起点。当你的应用需要更强大的功能时,可以无缝迁移到其他记忆模块! --- # GeneralTextMemory: 通用明文记忆 (/cn/open_source/modules/memories/general_textual_memory) ## 目录 - [记忆结构](#记忆结构) - [元数据域 (`TextualMemoryMetadata`)](#元数据域-textualmemorymetadata) - [API总结 (`GeneralTextMemory`)](#api总结-generaltextmemory) - [初始化](#初始化) - [核心方法](#核心方法) - [文件存储](#文件存储) - [示例用法](#示例用法) - [扩展与进阶](#扩展与进阶) - [互联网检索](#互联网检索) - [MultiModal Reader](#multimodal-reader) - [开发者注意事项](#开发者注意事项) ## 记忆结构 每个记忆被表达为一个`TextualMemoryItem`: | 字段 | 类型 | 描述 | | ---------- | --------------------------- | ---------------------------------- | | `id` | `str` | UUID (如果省略则自动生成) | | `memory` | `str` | 记忆内容主体 (必填) | | `metadata` | `TextualMemoryMetadata` | 元数据(用于搜索/过滤) | ### 元数据域 (`TextualMemoryMetadata`) | 字段 | 类型 | 描述 | | ------------- | -------------------------------------------------- | ----------------------------------- | | `type` | `"procedure"`, `"fact"`, `"event"`, `"opinion"` | 记忆类型 | | `memory_time` | `str (YYYY-MM-DD)` | 记忆所指的日期/时间 | | `source` | `"conversation"`, `"retrieved"`, `"web"`, `"file"` | 记忆源 | | `confidence` | `float (0-100)` | 确定性/可信度评分 | | `entities` | `list[str]` | 主要实体/概念 | | `tags` | `list[str]` | 主题标签 | | `visibility` | `"private"`, `"public"`, `"session"` | 访问范围 | | `updated_at` | `str` | 最近更新时间戳 (ISO 8601) | 所有的值都经过验证,无效的值将引发错误。 ## 搜索机制 与前文提到的`NaiveTextMemory` 使用**关键词匹配算法**不同,`GeneralNaiveTextMemory` 使用**向量语义搜索**。 **与NaiveTextMemory的算法特点对比** | 特性 | 关键词匹配 | 向量语义搜索 | | -------------- | ---------------------------- | -------------------------------- | | **理解语义** | ❌ 不理解同义词 | ✅ 理解相似概念 | | **资源占用** | ✅ 极低 | ⚠️ 需要嵌入模型和向量数据库 | | **执行速度** | ✅ 快速(O(n)) | ⚠️ 较慢(索引构建+查询) | | **适用规模** | < 1K 条记忆 | 10K - 100K 条记忆 | | **可预测性** | ✅ 结果直观 | ⚠️ 黑盒模型 | ## API总结 (`GeneralTextMemory`) ### 初始化 ```python GeneralTextMemory(config: GeneralTextMemoryConfig) ``` ### 核心方法 | 方法 | 描述 | | ------------------------ | --------------------------------------------------- | | `extract(messages)` | 从消息列表中提取记忆 (基于LLM) | | `add(memories)` | 添加一个或多个记忆 (条目或字典) | | `search(query, top_k)` | 使用向量相似度检索top-k记忆 | | `get(memory_id)` | 通过ID获取单个记忆 | | `get_by_ids(ids)` | 通过ID获取多个记忆 | | `get_all()` | 返回所有记忆 | | `update(memory_id, new)` | 通过ID更新一个记忆 | | `delete(ids)` | 通过ID删除记忆 | | `delete_all()` | 删除所有记忆 | | `dump(dir)` | 将所有记忆序列化到目录中的JSON文件 | | `load(dir)` | 从存储的文件中加载记忆 | ## 文件存储 当调用 `dump(dir)`, 系统会将记忆保存到: ``` / ``` 该文件包含所有记忆条目的JSON列表,可以使用`load(dir)`重新加载. ## 示例用法 ```python import os from memos.configs.memory import MemoryConfigFactory from memos.memories.factory import MemoryFactory config = MemoryConfigFactory( backend="general_text", config={ "extractor_llm": { ... }, "vector_db": { ... }, "embedder": { ... }, }, ) m = MemoryFactory.from_config(config) # 提取并添加记忆 memories = m.extract([ {"role": "user", "content": "I love tomatoes."}, {"role": "assistant", "content": "Great! Tomatoes are delicious."}, ]) m.add(memories) # 通过id手动创建并添加一个记忆 memory_id = "xxx" m.add( [ { "id": memory_id, "memory": "User is Chinese.", ... } ] ) # 检索记忆 results = m.search("Tell me more about the user", top_k=2) # 更新记忆 m.update(memory_id, {"memory": "User is Canadian.", ...}) # 删除记忆 m.delete([memory_id]) # 将所有记忆序列化到目录中的JSON文件/从存储的文件中加载记忆 m.dump("tmp/mem") m.load("tmp/mem") ``` > **Note**: **扩展:互联网检索** > GeneralTextMemory 可以与互联网检索结合使用,从网页提取内容并添加到记忆库。 > 查看示例:[从互联网检索记忆](./tree_textual_memory#从互联网检索记忆可选) > **Note**: **进阶:使用 MultiModal Reader** > 如果需要处理图片、URL、文件等多模态内容,可以使用 `MultiModalStructMemReader`。 > 查看完整示例:[使用 MultiModalStructMemReader](./tree_textual_memory#使用-multimodalstructmemreader高级) ## 开发者注意事项 * 使用Qdrant(或兼容)向量DB进行快速相似度搜索 * 嵌入和提取模型是可配置的(支持olama/OpenAI) * `/tests`中的集成测试涵盖了所有方法。 --- # PreferenceTextMemory: 存储和管理用户偏好的明文记忆 (/cn/open_source/modules/memories/preference_textual_memory) ## 目录 - [为什么需要偏好记忆](#为什么需要偏好记忆) - [优势特性](#优势特性) - [应用场景](#应用场景) - [核心概念与工作流程](#核心概念与工作流程) - [记忆结构](#记忆结构) - [元数据字段](#元数据字段) - [核心工作流](#核心工作流) - [API 参考](#api-参考) - [初始化](#初始化) - [核心方法](#核心方法) - [文件存储](#文件存储) - [动手实践:从 0 到 1](#动手实践从-0-到-1) - [创建 PreferenceTextMemory 配置](#创建-preferencetextmemory-配置) - [初始化 PreferenceTextMemory](#初始化-preferencetextmemory) - [抽取结构化记忆](#抽取结构化记忆) - [搜索记忆](#搜索记忆) - [备份与恢复](#备份与恢复) - [完整代码示例](#完整代码示例) ## 为什么需要偏好记忆 ### 优势特性 - **双重偏好提取**:自动识别显式偏好和隐式偏好 - **语义理解**:使用向量嵌入理解偏好的深层含义 - **智能去重**:自动检测和合并重复或冲突的偏好 - **精准检索**:基于向量相似度的语义搜索 - **持久化存储**:支持向量数据库(Qdrant/Milvus) - **可扩展性**:支持大规模偏好数据管理 - **个性化增强**:为每个用户维护独立的偏好档案 ### 应用场景 - 个性化对话代理(记住用户喜好) - 智能推荐系统(基于偏好推荐) - 客户服务系统(提供定制化服务) - 内容过滤系统(根据偏好筛选内容) - 学习辅助系统(适应学习风格) > **Alert**: 总结来说,当你需要构建能够"记住"用户喜好并据此提供个性化服务的系统时,`PreferenceTextMemory` 是最佳选择。 ## 核心概念与工作流程 ### 记忆结构 在MemOS中,偏好记忆以`PreferenceTextMemory`表示,每条记忆都是一个`TextualMemoryItem`,使用Milvus数据库存储。 - `id`: 唯一记忆ID(如果省略则自动生成) - `memory`: 主要文本 - `metadata`: 包括层次结构信息、嵌入、标签、实体、源和状态 偏好记忆又可以分为显式偏好记忆和隐式偏好记忆: - **显式偏好记忆**:用户明确表达的喜好或厌恶。**示例**: - "我喜欢深色模式" - "我不吃辣" - "请用简短的回答" - "我更喜欢技术文档而不是视频教程" - **隐式偏好记忆**:从用户行为和对话模式中推断出的偏好。**示例**: - 用户总是询问代码示例 → 偏好实践导向的学习 - 用户经常要求详细解释 → 偏好深入理解 - 用户多次提到环保话题 → 关注可持续发展 > **Alert**: **智能提取** > `PreferenceTextMemory` 使用 LLM 自动从对话中同时提取显式和隐式偏好,无需手动标注! ### 元数据字段 (`PreferenceTextualMemoryMetadata`) | 字段 | 类型 | 描述 | | ------------- | -------------------------------------------------- | ----------------------------------- | | `preference_type` | `"explicit_preference"`, `"implicit_preference"` | 偏好记忆类型,分为显式偏好记忆和隐式偏好记忆 | | `dialog_id` | `str` | 对话ID,用于关联偏好记忆与特定对话 | | `original_text` | `str` | 原始文本,包含用户偏好信息 | | `embedding` | `str` | 嵌入向量,用于语义搜索和检索 | | `preference` | `str` | 用户偏好信息 | | `create_at` | `str` | 创建时间戳 (ISO 8601) | | `mem_cube_id` | `str` | 记忆立方ID,用于关联偏好记忆与特定记忆立方 | | `score` | `float ` | 检索结果中偏好记忆和query的相似度评分 | ### 核心工作流 当您运行此示例时,您的工作流将: 1. **抽取:** 使用LLM从原始文本中提取结构化记忆. 2. **嵌入:** 为相似性搜索生成向量嵌入. 3. **存储:** 将偏好记忆存储到Milvus数据库中,同时更新元数据字段. 4. **搜索:** 通过向量相似度查询,返回最相关的偏好记忆. ## API 参考 ### 初始化 ```python PreferenceTextMemory(config: PreferenceTextMemoryConfig) ``` ### 核心方法 | 方法 | 描述 | | --------------------------- | ----------------------------------------------------- | | `get_memory(messages)` | 从原始对话中抽取偏好记忆. | | `search(query, top_k)` | 使用向量相似度检索top-k偏好记忆. | | `load(dir)` | 从存储的文件中加载偏好记忆. | | `dump(dir)` | 将所有偏好记忆序列化到目录中的JSON文件. | | `add(memories)` | 批量添加偏好记忆到Milvus数据库. | | `get_with_collection_name(collection_name, memory_id)` | 通过集合名称和记忆ID获取特定类型的偏好记忆. | | `get_by_ids_with_collection_name(collection_name, memory_ids)` | 通过集合名称和记忆IDs**批量**获取特定类型的偏好记忆. | | `get_all()` | 获取所有偏好记忆. | | `get_memory_by_filter(filter)` | 根据过滤条件获取偏好记忆. | | `delete(memory_ids)` | 删除指定ID的偏好记忆. | | `delete_by_filter(filter)` | 根据过滤条件删除偏好记忆. | | `delete_with_collection_name(collection_name, memory_ids)` | 删除指定集合名称和IDs的所有偏好记忆. | | `delete_all()` | 删除所有偏好记忆. | ### 文件存储 当调用 `dump(dir)` 时,MemOS将所有偏好记忆序列化到目录中的JSON文件中: ``` / ``` --- ## 动手实践:从 0 到 1 ### 创建 PreferenceTextMemory 配置 定义: - 你的embedding模型(例如,nomic-embed-text:latest), - 你的Milvus数据库后端, - 记忆抽取器(基于LLM)(可选). ```python from memos.configs.memory import PreferenceTextMemoryConfig config = PreferenceTextMemoryConfig.from_json_file("examples/data/config/preference_config.json") ``` ### 初始化 PreferenceTextMemory ```python from memos.memories.textual.preference import PreferenceTextMemory preference_memory = PreferenceTextMemory(config) ``` ### 抽取结构化记忆 使用记忆抽取器将对话、文件或文档解析为多个`TextualMemoryItem`. ```python scene_data = [[ {"role": "user", "content": "Tell me about your childhood."}, {"role": "assistant", "content": "I loved playing in the garden with my dog."} ]] memories = preference_memory.get_memory(scene_data, type="chat", info={"user_id": "1234"}) preference_memory.add(memories) ``` ### 搜索记忆 ```python results = preference_memory.search("Tell me more about the user", top_k=2) ``` ### 备份与恢复 支持偏好记忆的持久化存储与随时重载: ```python preference_memory.dump("tmp/pref_memories") preference_memory.load("tmp/pref_memories") ``` ### 完整代码示例 该示例整合了上述所有步骤,提供一个端到端的完整流程,以Milvus为例 —— 复制即可运行! ```python from memos.configs.memory import PreferenceTextMemoryConfig from memos.memories.textual.preference import PreferenceTextMemory # 创建PreferenceTextMemory config = PreferenceTextMemoryConfig.from_json_file("examples/data/config/preference_config.json") preference_memory = PreferenceTextMemory(config) preference_memory.delete_all() scene_data = [[ {"role": "user", "content": "Tell me about your childhood."}, {"role": "assistant", "content": "I loved playing in the garden with my dog."} ]] # 从原始对话中抽取偏好记忆,并添加到Milvus数据库中 memories = preference_memory.get_memory(scene_data, type="chat", info={"user_id": "1234"}) preference_memory.add(memories) # 搜索记忆 results = preference_memory.search("Tell me more about the user", top_k=2) # 持久化存储偏好记忆 preference_memory.dump("tmp/pref_memories") ``` --- # TreeTextMemory: 树形明文记忆 (/cn/open_source/modules/memories/tree_textual_memory) ## 目录 - [你将学到什么](#你将学到什么) - [核心概念与工作流程](#核心概念与工作流程) - [记忆结构](#记忆结构) - [元数据字段](#元数据字段-treenodetextualmemorymetadata) - [核心工作流](#核心工作流) - [API 参考](#api-参考) - [动手实践:从 0 到 1](#动手实践从-0-到-1) - [创建 TreeTextMemory 配置](#创建-treetextmemory-配置) - [初始化 TreeTextMemory](#初始化-treetextmemory) - [抽取结构化记忆](#抽取结构化记忆) - [搜索记忆](#搜索记忆) - [从互联网检索记忆(可选)](#从互联网检索记忆可选) - [替换工作记忆](#替换工作记忆) - [备份与恢复](#备份与恢复) - [完整代码示例](#完整代码示例) - [为什么选择 TreeTextMemory](#为什么选择-treetextmemory) - [下一步](#下一步) ## 你将学到什么 在本指南的最后,你会: - 从原始文本或对话中提取结构化记忆 - 在图数据库中存储他们作为**节点** - 将记忆链接成**层次结构**和语义图 - 使用**向量相似度+图遍历**进行搜索 ## 核心概念与工作流程 ### 记忆结构 每个节点在`TreeTextMemory` 是一个 `TextualMemoryItem`: - `id`: 唯一记忆ID(如果省略则自动生成) - `memory`: 主要文本 - `metadata`: 包括层次结构信息、嵌入、标签、实体、源和状态 ### 元数据字段 (`TreeNodeTextualMemoryMetadata`) | 字段 | 类型 | 描述 | | --------------- |-------------------------------------------------------| ------------------------------------------ | | `memory_type` | `"WorkingMemory"`, `"LongTermMemory"`, `"UserMemory"` | 生命周期分类 | | `status` | `"activated"`, `"archived"`, `"deleted"` | 节点状态 | | `visibility` | `"private"`, `"public"`, `"session"` | 访问范围 | | `sources` | `list[str]` | 来源列表 (例如: 文件, URLs) | | `source` | `"conversation"`, `"retrieved"`, `"web"`, `"file"` | 原始来源类型 | | `confidence` | `float (0-100)` | 确定性得分 | | `entities` | `list[str]` | 提及的实体或概念 | | `tags` | `list[str]` | 主题标签 | | `embedding` | `list[float]` | 基于向量嵌入的相似性搜索 | | `created_at` | `str` | 创建时间戳(ISO 8601) | | `updated_at` | `str` | 最近更新时间戳(ISO 8601) | | `usage` | `list[str]` | 使用历史 | | `background` | `str` | 附加上下文 | > **Note**: **最佳实践** > 使用有意义的标签和背景——它们有助于组织你的图进行多跳推理。 ### 核心工作流 当您运行此示例时,您的工作流将: 1. **抽取:** 使用LLM从原始文本中提取结构化记忆. 2. **嵌入:** 为相似性搜索生成向量嵌入. 3. **存储和链接:** 将具有关系的节点添加到图数据库(Neo4j)中. 4. **搜索:** 通过向量相似度查询,然后通过图跳数展开结果. > **Note**: **提示** 图链接有助于检索纯向量搜索可能遗漏的上下文! ## API 参考 ### 初始化 ```python TreeTextMemory(config: TreeTextMemoryConfig) ``` ### 核心方法 | 方法 | 描述 | | --------------------------- | ----------------------------------------------------- | | `add(memories)` | 添加一个或多个记忆(项目或字典) | | `replace_working_memory()` | 更换所有的WorkingMemory节点 | | `get_working_memory()` | 得到所有的WorkingMemory节点 | | `search(query, top_k)` | 使用向量+图搜索检索top-k个记忆 | | `get(memory_id)` | 通过ID获取单个记忆 | | `get_by_ids(ids)` | 通过IDs获取多个记忆 | | `get_all()` | 将整个记忆图导出为字典 | | `update(memory_id, new)` | 通过ID更新记忆 | | `delete(ids)` | 通过IDs删除记忆 | | `delete_all()` | 删除所有的记忆和关系 | | `dump(dir)` | 在目录中将图序列化为JSON | | `load(dir)` | 从保存的JSON文件加载图 | | `drop(keep_last_n)` | 备份图和删除数据库,保留N个备份 | ### 文件存储 当调用 `dump(dir)`, MemOS将树形明文记忆导出为JSON文件: ``` / ``` 这个文件包含一个JSON结构,有 `nodes` and `edges`. 它可以使用 `load(dir)`重新加载. --- ## 动手实践:从 0 到 1 ### 创建 TreeTextMemory 配置 定义: - 你的embedding模型(例如,nomic-embed-text:latest), - 你的图数据库后端(Neo4j), - 记忆抽取器(基于LLM)(可选). ```python from memos.configs.memory import TreeTextMemoryConfig config = TreeTextMemoryConfig.from_json_file("examples/data/config/tree_config.json") ``` ### 初始化 TreeTextMemory ```python from memos.memories.textual.tree import TreeTextMemory tree_memory = TreeTextMemory(config) ``` ### 抽取结构化记忆 使用记忆抽取器将对话、文件或文档解析为多个`TextualMemoryItem`. #### 使用 SimpleStructMemReader(基础) ```python from memos.mem_reader.simple_struct import SimpleStructMemReader reader = SimpleStructMemReader.from_json_file("examples/data/config/simple_struct_reader_config.json") scene_data = [[ {"role": "user", "content": "Tell me about your childhood."}, {"role": "assistant", "content": "I loved playing in the garden with my dog."} ]] memories = reader.get_memory(scene_data, type="chat", info={"user_id": "1234"}) for m_list in memories: tree_memory.add(m_list) ``` #### 使用 MultiModalStructMemReader(高级) `MultiModalStructMemReader` 支持处理多模态内容(文本、图片、URL、文件等),能够自动感知(智能路由)到不同的解析器: ```python from memos.configs.mem_reader import MultiModalStructMemReaderConfig from memos.mem_reader.multi_modal_struct import MultiModalStructMemReader # 创建 MultiModal Reader 配置 multimodal_config = MultiModalStructMemReaderConfig( llm={ "backend": "openai", "config": { "model_name_or_path": "gpt-4o-mini", "api_key": "your-api-key" } }, embedder={ "backend": "openai", "config": { "model_name_or_path": "text-embedding-3-small", "api_key": "your-api-key" } }, chunker={ "backend": "text_splitter", "config": { "chunk_size": 1000, "chunk_overlap": 200 } }, extractor_llm={ "backend": "openai", "config": { "model_name_or_path": "gpt-4o-mini", "api_key": "your-api-key" } }, # 可选:指定哪些域名直接返回 Markdown direct_markdown_hostnames=["github.com", "docs.python.org"] ) # 初始化 MultiModal Reader multimodal_reader = MultiModalStructMemReader(multimodal_config) # ======================================== # 示例 1: 处理包含图片的对话 # ======================================== scene_with_image = [[ { "role": "user", "content": [ {"type": "text", "text": "这是我家的花园"}, {"type": "image_url", "image_url": {"url": "https://example.com/garden.jpg"}} ] }, { "role": "assistant", "content": "你的花园很漂亮!" } ]] memories = multimodal_reader.get_memory( scene_with_image, type="chat", info={"user_id": "1234", "session_id": "session_001"} ) for m_list in memories: tree_memory.add(m_list) print(f"✓ 已添加 {len(memories)} 条多模态记忆") # ======================================== # 示例 2: 处理网页 URL # ======================================== scene_with_url = [[ { "role": "user", "content": "请分析这篇文章: https://example.com/article.html" }, { "role": "assistant", "content": "我会帮你分析这篇文章" } ]] url_memories = multimodal_reader.get_memory( scene_with_url, type="chat", info={"user_id": "1234", "session_id": "session_002"} ) for m_list in url_memories: tree_memory.add(m_list) print(f"✓ 已从 URL 提取并添加 {len(url_memories)} 条记忆") # ======================================== # 示例 3: 处理本地文件 # ======================================== # 支持的文件类型: PDF, DOCX, TXT, Markdown, HTML 等 file_paths = [ "./documents/report.pdf", "./documents/notes.md", "./documents/data.txt" ] file_memories = multimodal_reader.get_memory( file_paths, type="doc", info={"user_id": "1234", "session_id": "session_003"} ) for m_list in file_memories: tree_memory.add(m_list) print(f"✓ 已从文件提取并添加 {len(file_memories)} 条记忆") # ======================================== # 示例 4: 混合模式(文本 + 图片 + URL) # ======================================== mixed_scene = [[ { "role": "user", "content": [ {"type": "text", "text": "这是我的项目文档:"}, {"type": "text", "text": "https://github.com/user/project/README.md"}, {"type": "image_url", "image_url": {"url": "https://example.com/diagram.png"}} ] } ]] mixed_memories = multimodal_reader.get_memory( mixed_scene, type="chat", info={"user_id": "1234", "session_id": "session_004"} ) for m_list in mixed_memories: tree_memory.add(m_list) print(f"✓ 已从混合内容提取并添加 {len(mixed_memories)} 条记忆") ``` > **Alert**: **MultiModal Reader 优势** > - **智能路由**:自动识别内容类型(图片/URL/文件)并选择合适的解析器 > - **格式支持**:支持 PDF、DOCX、Markdown、HTML、图片等多种格式 > - **URL 解析**:自动提取网页内容(包括 GitHub、文档站点等) > - **大文件处理**:自动分块处理超大文件,避免 token 超限 > - **上下文保持**:使用滑动窗口保持分块间的上下文连续性 > **Note**: **配置提示** > - 使用 `direct_markdown_hostnames` 参数可以指定哪些域名直接返回 Markdown 格式 > - 支持 `mode="fast"` 和 `mode="fine"` 两种提取模式,fine 模式提取更详细 > - 查看完整示例: `/examples/mem_reader/multimodal_struct_reader.py` ### 搜索记忆 尝试向量搜索+图搜索: ```python results = tree_memory.search("Talk about the garden", top_k=5) for i, node in enumerate(results): print(f"{i}: {node.memory}") ``` ### 从互联网检索记忆(可选) 你也可以从 Google / Bing / Bocha(博查) 等搜索引擎实时获取网页内容,并自动切分为记忆节点。MemOS 提供了统一接口。 以下示例演示如何检索“Alibaba 2024 ESG report”相关网页,并自动提取为结构化记忆。 ```python # 创建embedder embedder = EmbedderFactory.from_config( EmbedderConfigFactory.model_validate({ "backend": "ollama", "config": {"model_name_or_path": "nomic-embed-text:latest"}, }) ) # 配置检索器(以 BochaAI 为例) retriever_config = InternetRetrieverConfigFactory.model_validate({ "backend": "bocha", "config": { "api_key": "sk-xxx", # 替换为你的 BochaAI API Key "max_results": 5, "reader": { # 自动分块的 Reader 配置 "backend": "simple_struct", "config": ..., # 你的mem-reader config }, } }) # 实例化检索器 retriever = InternetRetrieverFactory.from_config(retriever_config, embedder) # 执行网页检索 results = retriever.retrieve_from_internet("Alibaba 2024 ESG report") # 添加到记忆图中 for m in results: tree_memory.add(m) ``` 你也可以直接在 TreeTextMemoryConfig 中配置 internet_retriever 字段,例如: ```json { "internet_retriever": { "backend": "bocha", "config": { "api_key": "sk-xxx", "max_results": 5, "reader": { "backend": "simple_struct", "config": ... } } } } ``` 这样,在调用 tree_memory.search(query) 时,系统会自动调用互联网检索(如 BochaAI / Google / Bing)然后将结果与本地图中的节点一起排序返回,无需手动调用 retriever.retrieve_from_internet ### 替换工作记忆 用一个新的节点替换你当前的 `WorkingMemory`: ```python tree_memory.replace_working_memory( [{ "memory": "User is discussing gardening tips.", "metadata": {"memory_type": "WorkingMemory"} }] ) ``` ### 备份与恢复 支持树结构的持久化存储与随时重载: ```python tree_memory.dump("tmp/tree_memories") tree_memory.load("tmp/tree_memories") ``` ### 完整代码示例 该示例整合了上述所有步骤,提供一个端到端的完整流程 —— 复制即可运行! ```python from memos.configs.embedder import EmbedderConfigFactory from memos.configs.memory import TreeTextMemoryConfig from memos.configs.mem_reader import SimpleStructMemReaderConfig from memos.embedders.factory import EmbedderFactory from memos.mem_reader.simple_struct import SimpleStructMemReader from memos.memories.textual.tree import TreeTextMemory # 嵌入设置 embedder_config = EmbedderConfigFactory.model_validate({ "backend": "ollama", "config": {"model_name_or_path": "nomic-embed-text:latest"} }) embedder = EmbedderFactory.from_config(embedder_config) # 创建TreeTextMemory tree_config = TreeTextMemoryConfig.from_json_file("examples/data/config/tree_config.json") my_tree_textual_memory = TreeTextMemory(tree_config) my_tree_textual_memory.delete_all() # 阅读器设置 reader_config = SimpleStructMemReaderConfig.from_json_file( "examples/data/config/simple_struct_reader_config.json" ) reader = SimpleStructMemReader(reader_config) # 从对话中抽取 scene_data = [[ { "role": "user", "content": "Tell me about your childhood." }, { "role": "assistant", "content": "I loved playing in the garden with my dog." }, ]] memory = reader.get_memory(scene_data, type="chat", info={"user_id": "1234", "session_id": "2222"}) for m_list in memory: my_tree_textual_memory.add(m_list) # 搜索 results = my_tree_textual_memory.search( "Talk about the user's childhood story?", top_k=10 ) for i, r in enumerate(results): print(f"{i}'th result: {r.memory}") # 从文档添加[可选项] doc_paths = ["./text1.txt", "./text2.txt"] doc_memory = reader.get_memory( doc_paths, "doc", info={ "user_id": "your_user_id", "session_id": "your_session_id", } ) for m_list in doc_memory: my_tree_textual_memory.add(m_list) # 转储和丢弃[可选项] my_tree_textual_memory.dump("tmp/my_tree_textual_memory") my_tree_textual_memory.drop() ``` ## 为什么选择 TreeTextMemory - **结构层次:** 像思维导图一样组织记忆——节点可以有父母、孩子和交叉链接。 - **图风格的链接:** 超越纯粹的层次结构-建立多跳推理链。 - **语义搜索+图扩展:** 结合向量和图形的优点。 - **可解释性:** 追踪记忆是如何连接、合并或随时间演变的. > **Note**: **尝试一下** 从文档或web内容中添加记忆节点。手动链接它们或自动合并类似的节点! ## 下一步 - **了解更多[Neo4j](/open_source/modules/memories/neo4j_graph_db):** treeTextMemory由图数据库后端提供支持。了解Neo4j如何处理节点、边和遍历将帮助您设计更有效的记忆层次结构、多跳推理和上下文链接策略。 - **添加 [Activation Memory](/open_source/modules/memories/kv_cache_memory):** 使用运行时KV-cache来测试会话状态。 - **探索图推理:** 为多跳检索和答案合成构建工作流。 - **更进一步:** 为高级应用检查 [API Reference](/api-reference/search-memories), 或者在 `examples/`运行更多的示例. 现在你的Agent不仅能记住事实,还能记住它们之间的联系! --- # Neo4j 图数据库 (/cn/open_source/modules/memories/neo4j_graph_db) ## 为什么记忆需要图存储? 与向量存储不同,一个图数据库允许: - 将记忆组织成**链、层次和因果关系** - 执行**多跳推理**和**子图遍历** - 支持记忆**重复数据删除、冲突检测和调度** - 随时间动态地演化图记忆 这构成了长期的、可解释的和组成性记忆推理的主干。 ## 特色 - 跨不同图数据库的统一接口 - 内置对Neo4j的支持 - 支持向量增强检索(`search_by_embedding`) - 模块化、可插拔和可测试 - [v0.2.1 新特性] 支持**多租户图存储架构**(单库多用户) - [v0.2.1 新特性] 兼容**Neo4j** 社区版(Community Edition) ## 目录结构 ``` src/memos/graph_dbs/ ├── base.py # BaseGraphDB的抽象接口 ├── factory.py # 工厂从配置中实例化GraphDB ├── neo4j.py # Neo4jGraphDB的产品实现 ```` ## 如何使用 ```python from memos.graph_dbs.factory import GraphStoreFactory from memos.configs.graph_db import GraphDBConfigFactory # 步骤1:构建工厂配置 config = GraphDBConfigFactory( backend="neo4j", config={ "uri": "bolt://localhost:7687", "user": "your_neo4j_user_name", "password": "your_password", "db_name": "memory_user1", "auto_create": True, "embedding_dimension": 768 } ) # 步骤2:实例化图存储 graph = GraphStoreFactory.from_config(config) # 步骤3:增加记忆 graph.add_node( id="node-001", memory="Today I learned about retrieval-augmented generation.", metadata={"type": "WorkingMemory", "tags": ["RAG", "AI"], "timestamp": "2025-06-05", "sources": []} ) ```` ## 可插拔的设计 ### 接口: `BaseGraphDB` ```` 函数功能介绍: 1.节点操作: 插入:add_node(添加单节点) add_nodes_batch(批量添加节点) 查询:get_node(查询单节点) get_nodes(查询多个节点) get_memory_count(查询节点数量) node_not_exist(节点是否存在) search_by_embedding(向量搜索可添加filter条件过滤,filter使用参见函数neo4j_example.example_complex_shared_db_search_filter获取完整的方法文档) 更新:update_node(更新单个节点) 删除:delete_node(删除单个节点) clear (通过user_name删除所有相关节点) 参见函数neo4j_example.example_complex_shared_db_delete_memory获取完整的方法文档 2.边操作 插入:add_edge(添加三元组记忆) 查询:get_edges(查询多个关系) edge_exists(是否存在关系) get_children_with_embeddings(查询关系类型PARENT的节点列表) get_subgraph(查询多跳节点) 删除:delete_edge(删除关系) 3.导入导出操作: import_graph(从序列化的字典中导入整个图,参数包含所有待加载节点和边的字典 参数:{'nodes':[],'edges':[]) export_graph(以结构化形式导出所有图节点和边,支持分页) 参见src/memos/graph_dbs/base.py获取完整的方法文档。 ```` ### 当前的后端: | 后端 | 状态 | 文件 | | ------- | ------ | ---------- | | Neo4j | Stable | `neo4j.py` | ## 单库多租户(Shared DB, Multi-Tenant) 通过配置 `user_name` 字段,MemOS 支持在单个 Neo4j 数据库中隔离多个用户的记忆图谱,适用于协同系统、多角色场景: ```python config = GraphDBConfigFactory( backend="neo4j", config={ "uri": "bolt://localhost:7687", "user": "neo4j", "password": "your_password", "db_name": "shared-graph", "user_name": "alice", "use_multi_db": false, "embedding_dimension": 768, }, ) ``` 每个用户的数据通过 `user_name` 字段在读写、搜索、导出中逻辑隔离,系统自动完成过滤。 > **Note**: **示例参考** > 话不多说,都在代码里了`examples/basic_modules > /neo4j_example.example_complex_shared_db(db_name="shared-traval-group-complex-new")` ## Neo4j 社区版(Community Edition)支持 新增后端标识:`neo4j-community` 使用方式与标准 Neo4j 类似,但自动关闭企业功能: - ❌ 不支持 `auto_create` 数据库 - ❌ 不支持原生向量索引(必须使用外接向量库,目前只支持Qdrant) - ✅ 强制启用 `user_name` 逻辑隔离(社区版、或user_name属于同一业务不需要强隔离) 示例配置: ```python config = GraphDBConfigFactory( backend="neo4j-community", config={ "uri": "bolt://localhost:7687", "user": "neo4j", "password": "12345678", "db_name": "paper", "user_name": "bob", "auto_create": False, "embedding_dimension": 768, "use_multi_db": False, "vec_config": { "backend": "qdrant", "config": { "host": "localhost", "port": 6333, "collection_name": "neo4j_vec_db", "vector_dimension": 768, "distance_metric": "cosine" }, }, }, ) ``` > **Note**: **示例参考** `examples/basic_modules > /neo4j_example.example_complex_shared_db(db_name="paper", > community=True)` ## 扩展 你可以添加任何其他图形引擎的支持(例如,**TigerGraph**, **DGraph**, **Weaviate hybrid**): 1. 子类 `BaseGraphDB` 2. 创建配置数据类(例如, `DgraphConfig`) 3. 将它注册到: * `GraphDBConfigFactory.backend_to_class` * `GraphStoreFactory.backend_to_class` 参见 `src/memos/graph_dbs/neo4j.py` 作为参考实现。 --- # PolarDB 图数据库 (/cn/open_source/modules/memories/polardb_graph_db) ## 功能特性 - 完整的图数据库操作:节点增删改查、边管理 - 向量嵌入搜索:支持 IVFFlat 索引的语义检索 - 连接池管理:自动管理数据库连接,支持高并发 - 多租户隔离:支持物理和逻辑两种隔离模式 - JSONB 属性存储:灵活的元数据存储 - 批量操作:支持批量插入节点和边 - 自动时间戳:自动维护 `created_at` 和 `updated_at` - SQL 注入防护:内置参数化查询和字符串转义 ## 目录结构 ``` MemOS/ └── src/ └── memos/ ├── configs/ │ └── graph_db.py # PolarDBGraphDBConfig 配置类 └── graph_dbs/ ├── base.py # BaseGraphDB 抽象基类 ├── factory.py # GraphDBFactory 工厂类 └── polardb.py # PolarDBGraphDB 实现 ``` ## 快速开始 ### 1. 安装依赖 ```bash # 安装 psycopg2 驱动(二选一) pip install psycopg2-binary # 推荐:预编译版本 # 或 pip install psycopg2 # 需要 PostgreSQL 开发库 # 安装 MemOS pip install MemoryOS -U ``` ### 2. 配置 PolarDB #### 方式一:使用配置文件(推荐) ```json { "graph_db_store": { "backend": "polardb", "config": { "host": "localhost", "port": 5432, "user": "postgres", "password": "your_password", "db_name": "memos_db", "user_name": "alice", "use_multi_db": true, "auto_create": false, "embedding_dimension": 1024, "maxconn": 100 } } } ``` #### 方式二:代码初始化 ```python from memos.configs.graph_db import PolarDBGraphDBConfig from memos.graph_dbs.polardb import PolarDBGraphDB # 创建配置 config = PolarDBGraphDBConfig( host="localhost", port=5432, user="postgres", password="your_password", db_name="memos_db", user_name="alice", use_multi_db=True, embedding_dimension=1024, maxconn=100 ) # 初始化数据库 graph_db = PolarDBGraphDB(config) ``` ### 3. 基本操作示例 ```python # ======================================== # 步骤 1: 添加节点 # ======================================== node_id = graph_db.add_node( label="Memory", properties={ "content": "Python 是一种高级编程语言", "memory_type": "Knowledge", "tags": ["programming", "python"] }, embedding=[0.1, 0.2, 0.3, ...], # 1024维向量 user_name="alice" ) print(f"✓ 节点已创建: {node_id}") # ======================================== # 步骤 2: 更新节点 # ======================================== graph_db.update_node( id=node_id, fields={ "content": "Python 是一种解释型、面向对象的高级编程语言", "updated": True }, user_name="alice" ) print("✓ 节点已更新") # ======================================== # 步骤 3: 创建关系 # ======================================== # 先创建第二个节点 node_id_2 = graph_db.add_node( label="Memory", properties={ "content": "Django 是 Python 的 Web 框架", "memory_type": "Knowledge" }, embedding=[0.15, 0.25, 0.35, ...], user_name="alice" ) # 创建边 edge_id = graph_db.add_edge( source_id=node_id, target_id=node_id_2, edge_type="RELATED_TO", properties={ "relationship": "框架与语言", "confidence": 0.95 }, user_name="alice" ) print(f"✓ 关系已创建: {edge_id}") # ======================================== # 步骤 4: 向量搜索 # ======================================== query_embedding = [0.12, 0.22, 0.32, ...] # 查询向量 results = graph_db.search_by_embedding( embedding=query_embedding, top_k=5, memory_type="Knowledge", user_name="alice" ) print(f"\n🔍 找到 {len(results)} 个相似节点:") for node in results: print(f" - {node.get('content')} (相似度: {node.get('score', 'N/A')})") # ======================================== # 步骤 5: 删除节点 # ======================================== graph_db.delete_node(id=node_id, user_name="alice") print(f"✓ 节点 {node_id} 已删除") ``` ## 配置详解 ### PolarDBGraphDBConfig 参数说明 | 参数 | 类型 | 默认值 | 必填 | 说明 | |------|------|--------|------|------| | `host` | str | - | ✓ | 数据库主机地址 | | `port` | int | 5432 | ✗ | 数据库端口 | | `user` | str | - | ✓ | 数据库用户名 | | `password` | str | - | ✓ | 数据库密码 | | `db_name` | str | - | ✓ | 目标数据库名称 | | `user_name` | str | None | ✗ | 租户标识(用于逻辑隔离) | | `use_multi_db` | bool | True | ✗ | 是否使用多数据库物理隔离 | | `auto_create` | bool | False | ✗ | 是否自动创建数据库 | | `embedding_dimension` | int | 1024 | ✗ | 向量嵌入维度 | | `maxconn` | int | 100 | ✗ | 连接池最大连接数 | ### 多租户模式对比 | 特性 | 物理隔离 (`use_multi_db=True`) | 逻辑隔离 (`use_multi_db=False`) | |------|-----------------------------------|-------------------------------------| | **隔离级别** | 数据库级别 | 应用层标签过滤 | | **配置要求** | `db_name` 通常等于 `user_name` | 必须提供 `user_name` | | **性能** | 更好(独立资源) | 较好(共享资源) | | **成本** | 高(每租户独立DB) | 低(共享数据库) | | **适用场景** | 企业客户、高安全要求 | SaaS 多租户、开发测试 | | **数据迁移** | 方便(整库导出) | 需要按标签过滤 | ### 配置示例 #### 示例 1:物理隔离(企业版推荐) ```json { "graph_db_store": { "backend": "polardb", "config": { "host": "prod-polardb.example.com", "port": 5432, "user": "admin", "password": "secure_password", "db_name": "customer_001", "user_name": null, "use_multi_db": true, "auto_create": false, "embedding_dimension": 1536, "maxconn": 200 } } } ``` #### 示例 2:逻辑隔离(SaaS 推荐) ```json { "graph_db_store": { "backend": "polardb", "config": { "host": "shared-polardb.example.com", "port": 5432, "user": "app_user", "password": "app_password", "db_name": "shared_memos", "user_name": "tenant_alice", "use_multi_db": false, "auto_create": false, "embedding_dimension": 768, "maxconn": 50 } } } ``` ## 高级特性 ### 1. 批量插入节点 ```python # 批量添加节点(高性能) nodes_data = [ { "label": "Memory", "properties": {"content": f"节点 {i}", "memory_type": "Test"}, "embedding": [0.1 * i] * 1024, } for i in range(100) ] node_ids = graph_db.add_nodes_batch( nodes=nodes_data, user_name="alice" ) print(f"✓ 批量创建了 {len(node_ids)} 个节点") ``` ### 2. 复杂查询示例 ```python # 查找特定类型的记忆并按时间排序 def get_recent_memories(graph_db, memory_type, limit=10): """获取最近的记忆节点""" query = f""" SELECT * FROM "{graph_db.db_name}_graph"."Memory" WHERE properties->>'memory_type' = %s AND properties->>'user_name' = %s ORDER BY updated_at DESC LIMIT %s """ conn = graph_db._get_connection() try: with conn.cursor() as cursor: cursor.execute(query, [memory_type, "alice", limit]) results = cursor.fetchall() return results finally: graph_db._return_connection(conn) # 使用示例 recent = get_recent_memories(graph_db, "WorkingMemory", limit=5) print(f"最近 5 条工作记忆: {len(recent)} 条") ``` ### 3. 向量索引优化 ```python # 创建或更新向量索引 graph_db.create_index( label="Memory", vector_property="embedding", dimensions=1024, index_name="memory_vector_index" ) print("✓ 向量索引已优化") ``` ### 4. 连接池监控 ```python # 查看连接池状态(仅供调试) import logging logging.basicConfig(level=logging.DEBUG) # 获取连接时会输出详细日志 conn = graph_db._get_connection() # [DEBUG] [_get_connection] Successfully acquired connection from pool graph_db._return_connection(conn) # [DEBUG] [_return_connection] Successfully returned connection to pool ``` ## BaseGraphDB 接口 PolarDB 实现了 `BaseGraphDB` 抽象类的所有方法,确保与其他图数据库后端的互换性。 ### 核心方法 | 方法 | 说明 | 参数 | |------|------|------| | `add_node()` | 添加单个节点 | label, properties, embedding, user_name | | `add_nodes_batch()` | 批量添加节点 | nodes, user_name | | `update_node()` | 更新节点属性 | id, fields, user_name | | `delete_node()` | 删除节点 | id, user_name | | `delete_node_by_params()` | 按条件删除节点 | params, user_name | | `add_edge()` | 创建关系 | source_id, target_id, edge_type, properties, user_name | | `update_edge()` | 更新关系属性 | edge_id, properties, user_name | | `delete_edge()` | 删除关系 | edge_id, user_name | | `search_by_embedding()` | 向量相似度搜索 | embedding, top_k, memory_type, user_name | | `get_node()` | 获取单个节点 | id, user_name | | `get_memory_count()` | 统计节点数量 | memory_type, user_name | | `remove_oldest_memory()` | 清理旧记忆 | memory_type, keep_latest, user_name | ### 完整方法签名示例 ```python from typing import Any # 添加节点 def add_node( self, label: str = "Memory", properties: dict[str, Any] | None = None, embedding: list[float] | None = None, user_name: str | None = None ) -> str: """添加一个新节点到图数据库""" pass # 向量搜索 def search_by_embedding( self, embedding: list[float], top_k: int = 10, memory_type: str | None = None, user_name: str | None = None, filters: dict[str, Any] | None = None ) -> list[dict[str, Any]]: """基于向量嵌入进行相似度搜索""" pass # 批量操作 def add_nodes_batch( self, nodes: list[dict[str, Any]], user_name: str | None = None ) -> list[str]: """批量添加多个节点""" pass ``` ## 扩展开发指南 如果需要基于 PolarDB 实现自定义功能,可以继承 `PolarDBGraphDB` 类: ```python from memos.graph_dbs.polardb import PolarDBGraphDB from memos.configs.graph_db import PolarDBGraphDBConfig class CustomPolarDBGraphDB(PolarDBGraphDB): """自定义 PolarDB 图数据库实现""" def __init__(self, config: PolarDBGraphDBConfig): super().__init__(config) # 自定义初始化逻辑 self.custom_index_created = False def create_custom_index(self): """创建自定义索引""" conn = self._get_connection() try: with conn.cursor() as cursor: cursor.execute(f""" CREATE INDEX IF NOT EXISTS idx_custom_field ON "{self.db_name}_graph"."Memory" ((properties->>'custom_field')); """) conn.commit() self.custom_index_created = True print("✓ 自定义索引已创建") except Exception as e: print(f"❌ 创建索引失败: {e}") conn.rollback() finally: self._return_connection(conn) def search_by_custom_field(self, field_value: str): """基于自定义字段搜索""" query = f""" SELECT * FROM "{self.db_name}_graph"."Memory" WHERE properties->>'custom_field' = %s """ conn = self._get_connection() try: with conn.cursor() as cursor: cursor.execute(query, [field_value]) results = cursor.fetchall() return results finally: self._return_connection(conn) # 使用自定义实现 config = PolarDBGraphDBConfig( host="localhost", port=5432, user="postgres", password="password", db_name="custom_db" ) custom_db = CustomPolarDBGraphDB(config) custom_db.create_custom_index() results = custom_db.search_by_custom_field("special_value") ``` ## 参考资源 - [Apache AGE 官方文档](https://age.apache.org/) - [PostgreSQL 连接池文档](https://www.psycopg.org/docs/pool.html) - [PolarDB 官方文档](https://www.alibabacloud.com/product/polardb) - [MemOS GitHub 仓库](https://github.com/MemOS-AI/MemOS) ## 下一步 - 了解 [Neo4j 图数据库](./neo4j_graph_db.md) 的使用 - 查看 [通用文本记忆](./general_textual_memory.md) 的配置 - 探索 [树形文本记忆](./tree_textual_memory.md) 的高级特性 --- # 性能调优 (/cn/open_source/best_practice/performance_tuning) MemOS 的性能优化主要围绕 **记忆提取 (Mem-Reader)**、**向量嵌入 (Embedding)** 和 **检索排序 (Search Ranking)** 展开。大部分配置可以通过修改 YAML 配置文件(如 `memos_config_w_scheduler.yaml`)或直接调整源代码来实现。 ## 1. 记忆提取优化 (Mem-Reader Prompt) slow_embedder = { "backend": "sentence_transformer", "config": { "model_name_or_path": "nomic-ai/nomic-embed-text-v1.5" } } ``` `Mem-Reader` 组件负责从对话中提取关键信息。目前的实现中,Prompt 是定义在源代码模板中的。 ### 修改 Prompt 模板 要调整提取逻辑(例如忽略闲聊、专注于特定事实),你需要直接修改源码文件: * **文件路径**: `src/memos/templates/mem_reader_prompts.py` * **目标变量**: `SIMPLE_STRUCT_MEM_READER_PROMPT` (用于英文) 或 `SIMPLE_STRUCT_MEM_READER_PROMPT_ZH` (用于中文) **示例修改**: 在 `src/memos/templates/mem_reader_prompts.py` 中: ```python SIMPLE_STRUCT_MEM_READER_PROMPT = """ You are a preference extraction expert. Your task is to extract ONLY user preferences and dislikes from the conversation. Ignore all other information including plans and daily events. ... """ ``` ## 2. 向量嵌入模型优化 (Embedding Models) Embedding 模型的选择决定了语义检索的准确性和速度。通常在 YAML 配置文件中进行设置。 ### 配置文件修改 在你的配置文件(如 `memos_config.yaml`)中,找到 `mem_reader` 或 `text_mem` 下的 `embedder` 部分: ```yaml mem_reader: backend: "simple_struct" config: # ... 其他配置 embedder: # 方案 A: 使用 Ollama (速度快,适合本地) backend: "ollama" config: model_name_or_path: "nomic-embed-text:latest" # 方案 B: 使用 Sentence Transformer (精度高,显存占用大) # backend: "sentence_transformer" # config: # model_name_or_path: "BAAI/bge-m3" ``` * **推荐模型**: * **快速/本地**: `nomic-embed-text` (Ollama) * **高精度**: `BAAI/bge-m3` 或 `OpenAI` 的 `text-embedding-3-small` (需使用 `universal_api` backend) ## 3. 检索排序优化 (Search Ranking) 检索性能主要受召回数量 (`top_k`) 和重排序策略影响。 ### 调整召回数量 (Top-K) 在 `mem_scheduler` 的配置中调整 `top_k`。增加此值可以提高召回率,但会增加处理时间。 ```yaml mem_scheduler: backend: "general_scheduler" config: # 初始检索的候选数量 top_k: 20 # ... ``` ### 引入 Reranker (进阶) MemOS 支持在检索后引入 Reranker 进行精排。这通常需要在初始化 `Searcher` 组件时指定。如果你是作为开发者集成 MemOS,可以在代码中配置: ```python from memos.reranker.factory import RerankerFactory # 在初始化 Searcher 时 reranker = RerankerFactory.from_config({ "backend": "sentence_transformer", "config": { "model_name_or_path": "BAAI/bge-reranker-base" } }) ``` ## 4. 系统资源与容量限制 合理限制各类记忆的容量可以防止内存无限增长,并保持检索速度。这通常在 `mem_cube` 的配置中设置。 ### 内存容量配置 (Memory Size) 在 YAML 配置文件中,配置 `memory_size` 字典: ```yaml mem_cube: backend: "general" config: text_mem: backend: "tree" config: # 限制各类记忆的条目数 memory_size: WorkingMemory: 10 # 最近几轮对话的短期记忆 LongTermMemory: 2000 # 长期记忆上限 UserMemory: 500 # 用户画像/偏好上限 ``` ### 批处理与并发 在 `mem_scheduler` 中可以配置并发处理能力: ```yaml mem_scheduler: config: thread_pool_max_workers: 10 # 并行处理线程数 consume_interval_seconds: 0.01 # 消息队列消费间隔 enable_parallel_dispatch: true # 开启并行分发 ``` --- # 网络问题解决方案 (/cn/open_source/best_practice/network_workarounds) ## **下载 Huggingface 模型** ### 镜像站点(HF-Mirror) 要通过镜像站点下载 Huggingface 模型,可以按照以下步骤进行操作: #### 安装依赖项 运行以下命令安装必要的依赖项: ```bash pip install -U huggingface_hub ``` #### 设置环境变量 将环境变量 `HF_ENDPOINT` 设置为 `https://hf-mirror.com`。 #### 下载模型或数据集 使用 huggingface-cli 下载模型或数据集。例如: - 下载模型: ```bash huggingface-cli download --resume-download gpt2 --local-dir gpt2 ``` - 下载数据集: ``` huggingface-cli download --repo-type dataset --resume-download wikitext --local-dir wikitext ``` 获取更详细的说明和其他方法,请参见 [此链接](https://hf-mirror.com/)。 ### 其他来源 某些地区仍可能无法访问部分模型。在这种情况下,可以使用 modelscope: #### 安装 ModelScope 运行以下命令安装必要的依赖项: ```bash pip install modelscope[framework] ``` #### 下载模型或数据集 使用 modelscope 下载模型或数据集。例如: * 下载模型: ```bash modelscope download --model 'Qwen/Qwen2-7b' --local_dir 'path/to/dir' ``` * 下载数据集: ```bash modelscope download --dataset 'Tongyi-DataEngine/SA1B-Dense-Caption' --local_dir './local_dir' ``` 获取更详细的说明和其他方法,请参见 [官方文档](https://modelscope.cn/docs/home)。 ## **使用 Poetry** ### 安装过程中的网络错误 在某些地区使用 "poetry install" 可能会遇到网络错误,可以按照以下步骤解决: #### 更新配置 在 `pyproject.toml` 文件中添加以下配置以使用镜像源: ```toml [[tool.poetry.source]] name = "mirrors" url = "https://mirrors.tuna.tsinghua.edu.cn/pypi/web/simple/" priority = "primary" ``` #### 重新配置 Poetry 在终端中运行 `poetry lock` 命令,使用新的镜像源重新配置 Poetry。 **提示:** 注意 `poetry lock` 会修改 `pyproject.toml` 和 `poetry.lock` 文件。为避免提交不必要的更改: - 方案一:成功执行 `poetry install` 后,使用 `git reset --hard HEAD` 还原到 Git HEAD 节点。 - 方案二:执行 `git add` 时,排除 `pyproject.toml` 和 `poetry.lock` 文件,仅添加其他文件。 以后在添加或移除依赖包时,可以使用如下命令: ```bash poetry add ``` 更多命令和说明,请参见 [Poetry CLI 官方文档](https://python-poetry.org/docs/cli/)。 --- # 常见错误与解决方案 (/cn/open_source/best_practice/common_errors_solutions) ## 1. 数据库与向量相关错误 ### Embedding 维度不匹配 **现象**: 更改 Embedding 模型后(例如从 `openai` 切换到 `ollama`),系统报错或检索效果极差。 日志中可能出现 `Dimension mismatch` 或 Qdrant 相关的 `Wrong input vector size` 错误。 **原因**: Qdrant 在创建 Collection 时会根据配置文件中的 `vector_dimension` 固定向量维度。 * OpenAI `text-embedding-3-small`: 1536 维 * Ollama `nomic-embed-text`: 768 维 * BAAI `bge-m3`: 1024 维 MemOS 的 `QdrantVecDB` 在初始化时,如果发现 Collection 已存在,会跳过创建步骤。此时如果使用了新维度的模型,写入向量时就会报错。 **解决方案**: 1. **修改 Collection 名称**:在配置文件中更改 `collection_name`,让 MemOS 创建一个新的 Collection。 ```yaml vec_db: config: collection_name: "memos_v2" # 原名为 memos_v1 vector_dimension: 768 # 确保此维度与新模型一致 ``` 2. **删除旧数据**:如果你在开发环境,可以直接删除 Qdrant 的存储卷或 Drop 掉旧的 Collection。 ### 数据后端启动失败 (Neo4j/Qdrant) **现象**: 启动 MemOS 时报错 `ConnectionRefusedError`, `ServiceUnavailable` 或 `AuthError`。 **常见原因与检查清单**: 1. **Docker 容器未启动**: 确保你已经运行了必要的中间件容器。 ```bash docker ps # 检查是否有 neo4j 和 qdrant 容器在运行 ``` 2. **端口未映射**: 检查 `docker run` 命令是否包含了 `-p` 参数。 * Qdrant 需要暴露 `6333` (gRPC/HTTP) * Neo4j 需要暴露 `7474` (HTTP) 和 `7687` (Bolt) 3. **Neo4j 认证失败**: MemOS 默认配置通常使用 `neo4j/password` 或 `neo4j/neo4j`。 请检查你的环境变量或配置文件: ```bash export NEO4J_PASSWORD="your_actual_password" ``` *注意:Neo4j 首次启动要求修改默认密码,请确保已在浏览器 (http://localhost:7474) 中完成此步骤。* ## 2. 模型服务错误 ### Ollama 连接失败 **现象**: 报错 `Connection refused` 连接到 `localhost:11434` 失败,或者提示模型不存在。 **解决方案**: 1. **启动服务**:确保在终端运行了 `ollama serve`。 2. **拉取模型**:MemOS 的 `OllamaEmbedder` 会尝试检查本地模型,如果不存在会尝试 pull,但建议手动执行以确保成功: ```bash ollama pull nomic-embed-text ``` 3. **地址问题**:如果是 Docker 运行 MemOS,`localhost` 指向容器内部。需使用 `host.docker.internal` (Mac/Windows) 或宿主机 IP (Linux) 配置 `api_base`。 ## 3. 配置错误 ### 缺失必要字段 ```python # ✅ 始终需要包含必填字段 llm_config = { "backend": "openai", "config": { "api_key": "your-api-key", "model_name_or_path": "gpt-4" } } ``` ### 后端不匹配 ```python # ✅ KVCache 需要使用 HuggingFace 后端 # 参考 src/memos/memories/activation/kv.py kv_config = { "backend": "kv_cache", "config": { "extractor_llm": { "backend": "huggingface", "config": { "model_name_or_path": "Qwen/Qwen3-1.7B" } } } } ``` ## 4. 运行时资源问题 ### 记忆加载失败 (Schema Mismatch) **现象**: `mem_cube.load()` 报错,通常是因为 JSON 文件结构与当前代码版本不兼容。 **解决方案**: 重新初始化 MemCube 并覆盖旧数据(注意数据丢失风险): ```python try: mem_cube.load("memory_dir") except Exception: logger.warning("Loading failed, initializing new memory cube") mem_cube = GeneralMemCube(config) # 谨慎操作:这会覆盖旧数据 mem_cube.dump("memory_dir") ``` ### GPU 显存不足 **解决方案**: 使用 `CUDA_VISIBLE_DEVICES` 指定显卡,或切换更小的模型(如 0.5B/1.5B 版本)。 ```python import os os.environ["CUDA_VISIBLE_DEVICES"] = "0" ``` ## 5. 用户管理常见问题 **现象**: 调用 `get_user` 返回 None 或报错。 **解决方案**: MemOS 需要明确的用户注册流程。 ```python # 1. 注册 MemCube 到特定用户 mos.register_mem_cube(cube_path="path", user_id="user_id", cube_id="cube_id") # 2. 创建或获取用户 try: # 尝试创建用户 user_id = mos.create_user(user_name="john", role=UserRole.USER) except ValueError: # 如果用户已存在,则获取 user = mos.user_manager.get_user_by_name("john") ``` --- # MemOS MCP集成指南 (/cn/open_source/best_practice/mcp_for_cozespace_and_tools) 本指南将帮助您在Coze空间等平台中配置MemOS的MCP服务,实现智能体与记忆系统的无缝集成。 ## 选择MCP部署方式 MemOS提供两种MCP部署方式,您可以根据实际需求选择: ### 使用MemOS云服务(推荐) 如果您希望快速接入,无需自己部署服务器,推荐使用MemOS官方云服务。 **优势:** - ✅ 开箱即用,无需部署 - ✅ 高可用性保障 - ✅ 自动扩展和维护 - ✅ 支持多种客户端(Claude、Cursor、Cline等) **配置方式:** 请访问 [MemOS云服务MCP配置指南](https://memos-docs.openmem.net/cn/mcp_agent/mcp/guide) 获取详细的配置说明。 主要步骤: 1. 在 [MemOS API控制台](https://memos-dashboard.openmem.net/cn/apikeys/) 注册账号并获取API Key 2. 在MCP客户端中配置 `@memtensor/memos-api-mcp` 服务 3. 设置环境变量(`MEMOS_API_KEY`、`MEMOS_USER_ID`、`MEMOS_CHANNEL`) ### 自己部署MCP服务 如果您需要私有化部署或定制化需求,可以在自己的服务器上部署MCP服务。 **优势:** - ✅ 数据完全私有化 - ✅ 可定制化配置 - ✅ 完全掌控服务 - ✅ 适合企业内部使用 **前置要求:** - Python 3.9+ - Neo4j数据库(或其他支持的图数据库) - HTTPS域名(用于Coze等平台) 继续阅读下方内容了解详细部署步骤。 --- ## 自部署MCP服务配置 以下内容适用于需要自己部署MCP服务的用户。 ## 架构说明 自部署MCP服务采用以下架构: ``` 客户端(Coze/Claude等) ↓ [HTTPS] MCP服务器(8002端口) ↓ [HTTP调用] Server API(8001端口) ↓ MemOS核心服务 ``` **组件说明:** - **Server API**: 提供REST API接口(`/product/*`),处理记忆的增删改查 - **MCP服务器**: 通过HTTP传输暴露MCP协议,调用Server API完成操作 - **HTTPS反向代理**: Coze等平台要求使用HTTPS安全连接 ### 步骤1: 启动Server API Server API是MCP服务的后端,提供实际的记忆管理功能。 ```bash cd /path/to/MemOS python src/memos/api/server_api.py --port 8001 ``` 验证Server API是否正常运行: ```bash curl http://localhost:8001/docs ``` 如果返回API文档页面,说明启动成功。 > **Note**: **配置文件** > Server API会自动加载配置,确保Neo4j等依赖服务已正确配置。可参考 `examples/data/config/tree_config_shared_database.json` 配置示例。 ### 步骤2: 启动MCP HTTP服务 在另一个终端启动MCP服务: ```bash cd /path/to/MemOS python examples/mem_mcp/simple_fastmcp_serve.py --transport http --port 8002 ``` MCP服务启动后会显示类似以下信息: ``` ╭──────────────────────────────────────────────────╮ │ MemOS MCP via Server API │ │ Transport: HTTP │ │ Server URL: http://localhost:8002/mcp │ ╰──────────────────────────────────────────────────╯ ``` **环境变量配置(可选):** 可以通过`.env`文件或环境变量配置Server API地址: ```bash export MEMOS_API_BASE_URL="http://localhost:8001/product" ``` > **Note**: **工具列表** > MCP服务提供以下工具: > - `add_memory`: 添加记忆 > - `search_memories`: 搜索记忆 > - `chat`: 与记忆系统对话 > > 完整工具列表参考 `examples/mem_mcp/simple_fastmcp_serve.py` ### 步骤3: 配置HTTPS反向代理 Coze等平台要求使用HTTPS连接。您需要配置HTTPS反向代理(如Nginx)将流量转发到MCP服务。 **Nginx配置示例:** ```nginx server { listen 443 ssl http2; server_name your-domain.com; ssl_certificate /path/to/cert.pem; ssl_certificate_key /path/to/key.pem; location /mcp { proxy_pass http://localhost:8002/mcp; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; # SSE支持 proxy_buffering off; proxy_cache off; } } ``` > **Warning**: **HTTPS证书** > 确保使用有效的SSL证书,自签名证书可能无法被Coze等平台接受。可使用Let's Encrypt免费获取证书。 ### 步骤4: 测试MCP服务 使用客户端测试脚本验证服务: ```bash cd /path/to/MemOS python examples/mem_mcp/simple_fastmcp_client.py ``` 成功输出示例: ``` Working FastMCP Client ======================================== Connected to MCP server 1. Adding memory... Result: Memory added successfully 2. Searching memories... Result: [搜索结果] 3. Chatting... Result: [AI响应] ✓ All tests completed! ``` ## 在Coze空间配置MCP 服务部署完成后,在Coze空间中配置MCP连接。 ### 步骤1: 打开Coze空间并进入工具配置页面 ![Coze空间配置页面](https://statics.memtensor.com.cn/memos/coze_space_1.png) ### 步骤2: 添加自定义MCP工具 在工具配置页面中添加自定义工具: ![添加自定义工具](https://statics.memtensor.com.cn/memos/coze_space_2.png) ### 步骤3: 配置MCP连接地址 配置MCP连接URL,使用您配置的HTTPS地址: ``` https://your-domain.com/mcp ``` 可用的MCP工具: - **add_memory**: 添加新记忆 - **search_memories**: 搜索已有记忆 - **chat**: 基于记忆的对话 > **Note**: **测试连接** > 配置完成后,在Coze中测试MCP连接是否正常。确保能够成功调用各个工具。 --- ## 直接使用REST API(高级) 对于需要更灵活集成的场景,可以直接使用Server API的REST接口。 ### 步骤1: 启动Server API ```bash cd /path/to/MemOS python src/memos/api/server_api.py --port 8001 ``` **端口说明** - Server API默认运行在8001端口 - 提供 `/product/*` REST API端点 ### 步骤2: 在Coze IDE配置自定义工具 1. 在Coze中选择"IDE插件"创建方式 2. 配置请求到您部署的Server API服务 ![Coze IDE插件配置](https://statics.memtensor.com.cn/memos/coze_tools_1.png) ### 步骤3: 实现add_memory工具 ![配置add_memory操作](https://statics.memtensor.com.cn/memos/coze_tools_2.png) **代码示例:** IDE中配置`add_memory`操作并发布: ![配置add_memory操作](https://statics.memtensor.com.cn/memos/coze_tools_2.png) 详细代码如下 ```python import json import requests from runtime import Args from typings.add_memory.add_memory import Input, Output def handler(args: Args[Input])->Output: memory_content = args.input.memory_content user_id = args.input.user_id cube_id = args.input.cube_id # 调用Server API的add接口 url = "https://your-domain.com:8001/product/add" payload = json.dumps({ "user_id": user_id, "messages": memory_content, # 支持字符串或消息数组 "writable_cube_ids": [cube_id] if cube_id else None }) headers = { 'Content-Type': 'application/json' } response = requests.post(url, headers=headers, data=payload, timeout=30) response.raise_for_status() return response.json() ``` **其他工具实现:** 类似地实现search和chat工具: ```python # Search工具 def search_handler(args: Args[Input]) -> Output: url = "https://your-domain.com:8001/product/search" payload = json.dumps{ "user_id": args.input.user_id, "query": args.input.query, }) headers = { 'Content-Type': 'application/json' } response = requests.post(url, headers=headers, data=payload, timeout=30) response.raise_for_status() return response.json() # Chat工具 def chat_handler(args: Args[Input]) -> Output: url = "https://your-domain.com:8001/product/chat/complete" payload = json.dumps({ "user_id": args.input.user_id, "query": args.input.query }) response = requests.post(url, json=payload, timeout=30) return response.json() ``` ### 步骤4: 发布并测试工具 发布完成后,可以在"我的资源"中查看插件: ![发布后的插件资源](https://statics.memtensor.com.cn/memos/coze_tools_3.png) ### 步骤5: 集成到智能体工作流 将插件添加到智能体工作流中: 1. 创建新的智能体或编辑现有智能体 2. 在工具列表中添加已发布的MemOS插件 3. 配置工作流,调用记忆工具 4. 测试记忆存储和检索功能 --- ## 常见问题 ### Q1: MCP服务无法连接到Server API **解决方案:** - 检查Server API是否正常运行:`curl http://localhost:8001/docs` - 检查环境变量`MEMOS_API_BASE_URL`配置是否正确 - 查看MCP服务日志,确认调用地址 ### Q2: Coze无法连接到MCP服务 **解决方案:** - 确保使用HTTPS连接 - 检查SSL证书是否有效 - 测试反向代理配置:`curl https://your-domain.com/mcp` - 检查防火墙和安全组设置 ### Q3: Neo4j连接失败 **解决方案:** - 确保Neo4j服务正常运行 - 检查配置文件中的连接信息(uri、user、password) - 参考 `examples/data/config/tree_config_shared_database.json` 配置示例 ### Q4: 如何查看完整的API示例? **参考文件:** - MCP服务端: `examples/mem_mcp/simple_fastmcp_serve.py` - MCP客户端: `examples/mem_mcp/simple_fastmcp_client.py` - API测试: `examples/api/server_router_api.py` --- ## 总结 通过本指南,您可以: - ✅ 选择适合的MCP部署方式(云服务或自部署) - ✅ 完成MCP服务的完整部署流程 - ✅ 在Coze等平台中集成MemOS记忆功能 - ✅ 使用REST API直接集成 无论选择哪种方式,MemOS都能为您的智能体提供强大的记忆管理ders=headers, data=payload) return json.loads(response.text) > **Note**: **API参数说明** > - 使用Server API的标准参数格式 > - `messages`: 替代原来的 `memory_content`,支持字符串或消息数组 > - `writable_cube_ids`: 替代原来的 `mem_cube_id`,支持多个cube > - Server API运行在8001端口,路径为 `/product/add` > - 确保与MemOS Server API接口一致,可参考 `examples/api/server_router_api.py` 中的示例 > **IDE配置** 在IDE中可以自定义工具的参数、返回值格式等,确保与MemOS API接口一致。 采用此方法完成 search 接口以及用户注册接口的编写,并点点击发布 ### 发布并使用插件 发布完成后,可以在"我的资源"中查看插件,以插件形式融入智能体工作流: ![发布后的插件资源](https://statics.memtensor.com.cn/memos/coze_tools_3.png) ### 构建智能体并测试 构建最简易智能体后,即可进行记忆操作测试: 1. 创建新的智能体 2. 添加已发布的记忆插件 3. 配置工作流 4. 测试记忆存储和检索功能 通过以上配置,您就可以在Coze空间中成功集成MemOS的记忆功能,为您的智能体提供强大的记忆能力。 --- # 参与 MemOS 开发 (/cn/open_source/contribution/overview) - **首次贡献者:** 请先阅读 [环境配置指南](setting_up.md),以准备你的开发环境。 - **准备开始编码了吗?** 请查看 [开发流程](development_workflow.md) 指南,了解我们提交更改的流程。 - **撰写规范的提交信息:** 请参考我们的 [提交规范](commit_guidelines.md)。 - **参与文档编写:** 如果你正在帮助我们改进文档,请阅读 [文档编写指南](writing_docs.md)。 - **添加或完善测试用例:** 请参考 [测试编写指南](writing_tests.md)。 你的贡献让这个项目更加优秀!✨ 如果有任何问题,欢迎提交 issue 或参与讨论,也可以扫描下方二维码加入我们的 Discord 或微信社群与我们联系。 QR Code --- # 配置开发环境 (/cn/open_source/contribution/setting_up) #### Fork 并克隆仓库 在本地设置项目仓库: - 在 GitHub 上 fork 仓库 - 将你的 fork 克隆到本地: ```bash git clone https://github.com/YOUR-USERNAME/MemOS.git cd MemOS ``` - 添加上游仓库作为远程源: ```bash git remote add upstream https://github.com/MemTensor/MemOS.git ``` #### 准备开发依赖 确保本地已安装: - Git - Python 3.9+ - Make 验证 Python: ```bash python3 --version ``` #### 安装 Poetry MemOS 使用 Poetry 管理 Python 依赖。推荐使用官方安装脚本: ```bash curl -sSL https://install.python-poetry.org | python - ``` 验证安装是否成功: ```bash poetry --version ``` 如果提示 `poetry: command not found`,请将安装器输出中提示的 Poetry 可执行文件目录加入 PATH,然后重新打开终端再验证。 更多安装选项参考:[官方安装指南](https://python-poetry.org/docs/#installing-with-the-official-installer)。 #### 安装依赖并设置 Pre-commit 钩子 在仓库根目录安装所有依赖与开发工具: ```bash make install ``` 提示: - 如果你切换分支或依赖发生变化,可能需要**重新运行 `make install`** 以保持环境一致 ### 理解记忆模块与依赖选择 在配置环境之前,我们需要先了解 MemOS 的记忆模块分类及其对应的数据库依赖。这将决定你需要安装哪些组件。 #### 记忆类型 MemOS 的记忆系统主要分为两类(括号内为配置项 `backend` 的标识符): - **明文记忆 (Textual Memory)**:属于事实记忆,**需要选择其中一种**。 - `tree` (`tree_text`): 树状记忆(推荐),结构化程度最高。 - `general` (`general_text`): 通用记忆,基于向量检索。 - `naive` (`naive_text`): 简单记忆,无特殊依赖(仅用于测试)。 - **偏好记忆 (Preference Memory)**:属于用户偏好,**可选**。 - `pref`: 用于存储和检索用户偏好。 #### 数据库依赖矩阵 不同的记忆类型需要不同的数据库支持: | 记忆类型 | 依赖组件 | 备注 | | :--- | :--- | :--- | | **Tree** | **图数据库** | 必选。支持 Neo4j Desktop, Neo4j Community , PolarDB | | **General** | **向量数据库** | 必选。推荐使用 Qdrant(或兼容向量 DB) | | **Naive** | 无 | 无需安装数据库 | | **Pref** | **Milvus** | 如果启用偏好记忆,必须安装 Milvus | #### 关于 Tree 记忆与图数据库的选择 如果你选择使用 **Tree 明文记忆后端**(配置标识通常为 `tree_text`),则需要准备一个 **图数据库(Graph DB)** 作为存储与查询基础。目前可选方案包括: - **Neo4j Desktop**(PC 端推荐):在本机安装并通过图形界面管理数据库,适合快速上手与调试。 - **PolarDB**:云上托管的图数据库服务(付费),适合生产或团队协作场景。 - **Neo4j Community**(社区版):开源免费,适合服务器或 Linux 环境部署。 **特别说明**: - 使用 **Neo4j Desktop** 时,你主要关注数据库的启动与连接即可,日常调试更方便。 - 使用 **Neo4j Community** 时,需要注意:它**不提供原生向量索引能力**。如果你的流程需要向量检索/相似度搜索能力,通常需要通过**外挂向量库**(例如 Qdrant)来补齐相关能力。 #### 本教程的配置方案 为便于开发者快速跑通核心链路,本教程采用以下组合: - **明文记忆后端**:`tree_text`(概念上对应 Tree 记忆) - **图数据库**:Neo4j Community(可使用 Docker 启动) - **向量能力**:Qdrant(本地模式) 由于 Neo4j Community 不支持原生向量索引,本教程引入 Qdrant 作为向量能力的补充。为了降低环境复杂度,我们**不启动 Qdrant 的服务端进程**(不运行 Qdrant 容器),而是使用 Qdrant 的**本地模式**:在配置中以本地路径(`path`)形式指定存储位置,由系统在该目录下初始化并读写所需的数据文件。若未显式指定路径,则会使用默认路径进行初始化与持久化(具体默认位置以项目实现与配置为准)。 #### 创建配置文件 .env 内容,快速配置请见 docker 安装下的[env 配置](/open_source/getting_started/installation#2.-.env-内容) .env详细配置请见[env配置](/open_source/getting_started/rest_api_server/#本地运行) > **Note**: **请注意** > .env 文件配置需要放在MemOS 项目根目录下 ```bash cd MemOS touch .env ``` #### 配置Dockerfile文件 > **Note**: **请注意** > Dockerfile 文件在 docker 目录下 ```bash #进入docker目录下 cd docker ``` 包含快速模式和完整模式,可区分使用精简包(区分arm和x86)和全量包(区分arm和x86) ```bash ● 精简包:简化体量过大的 nvidia相关等依赖,对镜像实现轻量化,使本地部署更加轻量快速。 url: registry.cn-shanghai.aliyuncs.com/memtensor/memos-base:v1.0 url: registry.cn-shanghai.aliyuncs.com/memtensor/memos-base-arm:v1.0 ● 全量包:将 MemOS 全部依赖包打为镜像,可体验完整功能,通过配置 Dockerfile可直接构建启动。 url: registry.cn-shanghai.aliyuncs.com/memtensor/memos-full-base:v1.0.0 url: registry.cn-shanghai.aliyuncs.com/memtensor/memos-full-base-arm:v1.0.0 ``` ```bash # 当前示例使用精简包 url FROM registry.cn-shanghai.aliyuncs.com/memtensor/memos-base-arm:v1.0 WORKDIR /app ENV HF_ENDPOINT=https://hf-mirror.com ENV PYTHONPATH=/app/src COPY src/ ./src/ EXPOSE 8000 CMD ["uvicorn", "memos.api.server_api:app", "--host", "0.0.0.0", "--port", "8000", "--reload"] ``` #### 启动docker客户端 ```bash # 如果没有安装docker,请安装对应版本,下载地址如下: https://www.docker.com/ # 安装完成之后,可通过客户端启动docker,或者通过命令行启动docker # 通过命令行启动docker sudo systemctl start docker # 安装完成后,查看docker状态 docker ps # 查看docker镜像 (可不用) docker images ``` #### 构建并启动服务 : > **Note**: **请注意** > 构建命令同样在 docker 目录下 ```bash # 在docker目录下 docker compose up neo4j ``` #### 新建终端启动server端口 : ```bash cd MemOS make serve ``` --- # 开发流程 (/cn/open_source/contribution/development_workflow) 按照以下步骤参与项目开发。 #### 与上游仓库同步 如果你之前 fork 了该仓库,请与上游仓库的变更保持同步: ```bash git checkout dev # 切换到 dev 分支 git fetch upstream # 获取上游仓库的最新更改 git pull upstream dev # 将更改合并到本地 dev 分支 git push origin dev # 将合并后的代码推送到你自己的 fork ``` #### 创建功能分支 为你的新功能或修订创建一个新的分支: ```bash git checkout -b feat/descriptive-name ``` #### 添加你的功能或修订 在相应文件中实现你的功能、修订或改进。 * 例如,你可以在 `src/memos/hello_world.py` 中添加一个函数,并在 `tests/test_hello_world.py` 中编写相应的测试用例。 #### 测试你的更改 运行测试套件以确保更改正确: ```bash make test ``` #### 提交更改 在提交前或 PR 前,rebase 到最新 upstream/dev: ```bash git fetch upstream git rebase upstream/dev # 把你的 feat 分支基于最新 dev 重放 ``` 提交更改时请遵循项目的提交规范(参见 [提交规范](commit_guidelines.md))。 #### 推送到你的 Fork 仓库 将功能分支推送到你 fork 的远程仓库: ```bash git push origin feat/descriptive-name ``` #### 创建 Pull Request 提交你的更改以供审核: * **重要提示:** 请务必将 Pull Request 提交到: * ✅ 上游仓库的 `dev` 分支, * ❎ 而不是上游仓库的 `main` 分支。 * 打开 GitHub 上的原始仓库 * 点击 "Pull Requests" * 点击 "New Pull Request" * 选择 `dev` 作为目标分支,你的分支作为对比分支 * 仔细填写 PR 描述 --- # 提交规范 (/cn/open_source/contribution/commit_guidelines) 请遵循 [Conventional Commits](https://www.conventionalcommits.org/) 格式: - `feat:` 用于新增功能 - `fix:` 用于修复 bug - `docs:` 用于文档更新 - `style:` 用于格式调整(不影响代码逻辑) - `refactor:` 用于代码重构 - `test:` 用于新增或更新测试 - `chore:` 用于其他维护任务 - `ci:` 用于 CI/CD 或工作流相关变更 **示例:** `feat: add user authentication` --- # 文档编写指南 (/cn/open_source/contribution/writing_docs) ## 创建新文档 ### 创建 Markdown 文件 在 `content/` 目录或其子目录中创建新的 `.md` 文件。根据内容类型选择合适的位置。 ### 添加 Frontmatter 在文件顶部添加 YAML frontmatter 来提供元数据。frontmatter 支持以下字段: **必填字段:** - `title`(字符串) - 显示在导航和页面标题中的文档标题 **可选字段:** - `desc`(字符串) - 文档内容的简要描述 - `banner`(字符串) - 页面顶部展示的横幅图片链接 - `links`(数组) - 包含标签、URL 和图标的相关链接数组 ![Frontmatter 示例](https://statics.memtensor.com.cn/memos/frontmatter.png) **完整 Frontmatter 示例:** ```yaml --- title: MemOS 文档 desc: 欢迎阅读 MemOS 的官方文档——一个旨在赋能大语言模型(LLMs)实现高级、模块化记忆能力的 Python 包。 banner: https://statics.memtensor.com.cn/memos/memos-banner.gif links: - label: 'PyPI' to: https://pypi.org/project/MemoryOS/ target: _blank avatar: src: https://statics.memtensor.com.cn/icon/pypi.svg alt: PyPI logo - label: '开源地址' to: https://github.com/MemTensor/MemOS target: _blank icon: i-simple-icons-github --- ``` ### 编写内容 使用 Markdown 语法和 MDC 组件撰写文档内容。利用已有组件构建结构清晰、交互友好、内容丰富的文档。 ### 更新导航 将新文档添加到 `content/settings.yml` 中的 `nav` 部分,以便在站点导航中访问。 ### 合并到主分支 一旦变更合并到 `main` 分支,文档将自动更新并部署。 ## 组件示例 本项目使用 Nuxt Content 的 MDC(Markdown Components)语法,支持在 Markdown 中使用 Vue 组件。这些组件有助于创建风格一致、结构良好、体验优秀的文档内容。 ### Image 为文档添加图片时,可以使用多种方式进行引用: #### 使用 Base64Image 组件引用本地图片 对于存储在 `public/assets` 目录下的图片,推荐使用 `Base64Image` 组件,该组件能将图片直接嵌入页面以提高性能: ```mdc :Base64Image{src="/assets/memos-architecture.png" alt="MemOS Architecture"} ``` #### 使用 Markdown 语法引用远程图片 对于托管在外部服务器上的图片,使用标准的 Markdown 图片语法: ```markdown ![MemOS Architecture](https://statics.memtensor.com.cn/memos/memos-architecture.png) ``` ### Steps 使用 `steps` 组件将文档标题自动编号,生成逐步引导的教程。 --- class: "[&>div]:*:w-full" --- #### Fork 并克隆仓库 在本地设置项目仓库: - 在 GitHub 上 fork 仓库 - 将你的 fork 克隆到本地: ```bash git clone https://github.com/YOUR-USERNAME/MemOS.git cd MemOS ``` - 添加上游仓库作为远程源: ```bash git remote add upstream https://github.com/MemTensor/MemOS.git ``` #### 准备开发依赖 确保本地已安装: - Git - Python 3.9+ - Make 验证 Python: ```bash python3 --version ``` #### 安装 Poetry MemOS 使用 Poetry 管理 Python 依赖。推荐使用官方安装脚本: ```bash curl -sSL https://install.python-poetry.org | python3 - ``` 验证安装是否成功: ```bash poetry --version ``` 如果提示 `poetry: command not found`,请将安装器输出中提示的 Poetry 可执行文件目录加入 PATH,然后重新打开终端再验证。 更多安装选项参考:[官方安装指南](https://python-poetry.org/docs/#installing-with-the-official-installer)。 #### 安装依赖并设置 Pre-commit 钩子 在仓库根目录安装所有依赖与开发工具: ```bash make install ``` 提示: - 如果你切换分支或依赖发生变化,可能需要**重新运行 `make install`** 以保持环境一致 #code ````mdc #### Fork 并克隆仓库 在本地设置项目仓库: - 在 GitHub 上 fork 仓库 - 将你的 fork 克隆到本地: ```bash git clone https://github.com/YOUR-USERNAME/MemOS.git cd MemOS ``` - 添加上游仓库作为远程源: ```bash git remote add upstream https://github.com/MemTensor/MemOS.git ``` #### 准备开发依赖 确保本地已安装: - Git - Python 3.9+ - Make 验证 Python: ```bash python3 --version ``` #### 安装 Poetry MemOS 使用 Poetry 管理 Python 依赖。推荐使用官方安装脚本: ```bash curl -sSL https://install.python-poetry.org | python3 - ``` 验证安装是否成功: ```bash poetry --version ``` 如果提示 `poetry: command not found`,请将安装器输出中提示的 Poetry 可执行文件目录加入 PATH,然后重新打开终端再验证。 更多安装选项参考:[官方安装指南](https://python-poetry.org/docs/#installing-with-the-official-installer)。 #### 安装依赖并设置 Pre-commit 钩子 在仓库根目录安装所有依赖与开发工具: ```bash make install ``` 提示: - 如果你切换分支或依赖发生变化,可能需要**重新运行 `make install`** 以保持环境一致 ```` ### Accordion 使用 `accordion` 和 `accordion-item` 创建可折叠内容区域。适用于组织 FAQ、可展开详情或分组信息等场景。 --- class: "[&>div]:*:my-0" --- :accordion-item --- icon: i-lucide-circle-help label: MemOS 是否兼容通过 API 访问的大语言模型(LLM)? --- 是的。MemOS 设计时尽可能兼容各种类型的模型。不过需要注意的是,如果你使用的是基于 API 的模型,那么激活记忆和参数记忆将无法使用。 :::: : --- icon: i-lucide-circle-help label: MemOS 如何提升大语言模型应用的效果? --- MemOS 通过提供结构化的、持久化的记忆功能、智能调度机制、长期知识保留能力,以及用于快速推理的 KV cache,增强了大语言模型的应用效果。它支持精细化的访问控制与用户隔离,保障在多用户环境中的记忆安全。其模块化架构使得新记忆类型、LLM 及存储后端可以无缝集成,适用于各种智能应用场景。: : MemOS 开源版本是免费的。: #code ```mdc 是的。MemOS 的设计目标是尽可能兼容各种类型的模型。然而需要注意的是,如果你使用的是基于 API 的模型,那么激活记忆和参数记忆将无法使用。 MemOS 通过提供结构化、持久化的记忆,配合智能调度、长期知识保留机制以及用于快速推理的 KV cache,有效增强了大语言模型的应用能力。它支持细粒度的访问控制与用户隔离机制,确保在多用户环境中的记忆安全。其模块化架构支持无缝集成新的记忆类型、LLM 和存储后端,能够适配多种智能应用场景。 MemOS 开源版本是免费的。 ``` ### Badge 使用 badge 展示状态指示或标签。在内容中高亮版本号、状态或分类信息时非常实用。 --- label: Preview --- **v1.0.0** #code ```mdc **v1.0.0** ``` ### Callout 使用 callout 可以强调重要的上下文信息。Callout 用于引起用户注意,例如备注、提示、警告或注意事项,使关键信息更加突出。 你可以通过 `icon` 和 `color` 属性自定义样式,或者使用预定义的语义样式 `note`、`tip`、`warning`、`caution` 进行快捷调用。 --- class: "[&>div]:*:my-0 [&>div]:*:w-full" --- 这是一个支持完整 **markdown** 的 `callout` 提示框。 #code ```mdc 这是一个支持完整 **markdown** 的 `callout` 提示框。 ``` : > **Note**: 基础备注内容 > : : > **Note**: 带链接的备注 —— 点击跳转到快速开始指南 > : : > **Note**: 带自定义图标的备注 —— 了解更多关于 MemCube 的信息 > : : > **Tip**: 这里是一个有用的建议。 > : : > **Warning**: 请谨慎操作,此行为可能导致意外结果。 > : : > **Caution**: 此操作无法撤销。 > : #code ```mdc > **Note**: 基础备注内容 > **Note**: 带链接的备注 —— 点击跳转到快速开始指南 > **Note**: 带自定义图标的备注 —— 了解更多关于 MemCube 的信息 > **Tip**: 这里是一个有用的建议。 > **Warning**: 请小心执行此操作,它可能会导致意外结果。 > **Caution**: 此操作无法撤销。 ``` ### Card 使用 `card` 可高亮展示内容模块。卡片适用于展示功能、资源或相关信息,以视觉上区分并增强交互性。 你可以通过 `title`、`icon` 和 `color` 属性自定义样式。Card 还支持使用 `` 属性进行导航跳转。 --- class: "[&>div]:*:my-0 [&>div]:*:w-full" --- - [开源项目](https://github.com/MemTensor/MemOS): 使用我们的开源版本 #code ```mdc --- title: 开源项目 icon: i-simple-icons-github to: https://github.com/MemTensor/MemOS target: _blank --- 使用我们的开源版本 ``` ### CardGroup 使用 `card-group` 可将多个卡片以网格形式排列。适合展示结构化、响应式布局的卡片集合,视觉效果良好。 :- [最简Pipeline](/open_source/getting_started/examples#example-1-minimal-pipeline): 最小可用Pipeline — 添加、搜索、更新和导出明文记忆。: :- [仅 TreeTextMemory](/open_source/getting_started/examples#example-2-treetextmemory-only): 使用基于 Neo4j 的分层记忆,构建结构化、多跳的知识图谱。: :- [仅 KVCacheMemory](/open_source/getting_started/examples#example-3-kvcachememory-only): 通过短期 KV cache加速会话,实现快速上下文注入。: :- [混合 TreeText + KVCache](/open_source/getting_started/examples#example-4-hybrid): 在单一 MemCube 中结合可解释的图记忆与快速 KV cache。: #code ```mdc - [最简Pipeline 示例](/open_source/getting_started/examples#example-1-minimal-pipeline): 最小可运行的Pipeline 示例——添加、搜索、更新及导出明文记忆。 - [仅使用 TreeTextMemory](/open_source/getting_started/examples#example-2-treetextmemory-only): 使用基于 Neo4j 的层级记忆构建结构化的多跳知识图谱。 - [仅使用 KVCacheMemory](/open_source/getting_started/examples#example-3-kvcachememory-only): 通过短期KV cache加速会话,实现快速上下文注入。 - [混合使用 TreeText 和 KVCache](/open_source/getting_started/examples#example-4-hybrid): 在单一 MemCube 中结合可解释的图记忆与高速KV cache。 ``` ## 导航图标 在 `content/settings.yml` 中添加导航条目时,可以使用 `(ri:图标名称)` 的语法嵌入图标: ```yaml - "(ri:home-line) 首页": overview.md - "(ri:team-line) 用户管理": modules/mos/users.md - "(ri:flask-line) 测试编写": contribution/writing_tests.md ``` 可用图标请参考:[https://icones.js.org/](https://icones.js.org/) ## 本地预览 若需本地预览文档,可在项目根目录下执行以下命令。 首先安装依赖: ```bash pnpm install ``` 启动开发服务器: ```bash pnpm dev ``` 上述命令将启动本地 Web 服务器,通常访问地址为 `http://127.0.0.1:3000`。 ## 深入了解 ### Nuxt Content 与排版系统 本项目使用 Nuxt Content,支持丰富的排版组件与样式。如需了解更多组件用法与自定义选项,请参考: * [Nuxt UI Typography 文档](https://ui.nuxt.com/getting-started/typography) ## 编写规范 > **Note**: **文档编写建议** > > 1. **结构清晰**:使用恰当的标题层级组织内容 > 2. **合理使用组件**:如 note、card 等组件提升可读性与互动性 > 3. **代码示例清晰**:为技术文档提供清晰的代码片段,并使用语法高亮 > 4. **图标使用**:在导航中使用合适的图标以增强用户体验与层次感 提交前请先本地测试你的文档效果。运行 `pnpm dev` 以预览你的变更并确保所有组件正确渲染。 --- # 如何编写单元测试 (/cn/open_source/contribution/writing_tests) ## 编写测试 1. 在 `tests/` 目录下创建一个新的 Python 文件,文件名应以 `test_` 开头。 2. 在该文件中定义以 `test_` 开头的函数。 3. 使用 `assert` 语句检查预期结果。 以下是一个基本示例: ```python # tests/test_example.py def test_addition(): assert 1 + 1 == 2 ``` ## 运行测试 要运行所有测试,请在项目根目录下执行以下命令: ```bash make test ``` 该命令将自动发现并运行 `tests/` 目录下的所有测试用例。 ## 高级技巧 Pytest 提供了许多高级功能,例如 fixtures 和 mocking。 ### Fixtures Fixtures 是可以为测试提供数据或设置初始状态的函数。使用 `@pytest.fixture` 装饰器进行定义。 ### Mocking Mocking 用于用 mock 对象替换系统中的某些部分。这对于隔离被测试的代码非常有用。常用的工具是 `unittest.mock` 库,通常配合 `patch` 函数使用。 有关 mocking 的示例,请参见 `tests/test_hello_world.py`。 --- # 使用示例 (/cn/self_developed_model/extraction_usage_example) MemOS 提供记忆抽取接口,基于自研 **memos-extractor-0.6b** 小模型,开发者可直接传入对话内容,一键提取事实记忆与偏好记忆。 接口字段与 OpenAPI 说明:[Extract Memory](/cn/api_docs/core/extract_memory)。 鉴权、Base URL 与调用方式与 [MemOS Cloud 快速开始](/cn/memos_cloud/getting_started/quick_start) 一致。 ## 何时使用记忆抽取模型 记忆抽取接口适用于以下场景: - **轻量级记忆提取**:无需部署完整的 add/message 流程,直接从对话中提取结构化记忆。 - **低延迟高频调用**:基于 0.6B 自研小模型,适合对延迟敏感、调用频繁的业务场景。 - **灵活的抽取控制**:可按需选择抽取事实记忆、偏好记忆或全部,满足不同业务需求。 ## 工作原理 ![记忆抽取流程](https://cdn.memtensor.com.cn/img/1775554708977_az90s6_compressed.png) 抽取模型的完整调用流程可分为以下步骤: 1. **数据输入(Data Input)** 开发者传入原始对话数据(`messages`),每条消息包含 `role` 与 `content` 字段。 2. **格式化与清洗(Format & Clean Processing)** 对话内容经格式化处理,统一为标准格式;同时进行语言检测,识别对话所使用的语言。 3. **任务与语言选择(Task & Language Selector)** 根据 `extraction_types` 与检测到的语言,进入对应的抽取分支: - **Memory Reader**:事实记忆抽取 - **Explicit Preference**:显性偏好抽取 - **Implicit Preference**:隐性偏好抽取 4. **Prompt 构建(Builder)** 将当前分支所需的 Prompt 模板组装为最终推理请求。 5. **API 调用(API Call)** 按约定格式请求 memos-extractor-0.6b 模型完成推理。 6. **返回结果(Final Results)** 模型返回结构化结果,包含事实记忆列表和/或偏好记忆列表(随请求中的抽取类型而定)。 ## 快速上手 ```python [事实 + 偏好] import os, json, requests os.environ["MEMOS_API_KEY"] = "YOUR_API_KEY" os.environ["MEMOS_BASE_URL"] = "https://memos.memtensor.cn/api/openmem/v1" data = { "messages": [ {"role": "system", "content": "从对话中提取关键记忆。"}, {"role": "user", "content": "我叫张三,28岁,杭州后端,喜欢羽毛球。"}, {"role": "assistant", "content": "你好张三!"}, {"role": "user", "content": "回复尽量简洁,别太啰嗦。"}, ] } headers = {"Content-Type": "application/json", "Authorization": f"Token {os.environ['MEMOS_API_KEY']}"} url = f"{os.environ['MEMOS_BASE_URL']}/extract/memory" res = requests.post(url, headers=headers, data=json.dumps(data)) print(res.json()) ``` ```python [仅事实] import os, json, requests os.environ["MEMOS_API_KEY"] = "YOUR_API_KEY" os.environ["MEMOS_BASE_URL"] = "https://memos.memtensor.cn/api/openmem/v1" data = { "messages": [{"role": "user", "content": "下周三去北京出差,住朝阳全季。"}], "extraction_types": ["memory"], } headers = {"Content-Type": "application/json", "Authorization": f"Token {os.environ['MEMOS_API_KEY']}"} url = f"{os.environ['MEMOS_BASE_URL']}/extract/memory" res = requests.post(url, headers=headers, data=json.dumps(data)) print(res.json()) ``` ```python [仅偏好] import os, json, requests os.environ["MEMOS_API_KEY"] = "YOUR_API_KEY" os.environ["MEMOS_BASE_URL"] = "https://memos.memtensor.cn/api/openmem/v1" data = { "messages": [ {"role": "user", "content": "文档用 Markdown,代码块要高亮。"}, {"role": "assistant", "content": "好的。"}, {"role": "user", "content": "少用 emoji。"}, ], "extraction_types": ["preference"], } headers = {"Content-Type": "application/json", "Authorization": f"Token {os.environ['MEMOS_API_KEY']}"} url = f"{os.environ['MEMOS_BASE_URL']}/extract/memory" res = requests.post(url, headers=headers, data=json.dumps(data)) print(res.json()) ``` ### 输出示意 ```json [事实 + 偏好] { "code": 0, "message": "ok", "data": { "success": true, "memory_detail_list": [ { "memory_key": "用户身份与职业", "memory_value": "用户张三,28岁,在杭州从事后端开发,喜欢打羽毛球。", "memory_type": "UserMemory", "tags": ["人物", "职业", "地点", "爱好"] } ], "preference_detail_list": [ { "preference": "希望助理回复尽量简洁,不要过于啰嗦。", "reasoning": "用户在对话中明确要求「回复尽量简洁一些,不要太啰嗦」。", "preference_type": "explicit_preference" } ] } } ``` ```json [仅事实] { "code": 0, "message": "ok", "data": { "success": true, "memory_detail_list": [ { "memory_key": "出差行程与住宿", "memory_value": "用户下周三将去北京出差,计划入住朝阳区全季酒店。", "memory_type": "LongTermMemory", "tags": ["行程", "差旅", "住宿"] } ] } } ``` ```json [仅偏好] { "code": 0, "message": "ok", "data": { "success": true, "preference_detail_list": [ { "preference": "偏好使用带语法高亮的 Markdown 代码块呈现文档内容。", "reasoning": "用户明确表示喜欢 Markdown 与代码块高亮。", "preference_type": "explicit_preference" }, { "preference": "尽量减少 emoji 的使用。", "reasoning": "用户直接提出不要用太多 emoji。", "preference_type": "explicit_preference" } ] } } ``` ## 使用限制 - 接口输入上限:**8,000 tokens**。 - 当前仅支持**同步模式**,接口将在抽取完成后一次性返回结果。 - 当前仅支持传入**对话文本**:`messages` 中每条消息仅包含 `role` 与 `content`;**暂不支持多模态**输入,也无法通过本接口抽取多模态记忆。 ## 对比 add/message 接口 | 对比维度 | 记忆抽取接口 | add/message 接口 | | --- | --- | --- | | 核心能力 | 从对话中提取记忆,仅返回结果 | 写入对话并自动提取、存储记忆 | | 记忆存储 | ❌ 不写入 MemOS 记忆库 | ✅ 自动写入 MemOS 记忆库 | | 推理模型 | 自研 0.6B 小模型,低延迟 | MemOS 内置模型 | | 异步模式 | 暂不支持 | ✅ 支持 | | 偏好记忆 | ✅ 支持(显性 + 隐性) | ✅ 支持 | | 工具记忆 / 技能 | ❌ 不支持 | ✅ 支持 | | 典型使用场景 | 独立的记忆分析 / 预处理 / 质量评估 | 完整的对话记忆管理 | --- # 使用示例 (/cn/self_developed_model/reranker_usage_example) MemOS 提供记忆重排接口,基于 **memos-reranker** 系列模型(包括 0.6B 轻量版和 4B 增强版,基础模型采用 qwen-reranker 后训练),开发者可直接传入用户查询与候选记忆列表,一键完成记忆相关性重排。 接口字段与 OpenAPI 说明:[Rerank Memory](/cn/api_docs/core/rerank)。 鉴权、Base URL 与调用方式与 [MemOS Cloud 快速开始](/cn/memos_cloud/getting_started/quick_start) 一致。 ## 何时使用记忆重排模型 记忆重排接口适用于以下场景: - **记忆召回优化**:在检索到大量候选记忆后,通过重排精准筛选出与当前查询最相关的记忆,提升上下文注入质量。 - **低延迟高频调用**:基于 0.6B 小模型,适合对延迟敏感、调用频繁的业务场景。 - **灵活的排序控制**:支持自定义候选文档列表,可与任意检索系统配合使用,不依赖 MemOS 记忆库。 不建议在下面场景直接调用重排接口: - 还没有候选文档,只是想从记忆库里查找内容。此时应先调用 [Search Memory](/memos_cloud/mem_operations/search_memory)。 - 希望把内容写入记忆。重排接口不会写入 MemOS 记忆库,应使用 [Add Message](/memos_cloud/mem_operations/add_message)。 - 想对超长文档全文排序。请先检索、切分或截断候选内容,再把较短候选片段传给 `documents`。 ## 工作原理 记忆重排的 API 以及与模型的交互如下图所示: ![记忆重排流程](https://cdn.memtensor.com.cn/img/1776755224177_y8jat9_compressed.png) 重排模型的完整调用流程如下: 1. **查询输入** 开发者传入用户查询(`query`)和候选记忆文档列表(`documents`)。 2. **编码与表征** 经过模型编码输出相关性分数。 3. **相关性打分** 相关性分数主要分为 5 个阶段如图所示,开发者可以根据实际场景进行阈值的设定。 ## 快速上手 ```python [基础重排] import os import requests import json # 替换成你的 MemOS API Key os.environ["MEMOS_API_KEY"] = "YOUR_API_KEY" os.environ["MEMOS_BASE_URL"] = "https://memos.memtensor.cn/api/openmem/v1" data = { # 可选模型:memos-reranker-0.6b(轻量版)或 memos-reranker-4b(增强版) "model": "memos-reranker-0.6b", "query": "有什么酒可以推荐给我呢", "documents": [ "用户比较喜欢酱香型的,比方说茅台", "我不喝酒" ] } headers = { "Content-Type": "application/json", "Authorization": f"Token {os.environ['MEMOS_API_KEY']}" } url = f"{os.environ['MEMOS_BASE_URL']}/rerank" res = requests.post(url=url, headers=headers, data=json.dumps(data)) print(f"result: {res.json()}") ``` ```python [结合记忆检索的重排] import os import requests import json # 替换成你的 MemOS API Key os.environ["MEMOS_API_KEY"] = "YOUR_API_KEY" os.environ["MEMOS_BASE_URL"] = "https://memos.memtensor.cn/api/openmem/v1" data = { # 可选模型:memos-reranker-0.6b(轻量版)或 memos-reranker-4b(增强版) "model": "memos-reranker-0.6b", "query": "用户有什么兴趣爱好", "top_n": 3, "documents": [ "用户喜欢打羽毛球", "用户在杭州做后端开发", "用户偏好简洁的回复风格", "用户比较喜欢酱香型白酒", "用户下周三要去北京出差" ] } headers = { "Content-Type": "application/json", "Authorization": f"Token {os.environ['MEMOS_API_KEY']}" } url = f"{os.environ['MEMOS_BASE_URL']}/rerank" res = requests.post(url=url, headers=headers, data=json.dumps(data)) print(f"result: {res.json()}") ``` ## 使用限制 - `query` 为必填,建议传入清晰、短句式的当前问题。 - `documents` 为必填,必须是非空字符串数组;数组中所有候选文档的总 token 数上限为 **8k**。 - `top_n` 可选,用于返回前 N 条最相关结果;不传时默认返回全部结果。 - `model` 可选,支持 `memos-reranker-0.6b` 和 `memos-reranker-4b`。 - 当前仅支持**同步模式**,接口将在重排完成后一次性返回结果。 ## 常见错误与排查 | 错误码 | 常见原因 | 处理方式 | | --- | --- | --- | | `40000` | 请求体结构错误,或字段类型不符合要求 | 检查 `query` 是否为字符串,`documents` 是否为字符串数组 | | `40002` / `40003` | 必填字段为空,或 `documents` 为空 | 补充 `query` 和非空 `documents`,不要传空数组 | | `40309` | 单位时间输入 token 超限 | 减少候选文档数量和长度,降低调用并发,分批重试 | | `50000` | 系统内部异常 | 稍后重试;如果持续出现,请联系支持 | ## 对比 Embedding 检索 | 对比维度 | 记忆重排接口 | Embedding 向量检索 | | --- | --- | --- | | 核心能力 | 对候选文档精排,输出相关性分数 | 语义相似度召回,快速粗筛 | | 记忆存储 | ❌ 不写入 MemOS 记忆库 | ❌ 不写入 MemOS 记忆库 | | 推理模型 | 0.6B/4B 重排模型 | Embedding 模型 | | 精度 | ✅ 高(交叉编码,query-doc 交互) | 一般(双塔编码,独立表征) | | 速度 | 较慢(需逐对计算) | ✅ 快(向量近似检索) | | 异步模式 | 暂不支持 | 暂不支持 | | 典型使用场景 | 检索后精排 / 记忆质量评估 | 海量记忆库快速召回 | --- # 接入总览 (/cn/mcp_agent/overview) MemOS 面向 Agent 提供 MCP 服务、MemOS 插件、CLI 与 Coze 插件工具四种接入方式,其中插件包含云插件与本地插件两种形态。下表列出各方式适用的客户端与记忆存放位置;已经确定所用客户端的,可参考后文「按客户端选择」一节。 ## 接入方式对照 | 接入方式 | 适用客户端 | 记忆存放位置 | | --- | --- | --- | | [MCP 服务](/cn/mcp_agent/mcp/guide) | Claude Desktop、Cursor、VS Code 或 Trae、Chatbox 等支持 MCP 的客户端 | MemOS 云服务,也可自部署 MCP 服务 | | [云插件](/cn/openclaw/guide) | OpenClaw、DeepSeek Harness | MemOS 云服务,多 Agent 跨设备共享 | | [本地插件](/cn/openclaw/local_plugin) | OpenClaw、Hermes Agent、DeepSeek Harness | 本机 SQLite,数据不出本地 | | [CLI](/cn/mcp_agent/cli/guide) | 可执行 shell 命令的 Agent 与终端环境 | MemOS 云服务 | | [Coze 插件工具](/cn/mcp_agent/agent/guide) | Coze 平台智能体,零代码集成 | MemOS 云服务 | ## 按客户端选择 - **Claude Desktop、Cursor、VS Code、Trae、Chatbox**:使用 MCP 服务。在客户端配置中填写 MemOS MCP 地址即可,无需编写代码。 - **OpenClaw**:云插件与本地插件的差异见[对比说明](/cn/openclaw/plugin_compare)。要求开箱即用、多台设备共享记忆时,云插件更合适;要求数据保留在本机,并需要可观测性时,本地插件更合适。 - **Hermes Agent**:使用本地插件。Hermes 通过 Python Provider 接入同一套本地记忆核心。 - **DeepSeek Harness**:云插件与本地插件均支持,按记忆是否允许离开本机区分。 - **Coze**:使用 Coze 商店上架的插件工具,在智能体中添加即可,无需部署。 - **自建 Agent,可执行命令行**:使用 CLI。它把 `add`、`search`、`get` 等记忆操作封装为命令,也便于多个框架共用同一份记忆。 ## 云插件与本地插件的取舍 这两种方式都面向 OpenClaw、Hermes Agent 与 DeepSeek Harness 这类本地运行的 Agent,差异在于记忆的存放位置与管理方式。 | 维度 | 云插件 | 本地插件 | | --- | --- | --- | | 记忆存放 | MemOS 云服务 | 本机 SQLite | | 跨设备与多 Agent 共享 | 支持 | 仅本机 | | 数据是否离开本机 | 是 | 否 | | 可观测性 | 云端调用日志 | 本地管理面板,含任务轨迹、Analytics 与 Logs | | 适合场景 | 快速接入、跨设备协作、生产环境 | 隐私敏感、本地化运行、长期沉淀可复用经验 | 两种插件的完整对比与安装步骤见[云插件 vs 本地插件](/cn/openclaw/plugin_compare)。 --- # MemOS MCP 使用指南 (/cn/mcp_agent/mcp/guide) MemOS 记忆管理 MCP 是一款强大的 AI 记忆增强插件,支持**对话记忆存取**、**用户画像构建**与**向量知识库全生命周期管理**三大核心能力。 通过将 MemOS 接入 Claude、Cursor、Cline 等主流 AI 客户端,用户可以让 AI 持续积累个人记忆、理解用户偏好,并高效处理大规模专业文档,从根本上提升 AI 对话的连贯性与个性化水平。 ## 1. 能力介绍 ### 1.1 对话记忆管理 提供对话内容的写入、检索、删除与质量反馈功能,是 MemOS MCP 的基础能力模块。 | 工具 | 功能说明 | |---|---| | `add_message` | 将当前对话内容摘要写入用户记忆库,供后续检索使用 | | `search_memory` | 根据检索词在用户个人记忆库中搜索相关历史记忆 | | `delete_memory` | 从记忆库中删除指定的记忆条目 | | `add_feedback` | 对记忆条目提交质量反馈,优化记忆管理效果 | ### 1.2 用户画像系统 **`get_user_profile`**:一键调取用户的全维度记忆画像。 不同于单一的事实记忆(Facts),用户画像还整合了显性/隐性偏好(Preferences)以及工具使用经验(Tool Trajectories),让 AI 能够回答"我是谁?"、"我的偏好是什么?"等身份相关问题,实现真正的个性化交互。 ### 1.3 知识库全生命周期管理 支持为特定项目或领域创建独立的命名空间容器,便于结构化文档的隔离管理。 | 工具 | 功能说明 | |---|---| | `create_knowledge_base` | 创建独立的知识库容器,用于特定项目或领域的文档管理 | | `remove_knowledge_base` | 移除不再需要的知识库及其关联内容 | ### 1.4 智能文档上传 **`add_kb_document`**:支持将本地文件或在线资源注入指定知识库,是知识库能力的核心工具。 **核心特性:** - **本地文件直传**:首创 MCP 内部拦截机制,支持大模型直接传递本地路径。 - **多态路径识别**:完美支持 Windows (盘符)、Unix (绝对路径)、Home 目录 (~/) 以及环境变量路径。 - **零上下文损耗**:在本地静默完成 Base64 转换与 MIME 类型封装,彻底避免长文档撑爆上下文。 - **智能直链补全**:自动修正不规范的 URL(补全 http/https)并识别在线资源。 - **熔断安全策略**:内置防死磕指令,一旦接口报错立即熔断,防止消耗多余流量。 ### 1.5 文档精准管控 支持对已上传文档的批量查询与精准删除,实现知识库的动态维护。 | 工具 | 功能说明 | |---|---| | `get_kb_documents` | 通过 File ID 列表批量获取已上传文档的详细元数据 | | `delete_kb_documents` | 从指定知识库中精准删除特定文档,实现文档库动态精简 | ## 2. 快速配置 在客户端中填写如下配置: ```json { "mcpServers": { "memos-api-mcp": { "timeout": 60, "type": "stdio", "command": "npx", "args": [ "-y", "@memtensor/memos-api-mcp@latest" ], "env": { "MEMOS_API_KEY": "mpg-xxxxxxxxxxxxxxxxxxxxxxxxxxxxx", "MEMOS_USER_ID": "your-user-id", "MEMOS_CHANNEL": "MODELSCOPE" } } } } ``` 环境变量获取方式: - `MEMOS_API_KEY`: 在MemOS官网[API控制台](https://memos-dashboard.openmem.net/cn/apikeys/)上注册账号,然后在接口密钥页面新建api-key并复制粘贴在此处。 ![在MemOS API控制台上新建api-key](https://cdn.memtensor.com.cn/img/1763452232848_t268eh_compressed.png) - `MEMOS_USER_ID`: 确定性的用户自定义个人标识符。 - 对于同一用户,该环境变量需要在不同设备/客户端中保持一致; - 请不要使用随机值、设备ID或聊天会话ID作为用户标识符; - 推荐使用:个人email地址、姓名全称或员工ID作为用户标识符。 - `MEMOS_CHANNEL`: 填写为"MODELSCOPE"即可。 更多细节配置可参考: * [npm 包](https://www.npmjs.com/package/@memtensor/memos-api-mcp) * [Github](https://github.com/MemTensor/memos-api-mcp) ## 3. 在不同的客户端中使用 MemOS MCP ### 在Claude Desktop中使用 在Claude Desktop中使用MemOS,需点击左下角头像 -> "Settings" -> "Developer" -> "Edit Config", 并粘贴配置到Claude_desktop_config.json文件中,最后重启客户端,观察到memos-api-mcp服务处于running状态即可在聊天中使用。 ![在Claude中使用MemOS-验证](https://cdn.memtensor.com.cn/img/1763105334517_9ayhrp_compressed.png) 为了提升使用效果,建议用户在Claude Desktop中使用MemOS时修改作用于所有对话的用户偏好设置,具体方法为点击左下角头像 -> "General", 在"What personal preferences should Claude consider in responses?"下面的输入框中粘贴如下内容: ``` 你是MemOS记忆管理助手,致力于提供高效的记忆管理服务,基于用户过往的对话内容抽取记忆,并通过记忆检索提升用户与AI对话的一致性和个性化水平。在每次回答用户的问题之前,你需要调用memos-api-mcp的search_memory服务,利用恰当的检索词在用户的个人记忆库中搜索和当前话题有关的记忆。在基于这些记忆完成回答后,再调用memos-api-mcp的add_message服务,将当前对话内容摘要记录下来。(请注意,调用add_message这一步是必须进行的,无论用户说了什么或问了什么问题都要记录下来,否则在后续的对话中,search_memory将无法获取到更细致的用户信息,进而导致你不能准确地回答用户问题。) ``` ![在Claude Desktop中使用MemOS-修改用户偏好](https://cdn.memtensor.com.cn/img/1763105396189_i1tupr_compressed.png) 下面是在Claude Desktop中使用MemOS的示例,用户可借此判断是否已经成功在Claude Desktop中配置MemOS。 ![在Claude Desktop中使用MemOS的示例](https://cdn.memtensor.com.cn/img/1763105412700_asgfq9_compressed.png) ### 在Cursor中使用 在Cursor中使用MemOS,需进入"Cursor Settings" -> "Tools & MCP" -> "Add Custom MCP"(或"New MCP Server"), 并在弹出的mcp.json文件编辑页中粘贴配置,观察到memos-api-mcp处于启动状态,且能够在工具详情页面看到"add_message""search_memory"等若干工具,即可在Cursor聊天面板中使用。 ![在Cursor中使用MemOS](https://cdn.memtensor.com.cn/img/1763105278297_n23ukk_compressed.png) 为了提升使用效果,建议用户在Cursor中使用MemOS时修改User Rules,具体方法为进入"Cursor Settings" -> "Rules, Memories, Commands" -> "User Rules" -> "+ Add Rule", 然后将下面的内容复制粘贴后保存: ``` 你是MemOS记忆管理助手,致力于提供高效的记忆管理服务,基于用户过往的对话内容抽取记忆,并通过记忆检索提升用户与AI对话的一致性和个性化水平。在每次回答用户的问题之前,你需要调用memos-api-mcp的search_memory服务,利用恰当的检索词在用户的个人记忆库中搜索和当前话题有关的记忆。在基于这些记忆完成回答后,再调用memos-api-mcp的add_message服务,将当前对话内容摘要记录下来。(请注意,调用add_message这一步是必须进行的,无论用户说了什么或问了什么问题都要记录下来,否则在后续的对话中,search_memory将无法获取到更细致的用户信息,进而导致你不能准确地回答用户问题。) ``` ![在Cursor中使用MemOS-配置User rules](https://cdn.memtensor.com.cn/img/1763105535408_2xtvd3_compressed.png) 下面是在Cursor中使用MemOS的示例,用户可借此判断是否成功在Cursor中配置MemOS。 ![在Cursor中使用MemOS-使用示例](https://cdn.memtensor.com.cn/img/1763105558821_imga5z_compressed.png) ### 在Visual Studio Code或Trae中使用 在VS Code或Trae中使用MemOS,需安装Cline扩展并进行模型配置后,点击Cline面板内部右上角的"MCP Servers"图标 -> "Configure" -> "Configure MCP Servers", 并粘贴配置到cline_map_settings.json文件中,观察到memos-api-mcp处于启动状态即可在Cline智能体中使用。同时,推荐开启各工具的`Auto-approve`开关,避免智能体每次调用工具前询问,使用更流畅。 ![在Cline中使用MemOS-配置流程](https://cdn.memtensor.com.cn/img/1763105573529_oo765m_compressed.png) 为了提升使用效果,建议用户在Cline中使用MemOS时修改global rules,具体方法为点击Cline面板左下角的"Manage Cline Rules & Workflows" 图标 -> 点击Global Rules下方右侧的"+"图标 -> 在输入框内输入rules文件名,如"memos_rules.md" -> 将下面的内容复制粘贴到弹出的编辑器内: ```markdown # 🧠 MemOS Automatic Memory System — Mandatory Usage ## ⚠️ Always-On (No User Opt-In Required) This system must run **automatically for every turn**. Do **not** wait for the user to say "use memory", "use MCP", or "call a tool". The **client/orchestrator is responsible** for auto-invoking the tools. ## 🎯 Mandatory 3-Step Workflow (Enforced by Client Each Turn) \`\`\` Every user message → 1) 🔍 search_memory (AUTO, before answering) → 2) 💬 Answer (use only relevant memories; ignore noise) → 3) 💾 add_message (AUTO, after answering) \`\`\` ### 1) 🔍 Search Memory (Auto-invoked BEFORE answering) - **Trigger**: Must be auto-called **before** generating any answer (including simple greetings). - **Tool**: `search_memory` **Relevance rule**: The model must judge relevance and **only use relevant** memories. If results are irrelevant or noisy, **ignore them** and proceed. ### 2) 💬 Answer Use retrieved memories **only if relevant**. If none are relevant, answer normally. ### 3) 💾 Save Conversation (Auto-invoked AFTER answering) - **Trigger**: Must be auto-called after producing the final answer on **every turn**. - **Tool**: `add_message` **Purpose**: Persist Q&A for future personalization and continuity — even if no memory was used this turn. ## ✅ Non-Negotiable Client Responsibilities 1. **Auto-invoke** `search_memory` before **every** answer and `add_message` after **every** answer. 2. **No user opt-in**: Do not wait for the user to mention memory/tools/MCP. 3. **Store both user and assistant** messages every turn. 4. **Sequence** must be strictly: Search → Answer → Save. ``` ![在VS Code或Trae中使用MemOS-修改global rules](https://cdn.memtensor.com.cn/img/1763105598614_p0drfo_compressed.png) 下面是在Cline中使用MemOS的示例,用户可借此判断是否成功在Cline中配置了MemOS。 ![在Cline中使用MemOS的示例](https://cdn.memtensor.com.cn/img/1763105618134_ggy3m0_compressed.png) ### 在[Chatbox](https://chatboxai.app/zh)中使用 在Chatbox中使用MemOS,需点击左下角"设置" -> "MCP" -> "自定义MCP服务器-添加服务器" -> "添加自定义服务器",按照下面的配置添加memos-api-mcp服务。 ``` 名称:MemOS记忆管理助手 类型:本地(stdio) 命令:npx -y @memtensor/memos-api-mcp@latest 环境变量: MEMOS_API_KEY= MEMOS_USER_ID= ``` 填写完成后点击"测试",如果能在对话框最下方看到"add_message""search_memory"等若干工具,则证明配置成功。 ![在Chatbox中使用MemOS-验证](https://cdn.memtensor.com.cn/img/1763105637530_f98hyr_compressed.png) 为了提升使用效果,建议用户在Chatbox中使用MemOS时修改system_prompt,具体方式为左下角"设置" -> "对话设置" -> "新对话默认设置",并将prompt修改如下: ``` 你是MemOS记忆管理助手,致力于提供高效的记忆管理服务,基于用户过往的对话内容抽取记忆,并通过记忆检索提升用户与AI对话的一致性和个性化水平。在每次回答用户的问题之前,你需要调用memos-api-mcp的search_memory服务,利用恰当的检索词在用户的个人记忆库中搜索和当前话题有关的记忆。在基于这些记忆完成回答后,再调用memos-api-mcp的add_message服务,将当前对话内容摘要记录下来。(请注意,调用add_message这一步是必须进行的,无论用户说了什么或问了什么问题都要记录下来,否则在后续的对话中,search_memory将无法获取到更细致的用户信息,进而导致你不能准确地回答用户问题。) ``` ![在Chatbox中使用MemOS时修改system_prompt](https://cdn.memtensor.com.cn/img/1763105656492_ky1wbw_compressed.png) 下面是在Chatbox中使用MemOS的示例,用户可借此判断是否已经成功在Chatbox中配置MemOS。 ![在Chatbox中使用MemOS-效果示例](https://cdn.memtensor.com.cn/img/1763105677226_cygzzf_compressed.png) ## 4. Q&A Q:有时会遇到智能体在应当使用工具的场景没有使用的情况? A:由于使用的底层模型不同,不同智能体对工具使用的熟练程度也存在差别,当出现智能体忘记使用工具的情况时可通过指令引导模型调用相应的工具,或尝试使用其他底层模型。 ## 5. 联系我们 ![image.png](https://cdn.memtensor.com.cn/img/1758685658684_nbhka4_compressed.png) --- # MemOS CLI (/cn/mcp_agent/cli/guide) MemOS CLI 面向可以执行命令行的 Agent 和开发环境。它把常用记忆操作封装成 `memos` 命令,适合在终端里快速验证,也适合配合 Skill / Rule 让 Agent 在回答前检索记忆、回答后写入新记忆。 ## 1. 适合什么时候使用 - 你希望在终端里快速验证 `add`、`search`、`get`、`delete` 等记忆操作; - 你的 Agent 容易“失忆”,并且可以执行 shell 命令; - 你同时使用多种 Agent 框架,并且希望实现跨框架的记忆同步。 ## 2. 安装 ```bash npm install -g @memtensor/memos-cloud-cli ``` 安装后,可以通过以下命令确认 CLI 可用: ```bash memos --help ``` ## 3. 选择使用方式并配置 MemOS CLI 有两种使用方式:一种是安装到 Agent 中,让 Agent 自动使用记忆;另一种是在终端中手动执行 `memos` 命令。 ### 3.1 在 Agent 中使用 如果要让 Agent 自动检索和写入记忆,使用 `memos init` 安装记忆 Skill。当前 `--agent` 为必填参数,不传会直接报错,因为 CLI 需要知道 Skill 应该安装到哪个 Agent 目录。 ```bash memos init --agent codex ``` 也可以在初始化时同时写入 API Key: ```bash memos init --api-key YOUR_API_KEY --agent codex ``` 目前支持的 Agent 如下,使用时通过 `--agent` 传入对应参数: | Agent | `--agent` 参数 | | --- | --- | | Codex CLI | `codex` | | Cursor | `cursor` | | Claude Code | `claude` | | OpenClaw | `openclaw` | | Hermes | `hermes` | | Trae | `trae` | | Trae(国内版) | `trae-cn` | | OpenCode | `opencode` | | Antigravity | `antigravity` | | CodeBuddy | `workbuddy` | | Cline | `cline` | | GitHub Copilot | `copilot` | | DeepSeek Harness | `deepseek` | 例如,为 Cursor 安装记忆 Skill: ```bash memos init --agent cursor ``` 接入 DeepSeek Harness: ```bash memos init --agent deepseek ``` 该命令会在 `~/.dsh/skills/memos-memory/` 安装 Skill;如果设置了 `DSH_HOME`,则安装到 `$DSH_HOME/skills/memos-memory/`。同时,CLI 会写入对应的 `AGENTS.md`,并注册 DeepSeek Harness 原生生命周期插件。插件会在每轮开始时检索相关记忆,将结果注入上下文;在本轮正常结束后写入新的长期记忆。重启 DeepSeek Harness 后生效。 安装后,Agent 启动时会自动加载该 Skill。在每轮对话中,Agent 会: 1. **回答前**自动执行 `memos search`,检索与当前任务相关的长期记忆 2. **回答后**自动执行 `memos add`,将本轮出现的新事实、偏好等写入 MemOS 如果你已经安装了 MemOS 插件(如 OpenClaw 云插件),可以加上 `--memos-plugin` 生成插件感知的 Skill 引导: ```bash memos init --agent openclaw --memos-plugin ``` > **Tip**: 以 OpenClaw 为例,在 LOCOMO 评测中,单独接入 MemOS CLI 后 Token 消耗降低约 65.5%;接入 MemOS Cloud + CLI 后,正确率从 66.60% 提升到 77.27%。 | 参数 | 说明 | | --- | --- | | `-k, --api-key` | MemOS API Key | | `--user-id` | 默认用户 ID | | `--conversation-id` | 默认会话 ID | | `--memos-plugin` | 已安装 MemOS 插件时,生成插件感知的 Skill 引导 | | `--agent` | 将 Skill 安装到指定 Agent 的目录;必填 | ### 3.2 直接在终端使用 如果只在终端中手动使用 CLI,不安装 Agent Skill,则使用 `memos config set` 单独配置 CLI 变量。设置后,后续命令未传对应参数时会自动使用这些默认值。 配置 API Key: ```bash memos config set platform.api_key YOUR_API_KEY ``` 配置默认用户 ID: ```bash memos config set defaults.user_id user_123 ``` 配置默认会话 ID: ```bash memos config set defaults.conversation_id conv_001 ``` ## 4. 快速上手 完成上述 Agent 初始化或终端配置后,可以使用以下命令验证记忆操作。 #### 写入一条记忆: ```bash memos add "用户喜欢 Python 编程" ``` #### 搜索相关记忆: ```bash memos search "编程语言偏好" ``` #### 结合记忆进行对话: ```bash memos chat "你知道我的偏好吗?" ``` #### 获取某个用户的记忆: ```bash memos get user_123 ``` #### 查询某条记忆的原文: ```bash memos origin mem_123456 ``` #### 删除单条记忆,或删除某个用户的全部记忆: ```bash memos delete mem_123456 memos delete --user-id user_123 ``` ## 5. 命令参考 ### `memos add` 向 MemOS 写入一条记忆内容。 ```bash memos add "用户喜欢用 Python 做数据分析,常用 pandas" memos add --message "用户常用 Jupyter Notebook" --user-id user_123 ``` | 参数 | 说明 | | --- | --- | | `[MESSAGE]` | 要写入的记忆内容;与 `--message` 二选一 | | `-m, --message` | 要写入的记忆内容;与位置参数二选一 | | `--user-id` | 用户标识,默认取配置中的 `defaults.user_id` | | `--format` | 输出格式,默认 `agent` | ### `memos search` 搜索和当前查询相关的记忆。 ```bash memos search "用户的数据分析工具偏好" memos search "编程语言" --format json --detail detail ``` | 参数 | 说明 | | --- | --- | | `[QUERY]` | 搜索关键词;与 `--query` 二选一 | | `-q, --query` | 搜索关键词;与位置参数二选一 | | `--user-id` | 用户标识,默认取配置中的 `defaults.user_id` | | `--include-preference` | 是否召回偏好记忆(`true` / `false`),默认 `true` | | `--include-tool-memory` | 是否召回工具记忆(`true` / `false`),默认 `false` | | `--include-skill-memory` | 是否召回技能记忆(`true` / `false`),默认 `false` | | `--memory-limit-number` | 主记忆召回条数,默认 `9` | | `--preference-limit-number` | 偏好记忆召回条数,默认 `9` | | `--tool-memory-limit-number` | 工具记忆召回条数,默认 `6` | | `--skill-memory-limit-number` | 技能记忆召回条数,默认 `6` | | `--format` | 输出格式,默认 `agent` | | `--detail` | 非 JSON 输出的详略级别,默认 `simple`;支持 `simple`、`detail` | ### `memos get` 按用户获取记忆。 ```bash memos get user_123 memos get user_123 --format json --detail detail ``` | 参数 | 说明 | | --- | --- | | `[USER_ID]` | 用户标识;不传则回退到配置中的 `defaults.user_id` | | `--user-id` | `[USER_ID]` 的兼容别名,回退规则相同 | | `--page` | 页码;不传则请求体不带该字段 | | `--size` | 每页条数;不传则请求体不带该字段 | | `--include-preference` | 是否召回偏好记忆(`true` / `false`);不传时由接口默认值决定 | | `--include-tool-memory` | 是否召回工具记忆(`true` / `false`);不传时由接口默认值决定 | | `--format` | 输出格式,默认 `agent` | | `--detail` | 详略级别,默认 `simple`;支持 `simple`、`detail` | ### `memos origin` 按记忆 ID 查询该条记忆的原文。 ```bash memos origin mem_123456 memos origin mem_123456 --format json ``` | 参数 | 说明 | | --- | --- | | `MEMORY_ID` | 待查询原文的记忆 ID;必填;传 `MEMORY_ID` 表示查询该单条记忆的原文 | | `--format` | 输出格式,默认 `agent` | ### `memos delete` 删除一条记忆,或删除指定用户的全部记忆。 ```bash memos delete mem_123456 --format json memos delete --user-id user_123 --format json ``` | 参数 | 说明 | | --- | --- | | `[MEMORY_ID]` | 待删除的记忆 ID;传此参数表示删除单条记忆 | | `--user-id` | 删除该用户的全部记忆;与 `MEMORY_ID` 二选一 | | `--format` | 输出格式,默认 `agent` | ### `memos chat` 基于 MemOS 记忆进行问答。 ```bash memos chat "你知道我的偏好吗?" memos chat "你知道我的偏好吗?" --user-id user_123 --format table ``` | 参数 | 说明 | | --- | --- | | `[QUERY]` | 对话问题;与 `--query` 二选一 | | `-q, --query` | 对话问题;与位置参数二选一 | | `--user-id` | 用户标识,默认取配置中的 `defaults.user_id` | | `--format` | 输出格式,默认 `agent` | ### `memos extract` 从消息中提取候选记忆,但不写入。 ```bash memos extract "用户喜欢咖啡,也偏好深色模式" --format json ``` | 参数 | 说明 | | --- | --- | | `[MESSAGE]` | 待提取的消息内容;与 `--message` 二选一 | | `-m, --message` | 待提取的消息内容;与位置参数二选一 | | `--user-id` | 用户标识,默认取配置中的 `defaults.user_id` | | `--format` | 输出格式,默认 `agent` | ### `memos rerank` 对候选文档做相关性重排。 ```bash memos rerank "python 后端" "Flask guide" "React guide" --format json ``` | 参数 | 说明 | | --- | --- | | `[QUERY]` | 重排查询;与 `--query` 二选一 | | `[DOCUMENTS]...` | 候选文档文本;可传多个位置参数 | | `-q, --query` | 重排查询;与位置参数二选一 | | `--documents` | 候选文档文本;可重复传入 | | `--top-n` | 只返回前 N 条结果 | | `--format` | 输出格式,默认 `agent` | ### `memos feedback` 提交反馈内容,优化记忆管理效果。 ```bash memos feedback "偏好简洁、直接的技术回答。" --user-id user_123 --format json ``` | 参数 | 说明 | | --- | --- | | `[FEEDBACK_TEXT]` | 反馈内容;与 `--feedback-content` 二选一 | | `--feedback-content` | 反馈内容;与位置参数二选一 | | `--user-id` | 用户标识,默认取配置中的 `defaults.user_id` | | `--format` | 输出格式,默认 `agent` | ### `memos message` 获取原始对话消息记录。 ```bash memos message --user-id user_123 --conversation-id conv_001 memos message --user-id user_123 --limit 10 --format table ``` | 参数 | 说明 | | --- | --- | | `--user-id` | 用户标识;必填 | | `--conversation-id` | 会话标识,默认取配置中的 `defaults.conversation_id` | | `--limit` | 返回的最大消息数;默认 `6`,最大 `50` | | `--format` | 输出格式,默认 `agent` | ### `memos status` 查询异步任务的处理状态。任务 ID 来自 `add`、`feedback` 在异步模式下返回的 `task_id`。 ```bash memos status abc123-task-id --format json ``` | 参数 | 说明 | | --- | --- | | `[TASK_ID]` | 异步任务 ID;必填 | | `--format` | 输出格式,默认 `agent` | 返回的状态值包括 `running`、`completed`、`failed`。 ### `memos kb` 知识库管理子命令组,用于创建知识库、上传文档、查询与删除文件等。 #### `memos kb create` 创建一个知识库。 ```bash memos kb create --name "产品 FAQ" --description "常见产品问题" --format json ``` | 参数 | 说明 | | --- | --- | | `--name` | 知识库名称;必填 | | `--description` | 知识库描述;可选 | | `--format` | 输出格式,默认 `agent` | #### `memos kb remove` 删除(移除)一个知识库。 ```bash memos kb remove base_xxxxx --format json ``` | 参数 | 说明 | | --- | --- | | `[KB_ID]` | 知识库 ID;必填 | | `--format` | 输出格式,默认 `agent` | #### `memos kb add-file` 向知识库上传文档,支持 PDF、DOCX、DOC、TXT、JSON、MD、XML。 ```bash memos kb add-file --kb-id base_xxxxx --files '["https://example.com/doc.pdf"]' --format json memos kb add-file --kb-id base_xxxxx --files '[{"content":"https://cdn.example.com/file.docx"}]' --format json ``` | 参数 | 说明 | | --- | --- | | `--kb-id` | 目标知识库 ID;必填 | | `--files` | 文件条目的 JSON 数组:URL 字符串或 `{"content": "..."}` 对象;必填 | | `--format` | 输出格式,默认 `agent` | #### `memos kb get-file` 查询知识库文件的详情与处理状态。 ```bash memos kb get-file --file-ids '["file_id_1", "file_id_2"]' --format json ``` | 参数 | 说明 | | --- | --- | | `--file-ids` | 文件 ID 的 JSON 数组;必填 | | `--format` | 输出格式,默认 `agent` | #### `memos kb list-file` 分页列出知识库中的文件,可按类型过滤。 ```bash memos kb list-file --kb-id base_xxxxx memos kb list-file --kb-id base_xxxxx --type skill --page 2 --page-size 10 --format json ``` | 参数 | 说明 | | --- | --- | | `--kb-id` | 知识库 ID;必填 | | `--type` | 按类型过滤:`document` 或 `skill`;可选 | | `--page` | 页码;默认 `1` | | `--page-size` | 每页条数;默认 `20` | | `--format` | 输出格式,默认 `agent` | #### `memos kb delete-file` 从知识库中删除文件。 ```bash memos kb delete-file --kb-id base_xxxxx --file-ids '["file_id_1"]' --format json ``` | 参数 | 说明 | | --- | --- | | `--kb-id` | 知识库 ID;必填 | | `--file-ids` | 待删除文件 ID 的 JSON 数组;必填 | | `--format` | 输出格式,默认 `agent` | ## 6. 输出格式 所有子命令都支持 `--format`,默认输出格式为 `agent`。`search` 和 `get` 还额外支持 `--detail`。 | 格式 | 适用场景 | | --- | --- | | `table` | 终端人工阅读 | | `markdown` | 粘贴到文档中 | | `agent` | 默认格式,让 Agent 直接注入上下文 | | `json` | 脚本、工作流或结构化处理 | ```bash memos search "python" memos search "python" --format table --detail simple memos search "python" --format markdown --detail detail memos search "python" --format agent --detail simple memos search "python" --format json --detail detail ``` ## 7. 配置命令与环境变量 查看或修改本地配置: ```bash memos config show memos config get platform.api_key memos config set platform.api_key YOUR_API_KEY memos config set defaults.user_id user_123 memos config set defaults.conversation_id conv_001 ``` | 环境变量 | 说明 | | --- | --- | | `MEMOS_API_KEY` | 你的 API Key | | `MEMOS_BASE_URL` | API Base URL,默认 `https://memos.memtensor.cn/api/openmem/v1` | 全局选项: | 参数 | 说明 | | --- | --- | | `--api-key TEXT` | 覆盖本地配置中的 API Key | | `--base-url TEXT` | 覆盖 API Base URL | | `--version` | 显示版本号 | ## 8. CLI、Plugin 和 MCP | 接入方式 | 适合场景 | 特点 | | --- | --- | --- | | Plugin | 已有深度适配的 Agent 框架 | 集成最深,体验最好,但需要针对框架单独适配 | | CLI + Skill | 任意可调用命令行的 Agent 框架 | 通用性强,接入成本低,适合跨框架自动化 | | MCP | MCP 原生客户端 | 标准化工具协议,适合支持 MCP 的客户端 | --- # Coze 插件工具 (/cn/mcp_agent/agent/guide) ## 1.插件上架信息 MemOS云服务接口插件已在Coze商店上架!您可以直接[前往工具链接](https://www.coze.cn/store/plugin/7569918012912893995?from=store_search_suggestion)添加插件,实现零代码集成。 ## 2. 插件描述 ### 插件功能 * `search_memory`:该工具用于查询用户的记忆数据,可返回与输入最相关的片段。支持在用户与AI对话期间实时检索内存,也能在整个内存中进行全局搜索,可用于创建用户配置文件或支持个性化推荐,查询时需提供对话ID、用户ID、查询文本等参数,还可设置返回的记忆项数量。 * `add_memory`:此工具可将一条或多条消息批量导入到MemOS记忆存储数据库,方便在未来对话中检索,从而支持聊天历史管理、用户行为跟踪和个性化交互,使用时需指定对话ID、消息内容、发送者角色、对话时间和用户ID等信息。 ### 接口描述 * search_memory接口 | 参数名称 | 参数类型 | 描述 | 是否必填 | | --- | --- | --- | --- | | memory_limit_number | string | 限制返回的内存项数量,如果没有提供,则默认为6 | 否 | | memos_key | string | MemOS云服务的授权密钥 | 是 | | memos_url | string | MemOS云服务的URL地址 | 是 | | query | string | 用户输入 | 是 | | user_id | string | 与正在被查询的内存相关联的用户的唯一标识符 | 是 | * add_memory接口 | 参数名称 | 参数类型 | 描述 | 是否必填 | | --- | --- | --- | --- | | conversation_id | string | 对话的唯一标识符 | 是 | | memos_key | string | MemOS云服务的授权密钥 | 是 | | memos_url | string | MemOS云服务的URL地址 | 是 | | messages | Array | 消息对象的数组 | 是 | | user_id | string | 与正在被查询的内存相关联的用户的唯一标识符 | 是 | ## 3. Agent 调用示例 ### Agent开发人设与回复逻辑示例 ``` 你是一个问答机器人,每次都会阅读使用者的记忆和关注的内容,并且以非常清晰的逻辑答复,从而获得用户的好感。 ## 工作流内容 # 1. 访问{search_memory}检索数据资料 每次用户说话后,先调用MemOS记忆关系中的检索功能--{search_memory}插件,输入信息: 记录用户的名称作为user_id,如果是第一次访问,则将user_id设置由UUID随机生成的16位字符串。 将用户的说话内容作为query # 2. 处理{search_memory}输出内容: 获取data内容,如果其中有memory_detail_list字段,不论memory_detail_list列表是否为空,直接输出json形式的memory_detail_list列表;如果返回的message不为ok,则提示"插件检索失败"。 # 3. 就有检索得到的memory_detail_list回答用户的问题 提取memory_detail_list中每一项的memory_value字段值,将所有的字符串采用"\n"拼接起来作为回答用户问题的上下文资料context;大模型回答用户的query可以基于context提供的信息;如果上下文信息context为空字符,大模型直接回答用户的query即可。 接着将大模型回答的内容记录到answer里。 # 4. 访问{add_memory}存储数据资料 调用add_memory功能将用户问题和对应的回答存储起来,输入信息: chat_time: 调用{current_time}获取当前时间, 将时间戳整理为"%I:%M %p on %d %B, %Y UTC"格式 conversation_id: 记录当前的时间点chat_time精确到分钟,时间点字符串作为conversation_id user_id: 记录用户的名称作为user_id messages: 记录用户输入的query以及它获取的所有回答answer,分别作为messages中的role的content和assistant的content,chat_time采用刚刚获取的chat_time值,整理为一条messages: [ {"role": "user", "content": query, "chat_time": chat_time}, {"role": "assistant", "content": answer, "chat_time": chat_time} ] 获取{add_memory}插件反馈 data中success字段为True则为成功,*不必告知用户*;如果返回的字段不为True,则提示用户add_memory访问失败了。 ## 要求 每次访问 {add_memory}和{search_memory}的时候都需要传入两个固定参数: memos_url = "https://memos.memtensor.cn/api/openmem/v1" memos_key = "Token mpg-XXXXXXXXXXXXXXXXXXXXXXXXXXX" 你的角色是充满智慧和爱心的记忆助手,名字叫小智。 如果各插件都顺利运行,大模型回答的内容中不必提示用户成功了。 仅仅在用户第一次对话时用UUID生成一次user_id,该user_id在后续工作中复用。 ``` [Agent示例链接](https://www.coze.cn/s/85NOIg062vQ) ![Agent 工作流](https://cdn.memtensor.com.cn/img/coze_workflow_compressed.png) --- # 云插件 vs 本地插件 (/cn/openclaw/plugin_compare) ## 插件简介 ### 云插件 将记忆托管于 **MemOS Cloud**。安装云插件后,只需配置一个 MemOS Cloud API Key 即可使用,支持多 Agent 跨设备共享记忆,经基准测试可降低约 **72% 的 Token 消耗**,适合快速上手、跨设备协作和生产环境接入。 ### 本地插件 新版本地插件为 `@memtensor/memos-local-plugin`,是一套 **OpenClaw、Hermes 与 DeepSeek Harness 共用的本地优先记忆核心**。它把数据写入本机 SQLite,并沉淀为 L1 Trace、L2 Policy、L3 World Model 与可调用 Skill 四层记忆;同时通过反馈驱动自进化、三层检索和决策修复,让 Agent 在本机逐步积累可复用经验。适合对隐私、安全、本地化运行或可观测性有更高要求的开发者。 --- ## 核心区别 | 对比维度 | ☁️ MemOS 云插件 | 🖥️ MemOS 本地插件 | | --- | --- | --- | | 💾 **数据存储与隐私** | **云端存储**:记忆数据存储在 MemOS Cloud,便于跨设备、多实例共享。 | **本地存储**:每个 Agent 拥有独立运行目录。OpenClaw 默认在 `~/.openclaw/memos-plugin/`,Hermes 默认在 `~/.hermes/memos-plugin/`,DeepSeek Harness 同样把 SQLite、Skill 包、日志和配置保留在本机。 | | 🤖 **Agent 支持** | 当前支持 OpenClaw 与 DeepSeek Harness,依托 MemOS Cloud 提供统一记忆服务。 | 同一套核心支持 OpenClaw、Hermes 与 DeepSeek Harness:OpenClaw 通过 TypeScript 插件进程内集成,Hermes 通过 Python Provider + JSON-RPC 桥接到 Node 核心,DeepSeek Harness 通过其原生插件机制接入。 | | 🔑 **API 与模型配置** | 使用 MemOS Cloud API Key,由云端承担记忆处理、检索和演进。 | 通过 Memory Viewer 的 Settings 面板配置模型与团队共享。Embedding 默认可使用本地 provider,也可配置 OpenAI-compatible、Gemini、Cohere、Voyage、Mistral;OpenClaw 可继承宿主模型,Hermes 与 DeepSeek Harness 可在各自面板中配置 LLM provider 与 API Key。 | | 🔍 **检索能力** | 云端语义向量检索 + 图检索,由服务端统一优化。 | 三层检索:Tier 1 Skill、Tier 2 Trace/Episode、Tier 3 World Model;同时融合向量、FTS5、关键词 pattern 与错误特征等通道,并通过 RRF + MMR 控制相关性和多样性。 | | 🧠 **记忆进化** | 由云端服务自动完成:对写入记忆进行结构化处理、去冗余与自然语言纠错。 | Reflect2Evolve 本地流水线:对话与工具调用沉淀为 L1 Trace,跨任务归纳为 L2 Policy,再抽象为 L3 World Model;高价值策略会结晶为可调用 Skill,并根据反馈进入 active / retired 等生命周期。 | | 🛠️ **决策修复** | 主要依赖云端召回更相关的历史记忆,降低重复上下文和无效 Token。 | 工具失败、负反馈和任务结果会进入反馈通道;失败模式可触发 decision repair,在下一轮注入纠偏上下文,帮助 Agent 避免重复踩坑。 | | 👥 **多 Agent 与共享** | 支持多 Agent 场景和跨设备共享,适合团队协作。 | 默认按 Agent 隔离:OpenClaw、Hermes 与 DeepSeek Harness 拥有各自数据库和 Viewer。可选开启 Hub,在局域网 / VPN 内共享本地结晶的 Skill 和可选 Trace 摘要;共享不在算法关键路径上,失败会自动退化为本地模式。 | | 👀 **可视化与可观测性** | 通过 MemOS Cloud Dashboard 管理 API Key 和云端记忆能力。 | 内置本地 Viewer:Overview、Memories、Tasks、Policies、World Models、Skills、Analytics、Logs、Import、Settings、Help 等页面;HTTP + SSE 实时展示事件、日志、检索、Skill 和健康状态。 | | 🛠️ **部署与配置** | **极简**:先获取一次 API Key,再按 OpenClaw 或 DeepSeek Harness 完成安装与配置,主要依赖云服务。 | **极简**:安装与升级都是一行命令。安装器会自动检测系统中已安装的 OpenClaw、Hermes 或 DeepSeek Harness,安装 `@memtensor/memos-local-plugin`、创建运行目录并重启对应运行时。 | --- ## 安装速览 ### 云插件 先获取一次 API Key,再按 Agent 完成安装。OpenClaw 与 DeepSeek Harness 共用同一把 Key,不必重复申请。 **获取 API Key**:[MemOS Cloud Dashboard](https://memos-dashboard.openmem.net/cn/apikeys/) #### OpenClaw 1. **安装插件** ```bash openclaw plugins install @memtensor/memos-cloud-openclaw-plugin@latest ``` 2. **写入 API Key** ```bash mkdir -p ~/.openclaw && echo "MEMOS_API_KEY=mpg-..." > ~/.openclaw/.env ``` 3. **重启 gateway** ```bash openclaw gateway restart ``` **手动更新插件**: ```bash openclaw plugins update @memtensor/memos-cloud-openclaw-plugin@latest openclaw gateway restart ``` #### DeepSeek Harness 使用上面已创建的 API Key。 1. **将云插件安装到 DSH 默认的 web profile** ```bash npx @deepseek-ai/dsh plugin --profile web add @memtensor/memos-cloud-dsh-plugin@latest ``` 2. **在 `~/.dsh/.env` 中配置 API Key 和用户 ID** ```dotenv MEMOS_API_KEY=mpg-your-key MEMOS_USER_ID=your-stable-user-id ``` 每位用户使用稳定且不同的 ID。升级时沿用原 ID;此前未配置时,使用原默认值 `deepseek-harness-user`。 3. **在 `~/.dsh/settings.yaml` 中加入最小配置** ```yaml memos-cloud: apiKeyEnv: MEMOS_API_KEY ``` 4. **重新启动 DSH Web** 修改 `.env` 后,先在原终端按 `Ctrl+C` 停止 DSH,再启动: ```bash npx @deepseek-ai/dsh web ``` > 0.1.1 的旧凭据配置迁移、`.credentials.yaml` 备选格式与配置优先级,请参考 [DeepSeek Harness 接入指南](/cn/openclaw/guide#deepseek-harness-接入)。 ### 本地插件(一行命令) ```bash # 安装插件 curl -fsSL https://raw.githubusercontent.com/MemTensor/MemOS/main/apps/memos-local-plugin/install.sh | bash ``` 安装与升级使用同一条命令。安装器会自动检测本机是否安装 OpenClaw、Hermes 或 DeepSeek Harness。交互式终端会询问安装到哪个 Agent,非交互环境会自动安装到检测到的 Agent。 | Agent | 代码目录 | 数据与配置目录 | Viewer | | --- | --- | --- | --- | | OpenClaw | `~/.openclaw/plugins/memos-local-plugin/` | `~/.openclaw/memos-plugin/` | `http://127.0.0.1:18799` | | Hermes | `~/.hermes/plugins/memos-local-plugin/` | `~/.hermes/memos-plugin/` | `http://127.0.0.1:18800` | | DeepSeek Harness | 由安装器部署到对应插件目录 | 本机独立 `memos-plugin` 目录 | `http://127.0.0.1:18801` | > 升级或卸载插件代码不会删除已有本地数据、技能包或日志。OpenClaw、Hermes 与 DeepSeek Harness 各自运行独立 Viewer,没有共享端口或只读 peer 视图。 > > 模型、团队共享和常规选项都在对应 Agent 的 Memory Viewer 里配置:OpenClaw 默认 `http://127.0.0.1:18799`,Hermes 默认 `http://127.0.0.1:18800`,DeepSeek Harness 默认 `http://127.0.0.1:18801`。 --- # 云插件 (/cn/openclaw/guide) > **Note**: **兼容性建议** > 为避免插件加载或运行报错,建议在 MemOS 完成最新 OpenClaw 版本适配后,再升级 OpenClaw。 OpenClaw 近期备受关注,但在实际使用中,用户普遍会遇到两个难以回避的问题: 1. **Token 消耗过快**:OpenClaw 能处理许多长尾任务,但每次运行都会消耗大量 Token。当你让它监控屏幕、运行定时任务或处理复杂工作流时,Token 消耗更是惊人。 > ("你知道 Token 就是金钱🫠") 2. **记忆功能薄弱**:虽然很多人声称 OpenClaw 的记忆能力超越 ChatGPT,但实践中你会发现它虽然能记住一些信息,却往往不是你需要的关键信息。重要偏好可能被遗忘,而无关紧要的闲聊却被记得一清二楚。 > ("能不能请你记住一些对我真正重要的事情???") > **Tip**: **这不是 OpenClaw 的错,所有 AI Agent 都面临这些挑战。** 本教程将指导你通过 MemOS OpenClaw 插件解决这 3 个核心痛点: - **显著降低 Token 消耗** — 智能检索相关记忆,而非无差别加载全部历史 - **让记忆真正有用** — 专业级记忆分类与管理,记住该记的,遗忘该忘的 - **保留 OpenClaw 的核心优势** — 跨设备控制、主动交互、类人体验保持不变 --- ## 为什么 OpenClaw 成了"Token 杀手"🥷? ### OpenClaw 的问题 ```plaintext 第 1 次对话: 500 tokens 第 2 次对话: 500 + 800 = 1,300 tokens 第 3 次对话: 1,300 + 600 = 1,900 tokens 第 10 次对话: 10,000+ tokens ``` 当你让 OpenClaw 监控屏幕、执行定时任务并按计划运行时,这个数字增长得更快。 ### OpenClaw 原生记忆管理的三个关键缺陷 OpenClaw 的记忆存储在本地 `.md` 文件中,分为全局记忆和每日记忆。虽然听起来不错,但实际使用中存在三个不可避免的问题: #### 1. 全局记忆膨胀失控 随着全局记忆不断累积,上下文超载随之而来。更糟糕的是,这些记忆会持续干扰当前对话——你可能只想问一个简单的问题,它却把三个月前的每一句话都翻出来。 #### 2. 每日记忆检索困难 每日记忆不断累积,使检索变得繁琐。要回忆昨天的活动,你必须经历额外的检索过程。维护跨会话记忆几乎变得不可能。 #### 3. 记忆依赖模型的主动记录 OpenClaw 的记忆系统依赖模型自身记录信息,而非自动记录。这意味着它经常遗漏细节——你提到某件事,它马上就忘了。 > 我自己就遇到过好几次:我明确强调了某个项目配置,但第二天重启对话时,它完全没有印象,需要我重新解释一遍。 --- ## OpenClaw vs OpenClaw + MemOS:记忆方案对比 ### OpenClaw 原生记忆方案 #### 记忆存储方案 **核心哲学:文件即真理** — 摒弃不透明的向量数据库,选择 Markdown 文件作为记忆的核心载体。 ![OpenClaw记忆方案](https://cdn.memtensor.com.cn/img/1772698365666_utw5a2_compressed.png) #### 记忆检索方案:双引擎驱动 | 引擎 | 技术 | 特点 | |-----|------|------| | **向量搜索** (Vector Search) | 余弦相似度 | 捕捉语义关联,擅长处理"概念匹配",如将"登录流程"关联至"身份验证" | | **BM25 搜索** (Lexical Matching) | 基于 FTS5 的词法匹配 | 处理"精确 Token",如错误代码、函数名或特定 ID | **检索触发方式**:通过 Prompt 触发,模型自动决策 **加权分数融合**:`Score = (0.7 * VectorScore) + (0.3 * BM25Score)` #### 现有方案痛点 - **检索算法简陋**:召回不稳定、相关性弱,Agent 反复试错,Token 快速累积 - **上下文注入过量**:固定读取 today + yesterday + 长期记忆,无效上下文占比高 - **记忆缺少结构与去冗余**:工具调用长输出直接写入并反复重传,成本滚雪球 ### OpenClaw + MemOS 的记忆方案 ![MemOS-OpenClaw](https://cdn.memtensor.com.cn/img/1772627912577_gvwyaz_compressed.png) #### 三大核心效果 **效果一:Token 成本可控 💰** > 从"全量灌上下文"变成"按任务精确召回" OpenClaw 不再每次固定塞入 today+yesterday+长期记忆,而是由 MemOS 按当前任务检索最相关的少量记忆(可设定召回预算/条数),显著降低无效上下文占比,避免 Token 滚雪球。 **效果二:检索更稳更准 🎯** > 减少反复试错与重问,提升一次命中率 MemOS 提供更强的记忆组织与检索能力(结构化、分层/多粒度、语义检索 + 规则过滤等),让 OpenClaw 召回的内容相关性更强、稳定性更高,减少 Agent 因"召回不稳"导致的重复推理与反复确认。 **效果三:记忆更干净可用 ✨** > 结构化 + 去冗余 + 高压缩,避免"长输出污染" 工具调用的长输出(如遍历结果、config/schema 等)不会直接原样反复写入上下文;MemOS 可以做摘要/压缩、去重与归档,长期运行越用越"清爽",记忆质量随时间提升而不是劣化。 --- ## 集成 MemOS OpenClaw 插件后的效果👇🏻 - ✅ 每次仅检索 3-5 条相关记忆 - ✅ 在 2,000-3,000 tokens 内保持上下文稳定性 - ✅ 无论对话多长,成本始终保持可控 ### MemOS 插件能为 OpenClaw 带来的增强 | 功能 | 说明 | |-----|------| | **自动记忆所有对话** | 不依赖模型主动记录,确保关键信息不被遗漏 | | **精准召回** | 基于当前任务意图检索相关记忆,避免无关历史数据 | | **记住用户偏好** | 专门分类和存储偏好信息,跨会话保持有效 | MemOS OpenClaw 重构了 Token 消耗模型,将成本从"历史长度函数"转变为"任务相关性函数"。你的本地 OpenClaw 成本变得可控,系统运行更加稳定。 --- ## 快速开始 只需 3 步,即可让你的 Agent 具备基础记忆能力。 ### 1. 安装 OpenClaw 确保你的系统中已安装 OpenClaw 环境: ```bash # 安装最新版 npm install -g openclaw@latest # 初始化并配置启动 openclaw onboard ``` ### 2. 获取并配置 API Key #### 2.1 获取 Key 登陆/注册 MemOS Cloud 获取你的 API Key 🔗 [MemOS Cloud](https://memos-dashboard.openmem.net/cn/apikeys/) ![image.png](https://cdn.memtensor.com.cn/img/1772443326905_kkxve6_compressed.webp) #### 2.2 设置环境变量 插件会按顺序尝试读取 env 文件(**openclaw → moltbot → clawdbot**)。对于每个键,优先使用首个包含该值的文件。 如果这些文件都不存在(或缺少对应键),则会回退到进程环境变量。 **配置位置** - 文件(优先级顺序): - `~/.openclaw/.env` - `~/.moltbot/.env` - `~/.clawdbot/.env` - 每行格式为 `KEY=value` **快速配置(Shell)** ```bash echo 'export MEMOS_API_KEY="mpg-..."' >> ~/.zshrc source ~/.zshrc # or echo 'export MEMOS_API_KEY="mpg-..."' >> ~/.bashrc source ~/.bashrc ``` **快速配置(Windows PowerShell)** ```powershell [System.Environment]::SetEnvironmentVariable("MEMOS_API_KEY", "mpg-...", "User") ``` 如果缺少 `MEMOS_API_KEY`,插件会提示配置说明和 API Key 获取链接。 **最小配置** ```env MEMOS_API_KEY=YOUR_TOKEN ``` ### 3. 安装插件 #### 方案 A — NPM(推荐) ```bash openclaw plugins install @memtensor/memos-cloud-openclaw-plugin@latest openclaw gateway restart ``` > Windows 用户注意:如果遇到 `Error: spawn EINVAL`,这是 OpenClaw 插件安装器在 Windows 上的已知问题。请使用下面的方案 B(手动安装)。 请确认在 `~/.openclaw/openclaw.json` 中已启用: ```json { "plugins": { "entries": { "memos-cloud-openclaw-plugin": { "enabled": true } } } } ``` #### 方案 B — 手动安装(Windows 兼容方案) 1. 从 [NPM](https://www.npmjs.com/package/@memtensor/memos-cloud-openclaw-plugin) 下载最新的 `.tgz` 包。 2. 解压到本地目录(例如:`C:\Users\YourName\.openclaw\extensions\memos-cloud-openclaw-plugin`)。 3. 配置 `~/.openclaw/openclaw.json`(或 `%USERPROFILE%\.openclaw\openclaw.json`): ```json { "plugins": { "entries": { "memos-cloud-openclaw-plugin": { "enabled": true } }, "load": { "paths": [ "C:\\Users\\YourName\\.openclaw\\extensions\\memos-cloud-openclaw-plugin" ] } } } ``` > **Info**: 注意:解压后的目录通常包含一个 `package` 子目录。请将路径指向包含 `package.json` 的文件夹。 配置修改后请重启 gateway。 ### 4. 更新插件 你可以通过以下命令手动更新云服务插件到最新版本: ```bash openclaw plugins update @memtensor/memos-cloud-openclaw-plugin@latest openclaw gateway restart ``` ## DeepSeek Harness 接入 云插件通过 DSH 原生生命周期机制接入。每轮任务开始前,插件会从 MemOS Cloud 召回相关记忆。当前回合成功结束后,再把本轮用户与助手消息写回云端。整个过程无需修改 DSH 核心代码。云端记忆暂时不可用时,也不会中断当前任务。 API Key 与上文相同,创建一次即可,不必再申请。 ### 1. 将云插件安装到 DSH 默认的 web profile ```bash npx @deepseek-ai/dsh plugin --profile web add @memtensor/memos-cloud-dsh-plugin@latest ``` 安装、移除和版本管理都由 DSH 官方机制完成。 ### 2. 在 `~/.dsh/.env` 中配置 API Key 和用户 ID(推荐) 创建或编辑 `~/.dsh/.env`: ```dotenv MEMOS_API_KEY=mpg-your-key MEMOS_USER_ID=your-stable-user-id ``` `MEMOS_USER_ID` 用于记忆召回和写入,请为每位用户设置稳定且不同的 ID。未配置时默认为 `deepseek-harness-user`。已有用户升级时请沿用原 ID;此前使用默认值的用户可继续填写 `deepseek-harness-user`,以访问原有记忆。 **从旧配置升级到 0.1.1:** 如果此前将 `MEMOS_API_KEY` 直接写在 `.credentials.yaml` 顶层,请将 Key 移到上述 `.env`,或使用下面的凭据格式。 也可以将 API Key 保存在 `~/.dsh/.credentials.yaml` 的 `refs` 下。以下是新建文件的示例;编辑已有文件时,将 Key 合并到原有 `refs`,保留其他凭据和 `records`: ```yaml version: 1 refs: MEMOS_API_KEY: mpg-your-key records: {} ``` 使用凭据文件时,用户 ID 仍通过 `.env` 中的 `MEMOS_USER_ID` 或 `settings.yaml` 中的 `memos-cloud.userId` 配置。 ### 3. 在 `~/.dsh/settings.yaml` 中加入最小配置 ```yaml memos-cloud: apiKeyEnv: MEMOS_API_KEY ``` `apiKeyEnv` 填写凭据名称,实际 Key 保存在 `.env` 或 `.credentials.yaml` 中。`baseURL`、记忆召回和写入等普通选项在 `settings.yaml` 中配置。 同一选项支持多个来源时,优先级从高到低为:`settings.yaml` 中直接设置的值 → 继承的进程环境变量 → `.credentials.yaml` 中的凭据 → 启动目录的 `.env` → `~/.dsh/.env` → 插件默认值。其中,凭据文件仅用于 API Key。更新 Key 后仍读取到旧值时,请检查优先级更高的配置来源。 ### 4. 重新启动 DSH Web `.env` 在 DSH 启动时加载。修改配置后,先在运行 DSH 的终端按 `Ctrl+C` 停止服务,再启动: ```bash npx @deepseek-ai/dsh web ``` 安装后,DSH 会在每轮任务开始前自动获得相关的云端记忆。任务成功结束后,新的上下文和经验会继续沉淀。 完整配置项与兼容性说明请参考 [DSH 插件 README](https://github.com/MemTensor/MemOS-Cloud-OpenClaw-Plugin/blob/test/packages/dsh/README.md#configuration)。 ## 开源项目进阶配置 如果希望进一步解锁更多可能性,还可以通过 MemOS Github 项目进行进一步探索和配置! ### 可视化配置界面 (Config UI) 自 `v0.1.12` 版本起,云插件内置了本地可视化配置服务,让您可以更直观地管理和修改插件配置。 **如何访问:** 1. 启动 OpenClaw 节点或宿主网关。 2. 插件成功加载并检测到网关就绪后,会自动在后台启动 Config UI 服务。 3. 在终端控制台日志中会打印访问链接(默认地址通常为 `http://127.0.0.1:38463`)。 4. 在浏览器中打开该链接,即可进入插件的可视化管理后台。 **功能特点:** - **直观编辑**:支持以表单形式编辑所有核心配置(如知识库 ID、大模型检索参数、多 Agent 覆盖规则等)。 - **实时同步**:在界面上保存的配置变更会立即在插件运行时生效,无需重启服务。 - **状态监控**:界面提供与宿主网关的心跳检测,确保配置同步链路健康。 ### 多Agent支持与隔离(Multi-Agent) 插件内置对多 Agent 模式的强大支持(通过 `agent_id` 参数实现),非常适合在复杂工作流或团队代理场景下使用。 **1. 开启与数据隔离** - **开启方式**:在配置中设置 `"multiAgentMode": true` 或配置环境变量 `MEMOS_MULTI_AGENT_MODE=true`。 - **自动隔离**:开启后,插件会自动读取上下文中的 `ctx.agentId`。在进行记忆检索和写入时,会自动附带该 Agent 标识,从而保证同一用户下的不同 Agent 之间记忆数据完全隔离(注:默认的 `"main"` Agent 会被忽略以保证旧数据兼容性)。 **2. 按 Agent 开关记忆(白名单控制)** 在多 Agent 模式下,如果不想让所有 Agent 都产生记忆消耗,你可以使用 `allowedAgents` 精确控制白名单: ```json { "plugins": { "entries": { "memos-cloud-openclaw-plugin": { "enabled": true, "config": { "multiAgentMode": true, "allowedAgents": ["research-agent", "coding-agent"] } } } } } ``` *(提示:1. 如果 `allowedAgents` 未配置或为空数组 `[]`,则表示**所有 Agent** 都允许使用记忆检索和写入。2. 如果进行了配置,那么不在配置中的 Agent 将被完全跳过,只有配置中的 Agent 才会生效进行记忆检索和写入,从而避免 Token 浪费)。* **3. 按 Agent 独立配置参数(agentOverrides)** 除了简单的开关,你还可以通过 `agentOverrides` 为**每个 Agent 单独覆写记忆参数**。例如,让研究助手拥有更宽松的检索阈值,而让代码助手只读取特定的代码库知识: ```json { "plugins": { "entries": { "memos-cloud-openclaw-plugin": { "enabled": true, "config": { "multiAgentMode": true, "allowedAgents": ["research-agent", "coding-agent"], "memoryLimitNumber": 6, "relativity": 0.45, "agentOverrides": { "research-agent": { "knowledgebaseIds": ["kb-research-papers"], "memoryLimitNumber": 12, "relativity": 0.3, "queryPrefix": "research context: " }, "coding-agent": { "knowledgebaseIds": ["kb-codebase"], "memoryLimitNumber": 9, "addEnabled": false } } } } } } } ``` *(在上面的例子中,`coding-agent` 被禁止了记忆写入,且只能检索 `kb-codebase` 知识库中的前 9 条高相关性记忆)。* ### 环境变量深度定制 除了必需的 API Key,你还可以通过环境变量调整插件行为。 更多细节配置项可以见 [MemTensor GitHub 官方插件仓库](https://github.com/MemTensor/MemOS/tree/main/apps/MemOS-Cloud-OpenClaw-Plugin) ## 测试记忆功能 现在,可以与你的 Agent 进行多轮对话,例如: **第一次会话:** - "我最喜欢的编程语言是 Python" - "我正在开发一个电商项目" **第二次会话(新启动):** - "你还记得我喜欢用什么编程语言吗?" - "我之前说的项目进展如何?" 现在,你的 OpenClaw 会从 MemOS Cloud 中检索记忆并给出准确回答啦~ --- ## 配合 CLI 工具使用 如果你同时使用 OpenClaw 和其他可执行命令行的 Agent(如 Cursor、Codex、Claude Code),可以用 MemOS CLI 让它们共享同一套记忆。另外,同时使用插件与 CLI 工具时,OpenClaw 的记忆操作更灵活、效果更好。 ### 安装 CLI 并生成插件感知 Skill ```bash npm install -g @memtensor/memos-cloud-cli memos init --agent openclaw --memos-plugin ``` `--memos-plugin` 会让生成的 Skill 感知到已安装的 OpenClaw 云插件,避免重复写入记忆。 > **Tip**: 以 OpenClaw 为例,在 LOCOMO 评测中,单独接入 MemOS CLI 后 Token 消耗降低约 65.5%;接入 MemOS Cloud + CLI 后,正确率从 66.60% 提升到 77.27%。 ### 为其他 Agent 安装 Skill ```bash memos init --agent cursor memos init --agent codex ``` 安装后,这些 Agent 也会通过 CLI 自动检索和写入 MemOS 记忆,和 OpenClaw 共享同一个记忆空间。 ### 开始新对话 回到 OpenClaw,进行一轮会产生长期记忆的对话: ```text 我最近在做电商项目,主要使用 Python。请记住这件事。 ``` 然后开启新会话,继续询问: ```text 我最近在做什么项目?主要用什么语言? ``` 如果 OpenClaw 能结合上一轮内容回答,说明插件已完成记忆写入与召回;同时,生成的 CLI Skill 会感知已安装插件,避免重复写入。 > **Tip**: CLI 的完整命令参考和更多用法请查看 [MemOS CLI 使用指南](/cn/mcp_agent/cli/guide)。 --- # 本地插件 (/cn/openclaw/local_plugin) > **Note**: **兼容性建议** > 请使用当前版本支持的 OpenClaw、Hermes Agent 或 DeepSeek Harness 版本,以避免插件加载或运行错误。 `@memtensor/memos-local-plugin` 是 MemOS 新一代本地插件:一套本地优先的记忆核心,同时支持 **OpenClaw**、**Hermes Agent** 与 **DeepSeek Harness**。它不会把记忆数据托管到云端,而是在你的机器上维护 SQLite 数据库、技能包和日志,让 Agent 在本地持续积累可复用经验。 如果你只想快速接入云端托管记忆,请查看[云插件](/cn/openclaw/guide)。如果你更看重隐私、本机运行、可观测性,或希望 OpenClaw、Hermes 与 DeepSeek Harness 都使用同一套本地记忆能力,请使用本页面的本地插件。 ## 核心能力 | 能力 | 说明 | | --- | --- | | 本地优先 | OpenClaw、Hermes 与 DeepSeek Harness 各自拥有独立运行目录,SQLite、Skill、日志和配置都保留在本机。 | | 多 Agent 支持 | OpenClaw 通过 TypeScript 插件进程内接入;Hermes 通过 Python Provider + JSON-RPC 桥接到同一套 Node.js 记忆核心;DeepSeek Harness 通过其原生的插件机制接入。 | | 四层记忆 | L1 Trace 记录每一步执行,L2 Policy 归纳跨任务策略,L3 World Model 压缩环境认知,Skill 将高价值经验结晶为可调用能力。 | | 三层检索 | 按 Skill → Trace/Episode → World Model 检索,并融合向量、FTS5、关键词 pattern 与错误特征,使用 RRF + MMR 控制相关性和多样性。 | | 反馈驱动进化 | 工具结果、环境反馈、用户显式反馈会更新记忆价值,推动策略归纳、技能结晶和 decision repair。 | | 本地 Viewer | 提供 Overview、Memories、Tasks、Policies、World Models、Skills、Analytics、Logs、Import、Settings、Help 等页面。 | | 导入与迁移 | 支持 JSON 导入导出、旧版插件数据迁移,以及按当前 Agent 导入 OpenClaw 会话 JSONL、Hermes `MEMORY.md` 或 DeepSeek Harness 对应的会话数据。 | | 可选团队共享 | 默认完全隔离;如需协作,可在 Memory Viewer 的 Team Sharing 面板中开启局域网 / VPN 内 Skill 和可选 Trace 摘要共享。 | ## 工作原理 插件在每轮任务开始前检索相关上下文,并把结果注入给 Agent;任务结束后,它会把对话、工具调用、观察结果和反馈写入本地流水线。高价值模式会从原始 Trace 逐步沉淀为 Policy、World Model 和可调用 Skill。下次遇到相似任务时,Agent 可以直接得到“该怎么做”和“哪些坑要避开”的上下文。 | 阶段 | 发生了什么 | 产物 | | --- | --- | --- | | 1. Agent 接入 | OpenClaw、Hermes 与 DeepSeek Harness 通过各自 Adapter 把会话、工具调用和反馈交给统一的 `MemoryCore`。 | 标准化的 turn、tool outcome、feedback | | 2. 本地写入 | `MemoryCore` 把执行过程拆成可追溯的步骤记录。 | L1 Trace | | 3. 经验归纳 | 多个相似 Trace 会归纳为跨任务策略,并进一步压缩为环境认知。 | L2 Policy、L3 World Model | | 4. 技能结晶 | 高价值策略会生成可调用 Skill,并根据后续反馈更新可靠性。 | Skill、η、生命周期状态 | | 5. 检索注入 | 下一轮任务开始前,Retriever 从 Skill、Trace/Episode、World Model 三层召回上下文。 | 注入给 Agent 的本地记忆上下文 | ## 快速开始 ### Step 1:一行命令安装或升级 安装与升级使用同一条命令。当前安装脚本面向 macOS / Linux: ```bash curl -fsSL https://raw.githubusercontent.com/MemTensor/MemOS/main/apps/memos-local-plugin/install.sh | bash ``` 安装器会自动检测系统中是否已安装 OpenClaw、Hermes 或 DeepSeek Harness。交互式终端会询问安装到哪个 Agent;非交互环境会自动安装到检测到的 Agent。安装器会部署插件代码、安装生产依赖,并在需要时重启对应运行时。 > 不建议直接 `npm install` 这个包。安装脚本会处理 Agent 检测、目录布局、配置初始化和运行时重启。 ### Step 2:打开 Memory Viewer 安装完成后,打开对应的 Memory Viewer: | Agent | Memory Viewer | | --- | --- | | OpenClaw | `http://127.0.0.1:18799` | | Hermes | `http://127.0.0.1:18800` | | DeepSeek Harness | `http://127.0.0.1:18801` | 如果你同时安装了 OpenClaw、Hermes 和 DeepSeek Harness,它们会使用各自独立的 Viewer 和本地数据目录。 ### Step 3:在面板里完成配置 所有用户可见配置都从 Memory Viewer 修改: - **Settings → AI Models**:配置 Embedding、LLM、Skill Evolver,并用 Test 按钮确认可用。 - **Settings → Team Sharing**:开启或关闭团队共享,配置团队地址与 token。 - **Settings → General**:配置语言、日志详细程度、匿名 telemetry 等。 保存后,Viewer 会自动重启插件并加载新设置。 ### Step 4:启动对应 Agent 安装完成后,按你选择的 Agent 正常启动即可。插件会在 Agent 构建 prompt 前检索本地上下文,并在本轮任务结束后把对话、工具调用、观察结果和反馈写入本地记忆。 | Agent | 启动方式 | 插件接入方式 | | --- | --- | --- | | OpenClaw | 正常启动或重启 OpenClaw gateway | TypeScript 插件在 OpenClaw 进程内调用 `MemoryCore` | | Hermes | 运行 `hermes chat` | Python Provider 通过 JSON-RPC 调用 Node.js 记忆核心 | | DeepSeek Harness | 运行 `npx @deepseek-ai/dsh web` | DeepSeek Harness adapter 调用 `MemoryCore` | 如果 Hermes 所在机器无法运行 Node.js,Hermes Provider 会报告不可用,并回退到 Hermes 自身的内存模式。 ### Step 5:验证记忆功能 回到 Memory Viewer,建议检查以下页面: 1. **Overview**:确认核心状态、版本、事件流正常。 2. **Memories**:确认对话和工具步骤被写入为 Trace。 3. **Tasks / Policies / World Models / Skills**:查看经验如何逐步归纳和结晶。 4. **Import**:导入旧版数据、OpenClaw 会话 JSONL、Hermes `MEMORY.md`、DeepSeek Harness 对应的会话数据,或导入 / 导出 JSON 备份。 5. **Help**:查看每个字段含义,例如 `V`、`α`、`R_human`、`η`、support、gain 等。 ## Agent 差异 | 项目 | OpenClaw | Hermes | DeepSeek Harness | | --- | --- | --- | --- | | 接入方式 | TypeScript 插件,进程内调用 `MemoryCore` | Python `MemoryProvider`,通过 stdio JSON-RPC 调用 Node bridge | 通过 DeepSeek Harness adapter 接入 `MemoryCore` | | 默认 Viewer | `http://127.0.0.1:18799` | `http://127.0.0.1:18800` | 由 DeepSeek Harness 运行时提供 | | 模型配置 | 在 OpenClaw Viewer 的 Settings → AI Models 中配置 | 在 Hermes Viewer 的 Settings → AI Models 中配置 | 在 DeepSeek Harness Web UI 的 Settings → Models 中配置 | | 数据共享 | 默认与 Hermes、DeepSeek Harness 隔离 | 默认与 OpenClaw、DeepSeek Harness 隔离 | 默认与 OpenClaw、Hermes 隔离 | 三个 Agent 即使安装在同一台机器上,也会使用各自的数据库和 Viewer。只有显式开启 `hub:` 后,才会进行团队共享。 ## 可用工具 OpenClaw、Hermes 和 DeepSeek Harness 会通过各自宿主暴露记忆工具,常见能力包括: | 工具 | 用途 | | --- | --- | | `memory_search` | 按查询检索相关 Skill、Trace/Episode、World Model。 | | `memory_get` | 获取某条记忆详情。 | | `memory_timeline` | 查看某个 episode / task 的时间线。 | | `skill_list` | 列出可调用 Skill。 | | `skill_get` | 获取某个 Skill 的调用指南。 | | `memory_environment` | 查询 L3 World Model,了解项目结构、环境规律和约束。 | 插件也会记录工具调用成功 / 失败结果,用于后续 decision repair。 ## 数据管理 - **备份**:在 Viewer 的 Import 页面导出 JSON,或备份当前 Agent 的 `~/./memos-plugin/` 目录。 - **仅清空记忆**:在确认已备份后删除运行目录下的 `data/` 和 `skills/`。 - **清空日志**:删除 `logs/` 下普通日志。`audit.log` 会按月 gzip 保留。 - **彻底重置**:删除整个 `~/./memos-plugin/`,下次启动会重新创建空目录。 ## 更多资料 - [MemOS 本地插件项目](https://github.com/MemTensor/MemOS/tree/main/apps/memos-local-plugin) - [云插件 vs 本地插件](/cn/openclaw/plugin_compare) --- # OpenClaw 插件更新日志 (/cn/openclaw/changes) OpenClaw 插件更新日志已统一迁移到总更新日志的 **Plugin** tab,本页后续不再维护重复版本记录。 请前往 [更新日志](/cn/changelog) 并切换到 **Plugin** tab,查看 OpenClaw 云插件、OpenClaw 本地插件和 MemOS CLI 的最新发版记录。 --- # 知识库使用 (/cn/openclaw/examples/knowledge_base) ## 云插件 MemOS OpenClaw 云插件可以在每轮任务开始前,基于当前问题同时召回个人记忆和指定知识库内容。适合把产品文档、公司制度、项目资料、代码规范等长期资料接入 OpenClaw,让 Agent 在执行任务时自动参考这些资料。 ### 1. 创建知识库并获取 ID 知识库需要先在 [MemOS Cloud Dashboard](https://memos-dashboard.openmem.net) 中创建。 操作步骤: 1. 登录 [MemOS Cloud Dashboard](https://memos-dashboard.openmem.net)。 2. 进入知识库管理页面,创建新的知识库。 3. 上传需要被 Agent 检索的文档或 Skill 文件。 4. 等待文件处理完成。 5. 在知识库详情页复制知识库 ID,例如 `kb-company-handbook`。 > **Warning**: 请使用控制台中复制到的真实知识库 ID 替换下面示例里的 `kb-company-handbook`。知识库名称只是展示名,插件配置需要填写知识库 ID。 ### 2. 配置全局知识库 知识库相关配置分为两个方向: - `knowledgebaseIds` / `MEMOS_KNOWLEDGEBASE_IDS`:负责查询知识库,插件在 `/search/memory` 阶段从这些知识库中召回内容。 - `allowKnowledgebaseIds` / `MEMOS_ALLOW_KNOWLEDGEBASE_IDS`:负责写入知识库,插件在 `/add/message` 阶段允许把新增记忆写入这些知识库。 如果希望所有 OpenClaw 会话都可以检索同一个知识库,可以在 `~/.openclaw/openclaw.json` 中配置 `knowledgebaseIds`: ```json { "plugins": { "entries": { "memos-cloud-openclaw-plugin": { "enabled": true, "config": { "apiKey": "YOUR_MEMOS_API_KEY", "knowledgebaseIds": ["kb-company-handbook"], "memoryLimitNumber": 6, "relativity": 0.45 } } } } } ``` 配置完成后重启 OpenClaw gateway: ```bash openclaw gateway restart ``` ### 3. 使用环境变量配置 也可以在 `~/.openclaw/.env` 中配置知识库 ID: ```bash MEMOS_API_KEY=YOUR_MEMOS_API_KEY MEMOS_KNOWLEDGEBASE_IDS="kb-company-handbook,kb-product-docs" ``` `MEMOS_KNOWLEDGEBASE_IDS` 对应检索阶段的知识库范围,也就是插件调用 `/search/memory` 时会读取这些知识库。 如果需要把对话新增记忆写入知识库,需要额外配置写入参数: ```bash MEMOS_ALLOW_KNOWLEDGEBASE_IDS="kb-company-handbook" ``` > **Warning**: 知识库写入会让 Agent 产生的信息进入对应知识库,但知识库内容本身不会按 `agent_id` 做隔离过滤。也就是说,一旦多个 Agent 都配置读取同一个知识库,写入该知识库的信息就可能被这些 Agent 共同召回,从而削弱多 Agent 记忆隔离效果。 > > 如果你希望严格保持 Agent 隔离,建议不要把对话记忆写入共享知识库;只有在明确希望沉淀为团队共享知识时,再配置 `allowKnowledgebaseIds` 或 `MEMOS_ALLOW_KNOWLEDGEBASE_IDS`。 ### 4. 多 Agent 分别绑定知识库 当不同 Agent 负责不同任务时,建议开启多 Agent 模式,并通过 `agentOverrides` 为每个 Agent 配置自己的知识库: ```json { "plugins": { "entries": { "memos-cloud-openclaw-plugin": { "enabled": true, "config": { "multiAgentMode": true, "allowedAgents": ["research-agent", "coding-agent"], "memoryLimitNumber": 6, "relativity": 0.45, "agentOverrides": { "research-agent": { "knowledgebaseIds": ["kb-research-papers"], "memoryLimitNumber": 12, "queryPrefix": "research context: " }, "coding-agent": { "knowledgebaseIds": ["kb-codebase", "kb-api-docs"], "memoryLimitNumber": 9, "includeToolMemory": true, "addEnabled": false } } } } } } } ``` 上面的配置表示: - `research-agent` 会优先检索论文 / 研究资料知识库。 - `coding-agent` 会检索代码库和 API 文档知识库,并关闭对话写入,避免把临时调试过程沉淀到长期记忆中。 - 未出现在 `agentOverrides` 中的 Agent 会继承全局配置。 如果在多 Agent 场景中开启知识库写入,请确保写入目标不是多个 Agent 共同读取的共享知识库,否则不同 Agent 的信息可能通过知识库互相可见。 ### 5. 验证知识库召回 配置完成后,可以向 OpenClaw 提问一个只有知识库文档中才有答案的问题: ```text 你:根据公司报销制度,设计软件采购超过多少金额需要特殊审批? OpenClaw:根据知识库中的采购规则,设计软件采购超过 1000 元需要特殊审批…… ``` 如果回答没有引用知识库内容,可以按下面顺序排查: - 确认知识库文件在 Dashboard 中已经处理完成。 - 确认 `knowledgebaseIds` 或 `MEMOS_KNOWLEDGEBASE_IDS` 使用的是知识库 ID,不是知识库名称。 - 确认 OpenClaw gateway 已重启并加载了最新配置。 - 如果使用多 Agent,确认当前 Agent 在 `allowedAgents` 中,并且对应 `agentOverrides` 配置正确。 ### 配置参考 知识库相关配置请参考 [MemOS-Cloud-OpenClaw-Plugin 官方仓库](https://github.com/MemTensor/MemOS-Cloud-OpenClaw-Plugin): | 配置项 | 用途 | | --- | --- | | `knowledgebaseIds` | 查询知识库。插件配置中的知识库检索范围,对应 `/search/memory`。 | | `MEMOS_KNOWLEDGEBASE_IDS` | 查询知识库。环境变量形式的知识库检索范围,多个 ID 用英文逗号分隔。 | | `allowKnowledgebaseIds` | 写入知识库。插件配置中的新增记忆允许写入知识库范围,对应 `/add/message`。 | | `MEMOS_ALLOW_KNOWLEDGEBASE_IDS` | 写入知识库。环境变量形式的新增记忆允许写入知识库范围。 | | `agentOverrides..knowledgebaseIds` | 多 Agent 场景下,为某个 Agent 单独指定知识库。 | --- # 多智能体记忆隔离 (/cn/openclaw/examples/multi_agent) ## 云插件 MemOS Openclaw 云插件支持多个 Agent 之间完全隔离记忆和和消息历史。每个 Agent 都只能看到自己的记忆,不会串台。 ### 如何使用 只需简单配置,即可让不同 Agent 拥有独立的记忆空间。支持自动识别和静态指定两种模式。 #### 1. 开启多 Agent 模式 在 `openclaw.json` 配置中添加: ```json { "plugins": { "entries": { "memos-cloud-openclaw-plugin": { "config": { "multiAgentMode": true } } } } } ``` 或设置环境变量: ```bash MEMOS_MULTI_AGENT_MODE=true ``` #### 2. 自动识别 Agent 开启后,插件会自动读取 `ctx.agentId` ,不同 Agent 的记忆自动隔离。无需额外配置。 #### 3. 静态指定 Agent(可选) 如果需要固定某个 Agent ID,可以在配置中指定: ```json { "config": { "agentId": "marketing_agent" } } ``` #### 4. 按 Agent 单独配置参数(可选) 除了隔离记忆空间,还可以通过 `agentOverrides` 给不同 Agent 单独覆盖知识库、召回条数、相关性阈值、是否写入记忆等参数。未配置的字段会继承全局配置。 ```json { "plugins": { "entries": { "memos-cloud-openclaw-plugin": { "enabled": true, "config": { "multiAgentMode": true, "allowedAgents": ["research-agent", "coding-agent"], "knowledgebaseIds": [], "memoryLimitNumber": 6, "relativity": 0.45, "agentOverrides": { "research-agent": { "knowledgebaseIds": ["kb-research-papers", "kb-academic"], "memoryLimitNumber": 12, "relativity": 0.3, "includeToolMemory": true, "captureStrategy": "full_session", "queryPrefix": "research context: " }, "coding-agent": { "knowledgebaseIds": ["kb-codebase", "kb-api-docs"], "memoryLimitNumber": 9, "relativity": 0.5, "addEnabled": false } } } } } } } ``` 上面的配置表示: - `research-agent` 使用论文 / 学术知识库,召回更多记忆,并开启工具记忆。 - `coding-agent` 只读取代码库和 API 文档知识库,并关闭记忆写入。 - 其他 Agent 如果被允许使用记忆,则沿用全局的 `knowledgebaseIds`、`memoryLimitNumber` 和 `relativity`。 `.env` 中也可以使用 `MEMOS_AGENT_OVERRIDES` 配置 JSON 字符串,但优先级低于 `openclaw.json` 中的 `agentOverrides`: ```bash MEMOS_AGENT_OVERRIDES='{"research-agent":{"memoryLimitNumber":12,"relativity":0.3},"coding-agent":{"memoryLimitNumber":9,"addEnabled":false}}' ``` 常用可覆盖字段: | 字段 | 说明 | | --- | --- | | `knowledgebaseIds` | 当前 Agent 检索的知识库 ID 列表。 | | `memoryLimitNumber` | 当前 Agent 最多召回的记忆条数。 | | `preferenceLimitNumber` | 当前 Agent 最多召回的偏好记忆条数。 | | `includePreference` | 是否召回偏好记忆。 | | `includeToolMemory` | 是否召回工具记忆。 | | `toolMemoryLimitNumber` | 工具记忆最多召回条数。 | | `relativity` | 相关性阈值,取值范围通常为 `0-1`。 | | `recallEnabled` | 是否为当前 Agent 开启记忆召回。 | | `addEnabled` | 是否为当前 Agent 开启记忆写入。 | | `captureStrategy` | 写入策略,例如 `last_turn` 或 `full_session`。 | | `queryPrefix` | 当前 Agent 的检索 query 前缀。 | | `recallFilterEnabled` | 是否开启召回二次过滤。 | | `allowKnowledgebaseIds` | 当前 Agent 允许写入的知识库 ID 列表。 | | `tags` | 写入记忆时附加的标签。 | ### 原理介绍 - **/search/memory**:检索记忆——只返回当前 Agent 的记忆 - **/add/message**:添加记录——自动标记为当前 Agent 的数据 - **配置合并**:插件先读取全局配置,再用 `agentOverrides.` 覆盖当前 Agent 的局部配置 - **向下兼容**:默认 Agent `"main"` 会被忽略,保证老用户的单 Agent 数据不受影响 ### 适用场景 - **多角色协作**:战略/业务/营销/技术 Agent 分工协作 - **业务线独立**:不同业务线的 Agent 独立运行互不干扰 - **人设一致性**:保持 Agent 长期人设和行为风格一致 --- ## 本地插件 `@memtensor/memos-local-plugin` 同时支持 OpenClaw 与 Hermes。默认情况下,每个 Agent 使用独立运行目录和本地数据库;如果在同一套运行目录内区分多个会话 / Agent,检索会优先限定在当前 Agent 的上下文中。需要跨实例协作时,可以在 Memory Viewer 的 **Settings → Team Sharing** 中开启团队共享。 ### 规则 - **默认隔离**:OpenClaw 使用 `~/.openclaw/memos-plugin/`,Hermes 使用 `~/.hermes/memos-plugin/`,两者不会自动共享数据库。 - **当前 Agent 优先**:检索时优先使用当前 Agent / session 的 Trace、Policy、World Model 和 Skill。 - **可选共享**:开启 `hub.enabled` 后,可在局域网 / VPN 内共享本地结晶的 Skill 和可选 Trace 摘要。 - **失败降级**:Hub 不在算法关键路径上;共享服务不可用时,本地插件自动退回本机记忆模式。 ### 操作示例 ```text OpenClaw: memory_search("deploy config") → 优先检索 OpenClaw 本地库中的 Skill / Trace / World Model Hermes: memory_search("deploy config") → 优先检索 Hermes 本地库中的 Skill / Trace / World Model 开启 Hub 后: OpenClaw / Hermes 可以拉取团队共享 Skill 私有 Trace 默认仍留在各自机器和运行目录中 ``` ### 预期结果 - OpenClaw 与 Hermes 默认互不读取对方的本地数据库 - 同一团队内可显式共享高价值 Skill,减少重复踩坑 - 即使 Hub 不可用,本地记忆写入、召回和技能检索仍然可用 --- # 记忆召回的二次过滤 (/cn/openclaw/examples/recall_filter) ## 云插件 MemOS Openclaw 云插件支持使用指定的大语言模型对召回的记忆进行二次精准过滤。过滤后,只有与当前任务高度相关的记忆才会被注入到上下文中,有效避免无关记忆的干扰并节省 Token。 ### 如何使用 只需配置兼容 OpenAI 格式的模型接口(如本地 Ollama 或第三方大模型 API)并开启过滤开关,即可启用记忆二次过滤功能。 #### 1. 开启记忆过滤功能 在配置大模型过滤记忆时,**必须**配置 API Key 和 Base URL。 在 `openclaw.json` 配置中添加: ```json { "plugins": { "entries": { "memos-cloud-openclaw-plugin": { "config": { "recallFilterEnabled": true, "recallFilterBaseUrl": "http://127.0.0.1:11434/v1", "recallFilterApiKey": "sk-...", "recallFilterModel": "qwen2.5_7b" } } } } } ``` 或设置环境变量: ```bash MEMOS_RECALL_FILTER_ENABLED=true MEMOS_RECALL_FILTER_BASE_URL="http://127.0.0.1:11434/v1" MEMOS_RECALL_FILTER_API_KEY="sk-..." MEMOS_RECALL_FILTER_MODEL="qwen2.5_7b" ``` #### 2. 配置鉴权与进阶参数(可选) 如果需要调整超时时间及失败策略,可以在配置中指定: ```json { "config": { "recallFilterTimeoutMs": 6000, "recallFilterFailOpen": true } } ``` ### 原理介绍 - **召回后拦截**:在每轮对话前从云端召回记忆后,插件会把候选的记忆条目发送给你配置的过滤模型做二次筛选。 - **精准保留**:过滤模型判断后,只保留被标记为 `keep` 的相关条目,最终注入到 Agent 的上下文中。 - **高可用回退**:默认开启了失败放行(`recallFilterFailOpen: true`)。当过滤模型请求超时或失败时,会自动回退为“不过滤”全量注入,保证当前对话不被中断。 ### 适用场景 - **超长记忆精简**:长期对话积累大量记忆时,剔除与当前 Prompt 无关的内容,大幅降低主模型上下文的 Token 消耗。 - **提升推理精度**:为需要专注处理复杂任务的 Agent 过滤掉早期无关的记忆干扰,提高核心任务的推理准确度。 - **本地模型协同**:搭配本地运行的小模型(如 Ollama 运行的 `qwen2.5_7b`)作为低成本前置过滤器,在不增加主模型 API 费用的前提下提升记忆注入质量。 --- ## 本地插件 `@memtensor/memos-local-plugin` 的本地检索内置多阶段过滤。它会先从 Skill、Trace/Episode、World Model 三层召回候选,再通过 RRF + MMR 做融合与去冗余;如果配置了可用 LLM,还可以在注入前做相关性复核,进一步筛掉表面关键词相似但对当前任务帮助不大的内容。 ### 如何配置 直接在对应 Agent 的 Memory Viewer 里配置: | Agent | Memory Viewer | | --- | --- | | OpenClaw | `http://127.0.0.1:18799` | | Hermes | `http://127.0.0.1:18800` | 配置步骤: 1. 打开 Memory Viewer。 2. 进入 **Settings → AI Models**。 3. 在 **LLM** 区域选择 provider,并填写 endpoint、API Key、model 等信息。 4. 点击 **Test** 确认模型可用。 5. 保存设置;Viewer 会自动重启插件并加载新配置。 保存后,本地检索会在召回、RRF/MMR 排序之后使用该 LLM 做相关性复核。未配置 LLM 时,插件仍会使用内置的多通道召回和机械阈值过滤。 ### 本地召回流程 ```text 用户问题 → 构建检索 query 与标签 → Tier 1: Skill 候选 → Tier 2: Trace / Episode 候选 → Tier 3: World Model 候选 → 向量 / FTS5 / pattern / 错误特征多通道召回 → RRF 融合 + MMR 多样性控制 → 可选 LLM 相关性复核 → 注入给 Agent ``` ### 预期结果 - 注入上下文的记忆更聚焦,噪音更少 - Skill、Trace/Episode、World Model 不会只靠单一向量相似度命中 - LLM 不可用时会使用更严格的机械阈值回退,不影响基础召回 --- # 本地插件使用 (/cn/openclaw/examples/hermes_usage) ## 基本使用 `@memtensor/memos-local-plugin` 同时支持 OpenClaw 与 Hermes。安装完成后,按你使用的 Agent 正常启动即可;插件会在每轮任务开始前注入本地记忆上下文,并在任务结束后写入 Trace、Policy、World Model 和 Skill。 | Agent | 启动方式 | Viewer | | --- | --- | --- | | OpenClaw | 正常启动或重启 OpenClaw gateway | `http://127.0.0.1:18799` | | Hermes | `hermes chat` | `http://127.0.0.1:18800` | ### 验证记忆功能 1. 与 OpenClaw 或 Hermes Agent 进行任意对话。 2. 打开对应 Memory Viewer,确认对话内容已出现在 **Memories** / **Tasks** 页面。 3. 新开一个对话,让 Agent 回忆之前的内容: ```text 你:你还记得我之前让你帮我处理过什么事情吗? Agent:(调用 memory_search)是的,我们之前讨论过…… ``` --- ## 记忆工具 本地插件会通过各自 Agent 宿主暴露记忆工具。不同宿主展示名称可能略有差异,但核心能力一致。 | 工具 | 说明 | | --- | --- | | `memory_search` | 从 Skill、Trace/Episode、World Model 三层检索相关上下文。 | | `memory_get` | 获取某条记忆详情。 | | `memory_timeline` | 查看某个 episode / task 附近的时间线。 | | `skill_list` | 列出当前可用 Skill。 | | `skill_get` | 获取某个 Skill 的调用指南。 | | `memory_environment` | 查询 L3 World Model,了解项目结构、环境规律和约束。 | ### 调用示例 ```text Agent 调用: memory_search("Nginx 部署配置") → 返回相关 Skill、Trace 片段和环境认知 Agent 调用: skill_get("nginx-proxy") → 返回可执行步骤、适用条件和注意事项 ``` 插件也会记录工具调用成功 / 失败结果,用于后续 decision repair。 --- ## 团队共享 默认情况下,OpenClaw 与 Hermes 各自使用独立本地数据库。需要协作时,可以在 Memory Viewer 中启用 Team Sharing,把本地结晶出的 Skill 和可选 Trace 摘要共享给同一局域网 / VPN 内的其他实例。 ### 配置方式 打开对应 Agent 的 Memory Viewer,进入 **Settings → Team Sharing**,按面板提示填写团队地址和 token,保存后插件会自动重启并加载设置。 ### 预期效果 - 私有本地数据默认留在当前 Agent 的运行目录中。 - 明确共享的 Skill 可被其他实例检索和复用。 - Hub 不在算法关键路径上;共享失败时,本地记忆写入、召回和 Skill 检索仍可继续。 --- ## 多 Agent 场景 同一台机器上同时安装 OpenClaw 和 Hermes 时,它们的端口和数据完全隔离: | 资源 | OpenClaw | Hermes | | --- | --- | --- | | Viewer | `18799` | `18800` | | 数据目录 | `~/.openclaw/memos-plugin/` | `~/.hermes/memos-plugin/` | | 配置入口 | Viewer → Settings | Viewer → Settings | ```text OpenClaw: memory_search("deploy config") → 优先使用 OpenClaw 本地经验 Hermes: memory_search("deploy config") → 优先使用 Hermes 本地经验 开启 Hub 后: 两者可以显式复用团队共享 Skill ``` --- ## Viewer 管理 Memory Viewer 提供这些常用入口: | 页面 | 用途 | | --- | --- | | Overview | 查看核心状态、版本、事件流和健康状态。 | | Memories | 查看 L1 Trace 和原始执行记录。 | | Tasks | 查看按任务聚合的对话与执行结果。 | | Policies | 查看从多个 Trace 归纳出的策略。 | | World Models | 查看环境认知与约束。 | | Skills | 查看、检索或停用结晶出的 Skill。 | | Import | 导入旧版插件数据、OpenClaw 会话 JSONL、Hermes `MEMORY.md`,或导入 / 导出 JSON 备份。 | | Settings | 配置模型、团队共享、日志和 telemetry。 | | Help | 查看 `V`、`α`、`R_human`、`η`、support、gain 等字段含义。 | --- # 概述 (/cn/api_docs/start/overview) ## 1. 接口介绍 MemOS 提供了完整的接口,通过简单的 API 请求,即可将记忆相关的功能集成到您的 AI 应用内,实现不同用户与 AI 智能体的记忆生产、调度、召回与生命周期管理。 > **Tip**: **快速开始:** 从 [**MemOS 控制台**](https://memos-dashboard.openmem.net/apikeys/) 获取你的接口密钥,一分钟即可完成首次记忆操作。 ## 2. 入门指南 通过以下两个简单的核心步骤开始使用 MemOS API: * [**添加消息**](/api_docs/core/add_message):储存用户对话中的原始消息内容,生成记忆; * [**检索记忆**](/api_docs/core/search_memory):检索召回用户的相关记忆片段,为模型生成的回答内容提供参考。 ### 添加消息 ```python [Python (HTTP)] import os, requests, json os.environ["MEMOS_API_KEY"] = "YOUR_API_KEY" os.environ["MEMOS_BASE_URL"] = "https://memos.memtensor.cn/api/openmem/v1" data = { "user_id": "user_001", "conversation_id": "conv_001", "messages": [ {"role": "user", "content": "我下周二要去北京出差"}, {"role": "assistant", "content": "好的,需要我帮你查北京的天气或酒店吗?"} ] } headers = { "Content-Type": "application/json", "Authorization": f"Token {os.environ['MEMOS_API_KEY']}" } res = requests.post(f"{os.environ['MEMOS_BASE_URL']}/add/message", headers=headers, data=json.dumps(data)) print(res.json()) ``` ```python [Python (SDK)] # pip install MemoryOS -U from memos.api.client import MemOSClient client = MemOSClient(api_key="YOUR_API_KEY") res = client.add_message( user_id="user_001", conversation_id="conv_001", messages=[ {"role": "user", "content": "我下周二要去北京出差"}, {"role": "assistant", "content": "好的,需要我帮你查北京的天气或酒店吗?"} ] ) print(res) ``` ```bash [Curl] curl --request POST \ --url https://memos.memtensor.cn/api/openmem/v1/add/message \ --header 'Authorization: Token YOUR_API_KEY' \ --header 'Content-Type: application/json' \ --data '{ "user_id": "user_001", "conversation_id": "conv_001", "messages": [ {"role": "user", "content": "我下周二要去北京出差"}, {"role": "assistant", "content": "好的,需要我帮你查北京的天气或酒店吗?"} ] }' ``` ### 检索记忆 ```python [Python (HTTP)] import os, requests, json os.environ["MEMOS_API_KEY"] = "YOUR_API_KEY" os.environ["MEMOS_BASE_URL"] = "https://memos.memtensor.cn/api/openmem/v1" data = { "query": "用户最近有什么出行计划?", "user_id": "user_001" } headers = { "Content-Type": "application/json", "Authorization": f"Token {os.environ['MEMOS_API_KEY']}" } res = requests.post(f"{os.environ['MEMOS_BASE_URL']}/search/memory", headers=headers, data=json.dumps(data)) print(res.json()) ``` ```python [Python (SDK)] # pip install MemoryOS -U from memos.api.client import MemOSClient client = MemOSClient(api_key="YOUR_API_KEY") res = client.search_memory( query="用户最近有什么出行计划?", user_id="user_001" ) print(res) ``` ```bash [Curl] curl --request POST \ --url https://memos.memtensor.cn/api/openmem/v1/search/memory \ --header 'Authorization: Token YOUR_API_KEY' \ --header 'Content-Type: application/json' \ --data '{ "query": "用户最近有什么出行计划?", "user_id": "user_001" }' ``` ## 3. 接口分类 探索 MemOS 提供的丰富功能接口: * [**核心操作 API**](/api_docs/core/add_message):提供记忆核心操作能力,包括添加消息、检索记忆、删除记忆、修改记忆、反馈等。 * [**属性记忆 API**](/api_docs/core/bind_profile_template):管理属性记忆模板的绑定、编辑与删除。 * [**自研模型 API**](/api_docs/core/extract_memory):调用记忆抽取与重排模型能力。 * [**消息 API**](/api_docs/message/get_message):查询历史消息与异步任务状态。 * [**对话 API**](/api_docs/chat/chat):完成带有记忆召回与知识库增强的对话生成。 * [**知识库 API**](/api_docs/knowledge/create_kb):创建与管理知识库及其文档。 ## 4. 鉴权认证 所有API请求都需要认证,请在请求头的 `Authorization` 中包含您的接口密钥。从[**MemOS 控制台**](https://memos-dashboard.openmem.net/apikeys/)获取接口密钥。 > **Warning**: 请勿在客户端或公共仓库中暴露您的接口密钥,所有请求都应通过环境变量或服务器端调用进行。 ## 5. 下一步行动 * 👉 [**添加消息**](/api_docs/core/add_message):生成你的第一条记忆; * 👉 [**检索记忆**](/api_docs/core/search_memory):使用记忆过滤器实现记忆的高级检索。 --- # 项目配置 (/cn/api_docs/start/configuration) 如果你是从未登录的新用户,建议先根据你的使用场景完成首次调用: | 使用场景 | 适合你做什么 | | :--- | :--- | | [在 Agent 中使用](/cn/memos_cloud/getting_started/agent_usage) | 按插件或 CLI 等方式,把 MemOS 接入个人 Agent,让你的 Agent 拥有记忆 | | [在应用中集成](/cn/memos_cloud/getting_started/quick_start) | 使用 MemOS API / SDK,接入你开发的应用 | 登录后,MemOS 会自动创建一个默认项目,复制 API Key,即可在该项目中使用所有功能。如果你想了解: - 项目与 API Key 的关系; - 创建、切换、修改或删除项目; - 在项目中使用知识库; - 排查配置错误。 可继续阅读下文。 ## 1. 项目与 API Key 项目是 MemOS 规定的记忆隔离空间。每个项目都拥有独立的 API Key,用于访问该项目下的所有记忆、消息和调用日志。 项目之间不可互通,A 项目的 API Key 无法访问 B 项目的任何资源。 > **Note**: 切换项目后,需要重新进入「接口密钥」页面复制该项目的 API Key。 ![接口密钥页面](https://cdn.memtensor.com.cn/img/1781512123656_y385f1_compressed.png) ## 2. 管理项目 当你需要隔离不同应用、环境或业务空间时,可以在 [项目列表](https://memos-dashboard.openmem.net/cn/projects) 中可以创建、切换、修改和删除项目。 ![项目列表页面](https://cdn.memtensor.com.cn/img/1781512257467_ika6g4_compressed.png) ### 2.1 创建或切换项目 - 在「项目列表」点击新建,填写项目名称和描述,即可创建新项目; - 带有“当前项目”状态的项目,是控制台当前选中的项目; - 点击“切换为该项目”后,接口密钥、知识库列表、调用日志都会切换到该项目范围。 ![创建项目](https://cdn.memtensor.com.cn/img/1781512257467_ika6g4_compressed.png) ### 2.2 删除项目 - 当前项目不能直接删除,需要先切换到其他项目; - 删除项目会清空该项目下的记忆、消息、知识库关联、API Key 和相关数据; - 删除后不可恢复,只删除确认不再使用的测试项目或废弃项目。 ![删除项目确认](https://cdn.memtensor.com.cn/img/1781512309804_1plly3_compressed.png) ## 3. 关联知识库到项目 如果你的 应用 / Agent 有需要参考的固定文档,可以创建并关联知识库到项目。一个项目可以关联多个知识库,一个知识库也可以关联多个项目。在 [知识库](https://memos-dashboard.openmem.net/cn/knowledgeBase) 页面中: 1. 点击「添加知识库」; 2. 选择「新建知识库」或「关联已有知识库」; 3. 进入知识库详情页,上传文档并等待处理完成; 4. 调用 `search/memory` 或 `chat` 时,传入 `knowledgebase_ids`,表示本次检索支持的知识库范围。 ![知识库关联页面](https://cdn.memtensor.com.cn/img/1781512337899_cumfw9_compressed.png) > **Warning**: 如果 `knowledgebase_ids` 对应的知识库没有关联到当前 API Key 所属项目,`search/memory` 会返回 `50123`。使用知识库时,需要先将项目关联到对应的知识库。 完整流程请查看 [知识库介绍](/cn/memos_cloud/features/knowledge_base)。 ## 4. 常见配置错误 | 错误码 | 常见原因 | 处理方式 | | :--- | :--- | :--- | | `40000` | 请求参数名、类型或结构不符合接口要求 | 对照接口文档检查 JSON 字段,不要把对象、数组、字符串混传 | | `40002` | 必填字段为空 | 检查 `user_id`、`messages`、`query`、`conversation_id` 等必填字段 | | `40011` | `conversation_id` 过长 | 使用短 ID,例如订单号、会话号或内部 trace ID,不要放完整对话 | | `40103` / `40132` | API Key 无效、过期或无权访问当前项目 | 检查 API Key 是否完整、有效,并确认它属于当前项目 | | `40300` / `40304` | 接口调用次数或账户总调用次数耗尽 | 查看 [配额和限制](/cn/memos_cloud/support/limit),或在控制台确认当前额度 | | `40305` | 单次输入超过 Token 上限 | 缩短单次写入、检索或上传内容,不要一次传入过长历史对话或长文档 | | `50123` | 知识库未关联当前项目 | 在知识库页面把该知识库关联到当前项目,或移除错误的 `knowledgebase_ids` | 更多错误码说明,请查看 [错误码](/cn/api_docs/help/error_codes)。 --- # Add Message **POST** `/add/message` 该接口用于添加会话消息,支持多类型内容、批量添加。MemOS 会自动解析消息并处理记忆,用于后续对话时召回参考。 - operationId: `add_message` ## Request Body | Parameter | Type | Required | Description | |---|---|---|---| | `user_id` | string | array | No | 添加消息所关联的用户唯一标识符。支持传入字符串(单用户)或字符串数组(群聊多用户,上限 20 个)。 | | `agent_id` | string | array | No | 添加的消息所关联的 Agent 唯一标识符。支持传入字符串(单 Agent)或字符串数组(群聊多 Agent)。开启「为 Agent 创建独立记忆」后,Agent 作为独立主体拥有记忆。 | | `conversation_id` | string | No | 添加的消息所关联的会话唯一标识符,相同 conversation_id 下的多轮消息会被识别为同一上下文。 | | `messages` | array | Yes | 添加的消息对象数组,数组中所有消息的总 token 数上限为 40k。 | | `app_id` | string | No | 添加的消息所关联的应用唯一标识符,主要用于在检索记忆时查询某用户在该 App 下的专属记忆。 | | `allow_memory_view` | array | No | 允许抽取的记忆种类,不传时默认抽取所有种类。全部种类及取值说明见 记忆种类。 | | `custom_extract_prompt` | object | No | 自定义抽取提示词,按 key 指定本次添加消息时各环节使用的抽取策略,仅对本次请求生效。支持的 key 包括记忆种类和输入模态两类:记忆种类取值为 detail_factual、preference、skill、profile、event、tool_memory,含义见 记忆种类;输入模态取值为 image(图片内容)和 document(文件内容)。 | | `tags` | array | No | 自定义标签列表,用于标记添加消息的主题或分类。 | | `info` | object | No | 自定义元信息字段,能够存储任意与添加信息相关的结构化数据,例如位置、来源、版本等,主要用于在检索时精确过滤或追踪来源。 | | `allow_public` | boolean | No | 添加的消息产生的记忆是否允许写入公共记忆库。开启后,生成的记忆可被项目下的其他用户检索。 | | `allow_knowledgebase_ids` | array | No | 添加的消息,产生的记忆允许被写入的知识库范围。 | | `async_mode` | boolean | No | 是否启用异步添加记忆。开启后,记忆将在后台异步添加,避免阻塞调用链。 | #### `messages` object | Parameter | Type | Required | Description | |---|---|---|---| | `chat_time` | string | No | 对话发生的时间,可传入结构化时间或中文时间描述。传入该参数能够让记忆携带时间信息。 | | `role` | string (enum: user, assistant, system, tool) | Yes | 消息创建者的角色。 | | `role_id` | string | No | 具体发言人的 ID,群聊场景建议传入。 | | `role_name` | string | No | 发言人名称。传入后,抽取的记忆会标识发言人的名称。需与 role_id 同时传入。 | | `content` | string | array | Yes | 消息内容文本。 | | `tool_call_id` | string | No | role为tool时,工具调用消息的唯一标识。 | | `tool_calls` | array | No | role为assistant时,工具调用信息列表,用于在触发工具调用时传递。 | #### `tool_calls` object | Parameter | Type | Required | Description | |---|---|---|---| | `id` | string | No | 工具调用的唯一标识,用于关联本次工具调用。tool_calls中必填。 | | `type` | string (enum: function) | No | 工具调用类型,当前仅支持 function。tool_calls中必填。 | | `function` | object | No | 被调用的工具定义,tool_calls中必填。 | #### `function` object | Parameter | Type | Required | Description | |---|---|---|---| | `name` | string | No | 工具(函数)名称,tool_calls中必填。 | | `arguments` | string | No | 工具调用参数,需为 JSON 格式的字符串,tool_calls中必填。 | ### Request Example ```json { "user_id": "memos_user_123", "conversation_id": "0610", "messages": [ { "role": "user", "content": "我想暑假出去玩,你能帮我推荐下吗?" }, { "role": "assistant", "content": "好的!是自己出行还是和家人朋友一起呢?" }, { "role": "user", "content": "肯定要带孩子啊,我们家出门都是全家一起。" }, { "role": "assistant", "content": "明白了,所以你们是父母带孩子一块儿旅行,对吗?" }, { "role": "user", "content": "对,带上孩子和老人,一般都是全家行动。" }, { "role": "assistant", "content": "收到,那我会帮你推荐适合家庭出游的目的地。" } ] } ``` ## Response Successful Response | Parameter | Type | Required | Description | |---|---|---|---| | `code` | integer | Yes | 接口状态码,更多内容可查阅错误码列表了解详情。 | | `data` | object | No | | | `message` | string | Yes | 接口提示信息。 | #### `data` object | Parameter | Type | Required | Description | |---|---|---|---| | `success` | boolean | No | 是否添加成功。true表示成功,false表示失败。 | | `task_id` | string | No | 记忆处理任务的唯一标识。请调用 Get Task Status 接口查询任务处理结果。 | | `status` | string (enum: running, completed, failed) | No | 记忆处理任务当前的状态。 | ### Response Example ```json { "code": 0, "data": { "success": true, "status": "running" }, "message": "ok" } ``` URL: /cn/api_docs/core/add_message --- # Search Memory **POST** `/search/memory` 该接口用于检索指定用户或 Agent 的记忆,返回与查询内容最相关的记忆片段。 - operationId: `search_memory` ## Request Body | Parameter | Type | Required | Description | |---|---|---|---| | `user_id` | string | No | 查询的记忆所关联用户的唯一标识符。 | | `agent_id` | string | No | 查询的记忆所关联 Agent 的唯一标识符。仅开启「为 Agent 创建独立记忆」时可用,与 user_id 二选一。 | | `conversation_id` | string | No | 查询内容所在会话的唯一标识符,传入可以明确当前会话,本会话的记忆应当比其他历史会话的权重高。 | | `query` | string | Yes | 要在记忆中查询的文本内容,单次查询文本的token上限为40k。 | | `filter` | object | No | 记忆过滤条件,用于在语义召回前缩小候选范围。可以直接用 and / or 做全局过滤,也可以按 user、public、knowledgebase 分来源过滤。完整字段和示例见 记忆过滤。 | | `knowledgebase_ids` | array | No | 该字段用于限制当次搜索可访问的知识库范围,默认为空(即不检索任何知识库)。传入具体知识库 ID,则可检索指定的知识库;传入all,则可检索该项目下所有关联知识库。 | | `include_memory_view` | array | No | 允许检索的记忆种类。不传时默认召回事实记忆(detail_factual)和偏好记忆(preference)。详细说明见 记忆种类。 | | `memory_limit_number` | integer | No | 召回的记忆条数上限,在满足相关性阈值(relativity)的前提下最多返回该数量的记忆,不保证返回固定条数。默认值 9,最大值 25。 | | `relativity` | number | No | 召回记忆的相关性阈值(0~1)。用于过滤低相关记忆,并与限定返回的事实、偏好记忆最大条数,共同约束最终返回结果。不传时使用系统默认阈值,取值为0时表示不进行相关性过滤。 | #### `filter` object | Parameter | Type | Required | Description | |---|---|---|---| | `and` | array | No | 全局 AND 条件数组。数组内所有条件都满足时,候选记忆才会进入语义召回。常用字段包括 agent_id、app_id、tags.contains、create_time、update_time 和 info 中的自定义字段。 | | `or` | array | No | 全局 OR 条件数组。数组内任一条件满足时,候选记忆即可进入语义召回。 | | `user` | object | No | 用户个人记忆的过滤条件。 | | `public` | object | No | 项目级公共记忆的过滤条件。 | | `knowledgebase` | object | No | 知识库记忆的过滤条件,仅作用于本次 knowledgebase_ids 允许访问的知识库范围。 | #### `user` object | Parameter | Type | Required | Description | |---|---|---|---| | `and` | array | No | 用户记忆的 AND 条件数组。 | | `or` | array | No | 用户记忆的 OR 条件数组。 | #### `public` object | Parameter | Type | Required | Description | |---|---|---|---| | `and` | array | No | 公共记忆的 AND 条件数组。 | | `or` | array | No | 公共记忆的 OR 条件数组。 | #### `knowledgebase` object | Parameter | Type | Required | Description | |---|---|---|---| | `and` | array | No | 知识库记忆的 AND 条件数组。 | | `or` | array | No | 知识库记忆的 OR 条件数组。 | ### Request Example ```json { "query": "帮我总结今年和阅读相关的记忆", "user_id": "memos_user_123", "conversation_id": "0928", "knowledgebase_ids": [ "kb_xxx" ], "filter": { "knowledgebase": { "and": [ { "tags": { "contains": "阅读" } }, { "create_time": { "gte": "2025-01-01" } }, { "create_time": { "lte": "2025-12-31" } } ] }, "user": { "and": [ { "scene": "chat" } ] } } } ``` ## Response Successful Response | Parameter | Type | Required | Description | |---|---|---|---| | `code` | integer | Yes | 接口状态码,更多内容可查阅错误码列表了解详情。 | | `data` | object | No | | | `message` | string | Yes | 接口提示信息。 | #### `data` object | Parameter | Type | Required | Description | |---|---|---|---| | `memory_detail_list` | array | No | 返回的事实记忆片段详情列表。 | | `preference_detail_list` | array | No | 返回的偏好记忆片段详情列表。 | | `profile_detail_list` | array | No | 返回的属性记忆片段详情列表。 | | `event_detail_list` | array | No | 返回的事件记忆片段详情列表。 | | `tool_memory_detail_list` | array | No | 返回的工具记忆片段详情列表。 | | `preference_note` | string | No | 召回偏好记忆时,返回的偏好使用说明。 | | `skill_detail_list` | array | No | 返回的技能 Skill 详情列表。 | #### `memory_detail_list` object | Parameter | Type | Required | Description | |---|---|---|---| | `id` | string | No | 事实记忆的唯一标识符,系统内部用于区分不同的记忆条目。 | | `memory_key` | string | No | 事实记忆的标题或关键词,用于概括该事实记忆的主要内容。 | | `memory_value` | string | No | 事实记忆的具体内容。 | | `memory_type` | string (enum: WorkingMemory, LongTermMemory, UserMemory) | No | 事实记忆类型。
WorkingMemory:工作记忆,临时存储的短期信息。
LongTermMemory:长期记忆,持久保存的重要信息或事实。
UserMemory:用户记忆,与特定用户相关的个性化信息。 | | `create_time` | string | No | 事实记忆内容创建的时间,通常为 ISO 8601 格式。 | | `conversation_id` | string | No | 与该事实记忆关联的会话的唯一标识符。 | | `status` | string (enum: activated) | No | 事实记忆的状态,当前所有检索到的事实记忆都是activated。
activated:激活状态,当前可检索和使用的事实记忆。 | | `confidence` | number | No | 事实记忆的置信度分数,范围 0~1,数值越接近 1 表示该事实记忆越准确可靠。
置信度分数会随着模型对该事实记忆的推理次数增加而逐渐衰减,用于反映事实记忆随着时间或使用频率可能产生的不确定性。 | | `tags` | array | No | 与事实记忆相关的标签列表,用于分类、检索或主题标记。数组中的每个元素都是string,例如 ["人物", "事件", "工作"]。 | | `update_time` | string | No | 事实记忆最后一次被修改或更新的时间,通常为 ISO 8601 格式。 | | `relativity` | number | No | 查询内容与该事实记忆的相关性分数,范围 0~1,数值越接近 1 表示越相关。 | #### `preference_detail_list` object | Parameter | Type | Required | Description | |---|---|---|---| | `id` | string | No | 偏好记忆的唯一标识符,系统内部用于区分不同的记忆条目。 | | `preference_type` | string (enum: explicit_preference, implicit_preference) | No | 偏好记忆类型。
explicit_preference:显式偏好记忆。
implicit_preference:隐式偏好记忆。 | | `preference` | string | No | 偏好记忆的具体内容。 | | `reasoning` | string | No | 偏好记忆提取的原因。 | | `create_time` | string | No | 偏好记忆内容创建的时间,通常为 ISO 8601 格式。 | | `conversation_id` | string | No | 与该偏好记忆关联的会话的唯一标识符。 | | `status` | string (enum: activated) | No | 偏好记忆的状态,当前所有检索到的偏好记忆都是activated。
activated:激活状态,当前可检索和使用的事实记忆。 | | `update_time` | string | No | 偏好记忆最后一次被修改或更新的时间,通常为 ISO 8601 格式。 | | `relativity` | number | No | 查询内容与该偏好记忆的相关性分数,范围 0~1,数值越接近 1 表示越相关。 | #### `profile_detail_list` object | Parameter | Type | Required | Description | |---|---|---|---| | `id` | string | No | 属性记忆的唯一标识符。 | | `memory` | string | No | 属性记忆内容。 | | `memory_type` | string (enum: ProfileMemory) | No | 记忆类型,属性记忆为 ProfileMemory。 | | `template_id` | string | No | 属性模板 ID。 | | `profile_category` | string | No | 属性分类,例如「基础信息」。 | | `profile_field` | string | No | 属性字段名,例如「职业」。 | | `profile_path` | string | No | 属性路径,例如「基础信息.职业」。 | | `status` | string (enum: activated) | No | 属性记忆状态,当前检索结果均为 activated。 | | `created_at` | string | No | 属性记忆创建时间,ISO 8601 格式。 | | `updated_at` | string | No | 属性记忆最后一次更新时间,ISO 8601 格式。 | | `confidence` | number | No | 属性记忆的置信度分数,范围 0~1。 | | `relativity` | number | No | 查询内容与该属性字段的相关性分数,范围 0~1。 | | `algorithm_updatable` | boolean | No | 该属性字段是否允许算法自动更新。 | #### `event_detail_list` object | Parameter | Type | Required | Description | |---|---|---|---| | `id` | string | No | 事件记忆的唯一标识符。 | | `event_key` | string | No | 事件记忆的标题或关键词。 | | `event_value` | string | No | 事件记忆的具体内容。 | | `event_type` | string | No | 事件记忆类型,通常为 EventMemory。 | | `create_time` | string | No | 事件记忆创建时间,ISO 8601 格式。 | | `conversation_id` | string | No | 与该事件记忆关联的会话唯一标识符。 | | `status` | string (enum: activated) | No | 事件记忆状态,当前检索结果均为 activated。 | | `update_time` | string | No | 事件记忆最后一次更新时间,ISO 8601 格式。 | | `relativity` | number | No | 查询内容与该事件记忆的相关性分数,范围 0~1。 | | `event_time` | array | No | 事件时间列表。 | | `event_location` | array | No | 事件地点列表。 | | `event_roles` | array | No | 事件参与者列表。 | #### `tool_memory_detail_list` object | Parameter | Type | Required | Description | |---|---|---|---| | `id` | string | No | 工具记忆片段的唯一标识符。 | | `tool_type` | string (enum: ToolTrajectoryMemory, ToolSchema) | No | 工具记忆类型。ToolTrajectoryMemory 表示工具轨迹记忆;ToolSchema 表示工具信息记忆。 | | `tool_value` | string | No | 工具记忆的具体内容。 | | `tool_used_status` | array | No | 工具轨迹记忆列表,每条记录包含使用的工具及经验信息。 | | `create_time` | string | No | 工具记忆创建时间(ISO 8601 格式)。 | | `conversation_id` | string | No | 与该工具记忆关联的会话唯一标识符。 | | `status` | string (enum: activated) | No | 工具记忆状态,当前为 activated。 | | `update_time` | string | No | 工具记忆最后一次更新的时间(ISO 8601 格式)。 | | `relativity` | number | No | 工具记忆与查询内容的相关性分数。 | | `experience` | string | No | 整个轨迹的程序性经验,作为指导任务完成的总体经验。 | #### `skill_detail_list` object | Parameter | Type | Required | Description | |---|---|---|---| | `id` | string | No | 技能 Skill 的唯一标识符,系统内部用于区分不同的记忆条目。 | | `skill_value` | object | No | 技能 Skill 的结构化内容,可直接转为字符串后注入 Agent 的 prompt。 | | `skill_url` | string | No | 技能 Skill 的下载链接。Markdown Skill 可下载为 SKILL.md;ZIP 技能包可下载后获取 SKILL.md、脚本、参考资料等附件。 | | `skill_type` | string | No | 技能 Skill 的类型。 | | `create_time` | string | No | 技能 Skill 内容创建的时间,通常为 ISO 8601 格式。 | | `conversation_id` | string | No | 与该技能 Skill 关联的会话的唯一标识符。 | | `status` | string (enum: activated) | No | 技能 Skill 的状态,当前所有检索到的技能 Skill 都是 activated。activated:激活状态,当前可检索和使用的技能 Skill 。 | | `confidence` | number | No | 技能 Skill 的置信度分数,范围 0~1,数值越接近 1 表示该技能 Skill 越准确可靠。 置信度分数会随着模型对该技能 Skill 的推理次数增加而逐渐衰减,用于反映技能 Skill 随着时间或使用频率可能产生的不确定性。 | | `tags` | array | No | 与技能 Skill 相关的标签列表,用于分类、检索或主题标记。数组中的每个元素都是string,例如 ["人物", "事件", "工作"]。 | | `update_time` | string | No | 技能 Skill 最后一次被修改或更新的时间,通常为 ISO 8601 格式 | | `relativity` | string | No | 查询内容与该技能 Skill 的相关性分数,范围 0~1,数值越接近 1 表示越相关。 | ### Response Example ```json { "code": 0, "data": { "memory_detail_list": [ { "memory_type": "LongTermMemory", "status": "activated", "confidence": 0.95, "relativity": 0.87 } ], "preference_detail_list": [ { "preference_type": "explicit_preference", "status": "activated", "relativity": 0.87 } ], "profile_detail_list": [ { "memory_type": "ProfileMemory", "status": "activated" } ], "event_detail_list": [ { "status": "activated" } ], "tool_memory_detail_list": [ { "tool_type": "ToolTrajectoryMemory", "status": "activated" } ], "skill_detail_list": [ { "status": "activated" } ] } } ``` URL: /cn/api_docs/core/search_memory --- # Get Memories **POST** `/get/memory` 分页获取某个用户或 Agent 的记忆。 - operationId: `get_memory` ## Request Body | Parameter | Type | Required | Description | |---|---|---|---| | `user_id` | string | No | 获取的记忆所关联用户的唯一标识符。 | | `agent_id` | string | No | 获取的记忆所关联 Agent 的唯一标识符。仅开启「为 Agent 创建独立记忆」时可用,与 user_id 二选一。 | | `page` | integer | No | 分页页码,用于在返回结果较多时进行分页控制。 | | `size` | integer | No | 指定每一类记忆在当前页返回的条目数量,最大值为50。 | | `filter` | object | No | 记忆过滤的条件,用于在获取记忆前精确限定记忆范围。可用字段包括:"agent_id", "app_id", "create_time", "update_time"以及"info"中的字段。支持逻辑运算符(and,or)和比较运算符(gte、lte、gt、lt)。对于"info"字段,支持过滤传入的"business_type", "biz_id", "scene"和其他自定义字段。 | | `include_memory_view` | array | No | 允许获取的记忆种类,不传时默认获取所有种类的记忆。全部种类及取值说明见 记忆种类。 | ## Response Successful Response | Parameter | Type | Required | Description | |---|---|---|---| | `code` | number | Yes | 接口状态码,更多内容可查阅错误码列表了解详情。 | | `data` | object | No | | | `message` | string | Yes | 接口提示信息。 | #### `data` object | Parameter | Type | Required | Description | |---|---|---|---| | `memory_detail_list` | array | No | 返回的事实记忆片段详情列表。 | | `preference_detail_list` | array | No | 返回的偏好记忆片段详情列表。 | | `profile_detail_list` | array | No | 返回的属性记忆片段详情列表。 | | `event_detail_list` | array | No | 返回的事件记忆片段详情列表。 | | `tool_memory_detail_list` | array | No | 返回的工具记忆片段详情列表。 | | `skill_detail_list` | array | No | 返回的技能 Skill 详情列表。 | | `total` | integer | No | 获取的各类记忆总数中的最大值,用于判断是否存在下一页。 | | `size` | integer | No | 每一类记忆在当前页返回的条目数量。 | | `current` | integer | No | 当前获取的记忆所在页数。 | | `pages` | integer | No | 获取记忆的总页数。 | #### `memory_detail_list` object | Parameter | Type | Required | Description | |---|---|---|---| | `id` | string | No | 事实记忆的唯一标识符。 | | `memory_key` | string | No | 事实记忆的标题或关键词。 | | `memory_value` | string | No | 事实记忆的具体内容。 | | `memory_type` | string (enum: WorkingMemory, LongTermMemory, UserMemory) | No | 事实记忆类型。 | | `create_time` | string | No | 事实记忆创建时间,ISO 8601 格式。 | | `conversation_id` | string | No | 与该事实记忆关联的会话唯一标识符。 | | `status` | string (enum: activated) | No | 事实记忆状态,当前仅返回 activated。 | | `confidence` | number | No | 事实记忆的置信度分数,范围 0~1。 | | `tags` | array | No | 与事实记忆相关的标签列表。 | | `update_time` | string | No | 事实记忆最后一次更新时间,ISO 8601 格式。 | | `relativity` | number | No | 事实记忆的相关性分数,范围 0~1。 | | `sources` | array | No | 事实记忆的来源消息列表。 | | `info` | object | No | 添加消息时自定义的元信息字段。 | #### `preference_detail_list` object | Parameter | Type | Required | Description | |---|---|---|---| | `id` | string | No | 偏好记忆的唯一标识符。 | | `preference_type` | string (enum: explicit_preference, implicit_preference) | No | 偏好记忆类型。 | | `preference` | string | No | 偏好记忆的具体内容。 | | `reasoning` | string | No | 偏好记忆提取的原因。 | | `create_time` | string | No | 偏好记忆创建时间,ISO 8601 格式。 | | `conversation_id` | string | No | 与该偏好记忆关联的会话唯一标识符。 | | `status` | string (enum: activated) | No | 偏好记忆状态,当前仅返回 activated。 | | `update_time` | string | No | 偏好记忆最后一次更新时间,ISO 8601 格式。 | | `relativity` | number | No | 偏好记忆的相关性分数,范围 0~1。 | | `sources` | array | No | 偏好记忆的来源消息列表。 | | `info` | object | No | 添加消息时自定义的元信息字段。 | #### `profile_detail_list` object | Parameter | Type | Required | Description | |---|---|---|---| | `id` | string | No | 属性记忆实例的唯一标识符。 | | `project_id` | string | No | 项目 ID。 | | `profile_template_id` | string | No | 属性模板 ID。 | | `properties` | object | No | 属性记忆的结构化字段树。 | | `status` | string (enum: activated) | No | 属性记忆状态,当前仅返回 activated。 | | `created_at` | string | No | 属性记忆创建时间,ISO 8601 格式。 | | `updated_at` | string | No | 属性记忆最后一次更新时间,ISO 8601 格式。 | #### `event_detail_list` object | Parameter | Type | Required | Description | |---|---|---|---| | `id` | string | No | 事件记忆的唯一标识符。 | | `event_key` | string | No | 事件记忆的标题或关键词。 | | `event_value` | string | No | 事件记忆的具体内容。 | | `event_type` | string | No | 事件记忆类型,通常为 EventMemory。 | | `create_time` | string | No | 事件记忆创建时间,ISO 8601 格式。 | | `conversation_id` | string | No | 与该事件记忆关联的会话唯一标识符。 | | `status` | string (enum: activated) | No | 事件记忆状态,当前仅返回 activated。 | | `update_time` | string | No | 事件记忆最后一次更新时间,ISO 8601 格式。 | | `info` | object | No | 事件记忆的扩展信息。 | | `sources` | array | No | 事件记忆的来源消息列表。 | | `event_time` | array | No | 事件时间列表。 | | `event_location` | array | No | 事件地点列表。 | | `event_roles` | array | No | 事件参与者列表。 | #### `tool_memory_detail_list` object | Parameter | Type | Required | Description | |---|---|---|---| | `id` | string | No | 工具记忆片段的唯一标识符。 | | `tool_type` | string (enum: ToolTrajectoryMemory, ToolSchema) | No | 工具记忆类型。ToolTrajectoryMemory 表示工具轨迹记忆;ToolSchema 表示工具信息记忆。 | | `tool_value` | string | No | 工具记忆的具体内容。 | | `tool_used_status` | array | No | 工具轨迹记忆列表,每条记录包含使用的工具及经验信息。 | | `create_time` | string | No | 工具记忆创建时间,ISO 8601 格式。 | | `conversation_id` | string | No | 与该工具记忆关联的会话唯一标识符。 | | `status` | string (enum: activated) | No | 工具记忆状态,当前为 activated。 | | `update_time` | string | No | 工具记忆最后一次更新时间,ISO 8601 格式。 | | `relativity` | number | No | 工具记忆的相关性分数,范围 0~1。 | | `source` | string | No | 工具记忆的来源信息。 | | `experience` | string | No | 整个轨迹的程序性经验,作为指导任务完成的总体经验。 | | `info` | object | No | 添加消息时自定义的元信息字段。 | #### `skill_detail_list` object | Parameter | Type | Required | Description | |---|---|---|---| | `id` | string | No | 技能 Skill 的唯一标识符,系统内部用于区分不同的记忆条目。 | | `skill_value` | object | No | 技能 Skill 的结构化内容,可直接转为字符串后注入 Agent 的 prompt。 | | `skill_url` | string | No | 技能 Skill 的下载链接。Markdown Skill 可下载为 SKILL.md;ZIP 技能包可下载后获取 SKILL.md、脚本、参考资料等附件。 | | `skill_type` | string | No | 技能 Skill 的类型。 | | `create_time` | string | No | 技能 Skill 内容创建的时间,通常为 ISO 8601 格式。 | | `conversation_id` | string | No | 与该技能 Skill 关联的会话的唯一标识符。 | | `status` | string (enum: activated) | No | 技能 Skill 的状态,当前所有检索到的技能 Skill 都是 activated。activated:激活状态,当前可检索和使用的技能 Skill 。 | | `confidence` | number | No | 技能 Skill 的置信度分数,范围 0~1,数值越接近 1 表示该技能 Skill 越准确可靠。 置信度分数会随着模型对该技能 Skill 的推理次数增加而逐渐衰减,用于反映技能 Skill 随着时间或使用频率可能产生的不确定性。 | | `tags` | array | No | 与技能 Skill 相关的标签列表,用于分类、检索或主题标记。数组中的每个元素都是string,例如 ["人物", "事件", "工作"]。 | | `update_time` | string | No | 技能 Skill 最后一次被修改或更新的时间,通常为 ISO 8601 格式 | | `relativity` | string | No | 查询内容与该技能 Skill 的相关性分数,范围 0~1,数值越接近 1 表示越相关。 | ### Response Example ```json { "data": { "memory_detail_list": [ { "memory_type": "WorkingMemory", "status": "activated" } ], "preference_detail_list": [ { "preference_type": "explicit_preference", "status": "activated" } ], "profile_detail_list": [ { "status": "activated" } ], "event_detail_list": [ { "status": "activated" } ], "tool_memory_detail_list": [ { "tool_type": "ToolTrajectoryMemory", "status": "activated" } ], "skill_detail_list": [ { "status": "activated" } ] } } ``` URL: /cn/api_docs/core/get_memory --- # Get Memory **GET** `/get/memory/{memory_id}` 查询单条记忆信息。 - operationId: `get_memory_by_id` ## Response Successful Response | Parameter | Type | Required | Description | |---|---|---|---| | `code` | integer | Yes | 接口状态码。 | | `data` | object | No | | | `message` | string | Yes | 接口提示信息。 | #### `data` object | Parameter | Type | Required | Description | |---|---|---|---| | `id` | string | No | 记忆 ID | | `memory_view` | string (enum: detail_factual, preference, event, profile, skill, tool_memory) | No | 记忆种类 | | `title` | string | No | 记忆标题 | | `content` | any | No | 记忆内容 | | `conversation_id` | string | No | 来源会话 ID | | `message_ids` | array | No | 来源消息 ID 列表 | | `status` | string (enum: activated, resolving, archived, deleted) | No | 记忆状态 | | `algorithm_updatable` | boolean | No | 算法是否可更新 | | `created_at` | string | No | 创建时间 | | `updated_at` | string | No | 最后更新时间 | | `user_id` | string | No | 所属 user 主体 | | `agent_id` | string | No | 所属 agent 主体 | | `tags` | array | No | 自定义标签 | | `info` | object | No | 自定义元信息 | ### Response Example ```json { "code": 0, "data": { "memory_view": "detail_factual", "status": "activated" }, "message": "ok" } ``` URL: /cn/api_docs/core/get_memory_by_id --- # Delete Memory **POST** `/delete/memory` 删除指定用户或 Agent 的记忆,支持按 memory_ids 精确删除,或按 user_id/agent_id 清空全部记忆。 - operationId: `delete_memory` ## Request Body | Parameter | Type | Required | Description | |---|---|---|---| | `memory_ids` | array | No | 需要删除的记忆 ID 列表。 | | `user_id` | string | No | 删除该用户在当前项目下的全部记忆。与 memory_ids、agent_id 互斥。 | | `agent_id` | string | No | 删除该 Agent 在当前项目下的全部记忆。仅开启「为 Agent 创建独立记忆」时可用。与 memory_ids、user_id 互斥。 | ## Response Successful Response | Parameter | Type | Required | Description | |---|---|---|---| | `code` | integer | No | 接口状态码,更多内容可查阅错误码列表了解详情。 | | `data` | object | No | 返回删除信息 | | `message` | string | No | 删除提示信息 | #### `data` object | Parameter | Type | Required | Description | |---|---|---|---| | `success` | boolean | No | 是否删除成功。true 表示成功,false 表示失败。 | ### Response Example ```json { "data": { "success": true } } ``` URL: /cn/api_docs/core/delete_memory --- # Update Memory **POST** `/update/memory` 手动修改一条已有记忆的内容、标题或状态。支持所有记忆种类,包括事实记忆、偏好记忆、事件记忆、属性记忆的属性值等。 - operationId: `update_memory` ## Request Body | Parameter | Type | Required | Description | |---|---|---|---| | `memory_id` | string | Yes | 记忆 ID,来自 search/memory 或 get/memory 返回结果中的 id。 | | `content` | string | No | 更新后的记忆内容。 | | `title` | string | No | 更新后的记忆标题。 | ### Request Example ```json { "memory_id": "mem_event_001", "title": "和陈默去西湖露营", "content": "上周六和好友陈默去西湖边露营,天气很好,晚上一起看了星星。" } ``` ## Response Successful Response | Parameter | Type | Required | Description | |---|---|---|---| | `code` | integer | Yes | 接口状态码。 | | `data` | object | No | | | `message` | string | Yes | 接口提示信息。 | #### `data` object | Parameter | Type | Required | Description | |---|---|---|---| | `success` | boolean | No | 是否操作成功。 | ### Response Example ```json { "code": 0, "data": { "success": true }, "message": "ok" } ``` URL: /cn/api_docs/core/update_memory --- # Add Feedback **POST** `/add/feedback` 该接口用于添加对当前会话消息的反馈,MemOS能够基于用户的反馈更正记忆。 - operationId: `add_feedback` ## Request Body | Parameter | Type | Required | Description | |---|---|---|---| | `user_id` | string | Yes | 反馈内容所关联的用户唯一标识符。 | | `conversation_id` | string | Yes | 反馈内容所关联的会话唯一标识符。 | | `feedback_content` | string | Yes | 反馈内容文本。 | | `agent_id` | string | No | 反馈内容所关联的Agent唯一标识符,主要用于在检索记忆时查询某用户与该Agent的专属记忆。 | | `app_id` | string | No | 反馈内容所关联的应用唯一标识符,主要用于在检索记忆时查询某用户在该App下的专属记忆。 | | `feedback_time` | string | No | 反馈发生的时间,可传入结构化时间或自然语言时间描述。传入该参数能够让记忆携带时间信息。 | | `allow_public` | boolean | No | 反馈内容,产生的记忆,是否允许写入公共记忆库。开启后,生成的记忆可被项目下的其他用户检索。 | | `allow_knowledgebase_ids` | array | No | 反馈内容产生的记忆,允许被写入的知识库列表。 | ## Response Successful Response | Parameter | Type | Required | Description | |---|---|---|---| | `code` | integer | Yes | 接口状态码,更多内容可查阅错误码列表了解详情。 | | `data` | object | No | | | `message` | string | Yes | 接口提示信息 | #### `data` object | Parameter | Type | Required | Description | |---|---|---|---| | `success` | boolean | No | 是否添加成功。true 表示成功,false 表示失败。 | | `status` | string | No | 任务状态:running(运行中),completed(完成) | | `task_id` | string | No | 任务id | URL: /cn/api_docs/message/add_feedback --- # Add Profile Template **POST** `/add/profile_template` 在项目中创建属性记忆模板,返回模板 ID。创建成功后可通过绑定接口为用户或 Agent 创建属性记忆实例。 - operationId: `add_profile_template` ## Request Body | Parameter | Type | Required | Description | |---|---|---|---| | `name` | string | Yes | 模板名称,去除首尾空白后至少包含一个字符。 | | `metadata` | object | Yes | 属性树结构,最多三层嵌套,叶子节点为字段值对象。 | #### `metadata` object | Parameter | Type | Required | Description | |---|---|---|---| | `{分类名}` | object | No | 属性分类(可选的中间层),键名为用户自定义的分类名称。如无需分类可跳过此层,直接传字段值对象。 | #### `{分类名}` object | Parameter | Type | Required | Description | |---|---|---|---| | `{字段名}` | object | No | metadata 嵌套最内层的叶子节点。 | #### `{字段名}` object | Parameter | Type | Required | Description | |---|---|---|---| | `value` | string | No | 属性字段值。 | | `algorithm_updatable` | boolean | No | 是否允许算法自动更新该字段,默认为 true。 | ### Request Example ```json { "name": "客服用户属性", "metadata": { "基础信息": { "姓名": { "value": "", "algorithm_updatable": false }, "职业": { "value": "", "algorithm_updatable": true } }, "服务偏好": { "联系时段": { "value": "工作日白天", "algorithm_updatable": true } } } } ``` ## Response Successful Response | Parameter | Type | Required | Description | |---|---|---|---| | `code` | integer | No | 接口状态码。 | | `data` | object | No | | | `message` | string | No | 接口提示信息。 | #### `data` object | Parameter | Type | Required | Description | |---|---|---|---| | `profile_template_id` | string | No | 新建模板的 ID,后续查询、绑定、修改和删除均使用该 ID。 | ### Response Example ```json { "code": 0, "data": { "profile_template_id": "tpl_user_001" }, "message": "ok" } ``` URL: /cn/api_docs/core/add_profile_template --- # List Profile Templates **POST** `/list/profile_template` 分页返回项目内的属性记忆模板摘要,按创建时间倒序排列,创建时间相同的按模板 ID 倒序排列。 - operationId: `list_profile_template` ## Request Body | Parameter | Type | Required | Description | |---|---|---|---| | `page` | integer | No | 页码,从 1 开始。 | | `size` | integer | No | 每页条数,取值 1~100。 | ### Request Example ```json { "page": 1, "size": 10 } ``` ## Response Successful Response | Parameter | Type | Required | Description | |---|---|---|---| | `code` | integer | No | 接口状态码。 | | `data` | object | No | | | `message` | string | No | 接口提示信息。 | #### `data` object | Parameter | Type | Required | Description | |---|---|---|---| | `profile_templates` | array | No | 模板摘要列表。项目无模板或页码超出范围时返回空数组。 | | `total` | integer | No | 项目内模板总数。 | | `current` | integer | No | 本次返回的页码。 | | `size` | integer | No | 本次每页条数。 | | `pages` | integer | No | 总页数。页码超出范围时保留实际总数和总页数。 | #### `profile_templates` object | Parameter | Type | Required | Description | |---|---|---|---| | `profile_template_id` | string | No | 模板 ID。 | | `name` | string | No | 模板名称。 | | `project_id` | string | No | 模板所属项目 ID。 | | `instance_count` | integer | No | 当前绑定该模板的有效实例数量,可用于了解模板影响范围。实例的属性值通过记忆查询接口读取。 | | `create_time` | string | No | 模板创建时间,ISO 8601 格式。 | | `update_time` | string | No | 模板最近更新时间,ISO 8601 格式。 | ### Response Example ```json { "code": 0, "message": "ok" } ``` URL: /cn/api_docs/core/list_profile_template --- # Get Profile Template **POST** `/get/profile_template` 返回指定属性记忆模板的完整结构和摘要信息。 - operationId: `get_profile_template` ## Request Body | Parameter | Type | Required | Description | |---|---|---|---| | `profile_template_id` | string | Yes | 当前项目内的模板 ID。 | ### Request Example ```json { "profile_template_id": "tpl_user_001" } ``` ## Response Successful Response | Parameter | Type | Required | Description | |---|---|---|---| | `code` | integer | No | 接口状态码。 | | `data` | object | No | | | `message` | string | No | 接口提示信息。 | #### `data` object | Parameter | Type | Required | Description | |---|---|---|---| | `profile_template` | object | No | | #### `profile_template` object | Parameter | Type | Required | Description | |---|---|---|---| | `profile_template_id` | string | No | 模板 ID。 | | `name` | string | No | 模板名称。 | | `project_id` | string | No | 模板所属项目 ID。 | | `metadata` | object | No | 属性树结构,最多三层嵌套,叶子节点为字段值对象。 | | `instance_count` | integer | No | 当前绑定该模板的有效实例数量,可用于了解模板影响范围。实例的属性值通过记忆查询接口读取。 | | `create_time` | string | No | 模板创建时间,ISO 8601 格式。 | | `update_time` | string | No | 模板最近更新时间,ISO 8601 格式。 | #### `metadata` object | Parameter | Type | Required | Description | |---|---|---|---| | `{分类名}` | object | No | 属性分类(可选的中间层),键名为用户自定义的分类名称。如无需分类可跳过此层,直接传字段值对象。 | #### `{分类名}` object | Parameter | Type | Required | Description | |---|---|---|---| | `{字段名}` | ProfileFieldValue | No | | ### Response Example ```json { "code": 0, "message": "ok" } ``` URL: /cn/api_docs/core/get_profile_template --- # Update Profile Template **POST** `/update/profile_template` 修改模板名称或属性结构,变更同步到所有绑定该模板的用户或 Agent 属性记忆。 - operationId: `update_profile_template` ## Request Body | Parameter | Type | Required | Description | |---|---|---|---| | `profile_template_id` | string | Yes | 当前项目内的模板 ID。 | | `name` | string | Yes | 修改后的模板名称。只修改名称时,属性结构和已绑定实例的属性值保持原样。 | | `metadata` | object | Yes | 修改后的完整属性树。变更同步到全部已绑定实例:新增字段按模板中的值和自动更新设置填入;修改字段的值或自动更新设置会覆盖对应字段;删除字段会同时删除对应字段及已保存的值;未修改的字段保持原样。 | #### `metadata` object | Parameter | Type | Required | Description | |---|---|---|---| | `{分类名}` | object | No | 属性分类(可选的中间层),键名为用户自定义的分类名称。如无需分类可跳过此层,直接传字段值对象。 | #### `{分类名}` object | Parameter | Type | Required | Description | |---|---|---|---| | `{字段名}` | object | No | metadata 嵌套最内层的叶子节点。 | #### `{字段名}` object | Parameter | Type | Required | Description | |---|---|---|---| | `value` | string | No | 属性字段值。 | | `algorithm_updatable` | boolean | No | 是否允许算法自动更新该字段,默认为 true。 | ### Request Example ```json { "profile_template_id": "tpl_user_001", "name": "客服用户属性", "metadata": { "基础信息": { "姓名": { "value": "", "algorithm_updatable": false }, "职业": { "value": "", "algorithm_updatable": true }, "常住城市": { "value": "", "algorithm_updatable": true } }, "服务偏好": { "联系时段": { "value": "工作日白天", "algorithm_updatable": true } } } } ``` ## Response Successful Response | Parameter | Type | Required | Description | |---|---|---|---| | `code` | integer | No | 接口状态码。 | | `data` | object | No | | | `message` | string | No | 接口提示信息。 | #### `data` object | Parameter | Type | Required | Description | |---|---|---|---| | `success` | boolean | No | 是否操作成功。 | | `profile_template_id` | string | No | 被修改的模板 ID。 | | `affected_instances` | integer | No | 本次同步处理的已绑定属性记忆数量。 | ### Response Example ```json { "code": 0, "data": { "success": true }, "message": "ok" } ``` URL: /cn/api_docs/core/update_profile_template --- # Delete Profile Template **POST** `/delete/profile_template` 删除属性记忆模板,同时删除该模板的全部有效实例和绑定关系,其他模板和记忆保持原状。只需删除某个用户或 Agent 的实例时,请使用 /delete/profile。 - operationId: `delete_profile_template` ## Request Body | Parameter | Type | Required | Description | |---|---|---|---| | `profile_template_id` | string | Yes | 当前项目内的模板 ID。 | ### Request Example ```json { "profile_template_id": "tpl_user_001" } ``` ## Response Successful Response | Parameter | Type | Required | Description | |---|---|---|---| | `code` | integer | No | 接口状态码。 | | `data` | object | No | | | `message` | string | No | 接口提示信息。 | #### `data` object | Parameter | Type | Required | Description | |---|---|---|---| | `success` | boolean | No | 是否操作成功。 | | `profile_template_id` | string | No | 被删除的模板 ID。 | | `deleted_instances` | integer | No | 本次删除的有效实例数量,无绑定实例删除成功时为 0。 | ### Response Example ```json { "code": 0, "data": { "success": true }, "message": "ok" } ``` URL: /cn/api_docs/core/delete_profile_template --- # Bind Profile Template **POST** `/bind/profile_template` 为用户或 Agent 绑定属性记忆模板,创建属性记忆实例。绑定后,后续添加消息时自动更新对应的属性字段值。 - operationId: `bind_profile_template` ## Request Body | Parameter | Type | Required | Description | |---|---|---|---| | `bind_list` | array | Yes | 批量绑定列表,单次上限 20 条。 | #### `bind_list` object | Parameter | Type | Required | Description | |---|---|---|---| | `user_id` | string | No | 需要绑定到属性树模版的用户 ID。 | | `agent_id` | string | No | 需要绑定到属性树模版的 Agent ID,仅开启「为 Agent 创建独立记忆」时,可与 user_id 二选一传入。 | | `profile_template_id` | string | Yes | 需绑定的属性记忆模板 ID。 | ### Request Example ```json { "bind_list": [ { "user_id": "memos_user_123", "profile_template_id": "tpl_user_001" } ] } ``` ## Response Successful Response | Parameter | Type | Required | Description | |---|---|---|---| | `code` | integer | Yes | 接口状态码。 | | `data` | object | No | | | `message` | string | Yes | 接口提示信息。 | #### `data` object | Parameter | Type | Required | Description | |---|---|---|---| | `success` | boolean | No | 是否操作成功。 | ### Response Example ```json { "code": 0, "data": { "success": true }, "message": "ok" } ``` URL: /cn/api_docs/core/bind_profile_template --- # Edit Profile **POST** `/edit/profile` 编辑属性记忆实例,支持新增字段、更新字段值、删除字段、锁定字段不被算法自动更新。只影响当前实例,不修改模板也不影响其他实例。 - operationId: `edit_profile` ## Request Body | Parameter | Type | Required | Description | |---|---|---|---| | `user_id` | string | No | 用户 ID,与 agent_id 二选一。单视角项目必传。 | | `agent_id` | string | No | Agent ID,仅开启「为 Agent 创建独立记忆」时可用,与 user_id 二选一。 | | `profile_template_id` | string | Yes | 目标属性记忆模板 ID。 | | `metadata` | object | No | 要更新的字段。传入已有字段则更新值;传入新字段则添加到当前实例。 | | `remove_fields` | array | No | 要删除的字段路径列表,如 ["基础信息.职业"]。 | #### `metadata` object | Parameter | Type | Required | Description | |---|---|---|---| | `{分类名}` | object | No | 属性分类(可选的中间层),键名为用户自定义的分类名称。如无需分类可跳过此层,直接在 metadata 下传字段值对象。 | #### `{分类名}` object | Parameter | Type | Required | Description | |---|---|---|---| | `{字段名}` | object | No | metadata 嵌套最内层的叶子节点。 | #### `{字段名}` object | Parameter | Type | Required | Description | |---|---|---|---| | `value` | string | No | 属性字段值。 | | `algorithm_updatable` | boolean | No | 是否允许算法自动更新该字段,默认为 true。 | ### Request Example ```json { "user_id": "memos_user_123", "profile_template_id": "tpl_user_001", "metadata": { "基础信息": { "居住地": { "value": "上海", "algorithm_updatable": false } } } } ``` ## Response Successful Response | Parameter | Type | Required | Description | |---|---|---|---| | `code` | integer | Yes | 接口状态码。 | | `data` | object | No | | | `message` | string | Yes | 接口提示信息。 | #### `data` object | Parameter | Type | Required | Description | |---|---|---|---| | `success` | boolean | No | 是否操作成功。 | ### Response Example ```json { "code": 0, "data": { "success": true }, "message": "ok" } ``` URL: /cn/api_docs/core/edit_profile --- # Delete Profile **POST** `/delete/profile` 删除某个用户或 Agent 的属性记忆实例,该实例的所有字段值和绑定关系一并清除。不影响模板本身,也不影响其他主体的实例。 - operationId: `delete_profile` ## Request Body | Parameter | Type | Required | Description | |---|---|---|---| | `user_id` | string | No | 用户 ID,与 agent_id 二选一。 | | `agent_id` | string | No | Agent ID,与 user_id 二选一。 | | `profile_template_id` | string | Yes | 目标属性记忆模板 ID。 | ### Request Example ```json { "user_id": "memos_user_123", "profile_template_id": "tpl_user_001" } ``` ## Response Successful Response | Parameter | Type | Required | Description | |---|---|---|---| | `code` | integer | Yes | 接口状态码。 | | `data` | object | No | | | `message` | string | Yes | 接口提示信息。 | #### `data` object | Parameter | Type | Required | Description | |---|---|---|---| | `success` | boolean | No | 是否操作成功。 | ### Response Example ```json { "code": 0, "data": { "success": true }, "message": "ok" } ``` URL: /cn/api_docs/core/delete_profile --- # Extract Memory **POST** `/extract/memory` 基于 MemOS 自研抽取模型,从对话消息中直接抽取并返回事实与偏好记忆。 - operationId: `extract_memory` ## Request Body | Parameter | Type | Required | Description | |---|---|---|---| | `messages` | array | Yes | 需要抽取记忆的消息对象数组,数组中所有消息的总 Token 数上限为8k。 | | `extraction_types` | array | No |

限定抽取的记忆类型;不传则抽取全部支持的类型。

  • memory:事实记忆,从对话中提取用户相关的事实性信息。
  • preference:偏好记忆,从对话中提取用户的偏好信息,包含显性偏好(用户明确表达)和隐性偏好(从行为推断)。
| #### `messages` object | Parameter | Type | Required | Description | |---|---|---|---| | `role` | string (enum: user, assistant, system) | Yes | 消息创建者的角色。 | | `content` | string | Yes | 消息内容文本。 | ### Request Example ```json { "messages": [ { "role": "user", "content": "我暑假定好去广州旅游,住宿的话有哪些连锁酒店可选?" }, { "role": "assistant", "content": "您可以考虑【七天、全季、希尔顿】等等" }, { "role": "user", "content": "我选七天" }, { "role": "assistant", "content": "好的,有其他问题再问我。" } ], "extraction_types": [ "memory", "preference" ] } ``` ## Response Successful Response | Parameter | Type | Required | Description | |---|---|---|---| | `code` | integer | Yes | 接口状态码,更多内容可查阅错误码列表了解详情。 | | `data` | object | No | | | `message` | string | Yes | 接口提示信息。 | #### `data` object | Parameter | Type | Required | Description | |---|---|---|---| | `success` | boolean | No | 是否抽取成功。 | | `memory_detail_list` | array | No | 事实记忆列表。当请求中 extraction_types 包含 memory,或未传 extraction_types 时返回。 | | `preference_detail_list` | array | No | 偏好记忆列表。当请求中 extraction_types 包含 preference,或未传 extraction_types 时返回;结果中可包含显性偏好与隐性偏好。 | #### `memory_detail_list` object | Parameter | Type | Required | Description | |---|---|---|---| | `memory_key` | string | No | 记忆主题,对抽取到的事实记忆的概括性描述。 | | `memory_value` | string | No | 记忆内容,对抽取到的事实记忆的详细描述。 | | `memory_type` | string | No | 记忆类型分类标识。
示例:UserMemory、LongTermMemory。 | | `tags` | array | No | 记忆标签列表,用于对记忆内容进行分类标注。 | #### `preference_detail_list` object | Parameter | Type | Required | Description | |---|---|---|---| | `preference` | string | No | 偏好描述,对抽取到的用户偏好的具体内容。 | | `reasoning` | string | No | 推理依据,说明该偏好是如何从对话中推断得出的。 | | `preference_type` | string (enum: explicit_preference, implicit_preference) | No | 偏好类型:显性偏好为用户明确表达,隐性偏好为从行为或语境推断。 | ### Response Example ```json { "code": 0, "data": { "memory_detail_list": [ { "memory_key": "用户基本信息", "memory_value": "用户张三,28岁,在杭州从事后端开发,喜欢打羽毛球。", "memory_type": "UserMemory", "tags": [ "人物", "职业", "爱好" ] } ], "preference_detail_list": [ { "preference": "用户明确表示希望回复尽量简洁。", "reasoning": "对话中用户直接说明偏好。", "preference_type": "explicit_preference" } ] }, "message": "ok" } ``` URL: /cn/api_docs/core/extract_memory --- # Rerank **POST** `/rerank` 提供记忆重排接口,基于 memos-reranker 小模型,传入用户查询与候选记忆列表,一键完成记忆相关性重排。 - operationId: `rerank` ## Request Body | Parameter | Type | Required | Description | |---|---|---|---| | `model` | string (enum: memos-reranker-0.6b, memos-reranker-4b) | No | 模型名称。 | | `query` | string | Yes | 用户查询文本,用于与候选文档进行相关性匹配。 | | `documents` | array | Yes | 候选记忆/文档列表,每条为一段文本。数组中所有文档的总 token 数上限为 8k。 | | `top_n` | integer | No | 返回前 N 条最相关的结果。不传时默认返回全部结果。 | ### Request Example ```json { "model": "memos-reranker-0.6b", "query": "用户有什么兴趣爱好", "documents": [ "用户喜欢打羽毛球", "用户在杭州做后端开发", "用户偏好简洁的回复风格", "用户比较喜欢酱香型白酒", "用户下周三要去北京出差" ] } ``` ## Response Successful Response | Parameter | Type | Required | Description | |---|---|---|---| | `id` | string | Yes | 本次请求的唯一标识。 | | `model` | string | Yes | 使用的模型名称。 | | `usage` | object | Yes | token 用量统计。 | | `results` | array | Yes | 重排结果列表,按 relevance_score 降序排列。 | #### `usage` object | Parameter | Type | Required | Description | |---|---|---|---| | `prompt_tokens` | integer | Yes | 输入消耗的 token 数。 | | `total_tokens` | integer | Yes | 总消耗 token 数。 | #### `results` object | Parameter | Type | Required | Description | |---|---|---|---| | `index` | integer | Yes | 该文档在原始 documents 列表中的索引位置。 | | `document` | object | Yes | 文档对象。 | | `relevance_score` | number | Yes | 相关性分数,范围 0~1,越高表示与 query 越相关。 | #### `document` object | Parameter | Type | Required | Description | |---|---|---|---| | `text` | string | Yes | 文档原文内容。 | URL: /cn/api_docs/core/rerank --- # Get Message **POST** `/get/message` 该接口用于获取指定会话的用户与助手历史对话记录,可按数量限制返回结果。 - operationId: `get_message` ## Request Body | Parameter | Type | Required | Description | |---|---|---|---| | `user_id` | string | Yes | 与获取消息关联的用户的唯一标识符。 | | `conversation_id` | string | Yes | 与获取消息关联的会话的唯一标识符。 | | `message_limit_number` | integer | No | 限定返回的消息条数,用于控制消息列表的长度,不传时使用系统默认值6,最大值为50 | ### Request Example ```json { "user_id": "memos_user_123", "conversation_id": "0928", "message_limit_number": 6 } ``` ## Response Successful Response | Parameter | Type | Required | Description | |---|---|---|---| | `code` | integer | Yes | 接口状态码,更多内容可查阅错误码列表了解详情。 | | `data` | object | No | | | `message` | string | Yes | 接口提示信息。 | #### `data` object | Parameter | Type | Required | Description | |---|---|---|---| | `message_detail_list` | array | No | 消息添加结果对象。 | #### `message_detail_list` object | Parameter | Type | Required | Description | |---|---|---|---| | `role` | string (enum: user, assistant) | No | 消息发送者的角色。 | | `content` | string | No | 消息内容文本。 | | `create_time` | string | No | 消息创建时间。 | | `update_time` | string | No | 消息最近一次更新时间。 | ### Response Example ```json { "code": 0, "data": { "message_detail_list": [ { "role": "user" } ] } } ``` URL: /cn/api_docs/message/get_message --- # Get Task Status **POST** `/get/status` 查询 add/message、add/feedback 等异步任务的处理状态。任务完成后返回 memory_views,汇总本次任务新增/更新/删除数量,以及各记忆种类下触达的记忆 ID。 - operationId: `get_status` ## Request Body | Parameter | Type | Required | Description | |---|---|---|---| | `task_id` | string | Yes | 异步任务 ID,来自 add/message、add/feedback 等接口响应中的 task_id。 | ### Request Example ```json { "task_id": "c464e17e-f2ff-4e9a-a2c2-41cc55ab43b9" } ``` ## Response Successful Response | Parameter | Type | Required | Description | |---|---|---|---| | `code` | integer | Yes | 接口状态码,更多内容可查阅错误码列表了解详情。 | | `data` | object | No | | | `message` | string | Yes | 接口提示信息 | #### `data` object | Parameter | Type | Required | Description | |---|---|---|---| | `task_id` | string | No | 异步任务 ID,与请求中的 task_id 一致。 | | `status` | string (enum: running, completed, failed) | No | 任务当前状态:`running` 处理中,`completed` 已完成,`failed` 失败。 | | `memory_views` | object | No | 任务完成后返回的本轮记忆变更汇总。 | #### `memory_views` object | Parameter | Type | Required | Description | |---|---|---|---| | `added` | integer | No | 本次任务新增的记忆数量。 | | `updated` | integer | No | 本次任务更新的记忆数量。 | | `deleted` | integer | No | 本次任务删除或归档的记忆数量。 | | `detail_factual` | object | No | | | `preference` | object | No | | | `event` | object | No | | | `profile` | object | No | | | `skill` | object | No | | | `tool_memory` | object | No | | #### `detail_factual` object | Parameter | Type | Required | Description | |---|---|---|---| | `memory_ids` | array | No | 本次任务在该记忆种类下触达的记忆 ID 列表。 | #### `preference` object | Parameter | Type | Required | Description | |---|---|---|---| | `memory_ids` | array | No | 本次任务在该记忆种类下触达的记忆 ID 列表。 | #### `event` object | Parameter | Type | Required | Description | |---|---|---|---| | `memory_ids` | array | No | 本次任务在该记忆种类下触达的记忆 ID 列表。 | #### `profile` object | Parameter | Type | Required | Description | |---|---|---|---| | `memory_ids` | array | No | 本次任务在该记忆种类下触达的记忆 ID 列表。 | #### `skill` object | Parameter | Type | Required | Description | |---|---|---|---| | `memory_ids` | array | No | 本次任务在该记忆种类下触达的记忆 ID 列表。 | #### `tool_memory` object | Parameter | Type | Required | Description | |---|---|---|---| | `memory_ids` | array | No | 本次任务在该记忆种类下触达的记忆 ID 列表。 | ### Response Example ```json { "data": { "status": "running" } } ``` URL: /cn/api_docs/message/get_status --- # Chat **POST** `/chat` - operationId: `chat` ## Request Body | Parameter | Type | Required | Description | |---|---|---|---| | `user_id` | string | Yes | 对话内容所关联的用户唯一标识符。 | | `conversation_id` | string | Yes | 对话内容所在会话的唯一标识符,传入可明确当前会话,本会话的记忆应当比其他历史会话的权重高;不传可跨会话检索相关记忆,得到相关性更高的模型回答。 | | `query` | string | Yes | 用户输入的对话内容。 | | `filter` | object | No | 记忆过滤的条件,用于在检索记忆前精确限定记忆范围。可用字段包括:"agent_id", "app_id", "create_time", "update_time"与"info"中的字段。支持逻辑运算符(and,or)和比较运算符(gte、lte、gt、lt)。对于"info"字段,支持过滤传入的"business_type", "biz_id", "scene"和其他自定义字段。 | | `knowledgebase_ids` | array | No | 该字段用于限制当次搜索可访问的知识库范围,默认为空(即不检索任何知识库)。传入具体知识库 ID,则可检索指定知识库中的普通文档和已上传的 Skill;传入 all,则可检索该项目下所有关联知识库。 | | `memory_limit_number` | integer | No | 召回的事实记忆条数上限,在满足相关性阈值(relativity)的前提下最多返回该数量的记忆,不保证返回固定条数。默认值 9,最大值 25。 | | `include_preference` | boolean | No | 是否要召回偏好记忆,开启后系统会根据查询内容智能召回与用户偏好相关的记忆。默认 =true | | `preference_limit_number` | integer | No | 召回的偏好记忆条数上限,在满足相关性阈值(relativity)的前提下最多返回该数量的记忆,不保证返回固定条数。默认值 9,最大值 25。 | | `relativity` | number | No | 召回记忆的相关性阈值(0~1)。用于过滤低相关记忆,并与限定返回的事实、偏好记忆最大条数,共同约束最终返回结果。不传时使用系统默认阈值,取值为0时表示不进行相关性过滤。 | | `model_name` | string (enum: qwen3-32b, deepseek-r1, qwen2.5-72b-instruct) | No | 指定具体对话模型。 | | `system_prompt` | string | No | 自定义系统指令。 | | `stream` | boolean | No | 是否启用流式返回。 | | `max_tokens` | integer | No | 表示最大生成 token 数。 | | `temperature` | number | No | 控制生成随机性。取值范围:0 ≤ x ≤ 2 | | `top_p` | number | No | Nucleus 采样参数。取值范围:0 ≤ x ≤ 1 | | `add_message_on_answer` | boolean | No | 是否自动将用户与助手的会话内容写入记忆。启用后,开发者无需再调用add/message接口添加消息为记忆。 | | `app_id` | string | No | 对话内容所关联的应用唯一标识符。 | | `agent_id` | string | No | 对话内容所关联的Agent唯一标识符。 | | `tags` | array | No | 自定义标签列表,用于标记对话内容的主题或分类。 | | `info` | object | No | 自定义元信息字段,能够存储任意与对话内容相关的结构化数据,例如位置、来源、版本等,主要用于在检索时精确过滤或追踪来源。 | | `allow_public` | boolean | No | 是否允许加入公共记忆。 | | `allow_knowledgebase_ids` | array | No | 添加的消息产生的记忆允许被写入的知识库列表。 | ### Request Example ```json { "user_id": "memos_user_123", "stream": false, "query": "上海有哪些好玩的", "model_name": "deepseek-r1", "conversation_id": "23006762-a064-456e-a33b-d2452bdfa09f", "knowledgebase_ids": [ "2448808afa784cc5f7595da21ae5a3fd" ], "filter": { "and": [ { "create_time": { "gt": "2025-09-19" } } ] }, "system_prompt": "推荐公园", "add_message_on_answer": false, "allow_public": false, "allow_knowledgebase_ids": [], "agent_id": "agent_id_2025-12-15-01", "app_id": "app_id_2025-12-15-01", "tags": [], "info": {}, "max_tokens": 8192, "temperature": 0.7, "top_p": 0.95 } ``` ## Response Successful Response | Parameter | Type | Required | Description | |---|---|---|---| | `code` | integer | Yes | 接口状态码,更多内容可查阅错误码列表了解详情。 | | `data` | object | No | | | `message` | string | Yes | 提示信息 | #### `data` object | Parameter | Type | Required | Description | |---|---|---|---| | `response` | string | No | 回答的具体内容。 | URL: /cn/api_docs/chat/chat --- # 创建知识库 **POST** `/create/knowledgebase` 创建与项目关联的知识库 - operationId: `create_knowledgebase` ## Request Body | Parameter | Type | Required | Description | |---|---|---|---| | `knowledgebase_name` | string | Yes | 知识库名称 | | `knowledgebase_description` | string | No | 描述信息 | ## Response Successful Response | Parameter | Type | Required | Description | |---|---|---|---| | `code` | integer | Yes | 接口状态码,更多内容可查阅错误码列表了解详情。 | | `data` | object | No | | | `message` | string | Yes | 接口提示信息 | #### `data` object | Parameter | Type | Required | Description | |---|---|---|---| | `id` | string | No | 创建成功后返回的知识库 ID | URL: /cn/api_docs/knowledge/create_kb --- # 删除知识库 **POST** `/delete/knowledgebase` 删除知识库,或解除知识库与当前项目的关联。 - operationId: `delete_knowledgebase` ## Request Body | Parameter | Type | Required | Description | |---|---|---|---| | `knowledgebase_id` | string | Yes | 要删除或从当前项目中移除的知识库 ID | | `delete_all` | boolean | No | 是否彻底删除知识库。默认为 false,仅解除知识库与当前 API Key 所属项目的关联;设为 true 时,将删除知识库及其中的文件,并解除该知识库与所有项目的关联。 | ## Response Successful Response | Parameter | Type | Required | Description | |---|---|---|---| | `code` | integer | Yes | 接口状态码,更多内容可查阅错误码列表了解详情。 | | `data` | object | No | | | `message` | string | Yes | 接口提示信息 | #### `data` object | Parameter | Type | Required | Description | |---|---|---|---| | `success` | boolean | No | 是否移除成功。true 表示成功,false 表示失败。 | URL: /cn/api_docs/knowledge/remove_kb --- # 添加知识库文件 **POST** `/add/knowledgebase-file` 向指定知识库上传文件。默认上传普通文档;当 file[].type 为 skill 时,上传 Markdown Skill 文件或 ZIP 技能包。 - operationId: `add_knowledgebase-file` ## Request Body | Parameter | Type | Required | Description | |---|---|---|---| | `knowledgebase_id` | string | Yes | 目标知识库ID | | `file` | array | Yes | 上传文件列表。普通文档按文档解析流程处理;Skill 文件按 Skill 校验和解析流程处理。 | #### `file` object | Parameter | Type | Required | Description | |---|---|---|---| | `name` | string | No | 上传的文件名称。上传 Base64 内容时建议填写;上传 URL 时可不填。 | | `type` | string (enum: document, skill) | No | 上传文件类型。document 表示普通知识库文档;skill 表示 Skill 文件,支持 .md 单文件或 .zip 技能包。 | | `content` | string | No | 文件内容,支持 URL 或 Base64 编码。普通文档和 Skill 文件的支持格式、大小与数量限制,请查看知识库要求。 | ## Response Successful Response | Parameter | Type | Required | Description | |---|---|---|---| | `code` | integer | Yes | 接口状态码,更多内容可查阅错误码列表了解详情。 | | `data` | array | No | 上传文件的处理结果列表。 | | `message` | string | Yes | 接口信息 | #### `data` object | Parameter | Type | Required | Description | |---|---|---|---| | `id` | string | No | 文件 ID | | `type` | string (enum: document, skill) | No | 文件类型。document 表示普通文档;skill 表示 Skill 文件。 | | `name` | string | No | 文件名称 | | `sizeMB` | number | No | 文件大小,单位 MB | | `status` | string (enum: running, completed, failed) | No | 文件处理状态 | ### Response Example ```json { "data": [ { "type": "document", "status": "running" } ] } ``` URL: /cn/api_docs/knowledge/add_kb_doc --- # 获取知识库文件 **POST** `/get/knowledgebase-file` 通过两种方式获取文件信息:传 file_ids 获取指定文件详情,或传 knowledgebase_id 获取某个知识库下的文件列表。两种方式只能选择一种;同时传 knowledgebase_id 和 file_ids 会报错。 - operationId: `get_knowledgebase-file` ## Request Body | Parameter | Type | Required | Description | |---|---|---|---| | `knowledgebase_id` | string | No | 目标知识库 ID,不能与 file_ids 同时传。 | | `type` | string (enum: document, skill) | No | 文件类型筛选,仅在使用 knowledgebase_id 查询时生效。document 仅返回普通文档;skill 仅返回技能文件;不传则返回全部文件。 | | `page` | integer | No | 分页页码,仅在使用 knowledgebase_id 查询时生效。 | | `page_size` | integer | No | 每页条数,仅在使用 knowledgebase_id 查询时生效。 | | `file_ids` | array | No | 目标文件 ID 列表,传入后返回指定文件详情。 | ## Response Successful Response | Parameter | Type | Required | Description | |---|---|---|---| | `code` | integer | Yes | 接口状态码,更多内容可查阅错误码列表了解详情。 | | `data` | object | No | | | `message` | string | Yes | 接口提示信息 | #### `data` object | Parameter | Type | Required | Description | |---|---|---|---| | `total` | integer | No | 符合条件的文件总数 | | `page` | integer | No | 当前页码 | | `page_size` | integer | No | 每页条数 | | `file_detail_list` | array | No | | #### `file_detail_list` object | Parameter | Type | Required | Description | |---|---|---|---| | `id` | string | No | 文件 ID | | `type` | string (enum: document, skill) | No | 文件类型。document 表示知识文档;skill 表示技能文件。 | | `name` | string | No | 文件名称 | | `size` | string | No | 文件大小 | | `status` | string (enum: running, completed, failed) | No | 文件处理状态 | ### Response Example ```json { "data": { "file_detail_list": [ { "type": "document", "status": "running" } ] } } ``` URL: /cn/api_docs/knowledge/get_kb_doc --- # 下载知识库文件 **POST** `/download/knowledgebase-file` 下载知识库文件当前版本的原始内容,响应直接返回文件本体。 - operationId: `download_knowledgebase-file` ## Request Body | Parameter | Type | Required | Description | |---|---|---|---| | `file_id` | string | Yes | 知识库文件 ID。 | ### Request Example ```json { "file_id": "1f35642253606ed1e9dd8cd8113a8998" } ``` ## Response 二进制文件流。 URL: /cn/api_docs/knowledge/download_kb_doc --- # 更新知识库文件 **POST** `/update/knowledgebase-file` 为已有知识库文件提交新内容,生成下一个版本。 - operationId: `update_knowledgebase-file` ## Request Body | Parameter | Type | Required | Description | |---|---|---|---| | `file_id` | string | Yes | 要更新的知识库文件 ID。 | | `file` | object | Yes | 新版本文件。 | #### `file` object | Parameter | Type | Required | Description | |---|---|---|---| | `name` | string | No | 新版本文件名,Base64 内容时用于确定扩展名。 | | `content` | string | Yes | 新版本的文件内容,支持 URL 或 Base64 编码。 | ### Request Example ```json { "file_id": "1f35642253606ed1e9dd8cd8113a8998", "file": { "name": "Software_Procurement_Reimbursement_Policy.pdf", "content": "https://cdn.memtensor.com.cn/file/Software_Procurement_Reimbursement_Policy_v2.pdf" } } ``` ## Response 请求成功 | Parameter | Type | Required | Description | |---|---|---|---| | `code` | integer | Yes | API 状态码,详见Error Code。 | | `data` | object | No | | | `message` | string | Yes | API 响应消息 | #### `data` object | Parameter | Type | Required | Description | |---|---|---|---| | `file_id` | string | No | 逻辑文件 ID,后续更新与下载继续使用该 ID。 | | `version` | integer | No | 本次更新生成的版本号。 | | `current_version` | integer | No | 文件当前版本号。 | | `version_id` | string | No | 版本记录 ID。 | | `task_id` | string | No | 版本处理任务 ID,可用于查询进度。 | | `status` | string | No | 版本状态,提交后为 PROCESSING。 | URL: /cn/api_docs/knowledge/update_kb_doc --- # 删除知识库文件 **POST** `/delete/knowledgebase-file` 从指定知识库中删除文件。删除 Skill 文件时,与该文件关联的 Skill 会同步删除。 - operationId: `delete_knowledgebase-file` ## Request Body | Parameter | Type | Required | Description | |---|---|---|---| | `file_ids` | array | Yes | 要删除的文件 ID 列表。可传入普通文档 ID 或 Skill 文件 ID。 | ## Response Successful Response | Parameter | Type | Required | Description | |---|---|---|---| | `code` | integer | Yes | 接口状态码,更多内容可查阅错误码列表了解详情。 | | `data` | object | No | | | `message` | string | Yes | 接口提示信息 | #### `data` object | Parameter | Type | Required | Description | |---|---|---|---| | `success` | boolean | No | 是否删除成功。true 表示成功,false 表示失败。 | URL: /cn/api_docs/knowledge/delete_kb_doc --- # 错误码 (/cn/api_docs/help/error_codes) | 错误码 | 含义 | 推荐解决方法 | | :--- | :--- | :--- | | **参数错误** | | | | 40000 | 请求参数错误 | 检查参数名、类型及格式是否符合要求 | | 40001 | 请求数据不存在 | 检查资源 ID(如 memory_id)是否正确 | | 40002 | 必填参数不能为空 | 补充缺失的必填字段 | | 40003 | 参数为空 | 检查传入的列表或对象是否为空 | | 40006 | 不支持的类型 | 检查 type 字段取值 | | 40007 | 不支持的文件类型 | 仅上传允许的格式(.pdf, .docx, .doc, .txt, .json, .md, .xml) | | 40008 | Base64 内容非法 | 检查 Base64 字符串是否包含非法字符 | | 40009 | Base64 格式非法 | 检查 Base64 编码格式是否正确 | | 40010 | 用户 ID 过长 | user_id 长度不能超过 100 字符 | | 40011 | 会话 ID 过长 | conversation_id 长度不能超过 100 字符 | | 40020 | 项目 ID 非法 | 确认 Project ID 格式正确 | | **认证与权限错误** | | | | 40100 | 需要 API Key 认证 | 在 Header 中添加有效 API Key | | 40130 | 需要 API Key 认证 | 在 Header 中添加有效 API Key | | 40132 | API Key 无效或已过期 | 检查 API Key 状态或重新生成 | | **配额与限流错误** | | | | 40300 | 超过接口调用次数上限 | [获取更多额度](/memos_cloud/support/limit#_4-领取更多额度) | | 40301 | 超过请求 Token 调用上限 | 减少输入内容或获取更多额度 | | 40302 | 超过响应 Token 调用上限 | 缩短预期输出或获取更多额度 | | 40303 | 单次对话长度超过限制 | 缩减单次输入/输出长度 | | 40304 | 账户总 API 调用次数耗尽 | [获取更多额度](/memos_cloud/support/limit#_4-领取更多额度) | | 40305 | 输入超过单次 Token 上限 | 缩减输入内容 | | 40306 | 删除记忆鉴权失败 | 确认是否有权删除该记忆 | | 40307 | 删除记忆不存在 | 检查 memory_id 是否有效 | | 40308 | 删除记忆对应的用户不存在 | 检查 user_id 是否正确 | | **系统与服务错误** | | | | 50000 | 系统内部异常 | 服务器繁忙或出现异常,请联系支持 | | 50002 | 操作失败 | 检查操作逻辑或稍后重试 | | 50004 | 记忆服务暂时不可用 | 稍后重试记忆写入/获取操作 | | 50005 | 搜索服务暂时不可用 | 稍后重试记忆搜索操作 | | **知识库与操作错误** | | | | 50103 | 文件数量超过限制 | 单次上传文件数量不超过20个 | | 50104 | 单个文件大小超过限制 | 确保单个文件不超过 100MB | | 50105 | 所有文件总大小超过限制 | 确保单次上传总大小不超过 300MB | | 50107 | 文件上传格式不符合要求 | 检查并更换文件格式 | | 50120 | 知识库不存在 | 确认知识库 ID 是否正确 | | 50123 | 知识库不关联此项目 | 确认知识库是否已授权给当前项目 | | 50131 | 任务不存在 | 检查 task_id 是否正确(常见于查询处理状态) | | 50143 | 添加记忆失败 | 算法服务处理异常,请稍后重试 | | 50144 | 添加消息失败 | 保存聊天历史记录失败 | | 50145 | 保存反馈并写入记忆失败 | 反馈处理过程中出现异常 | --- # 用 MemOS 为 AI 应用构建共享知识库 (/cn/usecase/shared_knowledge_base) 产品手册放在云盘,新人指南留在群聊,客服政策存于同事电脑。新人入职的前半周,常常花在寻找最新版本上。 Memmy 通过基于 MemOS 接口的知识库能力解决这个问题:每个人维护自己的资料库,也可以共享给同事。成员通过同一个检索接口,查询同一份内容。 实现的关键在于分工。MemOS 没有“共享知识库”或“列出全部知识库”的接口,共享由 Memmy 在应用层实现。本文通过一个可在本地运行的 Demo,展示两层如何配合。 ## 先明确两层分工 共享知识库在界面上是一项功能,底层包含两种职责: | 负责方 | 管理内容 | 实现方式 | | --- | --- | --- | | MemOS | 文档原文、解析、分段与可检索记忆片段 | `/create/knowledgebase`、`/add/knowledgebase-file`、`/search/memory` 等接口 | | 应用 | 知识库归属、共享对象、当前用户是否有权查看 | 应用数据库中的归属与共享关系 | MemOS 回答“资料里写了什么”,应用确定“这个人能否读取”。检索时,应用计算当前用户可见的 `knowledgebase_ids`,将明确的列表交给 `/search/memory`。 这样的权限模型可以按团队、项目或有效期设计。应用也承担权限检查的责任,因此 Demo 将未授权用户的访问验证作为完整场景。 ## Demo 中的三个角色 ```text alice · 产品负责人 创建“产品手册”,上传手册和新人指南, 并把知识库共享给 bob。 bob · 客户成功 切换到自己的账号,在“共享知识库”中看到资料, 可以提问,但不能上传、删除或再次共享。 cara · 新同事 未加入共享名单,侧边栏不显示该知识库。 ``` alice 验证写入路径,bob 验证只读访问,cara 验证隔离。 ## 一次回答背后的流程 ```text 用户打开知识库页面 │ ├─ 应用按当前 user_id 加载“我的”与“共享给我”的列表 │ ├─ 拥有者上传文档 │ → /add/knowledgebase-file │ → 轮询 /get/knowledgebase-file,等待 completed │ ├─ 拥有者输入对方用户 ID │ → 应用在自己的数据库写入共享关系,此步不调用 MemOS │ ├─ 成员提问 │ → 应用确认访问权限 │ → 调用一次 /search/memory:user_id + knowledgebase_ids │ → 模型基于召回片段回答 │ └─ 可选:通过 /add/message 将本轮写入当前用户的记忆 ``` 知识库内容由获准成员共享同一份,个人记忆按 `user_id` 保持各自范围。bob 可以读取 alice 维护的手册,但不会因此取得 alice 的个人偏好;bob 的偏好也不会传回 alice。 ## 先运行 Demo 完整项目:[共享知识库 Demo](https://github.com/shinetata/MemOS-KnowledgeBase-Practice)。 准备 MemOS API Key 和兼容 OpenAI 的模型服务: ```bash git clone https://github.com/shinetata/MemOS-KnowledgeBase-Practice.git cd MemOS-KnowledgeBase-Practice python3 -m venv .venv source .venv/bin/activate pip install -r requirements.txt cp .env.example .env ``` 填写 `.env`: ```bash MEMOS_API_KEY=YOUR_MEMOS_API_KEY MEMOS_BASE_URL=https://memos.memtensor.cn/api/openmem/v1 OPENAI_API_KEY=YOUR_OPENAI_API_KEY OPENAI_BASE_URL=YOUR_OPENAI_BASE_URL OPENAI_MODEL=YOUR_MODEL_NAME ``` ```bash python app.py ``` 打开 [http://127.0.0.1:8765](http://127.0.0.1:8765)。Demo 内置 `alice`、`bob`、`cara` 三个用户,可通过左上角头像切换。共享时输入对方用户 ID,例如 `bob`;当前用户 ID 显示在侧边栏。 建议按完整流程体验:用 `alice` 建库 → 上传示例文档 → 等待可用 → 共享给 `bob` → 切换到 `bob` 提问 → 切换到 `cara` 验证不可见。`cara` 仍可进行普通问答,回复会说明没有参考知识库,与 bob 带引用的回答形成对照。 ## 四个关键实现选择 Demo 的核心位于 `memos_client.py`、`store.py`、`app.py` 三个文件,下面的代码分别对应其中的实现。 ### 选择一:文档解析交给 MemOS 创建知识库返回的 ID,直接保存在应用中并关联当前用户,成为权限关系的连接依据: ```python kb_id = memos.create_knowledgebase(name, description) store.create_kb(kb_id, owner_id, name, description) ``` 文件编码为 Data URI 后,交给 `/add/knowledgebase-file`。解析、分段与索引都在 MemOS 完成: ```python encoded = base64.b64encode(content).decode("ascii") memos.post("/add/knowledgebase-file", { "knowledgebase_id": kb_id, "file": [{ "type": "document", "name": filename, "content": f"data:{mime};base64,{encoded}", }], }) ``` 新上传文件通常返回 `running`,页面轮询 `/get/knowledgebase-file`,直到 `completed` 或 `failed`。解析完成前,检索无法召回该文档。Demo 在处理期间持续轮询,让用户看到状态变化。 ### 选择二:共享是应用数据库中的一条关系 拥有者输入对方 ID 后,应用检查权限和账号是否存在,再写入共享关系,此步不调用 MemOS: ```python def share_kb(self, owner_id, kb_id, member_id): if not self.can_manage(owner_id, kb_id): raise PermissionError("只有拥有者可以共享") if not self.get_user(member_id): raise KeyError("用户 ID 不存在") self.insert_share(kb_id, member_id) ``` Demo 通过稳定用户 ID 匹配成员。应用也可以像 Memmy 一样,先把手机号或邮箱解析为账号,再保存对应用户 ID。成员打开页面时,应用读取自己的两类关系: ```python owned = store.list_owned(user_id) shared = store.list_shared(user_id) ``` 拥有者可上传、删除与共享,成员只能浏览文件并提问。 ### 选择三:通过 knowledgebase_ids 落实权限范围 生成回答前,应用先验证访问权限,再将 ID 传入检索: ```python kb = require_view(user_id, kb_id) retrieved = memos.search_memory( query=query, user_id=user_id, knowledgebase_ids=[kb["kb_id"]], conversation_id=conversation_id, ) ``` 公开接口默认不检索任何知识库,显式传入的 ID 才会参与。`knowledgebase_ids` 承接服务端权限计算结果,每个 ID 都应属于当前用户的获准范围。Demo 只针对当前打开的知识库提问,因此传一个 ID;需要跨全部可见知识库提问时,则传入当前用户可访问的完整列表。 ### 选择四:一次检索,两类记忆 一次 `/search/memory` 可以同时返回知识库片段与当前用户的事实、偏好: ```python context_data = { "query": query, "user_id": user_id, "conversation_id": conversation_id, "knowledgebase_ids": [kb_id], "include_memory_view": ["detail_factual", "preference"], "memory_limit_number": 9, "relativity": 0.45, } ``` 提示词应明确两者用途:政策、流程和额度来自知识库;个人偏好可以影响表达,但以文档规则为准。知识库缺乏依据时,助手应说明,而非编造手册中没有的规定。 随后可通过 `/add/message` 将本轮写入当前 `user_id`。bob 下次提问时,MemOS 会带入 bob 自己的偏好,实现资料共享、个人记忆各自保留。 ## 验收检查 接入后走完三个角色,确认: 1. `alice` 建库、上传文档、等待可用,再共享给 `bob`,写入路径完整。 2. `bob` 在共享列表看到知识库并提问,界面不提供上传、删除入口;直接调用写入接口也会被服务端的拥有者权限检查拒绝。 3. `cara` 的侧边栏不显示该知识库,即使猜到 ID 并直接发给 API,也会被应用拒绝。她仍可问一般问题,但检索范围没有知识库,回答没有知识库引用。 第三项往往容易遗漏。服务端需要在每次检索前重新计算可见范围,前端隐藏只负责界面呈现。 ## 代码位置 - 仓库:[MemOS-KnowledgeBase-Practice](https://github.com/shinetata/MemOS-KnowledgeBase-Practice) 页面从左到右为窄导航栏、个人与共享知识库列表、当前库的文件面板,以及针对当前库的大问答区。核心检索逻辑集中在 `memos_client.py` 的这个方法中: ```python def search_memory(self, query, user_id, knowledgebase_ids, conversation_id): return self._post("/search/memory", { "query": query, "user_id": user_id, "conversation_id": conversation_id, "knowledgebase_ids": knowledgebase_ids, "include_memory_view": ["detail_factual", "preference"], "memory_limit_number": 9, "relativity": 0.45, }) ``` 知识库资料在授权成员之间共享,用户记忆保持个人范围。应用计算可见范围,MemOS 负责文档处理与检索。 --- # 在 Memmy 中集成 MemOS 知识库 (/cn/usecase/memmy_knowledge_base) Memmy 是一款桌面端 Agent 应用,让用户的工作在 DeepSeek Harness、Claude Code、Codex 等 Agent 之间延续。用户希望 Agent 回答时参考自己的资料,例如产品手册、项目文档和调研报告。Memmy 知识库为此而建:用户创建知识库、上传文件,再选择哪些知识库参与对话;Agent 回答前自动检索,并在回答中标注资料来源。 这项能力完全基于 MemOS 知识库接口实现。与一个服务端直接调用 MemOS 不同,Memmy 运行在大量终端用户自己的电脑上,用户之间还会互相共享资料。这些前提决定了它的接入方式。 本文以一个产品团队的使用场景为线索,依次说明创建、上传、检索、共享、删除每一步 Memmy 怎么做、为什么这样做。文中代码是示意,用于说明应用服务端如何调用 MemOS 公开接口,不能直接运行。 ## 使用场景 以产品团队为例,一次完整的使用过程如下: 1. **建库**:产品经理在 Memmy 中创建一个知识库,上传《MemOS产品介绍.md》和《MemOS 开源VS商业化.md》。两份文件的状态从「处理中」变为「可用」。 2. **共享**:产品经理在「共享管理」中输入销售同事的手机号,把这个知识库共享出去。 3. **提问**:销售同事在 Memmy 中问「MemOS 开源版和商业版有什么区别」。Agent 回答前自动检索,回答中引用《MemOS 开源VS商业化》并注明出处。 4. **更新**:产品经理又上传了一份新资料。销售同事无需任何操作,下一次提问即可检索到新内容。 5. **撤销**:销售同事转岗后,产品经理撤销共享。销售同事之后的提问不再检索这个知识库。 ![Memmy 知识库页面](https://cdn.memtensor.com.cn/img/1792586352599_qmi1ct_compressed.png) ## 整体架构 Memmy 由桌面端和 Memmy 云服务两部分组成。作为面向终端用户的桌面产品,它接入 MemOS 时需要满足四项约束: 1. **API Key 不能下发**:桌面端安装在用户自己的电脑上,写进安装包或本地配置的 API Key 等同于公开。因此 API Key 只放在 Memmy 云服务,桌面端使用用户的 Memmy 登录凭据访问云服务。 2. **归属需要应用判断**:MemOS 知识库归属于开发者项目,并不识别 Memmy 的终端用户。Memmy 为所有用户使用同一个 MemOS 项目,哪个用户拥有、能看到哪个知识库,由云服务在每次调用 MemOS 前判断。 3. **设置需要跟随账号**:同一账号可能在多台电脑上登录,每个知识库的「参与召回」设置保存在云服务。 4. **Agent 不接触凭据**:Agent 在运行中会调用工具、读取本地文件。知识库 Hook 只使用本机服务的访问令牌,检索链路不向 Agent 传递任何云端凭据。 由此形成三层结构:桌面端只与 Memmy 云服务通信,由云服务代表用户调用 MemOS。 ```mermaid flowchart LR subgraph Desktop["Memmy 桌面端"] direction TB Page["知识库页面"] Hook["知识库 Hook"] Local["本机服务"] Page --> Local Hook --> Local end subgraph Service["Memmy 云服务"] direction TB Auth["识别登录用户"] Biz["归属 · 共享 · 召回设置"] Scope["转换知识库 ID 计算召回范围"] Auth --> Biz --> Scope end subgraph Cloud["MemOS"] direction TB Store["知识库与文件"] Index["解析 · 分段 · 索引"] Search["知识检索"] Store --> Index --> Search end Desktop -->|Memmy 登录凭据| Service Service -->|MemOS API Key| Cloud ``` 落到具体功能上,Memmy 云服务与 MemOS 的分工如下。没有对应接口的功能,完全由 Memmy 云服务在应用层实现: | Memmy 功能 | Memmy 云服务负责 | MemOS 负责 | MemOS 接口 | | --- | --- | --- | --- | | 创建知识库 | 保存 Memmy 与 MemOS 知识库 ID 的对应关系 | 创建知识库 | `/create/knowledgebase` | | 上传文件 | 确认拥有者,转换知识库 ID | 存储文件,异步完成解析、分段与索引 | `/add/knowledgebase-file` | | 文件列表与处理状态 | 按文件夹筛选 | 返回文件信息与处理状态 | `/get/knowledgebase-file` | | 重命名、文件夹 | 保存名称与目录结构 | — | — | | 参与召回 | 保存每位用户对每个知识库的开关 | — | — | | Agent 回答前检索 | 计算召回范围,复核检索结果 | 在指定知识库中检索 | `/search/memory` | | 共享知识库 | 维护成员关系 | — | — | | 删除知识库或文件 | 先在应用侧删除 | 后台清理知识库与文件 | `/delete/knowledgebase`、`/delete/knowledgebase-file` | 云服务对 MemOS 的所有调用都经过同一个入口,API Key 只在这里出现: ```python MEMOS_BASE_URL = "https://memos.memtensor.cn/api/openmem/v1" MEMOS_API_KEY = os.environ["MEMOS_API_KEY"] # 只配置在云服务,不下发给桌面端 def memos_post(path, body): resp = requests.post( MEMOS_BASE_URL + path, headers={"Authorization": f"Token {MEMOS_API_KEY}"}, json=body, ) return resp.json()["data"] ``` 后文示例都通过 `memos_post` 调用 MemOS。Memmy 云服务自己保存的数据如下,示例用字典表示,实际可换成数据库;目录结构类似,示例中省略: ```python knowledge_bases = {} # Memmy 知识库 ID -> {"memos_kb_id", "owner_id", "name"} members = {} # Memmy 知识库 ID -> 被共享的用户 ID 集合 recall_selected = {} # (用户 ID, Memmy 知识库 ID) -> 是否参与召回 def can_access(user_id, kb_id): # 拥有者,或被共享的用户 owner_id = knowledge_bases[kb_id]["owner_id"] return user_id == owner_id or user_id in members.get(kb_id, set()) ``` ## 创建与上传 ### 创建知识库 用户提交名称后,云服务先在 MemOS 中创建知识库,再保存两个知识库 ID 的对应关系: ```python def create_knowledge_base(owner_id, name): data = memos_post("/create/knowledgebase", {"knowledgebase_name": name}) kb_id = str(uuid.uuid4()) # Memmy 知识库 ID,返回给桌面端 knowledge_bases[kb_id] = { "memos_kb_id": data["id"], # MemOS 知识库 ID,只留在云服务 "owner_id": owner_id, "name": name, } recall_selected[(owner_id, kb_id)] = True # 新建的知识库默认参与召回 return kb_id ``` 桌面端后续请求只携带 Memmy 知识库 ID,云服务不接受客户端传入的 MemOS 知识库 ID,MemOS 知识库 ID 因此无从被猜测或伪造。新建的知识库默认参与召回;重命名只修改 Memmy 中保存的名称,不调用 MemOS。 ### 上传与管理文件 上传前,桌面端与云服务按 MemOS 知识库的文档限制校验文件:格式为 PDF、DOCX、DOC、TXT、JSON、MD、XML 之一,单文件不超过 100 MB。云服务确认当前用户是拥有者后,把 Memmy 知识库 ID 转换为 MemOS 知识库 ID,再提交文件: ```python def upload_file(user_id, kb_id, filename, content): kb = knowledge_bases[kb_id] if kb["owner_id"] != user_id: raise PermissionError("只有拥有者可以上传文件") mime_type, _ = mimetypes.guess_type(filename) encoded = base64.b64encode(content).decode("ascii") files = memos_post("/add/knowledgebase-file", { "knowledgebase_id": kb["memos_kb_id"], # 转换为 MemOS 知识库 ID "file": [{ "name": filename, "content": f"data:{mime_type};base64,{encoded}", }], }) return files[0]["status"] # 通常为 running,表示 MemOS 正在处理 ``` 文件较大时,也可以先把文件放到 MemOS 能够访问的地址,再在 `content` 中传入 URL。 MemOS 收到文件后,异步完成解析、分段与索引,文件状态从 `running` 变为 `completed`,处理失败时为 `failed`。只有处理完成的内容才会进入检索结果。Memmy 页面据此展示「处理中」「可用」「失败」,有文件处理中时定时刷新。 文件名、处理状态等文件信息不在 Memmy 中另存,每次打开知识库都从 MemOS 实时查询,文件状态因此只有一个来源。Memmy 额外保存的只有目录:MemOS 知识库中的文件是平铺的,云服务记录文件夹层级和每个文件所在的文件夹,打开文件夹时按对应关系筛选。移动文件只修改对应关系,不需要重新上传,MemOS 也不会重新解析。 ## Agent 回答前的检索 这是整条链路的核心。用户之间的隔离,最终落在每次检索传入的知识库 ID 上:传错一个,就会把别人的资料交给 Agent。一次对话中,知识库检索的过程如下: ```mermaid sequenceDiagram participant User as 用户 participant Hook as 知识库 Hook participant Service as Memmy 云服务 participant MemOS as MemOS participant Agent as Agent User->>Hook: 在对话中提问 Note over Hook: Agent 运行前触发 Hook->>Service: 本轮问题 Service->>Service: 计算召回范围 alt 召回范围为空 Service-->>Hook: 不调用 MemOS,直接返回 else 召回范围不为空 Service->>MemOS: /search/memory(knowledgebase_ids = 召回范围) MemOS-->>Service: 知识库片段 Service->>Service: 复核召回范围,变化则丢弃结果 Service-->>Hook: 资料片段与来源 end Hook->>Agent: 把资料追加到本轮系统提示 Agent-->>User: 回答并引用来源 Hook->>Hook: 运行结束后移除注入内容 ``` 检索由知识库 Hook 在 Agent 运行前自动发起,Agent 本身不调用任何知识库接口。这样做不依赖 Agent 判断何时该查资料:用户开启「参与召回」后,提问时无需额外提醒「查一下知识库」。代价是每轮都会检索一次,与资料无关的问题也不例外。 Hook 拿到资料后追加到本轮系统提示;运行结束后移除这些内容,下一轮按新问题重新检索,资料不会在多轮对话中累积。 云服务在调用 MemOS 前后各检查一次召回范围:调用前计算范围,决定检索哪些知识库;调用后复核范围,确认检索期间范围没有变化。下面分别说明。 召回范围是以下两个集合的交集。交集为空时,云服务跳过检索,不调用 MemOS。 - 用户开启了「参与召回」的知识库。 - 用户当前有权访问的知识库,包括自己拥有的和被共享的。 以场景中的销售同事为例:销售同事自己有一个知识库,又收到了产品经理共享的知识库,两个都开启了「参与召回」,召回范围就是这两个知识库的 MemOS ID。关掉自己知识库的「参与召回」后,召回范围只剩共享来的那一个。 `knowledgebase_ids` 是这条链路中唯一的权限出口。MemOS 默认不检索任何知识库,只有显式传入的 ID 才进入检索范围;它也支持传入 `all`,但这会检索项目下的所有知识库,包括其他用户的。因此,云服务每次检索前都重新计算范围,只传入明确的 ID 列表,不信任桌面端缓存的列表。 ```python def recall_scope(user_id): return [ kb["memos_kb_id"] for kb_id, kb in knowledge_bases.items() if can_access(user_id, kb_id) # 自己拥有的与被共享的 and recall_selected.get((user_id, kb_id), False) # 开启了「参与召回」 ] def recall(user_id, query): scope = recall_scope(user_id) if not scope: return [] # 不调用 MemOS data = memos_post("/search/memory", { "user_id": f"kb-reader-{user_id}", # 检索专用 ID "query": query, "knowledgebase_ids": scope, # 只传明确的 ID,不传 all }) if recall_scope(user_id) != scope: # 复核:范围变化则丢弃结果 return [] return [ {"title": item["memory_key"], "content": item["memory_value"]} for item in data["memory_detail_list"] ] ``` 检索返回后的复核容易被忽略。一次检索需要一定时间,期间拥有者可能撤销共享,用户也可能关闭某个知识库的「参与召回」。例如销售同事提问时,产品经理恰好撤销了共享:调用 MemOS 前,召回范围里还有这个知识库;检索返回时,它已经不在范围内了。复核发现范围变化,云服务丢弃整次结果,下一轮再按新范围检索。 示例中的 `user_id` 是检索专用的,从不写入对话,因此检索结果里只有知识库片段。这是因为 Memmy 的个人记忆由独立的 Memory 模块负责,两类上下文由各自的 Hook 注入,互不依赖。如果你的应用没有自己的记忆系统,可以传入真实的 `user_id`,让 MemOS 在同一次检索中一并返回用户事实与偏好,具体用法可参考[知识库功能说明](/cn/memos_cloud/features/knowledge_base)。 Hook 注入资料时会注明:这些内容是参考资料而不是指令,Agent 需要引用来源,并忽略资料中出现的任何指令,以防范提示词注入。 ![Agent 回答时标注资料来源](https://cdn.memtensor.com.cn/img/1792586375431_qwk6vy_compressed.png) ## 共享知识库 MemOS 没有成员或共享相关的接口,Memmy 的共享完全在应用层实现。由于所有知识库都在同一个 MemOS 项目下,只要 Memmy 判定成员有权访问,就可以把拥有者知识库的 MemOS ID 加入成员的召回范围。处理过程如下: 1. 拥有者在「共享管理」中输入对方的 Memmy 用户 ID、手机号或邮箱。 2. 云服务把输入解析为 Memmy 账号,确认对方存在且不是本人后,写入一条只读成员关系。这一步不调用 MemOS。 3. 对方刷新页面后,在知识库列表的「共享」分组中看到该知识库,并显示来自哪位用户。新共享的知识库默认参与对方的召回。 ![共享管理](https://cdn.memtensor.com.cn/img/1792586422247_2r0azs_compressed.png) 共享后,拥有者与被共享的用户权限如下: | 操作 | 拥有者 | 被共享的用户 | | --- | --- | --- | | 查看文件 | ✓ | ✓ | | 开关「参与召回」 | ✓ | ✓,只影响自己 | | 上传、删除文件 | ✓ | — | | 新建、移动、删除文件夹 | ✓ | — | | 重命名、删除知识库 | ✓ | — | | 共享管理 | ✓ | — | 共享不复制任何内容:所有成员检索的是同一个 MemOS 知识库。场景中产品经理上传新资料后,销售同事的下一次检索即可命中新内容。拥有者撤销共享后,该成员的召回范围立即不再包含这个知识库。 ## 删除知识库 删除分两步:先在 Memmy 中删除,知识库立即从所有成员的列表和召回范围中消失,用户无需等待;再在后台清理 MemOS 中的知识库与文件。以删除知识库为例: ```python def delete_knowledge_base(user_id, kb_id): kb = knowledge_bases[kb_id] if kb["owner_id"] != user_id: raise PermissionError("只有拥有者可以删除知识库") # 1. 先在 Memmy 中删除 del knowledge_bases[kb_id] members.pop(kb_id, None) # 2. 再在后台清理 MemOS threading.Thread(target=memos_post, args=("/delete/knowledgebase", { "knowledgebase_id": kb["memos_kb_id"], "delete_all": True, })).start() ``` `delete_all` 默认为 `false`,只解除知识库与当前项目的关联,知识库与文件仍然保留;彻底删除必须显式传入 `true`。删除文件与文件夹遵循同样的顺序,后台调用 `/delete/knowledgebase-file`。后台清理可能失败,应用需要准备重试或定期对账,避免 MemOS 中残留已删除的数据。 ## 小结 Memmy 的接入可以归结为一句话:MemOS 负责"资料里写了什么",Memmy 负责"谁能用、用哪些"。任何同时拥有客户端与终端用户的 AI 产品,接入 MemOS 知识库时都可以沿用这套分层。 Memmy 的权限粒度是整个知识库。需要按文件区分可见范围时,可以把可见范围不同的文件放进不同的知识库。 --- # 构建记忆增强型的知识库问答助手 (/cn/usecase/knowledge_qa_assistant) ## 1. 概述 在 AI 应用开发中,构建一个能够理解上下文、记住历史交互的问答助手一直是核心需求。传统的大语言模型虽然强大,但缺乏长期记忆能力,每次对话都像"失忆"一样重新开始。RAG(检索增强生成)虽然能检索相关知识,但无法真正"记住"用户的偏好和历史交互。 MemOS提供了一个完整的记忆操作系统生态, 让 AI 应用具备真正的长期记忆能力。基于MemOS的知识库,结合提示词向AI大模型提供上下文信息,从而获得更精准和个性化的反馈。这种体验显著优于直接在互联网上与通用大模型对话 ### 1.1 MemOS记忆层 vs RAG:核心区别 传统 RAG(检索增强生成)方案的核心问题在于:**它是无状态的**。每次查询都是独立的,系统只能基于语义相似度检索知识库中的静态信息,但无法记住"你是谁"、"你之前说过什么"、"你的偏好是什么"。这就像一个失忆的图书管理员,每次都要重新问你的需求,无法根据你的阅读历史提供个性化建议。 MemOS 记忆层的核心价值在于:**让 AI 应用拥有长期记忆能力**。它不仅能检索知识,更能理解关系、时间与偏好,将当前问题与历史记忆关联起来,在"带着背景"的前提下查找和使用知识。随着用户的持续使用,MemOS 会根据对话内容动态演化和更新记忆,从而推动知识库的自动迭代与自我进化。 | 对比维度 | 传统 RAG 方案 | MemOS 记忆层 | | --- | --- | --- | | **记忆能力** | 只能检索,不能记忆 - 基于向量相似度检索静态知识库,无法动态记录用户交互历史 | 动态记忆能力 - 自动捕获、存储和管理对话历史与用户行为 | | **个性化** | 缺乏个性化 - 无法根据用户的历史行为调整回答策略 | 个性化体验 - 根据用户历史偏好提供定制化回答 | | **上下文管理** | 上下文割裂 - 多轮对话中的关联信息难以有效管理 | 智能关联 - 基于语义理解建立记忆之间的关联关系 | | **知识更新** | 知识更新困难 - 新增知识需要重新构建向量索引 | 实时更新 - 支持记忆的增量更新和优先级管理 | ### 1.2 真实场景对比: 企业知识库助手 让我们通过1个真实的业务场景,直观感受 RAG 和 MemOS 的核心差异: ```text DAY 1 员工询问:我的电脑是 MacBook Pro 13寸,Intel 芯片。我怎么安装公司内网代理? DAY 1 助手提供了 Intel 版本的安装步骤。 DAY 20 员工询问:内网代理打不开了,我该重新装哪个版本? ``` #### RAG 方案的问题 ```text # 根据用户发言检索"内网代理""打不开"相关内容,但无法召回"用户的设备型号" 检索到知识: 1. 内网代理常见故障排查 2. M1/M2(ARM)版本的内网代理安装说明 3. Windows 内网代理客户端安装说明 4. 网络连接与证书问题 5. 通用 FAQ ❌ 知识库助手:请尝试重新下载安装最新的Mac M1/M2(ARM)版本或Windows的内网代理客户端。以下是安装步骤:... ``` #### MemOS方案的优势 ```text # 根据员工问题检索"内网代理""打不开"相关记忆,自动识别该员工的设备型号 检索到记忆: 1. 用户在20天前安装了公司内网代理,他的设备是 MacBook Pro 13(Intel) 2. 内网代理常见故障排查 3. Intel 版本的内网代理安装说明 ✅ 知识库助手:你使用的是 Intel 芯片的 MacBook Pro,建议重新安装 Intel 版本 的内网代理客户端。以下是 Intel 版的下载链接和安装步骤:... ``` ### 1.3 为什么使用MemOS? 通过上述真实场景,我们可以清晰看到 MemOS 相比传统 RAG 的三大核心优势: 1. **懂用户:自动补全上下文** RAG 擅长从知识库中检索与查询语义相似的信息,但它是无状态的:每一次查询都是独立的,缺乏对具体用户和上下文的理解。用户必须在每次对话中重复说明背景信息。 MemOS 能够理解关系、时间与偏好等信息,知道"你是谁"、"在做什么"。只需提出问题,MemOS 会自动补全上下文,无需重复说明"我家狗狗不吃鸡肉"或"我的电脑是 Intel 芯片"。 2. **个性化:记住用户习惯与偏好** 不同岗位和工作习惯的用户,需要不同的服务方式。MemOS 能记住: "这个客户不喜欢过于激进的推销" "你更常使用 Python 而非 Java" "你上次咨询过报销政策,这次是否需要进入申请流程" 这种个性化能力让 AI 应用真正成为"你的"助手,而不是一个通用工具。 3. **知识进化:从交互中持续学习** 当实际流程中存在未写入文档的"经验规则"时,MemOS 会将其沉淀为新的记忆,持续补全和完善知识体系。随着终端用户的持续使用,MemOS 会根据对话内容动态演化和更新记忆,让知识库成为"记忆"的一部分,而不仅是静态文档的存储。 在此基础上,MemOS 2.0 提供的知识库以及多模态的能力,支持开发者将业务文档接入MemOS,结合开源大模型,可以快速搭建一个懂用户的问答助手 ## 2. 搭建教程 ### 2.1 知识库准备(5min) #### 创建知识库 通过[控制台](https://memos-dashboard.openmem.net/cn/knowledgeBase/)或API创建知识库, 本文是基于[MemOS的官方文档](https://github.com/MemTensor/MemOS-Docs)、记忆张量过去宣发的文章以及发布说明进行了知识库的分类,便于后续更新和管理,在此示例中,您可以只创建1个知识库,并上传部分文档用于测试 ![image.png](https://cdn.memtensor.com.cn/img/1768481403940_o97qz4_compressed.png) #### 上传文档 进入知识库,上传文档,要注意文档的要求,MemOS-Docs都是MD格式,可基于AI一键转换为TXT格式,再进行上传,上传时需关注文档要求,剩下的**存储,解析,分段,生成记忆**全部交给MemOS,你只需静静等待文档处理完毕,直到状态显示「可用」 ![image.png](https://cdn.memtensor.com.cn/img/1768481436752_31pl0b_compressed.png) ### 2.2 运行代码(5min) 以下代码示例基于python运行环境进行展示 #### 2.2.1 拷贝完整运行代码 ```python import os import requests import json from openai import OpenAI from datetime import datetime # 从云服务控制台获取MemOS_API_KEY os.environ["MEMOS_API_KEY"] = "mpg-xxx" # 替换为你自己的API_KEY os.environ["OPENAI_API_KEY"] = "sk-xxx" os.environ["MEMOS_BASE_URL"] = "https://memos.memtensor.cn/api/openmem/v1" # 替换为你自己的知识库ID,以下ID仅为示例,并非真实知识库ID os.environ["KNOWLEDGE_BASE_IDS"] = json.dumps([ "based540fb25-ddf1-4456-935b-41d901518e04", "base3908d457-da43-4dde-989e-020be132eff4", "base1db3a7ea-6ecc-4925-881a-e87800da8d2e" ]) openai_client = OpenAI(api_key=os.getenv("OPENAI_API_KEY")) class KnowledgeBaseAssistant: def __init__(self): self.openai_client = openai_client self.base_url = os.getenv("MEMOS_BASE_URL") self.knowledge_base_ids = json.loads(os.getenv("KNOWLEDGE_BASE_IDS")) self.headers = { "Content-Type": "application/json", "Authorization": f"Token {os.environ['MEMOS_API_KEY']}" } def search_memory(self, query, user_id): """查询相关记忆""" data = { "query": query, "user_id": user_id, "conversation_id": user_id, "knowledgebase_ids": self.knowledge_base_ids } res = requests.post(f"{self.base_url}/search/memory", headers=self.headers, data=json.dumps(data)) if res.json().get('code') != 0: print(f"❌ 查询记忆失败, {res.json().get('message')}") return [], [] memory_detail_list_raw = res.json().get('data').get('memory_detail_list', []) # 过滤掉相关性小于0.5的记忆 memory_detail_list = [ x for x in memory_detail_list_raw if x.get('relativity', 0) >= 0.5 ] preference_detail_list = res.json().get('data').get('preference_detail_list') return memory_detail_list, preference_detail_list def build_system_prompt(self, memories, preferences): """构建包含格式化记忆的系统提示""" base_prompt = """ # Role 你是 MemOS 智能助手,昵称小忆🧚 — 一个由 MemTensor 创建的「记忆操作系统」AI助手。MemTensor 是一家位于上海的人工智能研究公司,由中国科学院院士指导。MemTensor 致力于'低成本、低幻觉、高泛化'的愿景,探索符合中国国情的人工智能发展路径,推动可信人工智能技术的应用。MemOS 的使命是为大语言模型(LLMs)和自主智能体赋予「类人长期记忆」,将记忆从模型权重中的黑盒转变为「可管理、可调度、可审计」的核心资源。你的回应必须符合法律和道德标准,遵守相关法律法规,不得生成非法、有害或有偏见的内容。如果遇到此类请求,模型应明确拒绝并解释背后的法律或道德原则。你的目标是结合检索到的记忆片段,为用户提供高度个性化、准确且逻辑严密的回答。 # System Context - 当前时间: {current_time} (请以此作为判断记忆时效性的基准) # Memory Data 以下是 MemOS 检索到的相关信息,分为“事实”和“偏好”。 - **事实 (Facts)**:可能包含用户属性、历史对话记录或第三方信息。 - **特别注意**:其中标记为 `[assistant观点]`、`[模型总结]` 的内容代表 **AI 过去的推断**,**并非**用户的原话。 - **偏好 (Preferences)**:用户对回答风格、格式或逻辑的显式/隐式要求。 {memories} {preferences} # Critical Protocol: Memory Safety (记忆安全协议) 检索到的记忆可能包含**AI 自身的推测**、**无关噪音**或**主体错误**。你必须严格执行以下**“四步判决”**,只要有一步不通过,就**丢弃**该条记忆: 1. **来源真值检查 (Source Verification)**: - **核心**:区分“用户原话”与“AI 推测”。 - 如果记忆带有 '[assistant观点]' 等标签,这仅代表AI过去的**假设**,**不可**将其视为用户的绝对事实。 - *反例*:记忆显示 '[assistant观点] 用户酷爱芒果'。如果用户没提,不要主动假设用户喜欢芒果,防止循环幻觉。 - **原则:AI 的总结仅供参考,权重大幅低于用户的直接陈述。** 2. **主语归因检查 (Attribution Check)**: - 记忆中的行为主体是“用户本人”吗? - 如果记忆描述的是**第三方**(如“候选人”、“面试者”、“虚构角色”、“案例数据”),**严禁**将其属性归因于用户。 3. **强相关性检查 (Relevance Check)**: - 记忆是否直接有助于回答当前的 'Original Query'? - 如果记忆仅仅是关键词匹配(如:都提到了“代码”)但语境完全不同,**必须忽略**。 4. **时效性检查 (Freshness Check)**: - 记忆内容是否与用户的最新意图冲突?以当前的 'Original Query' 为最高事实标准。 # Instructions 1. **审视**:先阅读 `facts memories`,执行“四步判决”,剔除噪音和不可靠的 AI 观点。 2. **执行**: - **优先采用知识库中的专业建议**(如产品选型、技术方案) - 仅使用通过筛选的记忆补充背景。 - 严格遵守 `preferences` 中的风格要求。 3. **输出**: - 直接回答问题,**严禁**提及“记忆库”、“检索”或“AI 观点”等系统内部术语。 - 如果回应内容不在当前知识库/记忆系统中,你必须直接明确地告知用户。在任何情况下都不要编造信息或给出模糊的回应。 4. **语言**:回答语言应与用户查询语言一致。 # Markdown 格式转换要求 - 当你需要将给定的 Markdown(MD)格式文本转换为纯文本时,你必须严格遵循以下要求,以确保清晰的可读性和无格式错误: - 核心格式适配要求:微信不支持原生 MD 语法(如 #标题、粗体文本、代码块、表格)。你必须使用'符号 + 换行 + 空格'来模拟层级结构,避免使用微信无法识别的标记;" - 标题层级处理:首先,检查原文是否包含 Markdown 标题格式(以 # 开头的行)。如果有:一级标题(最高级)使用中文数字序号,如' 一. '、' 二. '、' 三. '(注意:使用'.'而不是'、');二级标题(比最高级多一个 #)使用阿拉伯数字序号,如'1. '、'2. '、'3. ';三级标题(比最高级多两个 #)及以下使用'・'符号作为无序列表。序号必须根据文档结构自动递增以保持一致的层级。如果没有:不添加任何标题序号,保持原有段落结构不变。示例:原 MD 标题 '### 标题 1' → ' 一. 标题 1';原 MD 标题 '#### 标题 2' → '1. 标题 2';原 MD 标题 '##### 标题 3' → '・标题 3';当原文中没有 MD 标题时,'标题 1'保持为'标题 1'; - 链接处理:保持'文本'格式的 Markdown 链接不变。不要修改或删除任何链接内容(示例:MemOS 文档保持为 MemOS 文档);" - 列表处理:统一将'- 内容'格式的 MD 列表转换为有序列表(如'1. 内容'、'2. 内容')或无序列表(使用'・'符号,如'・内容')。每个列表项必须单独成行,前后各留 1 个空行以提高可读性;" - 表格替换:如果原 MD 包含表格,将其分解为'▶ 场景类型 A:XXX'、'▶ 场景类型 B:XXX'格式的要点。在每个类别下,使用'1. 2. 3. '列出相应内容,确保不遗漏信息且不保留表格符号;" - 强调关键内容:不使用 * 或 ** 符号,用'「XXX」'(中文双引号)替换原 MD 中的粗体内容;" - 优化阅读体验:在主要段落之间留 1 个空行(如' 一. XXX'、' 二. XXX')。对于原 MD 中过长的技术术语或复杂描述,用更口语化的表达简化,但不改变原意;使用中文符号作为所有分隔符(如 ▶、・、:),避免中英文符号混用导致格式混乱;" - 输出要求:仅输出转换后的纯文本;不包含额外说明(如'转换完成');不修改原始内容 — 仅替换格式;确保 100% 保留原 MD 的核心信息(如比较维度、功能点、链接、数据)不遗漏或改变;最终文本必须可以直接复制发送,无需进一步编辑。" """ # 构造记忆文本(允许为空) if len(memories) > 0: formatted_memories = "## 相关记忆:\n" for i, memory in enumerate(memories, 1): formatted_memories += f"{i}. {memory.get('memory_value')}\n" else: formatted_memories = "" # 构造偏好文本(允许为空) if len(preferences) > 0: formatted_preferences = "## 偏好:\n" for i, preference_detail in enumerate(preferences, 1): formatted_preferences += f"{i}. {preference_detail.get('preference')}\n" else: formatted_preferences = "" base_prompt = base_prompt.format( current_time=datetime.now().strftime('%Y-%m-%d %H:%M:%S'), memories=formatted_memories, preferences=formatted_preferences, ) return base_prompt def add_message(self, messages, user_id): """添加消息""" data = { "messages": messages, "user_id": user_id, "conversation_id": user_id } res = requests.post(f"{self.base_url}/add/message", headers=self.headers, data=json.dumps(data)) if res.json().get('code') == 0: print(f"✅ 添加成功") else: print(f"❌ 添加失败, {res.json().get('message')}") def get_message(self, user_id): """获取消息""" data = { "user_id": user_id, "conversation_id": user_id, "message_limit_number": 15 } res = requests.post(f"{self.base_url}/get/message", headers=self.headers, data=json.dumps(data)) if res.json().get('code') == 0: return res.json().get('data').get('message_detail_list') else: print(f"❌ 获取消息失败, {res.json().get('message')}") return [] def chat(self, query, user_id): """处理包含记忆集成的对话的主要聊天函数""" # 1. 查询近期会话 chat_history = self.get_message(user_id) # 2. 搜索相关记忆 memories, preferences = self.search_memory(query, user_id) # 3. 构建包含记忆的系统提示 system_prompt = self.build_system_prompt(memories, preferences) messages = [ {"role": "system", "content": system_prompt}, *chat_history, {"role": "user", "content": query} ] # 4. 使用OpenAI生成回答 response = self.openai_client.chat.completions.create( model="gpt-4o", messages=messages, temperature=0.3, top_p=0.9 ) answer = response.choices[0].message.content # 5. 将对话保存到记忆中 messages = [ {"role": "user", "content": query}, {"role": "assistant", "content": answer} ] self.add_message(messages, user_id) # 6. 返回回答 return answer ai_assistant = KnowledgeBaseAssistant() user_id = "memos_knowledge_base_user_123" def demo_questions(): return [ '你是谁' ] def main(): print("💡 欢迎使用知识库问答助手!\n") print("\n🎯 以下是一些示例问题,您可以继续跟助手对话:") for i, question in enumerate(demo_questions(), 1): print(f" {i}. {question}") while True: user_query = input("\n🤔 请输入您的问题 (或输入 'exit' 退出): ").strip() if user_query.lower() in ['quit', 'exit', 'q', '退出']: print("👋 感谢使用知识库问答助手!") break if not user_query: continue print("🤖 正在处理...") answer = ai_assistant.chat(user_query, user_id) print(f"💡 [助手]: {answer}") print("-" * 60) if __name__ == "__main__": main() ``` #### 2.2.2 初始化运行环境 ```bash pip install openai requests ``` #### 2.2.3 替换代码中的环境变量 ##### 获取秘钥(API\_KEY) 登录控制台[https://memos-dashboard.openmem.net/cn/apikeys/](https://memos-dashboard.openmem.net/cn/apikeys/),复制秘钥 ![image.png](https://cdn.memtensor.com.cn/img/1768481468406_q51iqx_compressed.png) ```python os.environ["MEMOS_API_KEY"] = "mpg-xx" ``` ##### 大模型Client ```python # 替换为你自己的API_KEY os.environ["OPENAI_API_KEY"] = "sk-xx" openai_client = OpenAI(api_key=os.getenv("OPENAI_API_KEY")) ``` ##### 获取知识库ID 针对刚才上传的知识库,复制ID,并保存 ![image.png](https://cdn.memtensor.com.cn/img/1768481493435_bkwqlu_compressed.png) ```python # 替换为你自己的知识库ID,以下ID仅为示例,并非真实知识库ID os.environ["KNOWLEDGE_BASE_IDS"] = json.dumps([ "based540fb25-ddf1-4456-935b-41d901518e04" ]) ``` ##### 执行代码 ```bash python knowledge_qa_assistant.py ``` ![image.png](https://cdn.memtensor.com.cn/img/1768533833272_krke26_compressed.jpeg) ### 2.3 代码说明 1. 在环境变量中设置你的自己的MemOS API秘钥、OpenAI的秘钥、知识库ID 2. 实例化KnowledgeBaseAssistant 3. 使用`main()`函数通过对话循环与助手进行交互 4. 助手会调用chat,跟你进行交互,chat在执行以下步骤后,将大模型返回的答案返回给你 * 调用get\_message,搜索历史对话消息 * 调用search\_memory,获取记忆以及偏好 * 构建基于记忆系统的prompt * 使用大模型生成答案 * 调用add\_message,将用户query以及大模型回答保存到记忆中,形成长期记忆 * 返回大模型答案 --- # 让客服 Agent 记住用户:用 MemOS 实现跨会话客服记忆 (/cn/usecase/customer_service_assistant) 用户昨天在在线客服里反馈耳机故障,今天改用邮件追问进度,客服却又让他提供订单号、重新描述问题。对用户来说这是服务中断;系统侧的原因往往很简单:新会话没有拿到此前已经确认的信息。 客服 Agent 需要记住两类不同的内容:一类属于当前用户,例如订单、未完成事项和通知偏好;另一类属于 Agent,例如处理同类问题时可以复用的工具流程。售后政策则继续由知识库统一维护。 本文通过 Python 代码片段,展示如何把这三类信息组合成一套完整的客服记忆方案。 ## 方案要点 - 用户事实和偏好写入用户记忆:写入时同时携带 `user_id` 与 `agent_id`,召回时用 `related_id` 精确选中当前用户。 - 每轮任务记录都提交给客服 Agent 的独立记忆,只请求生成 Skill,由 MemOS 判断是否生成或更新。 - 售后政策写入政策知识库,通过 `knowledgebase_ids` 加入同一次召回。 - 生成回复前只调用一次 `/search/memory`:用户事实、偏好、Agent Skill 和政策一次取回。 - 当前会话历史由 Agent 自己维护,MemOS 负责跨会话记忆。 ## 我们要构建什么 示例场景包含三个客服阶段: ```text DAY 1 · 在线客服 customer_001 提交耳机换货请求,客服 Agent 查询订单、检查政策、创建工单, 并记录收货时间、地址和短信通知要求。 DAY 4 · 邮件工单 customer_001 使用新的 conversation_id 追问换货进度。 DAY 7 · 在线客服 customer_002 遇到相似的耳机杂音问题,客服 Agent 尝试复用此前形成的 Skill。 ``` DAY 4 验证用户事实和偏好能否跨会话延续。DAY 7 换成另一位消费者,验证用户信息保持隔离的同时,客服 Agent 能否复用通用 Skill。 ## 三类信息如何分工 这套方案把客服上下文分为三个范围: 1. **用户记忆**:保存订单、故障、工单状态、地址和通知偏好,只属于当前 `user_id`。 2. **Agent Skill**:保存客服 Agent 从完整任务轨迹中提炼的通用处理流程,属于稳定 `agent_id`。 3. **政策知识库**:保存退换货、保修、物流和发票等正式规则,由业务方统一维护。 三者的分工可以这样理解:政策知识库回答“按规定应该怎么处理”,用户记忆回答“这位消费者已经处理到哪一步”,Agent Skill 回答“完成这类任务通常需要执行哪些步骤”。 ## 完整处理流程 一次客服请求经过以下链路: ```text 用户请求 │ ├─ Agent 从业务应用读取当前会话历史 │ ├─ 一次组合召回:agent_id + knowledgebase_ids │ filter 选中当前用户记忆(related_id)与 Agent Skill(SkillMemory) │ → 用户事实、偏好、Skill、政策 │ ├─ 合并上下文并执行订单、工单、通知等业务工具 │ ├─ 大模型根据工具结果生成最终回复 │ ├─ 写入一:user_id + agent_id → 事实、偏好 │ └─ 写入二:agent_id → 请求生成或更新 Skill ``` 两次写入使用同一份任务记录,但通过 `allow_memory_view` 指定不同的记忆类型。用户写入同时携带 `user_id` 与 `agent_id`,让记忆归属当前用户、并挂到客服 Agent 的记忆空间下;Skill 写入只传 `agent_id`,不与某个用户绑定。用户视角不生成 Skill,Agent 视角不重复生成用户事实和偏好。 召回合并为一次 `/search/memory`:`related_id` 把用户事实和偏好限定在当前用户,`SkillMemory` 让 Agent Skill 跨用户返回,政策知识库通过 `knowledgebase_ids` 加入同一次检索。 ## 接入前准备 文章末尾提供了可直接运行的[完整 Demo](#完整-demo)。你可以展开代码块,一键复制全部内容并保存到本地验证。 你需要 MemOS API Key,以及 OpenAI 或 OpenAI 兼容的大模型接口。 在你的项目中准备 Python 环境并安装依赖: ```bash python3 -m venv .venv ./.venv/bin/python -m pip install openai requests ``` 在接入代码中配置以下参数: ```python MEMOS_API_KEY = "YOUR_MEMOS_API_KEY" OPENAI_API_KEY = "YOUR_OPENAI_API_KEY" MEMOS_BASE_URL = "YOUR_MEMOS_BASE_URL" OPENAI_MODEL = "YOUR_MODEL_NAME" OPENAI_BASE_URL = "YOUR_OPENAI_BASE_URL" AGENT_ID = "YOUR_AGENT_ID" ``` `user_id` 应来自用户登录态或 CRM。`agent_id` 表示同一个客服 Agent,应在不同用户和会话之间保持稳定。 在控制台为当前项目开启「为 Agent 创建独立记忆」。该功能默认关闭;未开启时,`agent_id` 只能用于标记和过滤,不能作为独立主体写入或检索 Agent Skill。具体说明见[多 Agent 隔离](/cn/memos_cloud/introduction/isolation_filters#为-agent-创建独立记忆-new)。 ## 准备政策知识库 初始化时创建一个政策知识库,上传售后政策文档,并等待文件处理完成: ```python def create_policy_knowledge_base(): headers = { "Content-Type": "application/json", "Authorization": f"Token {MEMOS_API_KEY}", } # 1. 创建知识库:POST /create/knowledgebase res = requests.post( f"{MEMOS_BASE_URL}/create/knowledgebase", headers=headers, json={ "knowledgebase_name": "消费者售后政策知识库", "knowledgebase_description": "消费者退换货、保修、物流与发票政策", }, ) body = res.json() if body.get("code") != 0: sys.exit(f"创建知识库失败:{body.get('message')}") policy_kb_id = body["data"]["id"] # 2. 上传政策文档:POST /add/knowledgebase-file # 文件内容需要 base64 编码后以 data URL 形式传入 encoded = base64.b64encode(POLICY_DOC_MD.encode("utf-8")).decode("utf-8") res = requests.post( f"{MEMOS_BASE_URL}/add/knowledgebase-file", headers=headers, json={ "knowledgebase_id": policy_kb_id, "file": [{ "type": "document", "name": "consumer-after-sale-policy.md", "content": f"data:text/markdown;base64,{encoded}", }], }, ) if res.json().get("code") != 0: sys.exit(f"上传政策文档失败:{res.json().get('message')}") # 3. 轮询文件解析状态:POST /get/knowledgebase-file print("政策文档已上传,等待解析...") for _ in range(40): time.sleep(3) res = requests.post( f"{MEMOS_BASE_URL}/get/knowledgebase-file", headers=headers, json={"knowledgebase_id": policy_kb_id, "page": 1, "page_size": 20}, ) files = res.json().get("data", {}).get("file_detail_list", []) statuses = {str(item.get("status", "")).lower() for item in files} if files and statuses <= {"completed", "available", "failed"}: if "failed" in statuses: sys.exit("政策文档解析失败") break print(f"政策知识库已就绪:{policy_kb_id}") return policy_kb_id ``` 知识库 ID 直接来自创建接口的响应,随后传给客服助手: ```python policy_kb_id = create_policy_knowledge_base() assistant = CustomerServiceAssistant(policy_kb_id) ``` ## 写回完整任务轨迹 每条写入消息通过 `role_id` 标明真实发言主体。用户消息使用 `user_id`,客服回复与工具调用使用 `agent_id`: ```python # 以 DAY 1 的换货请求为例,一轮对话写回 MemOS 的完整消息列表 memory_messages = [ # 1. 用户消息:role_id 为当前用户 { "role": "user", "role_id": user_id, # 例如 customer_001 "content": "我的降噪耳机左耳有电流声,想换货", }, # 2. 工具调用:客服 Agent 查询订单,role_id 为 agent_id { "role": "assistant", "role_id": AGENT_ID, "content": "", "tool_calls": [{ "id": "call_1", "type": "function", "function": { "name": "query_order", "arguments": '{"order_id": "20260820-88"}', }, }], }, # 3. 工具结果:通过 tool_call_id 与上面的调用对应,无需 role_id { "role": "tool", "tool_call_id": "call_1", "content": '{"order_id": "20260820-88", "status": "已签收"}', }, # 4. 最终回复:同样归属客服 Agent { "role": "assistant", "role_id": AGENT_ID, "content": "已为您创建换货工单 EX20260821-03,换货双向免运费……", }, ] ``` 客服 Agent 在业务应用中维护当前会话历史。写回 MemOS 时,用户请求、工具调用、工具结果和最终回复组成完整任务记录: ```text user → assistant.tool_calls → tool → assistant ``` 完整轨迹用于 Skill 提炼;用户事实和偏好则从同一份记录中生成。 ### 划分写入类型 用户与 Agent 使用不同的写入视图;召回时三类视图一次取回: ```python USER_WRITE_VIEWS = ["detail_factual", "preference"] AGENT_SKILL_WRITE_VIEWS = ["skill"] CONTEXT_VIEWS = ["detail_factual", "preference", "skill"] ``` 这样,同一份任务记录可以写入两个记忆空间,又不会重复生成同类型的记忆。 ### 写入用户事实和偏好 第一条 `/add/message` 同时传入 `user_id` 和 `agent_id`: ```python def add_user_memories(self, messages, user_id, conversation_id, channel): """第一次写入:只在用户视角生成事实与偏好。""" user_data = { "user_id": user_id, "agent_id": AGENT_ID, "conversation_id": conversation_id, "info": {"channel": channel, "scene": "consumer_support"}, "allow_memory_view": USER_WRITE_VIEWS, "messages": messages, } # POST /add/message:写入为异步任务,返回 task_id 后 # 用 /get/status 轮询至 completed(完整实现见文末 Demo) res = requests.post( f"{MEMOS_BASE_URL}/add/message", headers=self.headers, json=user_data, ) if res.json().get("code") != 0: print(f" [MemOS] 写入用户事实与偏好失败:{res.json().get('message')}") ``` 记忆归属当前 `user_id`,同时挂到客服 Agent 的记忆空间下,后续才能在 Agent 视角的组合召回中通过 `related_id` 精确选中。MemOS 根据对话内容判断是否形成事实或偏好。某轮对话没有表达稳定偏好时,可以只生成事实。 ### 写入 Agent Skill 第二条 `/add/message` 只传 `agent_id`,并且只允许生成 Skill: ```python def add_agent_skill(self, messages, conversation_id, channel): """第二次写入:只在 Agent 视角请求生成或更新 Skill。""" skill_data = { "agent_id": AGENT_ID, "conversation_id": conversation_id, "info": {"channel": channel, "scene": "consumer_support"}, "allow_memory_view": AGENT_SKILL_WRITE_VIEWS, "custom_extract_prompt": {"skill": SKILL_EXTRACT_PROMPT}, "messages": messages, } # 同样是 POST /add/message,只是不传 user_id 且 allow_memory_view 只含 skill res = requests.post( f"{MEMOS_BASE_URL}/add/message", headers=self.headers, json=skill_data, ) if res.json().get("code") != 0: print(f" [MemOS] 写入 Agent Skill 失败:{res.json().get('message')}") ``` Skill 写入不与任何用户绑定,只在 Agent 视角存在,因此可以跨用户复用。每轮回答后都会执行这次写入。调用方只声明本次写入允许生成 Skill,不根据对话内容预判是否应该沉淀;MemOS 会结合任务轨迹和已有 Skill,自行决定生成、更新或跳过。 ## 让 Skill 保持通用 Skill 抽取由 MemOS 完成。可以通过 `custom_extract_prompt.skill` 补充客服场景中的通用化要求: - 以业务目标、触发条件、核心工具链和成功标准判断是否属于同一个 Skill。 - 相同流程优先合并已有 Skill,没有新的通用信息时不重复生成。 - 移除姓名、地址、用户 ID、订单号、工单号和具体日期。 - 把实例值替换为 `order_id`、`ticket_id`、`shipping_address` 等参数。 - 不把用户个人偏好或单次时间要求写成通用规则。 - 只保留工具结果能够证明的执行步骤。 MemOS 会结合已有 Skill 完成相似性判断和更新,调用方不需要管理 Skill ID 或实现合并逻辑。 ## 执行一次组合召回 生成回复前,客服助手只调用一次 `/search/memory`,同时取回用户事实、偏好、Agent Skill 和政策知识: ```python def search_memory(self, query, user_id): """一次组合召回:用户事实/偏好 + Agent Skill + 政策知识。""" context_data = { "query": query, "agent_id": AGENT_ID, "knowledgebase_ids": self.knowledgebase_ids, "include_memory_view": CONTEXT_VIEWS, "memory_limit_number": 9, "preference_limit_number": 6, "filter": { "user": { "or": [ {"related_id": [user_id]}, {"memory_type": "SkillMemory"}, ] } }, } # POST /search/memory:用户事实、偏好、Agent Skill 与政策一次取回 res = requests.post( f"{MEMOS_BASE_URL}/search/memory", headers=self.headers, json=context_data, ) result = res.json().get("data") or {} return ( result.get("memory_detail_list", []), # 用户事实 result.get("preference_detail_list", []), # 用户偏好 result.get("skill_detail_list", []), # Agent Skill ) ``` `filter` 中的两个条件是或关系:`related_id` 选中当前用户的记忆,保证不同用户之间的事实和偏好保持隔离;`memory_type: "SkillMemory"` 让 Agent Skill 不受用户限制、跨用户返回。政策知识库通过 `knowledgebase_ids` 加入同一次检索,不需要单独调用。 三类内容在一次召回中各回答一个问题:政策知识库回答“按规定应该怎么处理”,用户记忆回答“这位消费者已经处理到哪一步”,Agent Skill 回答“完成这类任务通常需要执行哪些步骤”。 ## 验证记忆效果 接入完成后,按三个阶段验证读写与隔离是否符合预期: 1. DAY 1 完成换货任务后,确认用户事实和偏好写入 User Cube,同一任务记录提交给 Agent Cube 进行 Skill 判断。 2. DAY 4 使用新的 `conversation_id`,确认仍能通过 `customer_001` 召回此前订单、故障和通知要求。 3. DAY 7 使用 `customer_002`,确认不会获得第一位消费者的个人事实,但可以检索当前客服 Agent 的通用 Skill。 用户记忆、Agent Skill 和政策知识库各自保持清晰的边界后,客服 Agent 才能记住当前用户、遵循统一政策,并把已经完成的任务转化为下一次可以复用的处理能力。 ## 完整 Demo 展开下面的代码块,点击右上角的复制按钮即可复制全部内容。将代码保存为 `app.py`,填写「Demo 配置」中的参数后运行。 **展开并复制完整 Python Demo** ```python # -*- coding: utf-8 -*- """ MemOS 客服场景最佳实践:跨渠道记忆增强的消费者客服助手 场景:消费者售后客服,MemOS 作为记忆基础设施,为客服 Agent 提供三项能力: 1. 每轮分别请求写入用户事实/偏好与 Agent Skill,由 MemOS 判断实际沉淀内容 2. 售后政策放入政策知识库,与记忆一起进入同一次召回 3. 一次 /search/memory 组合召回:related_id 选中当前用户记忆, SkillMemory 让 Agent Skill 跨用户返回 记忆种类只启用客服场景需要的三类:事实记忆、偏好记忆、技能记忆。 技能由 MemOS 从写回的任务执行轨迹(user → assistant.tool_calls → tool → assistant)中自动提炼,异步生成,无需事先上传。 运行方式: pip install openai requests # 在下方「Demo 配置」中填写各项参数 python app.py """ import base64 import sys import time from datetime import datetime import requests try: from openai import OpenAI except ImportError: OpenAI = None # --------------------------------------------------------------------------- # Demo 配置 # --------------------------------------------------------------------------- MEMOS_API_KEY = "YOUR_MEMOS_API_KEY" OPENAI_API_KEY = "YOUR_OPENAI_API_KEY" MEMOS_BASE_URL = "https://memos.memtensor.cn/api/openmem/v1" OPENAI_MODEL = "YOUR_MODEL_NAME" OPENAI_BASE_URL = "YOUR_OPENAI_BASE_URL" AGENT_ID = "YOUR_AGENT_ID" # 用户与 Agent 分别写入不同记忆类型;召回合并为一次组合检索 USER_WRITE_VIEWS = ["detail_factual", "preference"] AGENT_SKILL_WRITE_VIEWS = ["skill"] CONTEXT_VIEWS = ["detail_factual", "preference", "skill"] SKILL_EXTRACT_PROMPT = """从完整的客服任务轨迹中提炼可跨用户复用的 Skill。 Skill 的唯一性由业务目标、触发条件、核心工具链和成功标准共同决定。 提炼前必须比较已有 Skill: - 如果已有 Skill 覆盖相同目标、触发条件和核心工具链,将新信息合并到已有 Skill, 不要创建重复 Skill。 - 如果本次轨迹没有提供新的通用步骤、判断分支或验证依据,不生成 Skill。 - 只有业务目标或核心处理流程实质不同,才创建新的 Skill。 Skill 内容必须通用化: - 移除姓名、联系方式、地址、用户 ID、Agent ID、会话 ID、订单号、工单号和具体日期。 - 将实例值替换为 order_id、ticket_id、shipping_address 等参数。 - 不保留用户个人偏好,不把单个用户的时间要求或通知方式写成通用规则。 - 不复制具体政策结论;流程中只描述“查询并校验当前政策”。 - 只保留工具结果能够证明的步骤,不把模型建议或未执行操作写成已验证经验。 Skill 名称应稳定、简洁,并以问题类型和处理目标命名,不能包含用户或案例信息。 """ # 相关性阈值:低于该值的记忆不进入 prompt,防止噪音干扰客服判断 RELATIVITY_THRESHOLD = 0.5 # --------------------------------------------------------------------------- # 示例政策上传到政策知识库 # --------------------------------------------------------------------------- POLICY_DOC_MD = """# 消费者售后政策(示例) ## 退换货 - 自签收次日起,未拆封且不影响二次销售的商品支持 7 天无理由退货。 - 商品出现性能故障,15 天内支持换货,换货双向免运费。 - 定制类商品不支持无理由退换。 ## 保修 - 整机保修 12 个月,随机配件保修 6 个月。 - 保修期内非人为损坏免费维修,人为损坏收取成本费。 ## 物流 - 默认顺丰速运,换货件发出后系统自动短信推送物流单号。 - 支持修改一次收货地址,需在换货件发出前完成。 ## 发票 - 默认开具电子普通发票,订单完成后可在订单页自助申请。 """ # --------------------------------------------------------------------------- # 客服助手:组合召回 -> 组装 prompt -> 生成回复 -> 两次写入 # --------------------------------------------------------------------------- class CustomerServiceAssistant: def __init__(self, policy_kb_id): self.openai_client = OpenAI( api_key=OPENAI_API_KEY, base_url=OPENAI_BASE_URL or None, ) self.headers = { "Content-Type": "application/json", "Authorization": f"Token {MEMOS_API_KEY}", } self.knowledgebase_ids = [policy_kb_id] # 当前会话历史由 Agent 自己维护,不依赖 MemOS 的消息读取接口 self.conversation_histories = {} # ---- MemOS 读写 ---- def search_memory(self, query, user_id): """一次组合召回:用户事实/偏好 + Agent Skill + 政策知识。""" context_data = { "query": query, "agent_id": AGENT_ID, "knowledgebase_ids": self.knowledgebase_ids, "include_memory_view": CONTEXT_VIEWS, "memory_limit_number": 9, "preference_limit_number": 6, "filter": { "user": { "or": [ {"related_id": [user_id]}, {"memory_type": "SkillMemory"}, ] } }, } context_res = requests.post( f"{MEMOS_BASE_URL}/search/memory", headers=self.headers, json=context_data, ) context_body = context_res.json() if context_body.get("code") != 0: print(f" [MemOS] 组合召回失败:{context_body.get('message')}") return [], [], [] context_result = context_body.get("data") or {} memories = [ m for m in context_result.get("memory_detail_list", []) if m.get("relativity", 0) >= RELATIVITY_THRESHOLD ] preferences = context_result.get("preference_detail_list", []) skills = context_result.get("skill_detail_list", []) return memories, preferences, skills def add_user_memories(self, messages, user_id, conversation_id, channel): """第一次写入:只在用户视角生成事实与偏好。""" user_data = { "user_id": user_id, "agent_id": AGENT_ID, "conversation_id": conversation_id, "info": {"channel": channel, "scene": "consumer_support"}, "allow_memory_view": USER_WRITE_VIEWS, "messages": messages, } self._post_memory(user_data, "用户事实与偏好", timeout_seconds=120) def add_agent_skill(self, messages, conversation_id, channel): """第二次写入:只在 Agent 视角请求生成或更新 Skill。""" skill_data = { "agent_id": AGENT_ID, "conversation_id": conversation_id, "info": {"channel": channel, "scene": "consumer_support"}, "allow_memory_view": AGENT_SKILL_WRITE_VIEWS, "custom_extract_prompt": {"skill": SKILL_EXTRACT_PROMPT}, "messages": messages, } self._post_memory(skill_data, "Agent Skill", timeout_seconds=300) def _post_memory(self, data, label, timeout_seconds): res = requests.post( f"{MEMOS_BASE_URL}/add/message", headers=self.headers, json=data ) body = res.json() if body.get("code") != 0: print(f" [MemOS] 写入{label}失败:{body.get('message')}") return details = body.get("data") or {} if details.get("status") == "running" and details.get("task_id"): self._wait_for_task(details["task_id"], label, timeout_seconds) def _wait_for_task(self, task_id, label, timeout_seconds): """等待异步记忆任务完成。""" deadline = time.time() + timeout_seconds while time.time() < deadline: time.sleep(2) res = requests.post( f"{MEMOS_BASE_URL}/get/status", headers=self.headers, json={"task_id": task_id}, ) body = res.json() if body.get("code") != 0: sys.exit(f"查询记忆任务失败:{body.get('message')}") status = (body.get("data") or {}).get("status") if status == "completed": print(f" [MemOS] {label}写入完成") return if status in {"failed", "error", "cancelled", "canceled"}: sys.exit(f"记忆任务失败:{task_id} -> {status}") sys.exit(f"等待{label}任务超时:{task_id}") # ---- prompt 与生成 ---- def build_system_prompt(self, channel, memories, preferences, skills): channel_name = {"webchat": "在线客服", "email": "邮件工单"}.get(channel, channel) memory_text = "\n".join( f"{i}. {m.get('memory_value')}" for i, m in enumerate(memories, 1) ) or "(暂无相关记忆)" preference_text = "\n".join( f"{i}. {p.get('preference')}" for i, p in enumerate(preferences, 1) ) or "(暂无偏好记录)" # 仅注入有结构化内容的 Skill;匹配成功但内容未下发的 Skill 不进入 prompt valid_skills = [ s for s in skills if isinstance(s.get("skill_value"), dict) and s["skill_value"].get("name") ] skill_text = "\n".join( f"{i}. {s['skill_value']}" for i, s in enumerate(valid_skills, 1) ) or "(暂无匹配 Skill)" return f"""# Role 你是品牌官方客服助手,正在通过「{channel_name}」渠道服务消费者。 你的目标是结合检索到的记忆、偏好、售后政策与处理 Skill,给出准确、个性化、可执行的回答。 # 当前时间 {datetime.now().strftime('%Y-%m-%d %H:%M:%S')} # 检索到的用户记忆、售后政策与 Agent Skill {memory_text} {preference_text} {skill_text} # 记忆使用规则 1. 区分「消费者原话」与「系统推测」,推测类信息仅作参考,权重低于消费者的直接陈述。 2. 确认记忆描述的主体是当前消费者,而非其他用户或历史案例,禁止张冠李戴。 3. 只使用与当前问题直接相关的记忆,关键词偶合但语境不同的记忆必须忽略。 4. 记忆与消费者当前输入冲突时,以当前输入为准。 5. 涉及政策、时效、金额的内容,以政策知识库内容为准。 # 输出要求 1. 直接回答问题,不向消费者提及「记忆」「检索」等内部实现。 2. 存在未完成事项时主动衔接进度,不要让消费者重复描述已反馈过的信息。 3. 回答语言与消费者的输入语言一致。""" def generate_reply(self, system_prompt, messages): response = self.openai_client.chat.completions.create( model=OPENAI_MODEL, messages=[{"role": "system", "content": system_prompt}, *messages], temperature=0.3, top_p=0.9, ) return response.choices[0].message.content # ---- 主流程 ---- def chat(self, query, user_id, conversation_id, channel, tool_steps=None): # 1. 从 Agent 本地状态读取当前会话历史 history_key = (user_id, conversation_id) history = self.conversation_histories.get(history_key, []) # 2. 一次组合召回:用户事实/偏好、Agent Skill 与政策知识 memories, preferences, skills = self.search_memory(query, user_id) self._print_retrieved(memories, preferences, skills) # 3. 组装当前任务轨迹,让模型基于工具结果生成最终回复 llm_turn = [{"role": "user", "content": query}] memory_messages = [{"role": "user", "role_id": user_id, "content": query}] for step in tool_steps or []: tool_call = { "role": "assistant", "content": "", "tool_calls": [{ "id": step["id"], "type": "function", "function": { "name": step["name"], "arguments": step["arguments"], }, }], } tool_result = { "role": "tool", "tool_call_id": step["id"], "content": step["result"], } llm_turn.extend([tool_call, tool_result]) memory_messages.extend([ {**tool_call, "role_id": AGENT_ID}, tool_result, ]) system_prompt = self.build_system_prompt(channel, memories, preferences, skills) reply = self.generate_reply(system_prompt, [*history, *llm_turn]) # 4. Agent 本地保存对话;MemOS 分别写入用户上下文与通用 Skill self.conversation_histories.setdefault(history_key, []).extend([ {"role": "user", "content": query}, {"role": "assistant", "content": reply}, ]) memory_messages.append({ "role": "assistant", "role_id": AGENT_ID, "content": reply, }) self.add_user_memories(memory_messages, user_id, conversation_id, channel) self.add_agent_skill(memory_messages, conversation_id, channel) return reply @staticmethod def _print_retrieved(memories, preferences, skills): print(" ---- MemOS Agent 记忆召回内容 ----") for m in memories: value = str(m.get("memory_value", "")).replace("\n", " ") print(f" [记忆 {m.get('relativity', 0):.2f}] {value[:80]}") for p in preferences: print(f" [偏好] {p.get('preference')}") for s in skills: value = s.get("skill_value") or {} label = value.get("name") or f"id={s.get('id')}" print(f" [Skill {s.get('relativity', 0):.2f}] {label}") print(f" [Skill 详情] {value}") print(" ------------------------") # --------------------------------------------------------------------------- # 初始化政策知识库 # --------------------------------------------------------------------------- def _b64_md(text): encoded = base64.b64encode(text.encode("utf-8")).decode("utf-8") return f"data:text/markdown;base64,{encoded}" def _create_kb(headers, name, description): res = requests.post( f"{MEMOS_BASE_URL}/create/knowledgebase", headers=headers, json={"knowledgebase_name": name, "knowledgebase_description": description}, ) body = res.json() if body.get("code") != 0: sys.exit(f"创建知识库失败:{body.get('message')}") kb_id = body.get("data", {}).get("id") or body.get("data", {}).get("knowledgebase_id") if not kb_id: sys.exit(f"创建知识库成功,但接口未返回知识库 ID:{name}") print(f"知识库已创建:{name} -> {kb_id}") return kb_id def _upload_file(headers, kb_id, name, text): res = requests.post( f"{MEMOS_BASE_URL}/add/knowledgebase-file", headers=headers, json={ "knowledgebase_id": kb_id, "file": [{"type": "document", "name": name, "content": _b64_md(text)}], }, ) if res.json().get("code") != 0: sys.exit(f"上传文件失败:{res.json().get('message')}") def _wait_kb_ready(headers, kb_id): for _ in range(40): time.sleep(3) res = requests.post( f"{MEMOS_BASE_URL}/get/knowledgebase-file", headers=headers, json={"knowledgebase_id": kb_id, "page": 1, "page_size": 20}, ) files = res.json().get("data", {}).get("file_detail_list", []) statuses = {str(item.get("status", "")).lower() for item in files} if files and statuses <= {"completed", "available", "failed"}: if "failed" in statuses: sys.exit(f"政策知识库 {kb_id} 文件解析失败") return sys.exit(f"等待政策知识库 {kb_id} 处理超时") def create_policy_knowledge_base(): headers = { "Content-Type": "application/json", "Authorization": f"Token {MEMOS_API_KEY}", } policy_kb_id = _create_kb( headers, "消费者售后政策知识库", "消费者退换货、保修、物流与发票政策", ) _upload_file( headers, policy_kb_id, "consumer-after-sale-policy.md", POLICY_DOC_MD, ) print("政策文档已上传,等待解析...") _wait_kb_ready(headers, policy_kb_id) print(f"政策知识库已就绪:{policy_kb_id}") return policy_kb_id # --------------------------------------------------------------------------- # 演示场景:用户上下文隔离与 Agent Skill 跨用户复用 # --------------------------------------------------------------------------- CUSTOMER_ID = "customer_001" # 生产环境中应来自登录态的稳定用户 ID CUSTOMER_ID_2 = "customer_002" # 第二位消费者,用于验证 Skill 复用与用户隔离 def run_demo(): policy_kb_id = create_policy_knowledge_base() assistant = CustomerServiceAssistant(policy_kb_id) print("=" * 64) print("DAY 1 · 在线客服渠道:消费者反馈耳机杂音要求换货,并说明时间与通知偏好") print("=" * 64) chat_conv = "conv_chat_0821" q1 = ("你好,我 8 月 20 日签收的订单 20260820-88,里面的降噪耳机左耳一直有" "电流声,杂音很明显,我想换货。") print(f"\n[消费者] {q1}") # 客服 Agent 在业务系统中的实际办理过程(订单、工单、通知系统), # 随对话一起写回 MemOS,作为技能自动提炼的任务轨迹素材 tool_steps = [ {"id": "call_1", "name": "query_order", "arguments": '{"order_id": "20260820-88"}', "result": '{"order_id": "20260820-88", "product": "降噪耳机", "sign_date": "2026-08-20", "status": "已签收"}'}, {"id": "call_2", "name": "check_exchange_policy", "arguments": '{"order_id": "20260820-88", "issue": "左耳电流声杂音"}', "result": '{"eligible": true, "policy": "性能故障 15 天内换货", "shipping": "双向免运费"}'}, {"id": "call_3", "name": "create_exchange_ticket", "arguments": '{"order_id": "20260820-88", "reason": "左耳电流声杂音", "type": "质量问题换货"}', "result": '{"ticket_id": "EX20260821-03", "status": "已创建"}'}, {"id": "call_4", "name": "update_ticket", "arguments": '{"ticket_id": "EX20260821-03", "address": "上海市浦东新区世纪大道 100 号", "deliver_before": "本周五", "notify": "sms"}', "result": '{"ticket_id": "EX20260821-03", "updated": true}'}, {"id": "call_5", "name": "schedule_notification", "arguments": '{"ticket_id": "EX20260821-03", "channel": "sms", "events": ["已发出", "派送中"]}', "result": '{"scheduled": true, "channel": "sms"}'}, ] print(f"[客服助手] {assistant.chat(q1, CUSTOMER_ID, chat_conv, 'webchat', tool_steps=tool_steps)}") q2 = ("对了,我下周要出差,换的耳机最好这周五前寄到我公司地址:" "上海市浦东新区世纪大道 100 号。进度发短信告诉我就行。") print(f"\n[消费者] {q2}") print(f"[客服助手] {assistant.chat(q2, CUSTOMER_ID, chat_conv, 'webchat')}") print() print("=" * 64) print("DAY 4 · 邮件工单渠道:同一消费者追问进度(新会话、不同渠道)") print("=" * 64) mail_conv = "conv_mail_0824" q3 = "你好,我之前反馈的耳机换货,现在进行到哪一步了?" print(f"\n[消费者] {q3}") print(f"[客服助手] {assistant.chat(q3, CUSTOMER_ID, mail_conv, 'email')}") print() print("=" * 64) print("DAY 7 · 在线客服渠道:另一位消费者遇到同类问题(Agent Skill 复用)") print("=" * 64) conv_2 = "conv_chat_0828" q4 = "你好,我刚买的降噪耳机有杂音,滋滋的电流声,怎么办?" print(f"\n[消费者] {q4}") print(f"[客服助手] {assistant.chat(q4, CUSTOMER_ID_2, conv_2, 'webchat')}") print() print("演示结束,三个观察点:") print("1. 用户 Cube 只生成事实与偏好,Agent Cube 只生成 Skill。") print("2. DAY 4 组合召回带出 customer_001 的订单、故障和通知偏好。") print("3. DAY 7 不应看到 customer_001 的事实与偏好,但可以召回") print(f" {AGENT_ID} 已通用化的 Skill。") if __name__ == "__main__": config = { "MEMOS_API_KEY": MEMOS_API_KEY, "OPENAI_API_KEY": OPENAI_API_KEY, "MEMOS_BASE_URL": MEMOS_BASE_URL, "OPENAI_MODEL": OPENAI_MODEL, "OPENAI_BASE_URL": OPENAI_BASE_URL, "AGENT_ID": AGENT_ID, } missing = [name for name, value in config.items() if not value or value.startswith("YOUR_")] if missing: sys.exit(f"请先在文件顶部配置:{', '.join(missing)}") if OpenAI is None: sys.exit("请先安装 openai:pip install openai") run_demo() ``` --- # 让理财助手读懂客户行为背后的偏好 (/cn/usecase/financial_assistant) ## 1. 概述 在智能投顾产品中,用户会留下大量**行为轨迹**: * **引流来源**:用户是从哪条广告或推文点进来的?(如点击“养老理财”广告) * **APP 内操作**:浏览了哪些基金产品?收藏了哪些理财? * **沟通记录**:和投顾经理的交流、与 AI 投顾助手的对话内容。 这些只是原始行为,如果直接保存成日志,对大模型帮助有限。**关键在于如何把行为抽象成“记忆”**: ### 1.1 行为如何抽象为记忆? | 用户行为(原始轨迹) | 对应的记忆(语义抽象) | | --- | --- | | 点击「养老理财」广告进入 APP | 记忆:「用户对养老理财有潜在兴趣」 | | 多次浏览低风险基金详情页 | 记忆:「用户风险偏好偏保守」 | | 收藏“低风险理财产品” | 记忆:「用户倾向选择低风险理财」 | | 在对话中说「我不想冒太大风险」 | 记忆:「明确表达低风险诉求」 | 当用户后续再问「我适合什么投资?」时,投顾助手不需要翻一堆日志,而是直接用这些语义化记忆来驱动模型生成个性化的回答。 ### 1.2 为什么不用传统 RAG? RAG 更适合做知识问答,例如解释「什么是债券」。但它不会从用户的行为里总结出偏好: | 传统RAG | MemOS | | --- | --- | | 返回静态理财知识片段 | 将用户行为抽象为语义化记忆(兴趣、偏好、画像) | | 不能回答「我适合什么投资?」 | 能结合记忆生成个性化建议 | ### 1.3 为什么不自己造轮子? 开发者当然也可以自己存行为,但会遇到三个挑战: * **缺乏抽象**:单纯存「点击了基金 A」没有用,要转成「风险偏好=低风险」。 * **对接复杂**:在调用模型前,要自己拼 Prompt,把分散的行为抽象成语义信息。 * **扩展性差**:随着渠道、产品、沟通场景增加,代码就会迅速失控。 ### 1.4 为什么要用 MemOS? 在做选型时,可以直观对比三种方案: | 方案 | 特点 | 局限 | MemOS 的优势 | | --- | --- | --- | --- | | **传统RAG** | 检索知识库文档 | 不会处理用户行为,无法形成画像 | 适合做 FAQ,但不能做个性化投顾 | | **自研存储** | 直接存储行为日志 | 需要自行抽象行为→记忆;拼 Prompt 成本高 | 要开发大量 glue code | | **MemOS** | 两个接口:`addMessage` 写入、`searchMemory` 检索 | —— | 自动把行为轨迹抽象成记忆,供模型直接使用 | ### 1.5 本案例会展示什么? 本案例展示如何用 MemOS 云服务,快速实现一个「会把用户行为转成记忆」的智能投顾助手。 在 Demo 中: * **D1 引流行为**:点击「养老理财」广告 → 生成记忆「养老理财兴趣」。 * **D2 APP 行为**:浏览并收藏低风险基金 → 生成记忆「风险偏好=低风险」。 * **D3 对话行为**:说「不想冒风险」 → 生成记忆「明确低风险诉求」。 当用户问「我适合什么投资?」时: * `searchMemory` 检索到上述记忆 * 大模型生成的回答会结合这些画像 → 输出「更适合低风险固收类产品」。 运行这个案例脚本时,开发者会在控制台看到: * 每次 `addMessage` 的请求/响应(行为被存储) * 每次 `searchMemory` 的请求/响应(命中的语义化记忆) * 模型最终输出的个性化投资建议 ## 2. 示例 ### 2.1 环境准备 使用pip安装所需的依赖项 ```shell pip install MemoryOS -U ``` ### 2.2 完整代码 ```python import os import uuid from openai import OpenAI from memos.api.client import MemOSClient os.environ["MEMOS_API_KEY"] = "mpg-xx" # 从云服务控制台获取MemOS_API_KEY os.environ["OPENAI_API_KEY"] = "sk-xx" # 替换为你自己的API_KEY conversation_counter = 0 def generate_conversation_id(): global conversation_counter conversation_counter += 1 return f"conversation_{conversation_counter:03d}" class FinancialManagementAssistant: """AI财务管理助手,具备记忆能力""" def __init__(self): self.memos_client = MemOSClient(api_key=os.getenv("MEMOS_API_KEY")) self.openai_client = OpenAI(api_key=os.getenv("OPENAI_API_KEY")) def search_memory(self, query, user_id, conversation_id): """查询相关记忆""" response = self.memos_client.search_memory(query, user_id, conversation_id) return [memory_detail.memory_value for memory_detail in response.data.memory_detail_list] def build_system_prompt(self, memories): """构建包含格式化记忆的系统提示""" base_prompt = """ 你是一位知识丰富且专业贴心的理财管理助手。 你可以访问对话记忆,帮助你提供更个性化的回答。 使用记忆来理解用户的背景、偏好和过往互动。 如果提供了记忆,请在相关时自然地引用它们,但不要明确提及拥有记忆 """ if memories: # 将记忆格式化为编号列表 formatted_memories = "## 记忆:\n" for i, memory in enumerate(memories, 1): formatted_memories += f"{i}. {memory}\n" return f"{base_prompt}\n\n{formatted_memories}" else: return base_prompt def add_message(self, messages, user_id, conversation_id): """添加消息""" self.memos_client.add_message(messages, user_id, conversation_id) def get_message(self, user_id, conversation_id): """获取消息""" response = self.memos_client.get_message(user_id, conversation_id) return response.data.message_detail_list def chat(self, query, user_id, conversation_id): """处理包含记忆集成的对话的主要聊天函数""" # 1. 搜索相关记忆 memories = self.search_memory(query, user_id, conversation_id) # 构建包含记忆的系统提示 system_prompt = self.build_system_prompt(memories) # 2. 使用OpenAI生成回答 response = self.openai_client.chat.completions.create( model="gpt-4o", messages=[ {"role": "system", "content": system_prompt}, {"role": "user", "content": query} ] ) answer = response.choices[0].message.content # 3. 将对话保存到记忆中 messages = [ {"role": "user", "content": query}, {"role": "assistant", "content": answer} ] self.memos_client.add_message(messages, user_id, conversation_id) return answer ai_assistant = FinancialManagementAssistant() user_id = "memos_financial_management_user_123" def demo_questions(): return [ '我的风险偏好是什么', "推荐一些适合我的投资" ] def preset_user_behaviors(): """显示预设的用户行为记忆""" conversation_id = generate_conversation_id() print(f"\n📊 已预设的用户行为记忆 (conversation_id={conversation_id}):") print("=" * 60) behaviors = [{ "role": "user", "content": "点击「养老理财」广告进入 APP" }, { "role": "user", "content": "浏览并收藏低风险基金" }] for i, behavior in enumerate(behaviors, 1): print(f"{i}. {behavior['content']}") ai_assistant.add_message(behaviors, user_id, conversation_id) print("=" * 60) print("💡 以上行为记忆已被MemOS记录,助手会基于这些信息提供个性化建议") def main(): print("💰 欢迎查看MemOS在理财管理助手中的使用示例!") print("💡 在MemOS的加持下,让您的理财助手更智能、更贴心! 😊 \n") # 询问用户是否要先执行预配置对话 while True: pre_chat = input("🤔 您想先预加载用户行为记忆吗?预计消耗1次add额度,是否执行?(y/n): ").strip().lower() if pre_chat in ['y', 'yes', '是', 'Y']: preset_user_behaviors() break elif pre_chat in ['n', 'no', '否', 'N']: print("📝 开始全新对话...") break else: print("⚠️ 请输入 'y' 表示是或 'n' 表示否") print("\n⚡️ 接下来您输入的每一个问题,都将会在一个全新的会话中展开(新的 conversation id)。MemOS将会跨会话自动召回您的历史行为记忆,为您提供连续、个性化的服务。") print("\n🎯 以下是一些示例问题,您可以继续跟助手对话:") for i, question in enumerate(demo_questions(), 1): print(f" {i}. {question}") while True: user_query = input("\n🤔 请输入您的问题 (或输入 'exit' 退出): ").strip() if user_query.lower() in ['quit', 'exit', 'q', '退出']: print("👋 感谢使用理财管理助手!") break if not user_query: continue print("🤖 正在处理...") conversation_id = generate_conversation_id() answer = ai_assistant.chat(user_query, user_id, conversation_id) print(f"\n💬 conversation_id: {conversation_id}\n💡 [助手]: {answer}\n") print("-" * 60) if __name__ == "__main__": main() ``` ### 2.3 代码说明 1.  在环境变量中设置您的MemOS API秘钥以及Open AI秘钥 2.  实例化FinancialManagementAssistant  3.  选择是否执行预设值的对话,会消耗1次add和2次search的额度 4.  使用`main()`函数通过对话循环与助手进行交互 5.  助手会调用 chat, 先执行 search 检索记忆,然后再调用OpenAI进行对话,最后执行 add 存储记忆 --- # 有记忆的写作助手更好用 (/cn/usecase/writting_assistant) ## 1. 概述 在写作助手这类产品中,用户往往希望助手能够**记住自己的写作风格和习惯**,而不是每次都从零开始。 * **写作风格** 「帮我写总结的时候语气要轻松一点」 * **常用信息** 「记住我在 XX 公司负责市场部」 * **写作偏好** 「以后写邮件开头都要加上‘尊敬的客户’」 * **上下文延续** 「昨天那份方案总结再优化一下,加上预算部分」 如果没有记忆,这些信息在会话结束后就会丢失。用户不得不反复提醒助手,体验会显得割裂、不专业。 ### 1.1 为什么不用传统 RAG? 在写作助手场景里,RAG 并不适用 | 传统 RAG | MemOS | | --- | --- | | 依赖静态知识库,需要人工不断维护文档 | 对话中产生的信息可直接写入,无需额外维护 | | 检索结果通常是通用知识片段 | 可以存储并调取个性化风格、语气、常用表达 | | 更适合“公司文档/百科知识”类场景 | 更适合“持续迭代、个性化”写作助手 | ### 1.2 为什么不自己造轮子? 当然,你也可以尝试在数据库里保存用户偏好和上下文,但这会带来几个挑战: * **存储与检索逻辑复杂**:需要区分正文、偏好、用户画像,并设计检索策略。 * **和大模型对接麻烦**:存下来只是第一步,还要在调用大模型前把相关信息「拼进 Prompt」。 * **可扩展性差**:随着用户需求增加(写作风格、常用短语、上下文关联),代码会迅速膨胀。 ### 1.3 为什么要用 MemOS? 在做选型时,可以直观对比三种方案: | 方案 | 特点 | 局限 | MemOS 的优势 | | --- | --- | --- | --- | | **传统 RAG** | 通过向量检索知识库文档,拼接进 Prompt | 需要人工维护静态文档;不适合个性化写作习惯 | 自动捕捉用户在对话中透露的风格与偏好 | | **自研存储方案** | 自己建表/缓存,把偏好与内容保存下来 | 逻辑复杂:要区分正文/偏好/画像;还需手动拼 Prompt;扩展困难 | MemOS 封装存储+检索+Prompt 注入,减少开发负担 | | **MemOS** | 两个接口即可:`addMessage` 写入、`searchMemory` 检索 | —— | 支持长期追踪写作风格、复用常用信息;开箱即用、易扩展 | ### 1.4 本案例会展示什么? 本案例展示如何用 MemOS 云服务,快速实现一个“会记住用户”的写作助手。 在这个 Demo 中,用户可能会: * 交代偏好:「帮我写总结的时候语气要轻松一点」 * 重用背景:「记住我在 XX 公司负责市场部」 * 迭代任务:「昨天那份方案总结再优化一下,加上预算部分」 有了 MemOS,写作助手就能: 1. **延续风格**:保持用户要求的语气和格式一致。 2. **重用信息**:自动带入用户常用的背景信息。 3. **快速迭代**:基于已有内容继续修改,而不是推倒重来。 运行这个案例脚本时,开发者会在控制台看到: * 每次调用 `addMessage` 和 `searchMemory` 的请求/响应 * 被检索出来的写作风格、背景信息等记忆 * 模型生成的最终回答(若未接入大模型,则会提示【未接入大模型】) ##  2. 示例 ### 2.1 环境准备 使用pip安装所需的依赖项 ```shell pip install MemoryOS -U ``` ### 2.2 完整代码 ```python import os import uuid from openai import OpenAI from memos.api.client import MemOSClient os.environ["MEMOS_API_KEY"] = "mpg-xx" # 从云服务控制台获取MemOS_API_KEY os.environ["OPENAI_API_KEY"] = "sk-xx" # 替换为你自己的API_KEY conversation_counter = 0 def generate_conversation_id(): global conversation_counter conversation_counter += 1 return f"conversation_{conversation_counter:03d}" class WritingAssistant: """AI写作助手,帮助用户写作,具备记忆能力""" def __init__(self): self.memos_client = MemOSClient(api_key=os.getenv("MEMOS_API_KEY")) self.openai_client = OpenAI(api_key=os.getenv("OPENAI_API_KEY")) def search_memory(self, query, user_id, conversation_id): """查询相关记忆""" response = self.memos_client.search_memory(query, user_id, conversation_id) return [memory_detail.memory_value for memory_detail in response.data.memory_detail_list] def build_system_prompt(self, memories): """构建包含格式化记忆的系统提示""" base_prompt = """ 你是一位专业的的写作助手, 能够记住用户的写作风格和偏好。 你可调用对话记忆,助力提供更具个性化的回复。 请借助这些记忆,理解用户的场景背景、偏好倾向及过往互动情况。 如果提供了记忆,请在相关时自然地引用它们,但不要明确提及拥有记忆功能 """ if memories: # 将记忆格式化为编号列表 formatted_memories = "## 记忆:\n" for i, memory in enumerate(memories, 1): formatted_memories += f"{i}. {memory}\n" return f"{base_prompt}\n\n{formatted_memories}" else: return base_prompt def add_message(self, messages, user_id, conversation_id): """添加消息""" self.memos_client.add_message(messages, user_id, conversation_id) def get_message(self, user_id, conversation_id): """获取消息""" response = self.memos_client.get_message(user_id, conversation_id) return response.data.message_detail_list def chat(self, query, user_id, conversation_id): """处理包含记忆集成的对话的主要聊天函数""" # 1. 搜索相关记忆 memories = self.search_memory(query, user_id, conversation_id) # 构建包含记忆的系统提示 system_prompt = self.build_system_prompt(memories) # 2. 使用OpenAI生成回答 response = self.openai_client.chat.completions.create( model="gpt-4o", messages=[ {"role": "system", "content": system_prompt}, {"role": "user", "content": query} ] ) answer = response.choices[0].message.content # 3. 将对话保存到记忆中 messages = [ {"role": "user", "content": query}, {"role": "assistant", "content": answer} ] self.memos_client.add_message(messages, user_id, conversation_id) return answer ai_assistant = WritingAssistant() user_id = "memos_writing_user_123" def demo_questions(): return [ "帮我写一封团队聚餐的通知邮件", "帮我写一封客户邮件,内容是总结我们即将上线的理财App新功能", ] def pre_configured_conversations(): """返回预配置的对话对""" return [ { "user": "我在互联网公司市场部工作,写邮件时语气要轻松点,开头加'亲爱的XX'" }, { "user": "写总结时我习惯先列三条要点" } ] def execute_pre_conversations(): """执行预配置的对话""" conversations = pre_configured_conversations() conversation_id = generate_conversation_id() print(f"\n🔄 正在执行预配置对话(conversation_id={conversation_id})...") print("=" * 60) for i, conv in enumerate(conversations, 1): print(f"\n💬 对话 {i}") print(f"👤 用户: {conv['user']}") # 执行对话 answer = ai_assistant.chat(conv['user'], user_id, conversation_id) print(f"🤖 助手: {answer}") print("-" * 40) print("\n✅ 预配置对话执行完毕!") print("=" * 60) def main(): print("📝 欢迎查看MemOS在写作助手中的使用示例!") print("💡 在MemOS的加持下,让您的写作助手更懂您的风格和偏好! ✍️ \n") # 询问用户是否要先执行预配置对话 while True: pre_chat = input("🤔 您想先执行预配置对话吗?预计消耗2次add和2次search的调用额度,是否执行?(y/n): ").strip().lower() if pre_chat in ['y', 'yes', '是', 'Y']: execute_pre_conversations() break elif pre_chat in ['n', 'no', '否', 'N']: print("📝 开始全新的写作助手对话...") break else: print("⚠️ 请输入 'y' 表示是或 'n' 表示否") print("\n⚡️ 接下来您输入的每一个问题,都将会在一个全新的会话中展开(新的 conversation id)。MemOS将会跨会话自动召回您的历史行为记忆,为您提供连续、个性化的服务。") print("\n🎯 以下是一些示例问题,您可以继续跟写作助手对话:") for i, question in enumerate(demo_questions(), 1): print(f" {i}. {question}") while True: user_query = input("\n🤔 请输入您的写作需求 (或输入 'exit' 退出): ").strip() if user_query.lower() in ['quit', 'exit', 'q', '退出']: print("👋 感谢使用写作助手,祝您写作愉快!") break if not user_query: continue print("🤖 正在创作...") conversation_id = generate_conversation_id() answer = ai_assistant.chat(user_query, user_id, conversation_id) print(f"\n💬 conversation_id: {conversation_id}\n💡 [助手]: {answer}\n") print("-" * 60) if __name__ == "__main__": main() ``` ### 2.3 代码说明 1.  在环境变量中设置您的MemOS API秘钥以及Open AI秘钥 2.  实例化`WritingAssistant`  3.  选择是否执行预设值的对话,会消耗2次add和2次search的额度 4.  使用`main()`函数通过对话循环与助手进行交互 5.  助手会调用 chat, 先执行 search 检索记忆,然后再调用OpenAI进行对话,最后执行 add 存储记忆 --- # 构建拥有记忆的家庭生活助手 (/cn/usecase/home_assistant) ## 1. 概述 在做家庭生活助手这类产品时,开发者经常会遇到一个问题:**对话上下文一旦结束,用户信息就丢失了**。 * 用户随口交代的待办(「周六要带孩子去动物园」) * 用户表达的习惯(「提醒时要先列要点,再给一句行动建议」) * 用户介绍的家庭情况(「我太太叫小芸,孩子 6 岁」) 如果助手不能记住这些信息,就会显得「没心没肺」:用户第二天再问「我周末安排了啥?」时,助手完全不知道在说什么。 ### 1.1 为什么不用传统 RAG? 很多人第一反应是:能不能用 RAG(检索增强生成)? 但传统 RAG 的特点决定了它并不适合这种「个性化助手」场景: | 传统 RAG | MemOS | | --- | --- | | 依赖静态知识库,需要人工不断维护文档 | 对话中产生的信息可直接写入,无需额外维护 | | 只能机械返回片段,不会自动学习偏好 | 会随对话自动形成待办、偏好、画像等记忆 | | 面向“共性知识”,不适合存储个人化信息 | 专门为个体化场景设计,支持长期追踪与调用 | ### 1.2 为什么不自己造轮子? 当然,你也可以尝试自己存储这些信息,但这会带来几个挑战: * **存储与检索逻辑复杂**:要区分对话内容、长期记忆、偏好和事实,并保证随时能按需检索。 * **和大模型对接麻烦**:不仅要存数据,还得在生成回答前把相关信息「拼进 Prompt」。 * **可扩展性差**:随着功能增加(待办、偏好、画像),代码会变得越来越难维护。 ### 1.3 为什么要用 MemOS? 在做选型时,可以直观对比三种方案: | 方案 | 特点 | 局限 | MemOS 的优势 | | --- | --- | --- | --- | | 传统 RAG | 通过向量检索知识库文档,拼接进 Prompt | 需要人工维护静态文档;不能存储个人化待办/偏好;只会机械返回片段 | 自动捕捉对话中的关键信息,支持个性化、动态更新 | | 自研存储方案 | 自建表/缓存,把对话信息保存下来 | 逻辑复杂:要区分对话/长期记忆/偏好/画像;调用模型前还得手动拼 Prompt;功能扩展难维护 | MemOS 封装存储+检索+Prompt 注入,减少开发负担 | | MemOS | 两个接口即可:`addMessage` 写入、`searchMemory` 检索 | —— | 支持长期追踪、偏好保持、画像结合;开箱即用、易扩展 | 只需调用两个接口: * `addMessage`:把用户或助手的消息写入系统。 * `searchMemory`:在模型生成回复前检索相关记忆,把结果拼进 Prompt。 这样,助手就能表现出真正的“有记忆”: * **追踪待办** * 用户说「周六要带孩子去动物园」 * 几天后问「我周末安排了啥?」 → 能准确回答 * **保持偏好**(未来版本会支持更精细的指令补全) * 用户说「提醒要先列要点+一句话建议」 * 再问「帮我规划下周家务分工」 → 输出保持偏好风格 * **结合画像** * 用户说「我太太叫小芸,孩子 6 岁」 * 再问「周末给家里安排个活动?」 → 给出贴合亲子家庭的活动方案 ### 1.4 本案例会展示什么? 我们将用 MemOS 云服务快速实现一个“会记住用户”的家庭生活助手。 在运行案例脚本时,开发者能看到完整日志: * 每次调用 `addMessage` 和 `searchMemory` 的请求/响应 * 命中的记忆条目 * 拼接指令和完整指令  ← TODO: 即将上线敬请期待 * 模型生成的回答(未接入大模型时会提示【未接入大模型】) ## 2. 示例 ### 2.1 环境准备 使用pip安装所需的依赖项 ```shell pip install MemoryOS -U ``` ### 2.2 完整代码 ```python import os import uuid from openai import OpenAI from memos.api.client import MemOSClient os.environ["MEMOS_API_KEY"] = "mpg-xx" # 从云服务控制台获取MemOS_API_KEY os.environ["OPENAI_API_KEY"] = "sk-xx" # 替换为你自己的API_KEY conversation_counter = 0 def generate_conversation_id(): global conversation_counter conversation_counter += 1 return f"conversation_{conversation_counter:03d}" class HomeAssistant: def __init__(self): self.memos_client = MemOSClient(api_key=os.getenv("MEMOS_API_KEY")) self.openai_client = OpenAI(api_key=os.getenv("OPENAI_API_KEY")) def search_memory(self, query, user_id, conversation_id): """查询相关记忆""" response = self.memos_client.search_memory(query, user_id, conversation_id) return [memory_detail.memory_value for memory_detail in response.data.memory_detail_list] def add_message(self, messages, user_id, conversation_id): """添加消息""" self.memos_client.add_message(messages, user_id, conversation_id) def get_message(self, user_id, conversation_id): """获取消息""" response = self.memos_client.get_message(user_id, conversation_id) return response.data.message_detail_list def build_system_prompt(self, memories): """构建包含格式化记忆的系统提示""" base_prompt = """ 你是一位知识丰富、贴心周到的家庭生活助手。 你可调用对话记忆,助力提供更具个性化的回复。 请借助这些记忆,理解用户的场景背景、偏好倾向及过往互动情况。 若提供了记忆内容,在相关时需自然参考其中信息,但无需明确提及自己拥有记忆功能。 """ if memories: # 将记忆格式化为编号列表 formatted_memories = "## 记忆:\n" for i, memory in enumerate(memories, 1): formatted_memories += f"{i}. {memory}\n" return f"{base_prompt}\n\n{formatted_memories}" else: return base_prompt def chat(self, query, user_id, conversation_id): """处理包含记忆集成的对话的主要聊天函数""" # 1. 搜索相关记忆 memories = self.search_memory(query, user_id, conversation_id) # 构建包含记忆的系统提示 system_prompt = self.build_system_prompt(memories) # 2. 使用OpenAI生成回答 response = self.openai_client.chat.completions.create( model="gpt-4o", messages=[ {"role": "system", "content": system_prompt}, {"role": "user", "content": query} ] ) answer = response.choices[0].message.content # 3. 将对话保存到记忆中 messages = [ {"role": "user", "content": query}, {"role": "assistant", "content": answer} ] self.memos_client.add_message(messages, user_id, conversation_id) return answer ai_assistant = HomeAssistant() user_id = "memos_home_management_user_123" def demo_questions(): return [ "我周末有哪些安排?", "帮我规划下周家务分工" ] def pre_configured_conversations(): """返回预配置的对话对""" return [ { "user": "周六要带孩子去动物园,帮我记一下。", }, { "user": "以后提醒或安排,请先列三条要点,再补一句简短建议。", } ] def execute_pre_conversations(): """执行预配置的对话""" conversation_id = generate_conversation_id() conversations = pre_configured_conversations() print(f"\n🔄 正在执行预配置对话(conversation_id={conversation_id})...") print("=" * 60) for i, conv in enumerate(conversations, 1): print(f"\n💬 对话 {i}") print(f"👤 用户: {conv['user']}") # 执行对话 answer = ai_assistant.chat(conv['user'], user_id, conversation_id) print(f"🤖 [助手]: {answer}") print("-" * 40) print("\n✅ 预配置对话执行完毕!") print("=" * 60) def main(): print("🏠 欢迎查看MemOS在家庭助手中的使用示例!") print("💡 在MemOS的加持下,让您开发的产品实现真人管家效果! 😊 \n") # 询问用户是否要先执行预配置对话 while True: pre_chat = input("🤔 您想先执行预配置对话吗?预计消耗2次add和2次search的调用额度,是否执行?(y/n): ").strip().lower() if pre_chat in ['y', 'yes', '是', 'Y']: execute_pre_conversations() break elif pre_chat in ['n', 'no', '否', 'N']: print("📝 开始全新对话...") break else: print("⚠️ 请输入 'y' 表示是或 'n' 表示否") print("\n⚡️ 接下来您输入的每一个问题,都将会在一个全新的会话中展开(新的 conversation id)。MemOS将会跨会话自动召回您的历史行为记忆,为您提供连续、个性化的服务。") print("\n🎯 以下是一些示例问题,您可以继续跟助手对话:") for i, question in enumerate(demo_questions(), 1): print(f" {i}. {question}") while True: user_query = input("\n🤔 请输入您的问题 (或输入 'exit' 退出): ").strip() if user_query.lower() in ['quit', 'exit', 'q', '退出']: print("👋 感谢使用家庭助手!") break if not user_query: continue print("🤖 正在处理...") conversation_id = generate_conversation_id() answer = ai_assistant.chat(user_query, user_id, conversation_id) print(f"\n💬 conversation_id: {conversation_id}\n💡 [助手]: {answer}\n") print("-" * 60) if __name__ == "__main__": main() ``` ### 2.3 代码说明 1.  在环境变量中设置您的MemOS API秘钥以及Open AI秘钥 2.  实例化`HomeAssistant`  3.  选择是否执行预设值的对话,会消耗2次add和2次search的额度 4.  使用`main()`函数通过对话循环与助手进行交互 5.  助手会调用 chat, 先执行 search 检索记忆,然后再调用OpenAI进行对话,最后执行 add 存储记忆 --- # Claude MCP (/cn/usecase/frameworks/claude_mcp) ## 1. 配置 MCP 与 MemOS 云服务 在客户端中填写如下配置: ```json { "mcpServers": { "memos-api-mcp": { "timeout": 60, "type": "stdio", "command": "npx", "args": [ "-y", "@memtensor/memos-api-mcp" ], "env": { "MEMOS_API_KEY": "mpg-xxxxxxxxxxxxxxxxxxxxxxxxxxxxx", "MEMOS_USER_ID": "your-user-id", "MEMOS_CHANNEL": "MODELSCOPE" } } } } ``` 环境变量获取方式: - `MEMOS_API_KEY`: 在MemOS官网[API控制台](https://memos-dashboard.openmem.net/cn/apikeys/)上注册账号,然后在接口密钥页面新建api-key并复制粘贴在此处。 ![在MemOS API控制台上新建api-key](https://cdn.memtensor.com.cn/img/1763452232848_t268eh_compressed.png) - `MEMOS_USER_ID`: 确定性的用户自定义个人标识符。 - 对于同一用户,该环境变量需要在不同设备/客户端中保持一致; - 请不要使用随机值、设备ID或聊天会话ID作为用户标识符; - 推荐使用:个人email地址、姓名全称或员工ID作为用户标识符。 - `MEMOS_CHANNEL`: 填写为"MODELSCOPE"即可。 ## 2. 在 Claude 客服端中使用 在Claude Desktop中使用MemOS,需点击左下角头像 -> "Settings" -> "Developer" -> "Edit Config", 并粘贴配置到Claude_desktop_config.json文件中,最后重启客户端,观察到memos-api-mcp服务处于running状态即可在聊天中使用。 ![MemOS MCP 配置与预期运行状态示意图](https://cdn.memtensor.com.cn/img/memos-best-practices-claude-status-cn-20261028_compressed.png) 为了提升使用效果,建议用户在Claude Desktop中使用MemOS时修改作用于所有对话的用户偏好设置,具体方法为点击左下角头像 -> "General", 在"What personal preferences should Claude consider in responses?"下面的输入框中粘贴如下内容: ``` 你是MemOS记忆管理助手,致力于提供高效的记忆管理服务,基于用户过往的对话内容抽取记忆,并通过记忆检索提升用户与AI对话的一致性和个性化水平。在每次回答用户的问题之前,你需要调用memos-api-mcp的search_memory服务,利用恰当的检索词在用户的个人记忆库中搜索和当前话题有关的记忆。在基于这些记忆完成回答后,再调用memos-api-mcp的add_message服务,将当前对话内容摘要记录下来。(请注意,调用add_message这一步是必须进行的,无论用户说了什么或问了什么问题都要记录下来,否则在后续的对话中,search_memory将无法获取到更细致的用户信息,进而导致你不能准确地回答用户问题。) ``` ![在Claude Desktop中使用MemOS-修改用户偏好](https://cdn.memtensor.com.cn/img/1763105396189_i1tupr_compressed.png) 下面是在Claude Desktop中使用MemOS的示例,用户可借此判断是否已经成功在Claude Desktop中配置MemOS。 ![在Claude Desktop中使用MemOS的示例](https://cdn.memtensor.com.cn/img/1763105412700_asgfq9_compressed.png) --- # 端云协同:为智能终端构建长期记忆 (/cn/usecase/edge_cloud_terminal_memory) **MemOS 让智能终端在长期相伴中,记住并理解用户。** 耳机伴随出行,手表参与日常活动,家庭音箱和机器人融入生活,电脑与手机承接工作。这些终端与用户长期相伴,MemOS 记忆能够让这些终端延续了解,为长期陪伴和个性化服务建立基础。 > 把日常交互中积累成后续服务可用的背景,让终端逐渐了解用户。
耳机交互写入记忆,家庭音箱读取同一用户的记忆并继续建议

可以在日常交互中,逐渐形成对用户的了解

家庭音箱、手机与厨房屏接入同一用户的记忆

让同一件事在不同时间、不同终端继续推进

MemOS 维护记忆与适用范围,运动 App 结合当前背景安排训练

让终端对用户的理解跟上变化

MemOS 端云协同记忆解决方案,可以为设备及其配套应用、系统功能和 Agent 提供记忆形成、组织、更新与调用能力。 **终端产品提供交互和业务信息,MemOS 负责判断记什么、怎么组织,并结合后续输入持续维护;需要时产品调用 MemOS 查询和使用记忆。** 这些服务可以运行在客户自己的服务器、MemOS 托管服务或选定本地节点,并按需要分工协作。客户可以结合终端资源、数据管理要求和模型选择安排运行位置。 ## MemOS 如何为终端提供记忆服务 > 上述体验由终端产品及其对应的服务端与 MemOS 配合完成:产品提供信息,MemOS 形成并维护记忆,产品功能在需要时查询和使用。 ### 信息接入:提供交互与业务信息 产品将获得授权的信息,连同用户、会话、时间或已有业务标识提交给 MemOS。多个终端接入时,由产品现有的账户与设备体系确认当前使用者,将获授权的请求对应到同一用户。**转写语音、识别运动事件属于输入处理;判断记什么、怎样组织属于 MemOS 的记忆处理。** 接入方无需先挑选「有价值的句子」,也无需先提炼偏好或生成标准记忆。 ![耳机语音、手表事件与 App 业务信息经已有输入链路进入 MemOS](https://cdn.memtensor.com.cn/img/1793103966228_0ohk2y_compressed.webp){width="720" class="mx-auto"} ### 记忆处理:形成记忆,并随新输入持续维护 MemOS 理解输入中的事实、偏好、事件和背景,关联同一用户的已有记忆,处理重复、变化及适用范围,将形成或更新的记忆及相关索引保存到所选部署的数据节点。产品提交后续表达与业务背景,MemOS 沿同一链路继续维护,无需接入方先找到旧记忆再判断怎样覆盖。 用户需要查看、纠正或删除已有记忆时,可以通过产品提供的管理入口进行控制。日常的新信息与变化继续通过正常输入参与维护。记忆类型与加工说明见[记忆种类](/cn/memos_cloud/introduction/memory_types)和[写入说明](/cn/memos_cloud/mem_operations/add_message)。 ![新输入与已有记忆关联,按适用范围更新后保存到所选数据节点](https://cdn.memtensor.com.cn/img/1793103995169_pxb90b_compressed.webp){width="720" class="mx-auto"} ### 按需查询:把相关记忆交给当前终端功能 产品以当前问题和上下文查询 MemOS。MemOS 从已保存的记忆与索引中检索相关内容,返回给产品的业务服务、工具或模型,再由产品完成当前功能并向终端呈现结果。**MemOS 提供记忆背景,产品功能完成路线规划、内容推荐、数据计算和设备动作。** 新的交互和业务结果还可以再次作为输入,参与后续记忆维护。 耳机、手机和家庭音箱可以使用各自的会话,按当前问题查询同一用户已积累的记忆,增加终端不改变数据保存位置。 ![产品按当前问题查询,MemOS 返回相关记忆供业务功能使用](https://cdn.memtensor.com.cn/img/1793104021020_9iy9qe_compressed.webp){width="720" class="mx-auto"} ## 端侧怎样部署 为耳机、手表、手机或电脑提供持续记忆,在部署时需要关注几个核心要素:**MemOS 在哪里运行、记忆数据保存在哪里、大模型在哪里提供计算,以及终端怎样使用。** 下面按四种常见模式,说明这些环节怎样配合。 | 部署模式 | MemOS 与记忆数据在哪里 | 大模型在哪里 | 终端怎样使用 | | --- | --- | --- | --- | | 家庭中枢端云协同 | MemOS 在家庭中枢运行,记忆与索引保存在本地 | 调用客户自建或选定的远程大模型 | 终端访问中枢,请求经本地隐私处理后发往远程计算,结果回到本地继续保存和使用 | | 客户私有部署 | 位于客户管理的服务器环境,数据由客户保存和管理 | 本例使用客户环境中的大模型及配套处理 | 终端经产品服务端写入、查询记忆,再用于产品功能 | | MemOS 托管服务 | 位于 MemOS 托管环境,由托管方运行和保存 | 记忆处理所需的大模型由托管服务提供 | 产品服务端调用托管接口,取得记忆后用于自己的功能 | | 家庭中枢纯本地 | MemOS、记忆与索引位于家庭中枢或同场所节点 | 大模型及配套处理也在本地 | 终端经家庭网络访问本地记忆与产品功能 | ### 端云协同:本地保存记忆,隐私处理后调用远程大模型 这套方案将**记忆保存在本地,先在中枢按配置处理敏感信息,再按需调用远程大模型**。手机 App、家庭音箱、厨房屏等终端经授权访问家庭中枢上的 MemOS,记忆内容、检索索引和真实值与代号的映射持续保存在中枢本地。 大模型由客户自己的推理服务器或选定模型服务提供。MemOS 内部隐私模块在本地完成指定信息的替换和结果还原;记忆加工及查询中需要远程模型参与的请求,均按对应隐私路径处理。本例的检索等轻量处理留在中枢,终端取得还原后的可用记忆背景。 家庭中枢可以采用常在线小主机或家用服务器,例如 32 GB 内存、1 TB NVMe SSD,以及千兆或 2.5 GbE 有线网络,作为家庭少用户场景的资源参考。它承担本地服务、记忆保存、检索、隐私处理和设备接入,远程节点承担大模型计算。 中枢固定放置、持续供电联网,手机或电脑离开后仍可继续运行;家中终端经局域网访问,外出则通过受控的远程接入网关或配套服务衔接。 记忆写入先保存记录并返回受理结果,后台再组织隐私处理和大模型调用。 > **Note**: 这一隐私处理的详细技术思路见 [MemPrivacy:端云协同智能体的个性化记忆隐私保护](https://arxiv.org/abs/2605.09530)。 ![家庭中枢运行 MemOS 并保存记忆,敏感信息在本地替换后再调用远程大模型](https://cdn.memtensor.com.cn/img/1793104048129_7s9zki_compressed.webp){width="720" class="mx-auto"} **家庭中枢内的 MemOS 怎样处理远程请求中的敏感信息** 例如,手机或家庭音箱经中枢的接入程序,将包含朋友姓名、集合时间和地址的交互提交给 MemOS。MemOS 准备记忆加工请求时,内部隐私模块将指定姓名和地址替换为代号,保留中枢上的本地映射,再调用远程模型。结果返回后,在 MemOS 内部完成还原,继续组织、维护和保存记忆。 ```text MemOS 接收:周六十点到王晨家集合,地址是某小区某栋某室。 MemOS 内部处理后发往模型:周六十点到〔人物01〕家集合,地址是〔地址01〕。 中枢内的本地映射:〔人物01〕→王晨;〔地址01〕→某小区某栋某室。 模型结果返回后:MemOS 内部还原指定内容,继续组织并保存记忆。 ``` ![敏感信息替换为代号后发往远程模型,返回结果在中枢内还原](https://cdn.memtensor.com.cn/img/1793104101624_41s0z8_compressed.webp){width="720" class="mx-auto"} ### 客户私有部署:在客户控制的服务器环境运行 MemOS **私有部署与使用公有云资源可以同时成立。** 客户在自己的公有云账号中租用服务器,部署服务、保存数据并管理大模型,仍属于客户私有部署;它与最终用户家中的本地中枢,以及直接调用 MemOS 托管服务,是不同的运作方式。 以耳机厂商为例,耳机通过配套手机 App 接入厂商的产品服务端。服务端负责账号、授权和业务请求。**MemOS 在客户管理的服务器上运行,输入记录、形成的记忆与检索索引保存在客户指定的数据节点。** 本例同时在客户环境中运行大模型,为记忆理解、整理和维护提供计算。客户可使用机房服务器、已有虚拟机或自己云账号中的服务器。 终端提交信息后,MemOS 保存记录,在后台调用大模型加工并维护记忆。下次需要背景时,MemOS 从客户保存的数据中查找相关记忆,返回给产品服务端,再由产品的问答、推荐或计划功能使用。整个过程中,客户管理服务、数据、大模型及访问权限。 若改用外部大模型 API,记忆库仍可保留在客户环境,但相关请求内容会发往该服务。 ![MemOS 与记忆数据部署在客户管理的服务器环境,终端经产品服务端接入](https://cdn.memtensor.com.cn/img/1793104177725_9yld8v_compressed.webp){width="720" class="mx-auto"} ### 托管云服务:调用由 MemOS 运营的记忆服务 仍以耳机与配套 App 为例,终端交互和产品业务由客户自己的产品承接,产品服务端调用 MemOS 托管接口。**MemOS 在托管环境中运行,记忆内容与索引保存在托管环境,记忆处理所需的大模型及配套处理也由托管服务提供。** 客户无需为这些记忆能力维护服务器或大模型运行环境。 写入时,产品服务端提交获授权的信息,先取得受理结果,MemOS 在后台完成加工和保存。查询时,产品提交当前问题,MemOS 返回相关记忆,再由产品自己的问答、推荐或计划功能使用。产品业务所需的大模型与工具仍由客户产品组织,接入时说明它们会收到哪些记忆内容。 用户的记忆在托管环境中持续积累,各终端经产品服务端授权访问。 ![产品服务端调用 MemOS 托管接口,记忆与索引保存在托管环境](https://cdn.memtensor.com.cn/img/1793104247535_m2851g_compressed.webp){width="720" class="mx-auto"} ### 纯本地运行:由固定的家庭 AI 中枢承载记忆与模型 希望将记忆和大模型计算都放在家中时,可以采用带相应算力的固定主机,例如紧凑 AI 工作站或家用服务器。手机、音箱、厨房屏等终端经家庭网络和授权入口访问中枢。 **本方案将记忆保存和大模型计算一并留在本地。** MemOS 在中枢运行,记忆内容与索引保存在本地 SSD,大模型及其配套处理也在中枢或同场所固定节点运行。终端提交信息后,MemOS 在本地保存、加工和维护记忆;需要背景时,再从本地查找并交给当前产品功能使用。 本图将所用问答、语音等业务模型也安排在本地。要实现完整离线,相应工具与资料依赖也需在本地提供,并核验整条链路的实际可用范围。一台主机可以同时承担服务、存储和大模型,也可以连接同场所的固定算力节点。家庭少用户场景可用 64–128 GB 统一内存、2–4 TB SSD 的紧凑 AI 主机作为资源量级参考;采用独立显卡时分别核算系统内存与显存,再按所选大模型、上下文和并发验证。紧凑主机形态可参考 [DGX Spark 官方硬件说明](https://docs.nvidia.com/dgx/dgx-spark/hardware.html)。 需要留存的原始材料、记忆备份和日志按本地目录与权限管理,NAS 可保存资料与备份。已有 NAS 能否同时运行记忆服务或大模型,取决于处理器、内存及软件环境。 ![记忆与业务模型都在家庭中枢或同场所节点运行,终端经家庭网络访问](https://cdn.memtensor.com.cn/img/1793104358743_ld177g_compressed.webp){width="720" class="mx-auto"} ## 接口接入示例:写入、状态跟踪与记忆查询 部署方式确定后,产品需要接通信息写入、加工状态跟踪和记忆查询。下面以 MemOS 托管 API 展示调用示例,并说明部署在家庭中枢时的接入流程。示例中的用户与凭证用于演示,接入时替换为实际配置。 ### 服务端接口:异步写入与跨端查询 下面以 MemOS 托管 API 演示,由产品服务端保管项目 API Key,并依据产品账户校验用户访问权限。客户私有部署时,使用实际交付版本指定的服务地址、鉴权与接口。`user_id` 对应记忆用户,`conversation_id` 对应当前会话;同一用户的不同终端可以使用各自的会话标识。API Key 的项目范围见[项目配置](/cn/api_docs/start/configuration)。 ![终端交互经产品服务端提交,写入、加工与查询在同一账户体系下完成](https://cdn.memtensor.com.cn/img/1793104423004_hsqwrg_compressed.webp){width="720" class="mx-auto"} 手机 App 获得耳机交互的转写文本后,由产品服务端提交完整表达,MemOS 负责记忆加工: ```bash curl --request POST \ --url 'https://memos.memtensor.cn/api/openmem/v1/add/message' \ --header 'Authorization: Token YOUR_MEMOS_API_KEY' \ --header 'Content-Type: application/json' \ --data '{ "user_id": "demo_user_001", "conversation_id": "weekend_plan_001", "messages": [ {"role": "user", "content": "周六早上想带爸妈去苏州转转,周日晚上回来。对了,我妈吃不了辣。"} ], "async_mode": true }' ``` 本例使用 `async_mode: true`。写入接口先返回受理结果与 `data.task_id`、`data.status`,MemOS 在后台继续加工并按托管服务配置保存记忆与索引;受理成功与加工完成是两个状态。产品服务端保存任务标识,按需要跟踪处理进度。字段与处理方式见[写入接口](/cn/api_docs/core/add_message)和[异步说明](/cn/memos_cloud/features/async_mode)。 周五用户在手机 App 中补充「周六上午有点事,吃完午饭再走吧。园林就放周日逛」,产品服务端继续异步提交新表达与会话背景,并记录这次返回的任务标识。需要确认本次写入或补充的完整加工结果时,使用对应 `task_id` 查询任务状态: ```bash curl --request POST \ --url 'https://memos.memtensor.cn/api/openmem/v1/get/status' \ --header 'Authorization: Token YOUR_MEMOS_API_KEY' \ --header 'Content-Type: application/json' \ --data '{"task_id": "YOUR_TASK_ID"}' ``` 任务的 `data.status` 可以是 `running`、`completed` 或 `failed`。联调时可在 `completed` 后核对本次完整处理结果;线上查询可以使用已加工可用的记忆,`running` 也可能已有可检索内容。状态字段与失败信息见[任务状态接口](/cn/api_docs/message/get_status)。 回家后,用户向家庭音箱问起出游。音箱服务经产品服务端使用相同 `user_id` 查询,填写当前音箱会话的 `conversation_id`: ```bash curl --request POST \ --url 'https://memos.memtensor.cn/api/openmem/v1/search/memory' \ --header 'Authorization: Token YOUR_MEMOS_API_KEY' \ --header 'Content-Type: application/json' \ --data '{ "user_id": "demo_user_001", "conversation_id": "home_speaker_continue_002", "query": "周末去苏州那个,现在怎么安排的?还有啥要注意的?" }' ``` 当前会话标识参与查询上下文,不要求所有终端共用一个会话。查询返回中,事实内容位于 `data.memory_detail_list[].memory_value`,偏好内容位于 `data.preference_detail_list[].preference`。产品服务端将相关记忆交给自己的问答或行程功能,生成音箱回答;手机 App 也可以在计划页查询并使用。具体召回取决于输入与处理结果,字段详见[记忆搜索接口](/cn/api_docs/core/search_memory)。 联调时,用同一演示用户完成首次写入、后续补充和另一终端的查询,确认记忆加工状态、召回内容及产品实际使用结果。用户需要精确管理已有内容时,再将[修改](/cn/api_docs/core/update_memory)和[删除](/cn/memos_cloud/mem_operations/delete_memory)接入产品的记忆管理入口。 ### 中枢接口:本地写入与查询 在家庭中枢部署 MemOS 后,手机、音箱等终端通过中枢的授权服务入口提交信息和查询记忆。端云协同与纯本地方案使用相同的记忆业务流程,记忆与索引均保存在中枢本地;大模型沿用前述部署方案。 ![终端经中枢授权入口写入与查询,记忆和索引留在本地](https://cdn.memtensor.com.cn/img/1793104448186_ghw8d9_compressed.webp){width="720" class="mx-auto"} 以下按 MemOS 云服务接口格式给出调用示例。调用前先设置环境变量:`MEMOS_ADD_MESSAGE_URL`、`MEMOS_GET_STATUS_URL` 和 `MEMOS_SEARCH_MEMORY_URL` 分别填写中枢部署提供的写入、状态查询和记忆查询接口完整地址,`MEMOS_API_KEY` 填写访问凭证。具体地址、路径、鉴权及存储配置以实际交付版本为准。 写入交互信息:产品将完整表达连同用户、会话等标识提交给中枢上的 MemOS。例如: ```bash curl --request POST \ --url "${MEMOS_ADD_MESSAGE_URL}" \ --header "Authorization: Token ${MEMOS_API_KEY}" \ --header 'Content-Type: application/json' \ --data '{ "user_id": "demo_user_001", "conversation_id": "home_hub_dinner_001", "messages": [ {"role": "user", "content": "下班回来都累死了,晚饭弄点省事的吧。哦对,别放香菜。"} ], "async_mode": true }' ``` 写入接口返回受理结果后,MemOS 在后台形成、维护并保存记忆。接入程序保存返回的 `data.task_id`,并用它查询加工状态;将下例中的 `YOUR_TASK_ID` 替换为本次任务标识。`data.status` 为 `running`、`completed` 或 `failed`,查询记忆时使用已加工可用的内容。 ```bash curl --request POST \ --url "${MEMOS_GET_STATUS_URL}" \ --header "Authorization: Token ${MEMOS_API_KEY}" \ --header 'Content-Type: application/json' \ --data '{"task_id": "YOUR_TASK_ID"}' ``` 查询相关记忆:用户随后在家庭音箱询问晚饭安排时,产品以同一用户的身份和当前问题查询 MemOS。例如: ```bash curl --request POST \ --url "${MEMOS_SEARCH_MEMORY_URL}" \ --header "Authorization: Token ${MEMOS_API_KEY}" \ --header 'Content-Type: application/json' \ --data '{ "user_id": "demo_user_001", "conversation_id": "home_speaker_dinner_002", "query": "今晚吃啥?想弄点省事的。" }' ``` MemOS 从中枢保存的记忆与索引中检索相关内容,返回给产品的问答或菜单功能使用;产品结合当前问题与相关记忆生成回答。 联调时确认写入记录可跟踪加工状态、查询返回可用背景,并检查重启后的记忆查询及备份、删除的作用范围。更多服务端调用方式见[快速接入](/cn/memos_cloud/getting_started/quick_start)。 --- # MemT-1.0 与 MemOS 如何分工?从一次编码任务开始选型 (/cn/usecase/blog/memt_memos_agent_memory) ![MemT-1.0 与 MemOS 选型](https://cdn.memtensor.com.cn/img/1793872135595_gjhz96_compressed.png) Agent 修好了一个构建错误。下次遇到相似问题,它能不能少走一遍之前已经排除的弯路? 过了几天,项目又升级了依赖,启动命令也变了。Agent 既要用上之前的排查经验,也要知道现在该执行哪条命令。 [记忆张量MemTensor](https://memtensor.com/){target="_blank"} 的 MemT-1.0 将记忆引入模型计算,让历史信息能够以记忆状态参与后续任务;MemOS 则提供面向应用的记忆组织、检索与维护能力。把两者放在同一个工作流中看,更容易理解经验如何复用、变化的信息又如何继续被使用。 ## 经验复用与事实更正,需要不同的操作 设想 Agent 曾经修好一个构建错误,留下两类信息。一类是排查经验:先检查依赖,再检查配置。另一类是项目事实:当前使用哪个运行时,部署命令是什么。 排查经验可以在新任务中帮助缩小搜索范围;项目事实一旦变化,就要让后续操作采用新值。把一份过期配置保存得更牢,并不会让构建更可靠。 因此,选择记忆方式时,可以先看信息将来要怎样使用。需要直接查看原文、引用来源和逐条更正的内容,保留可定位的记录;需要在后续任务中反复使用的排查方法,也可以整理成经验,由应用检索,或写入模型记忆状态供后续使用。 ## MemT 改变经验怎样参与模型计算 [MemT-1.0 技术报告](https://arxiv.org/html/2610.26825v1){target="_blank"}描述了动态局部记忆与可训练的超记忆模块。历史信息进入记忆状态,后续生成读取这些状态,减少每次重新处理全部历史文本的需要。对持续多轮的任务来说,项目背景和历史交互可以通过记忆状态影响后续回答,不必在每次生成时一直保留全部历史文本。在技术报告的长历史实验中,128K tokens 历史长度下,MemT-1.0-Nano 的端到端推理速度约为完整上下文方案的 1.86 倍,单条轨迹的持久状态存储约为后者的 1/66。 训练阶段学习记忆机制,推理阶段则更新和使用动态状态。理解这个区别,才能正确设计评估:既观察同一历史下的后续表现,也观察历史变长时的处理开销。 固定容量的状态还涉及细节保留的取舍。技术报告在长历史效率之外,也讨论了细致检索历史证据的挑战。若任务要求找回合同原句或精确引用一次决定,可将原始材料作为可检索依据,同时评估模型如何利用压缩后的经验。 对于编码任务,可以进一步看:过去的经验是否改变了 Agent 处理新问题的方式? 在一次 Django 日期解析任务中,没有经验指导的 Agent 找到相关代码后较早开始修改;写入经验后,Agent 先建立复现测试,再修改代码。在 MemT-1.0-Nano 的执行轨迹中,Agent 还在修改后回头检查了边界条件,并进行了额外验证。 这组[编程实验](https://arxiv.org/html/2610.26825v1){target="_blank"}先从历史任务中整理可复用经验,再将相关经验写入模型记忆状态。在 SWE-bench Verified 的执行前写入设置下,MemT-1.0-Nano 的平均成功率为 69.33%,无经验基线为 66.07%;同一任务独立运行三次、全部成功的比例分别为 61.60% 和 54.00%。 对编码 Agent 来说,经验的价值不只体现在能否复述过去,还体现在它能否帮助完成新的工作。 ## MemOS 让变化中的信息持续可用 [MemOS 生命周期管理](/cn/memos_cloud/introduction/mem_lifecycle/)覆盖记忆生成、使用、合并和清理;[修改接口](/cn/api_docs/core/update_memory/)提供按记忆 ID 更正内容的入口。项目规则因而可以成为能够检索、查看和更新的对象。 例如,团队将旧的手动启动步骤改成自动脚本。应用可以更新对应的记忆,记录新的启动方式、适用项目和版本;团队成员也可以通过[自然语言反馈](/cn/memos_cloud/mem_operations/add_feedback/)提交修正。 下一次构建时,应用检索与当前项目有关的记忆,把新的启动规则提供给 Agent。此前形成的排查经验仍然可以使用,同时需要按照新的项目条件判断哪些步骤适用。 | **信息** | **选型时优先观察什么** | | --- | --- | | 一次调试形成的方法 | 相似新任务是否更容易完成 | | 当前命令与项目约定 | 能否找到当前值并及时更正 | | 原始错误日志 | 能否定位原文和具体证据 | 同一工作流可以同时需要这些信息。例如,MemOS 可以将对话中的方法整理成可检索的 [Skill](/cn/memos_cloud/features/self-evolving/),让 Agent 在相似任务中参考;对于使用 MemT 的应用,也可以将相关经验写入模型记忆状态,让经验参与后续生成。 项目命令和原始日志则可以继续以可定位的形式管理。这样,经验复用、事实更新和证据查询就能在同一个工作流中互相配合。 ## 用一次条件变化判断方案是否适合 可以选一个真实仓库,准备连续三项任务:解决问题、复用方法、升级依赖。第三项让旧方法的某个前提发生变化,观察 Agent 是否改用新的规则。 比较时,尽量保持任务输入、工具环境和通过条件一致,记录实际完成情况、处理时间,以及是否需要人工重新解释。 对 MemT,可以对照有无相关经验时的任务表现,观察经验如何影响后续操作;对 MemOS,可以检查信息更新后,应用能否检索并使用新的项目规则。如果比较不同模型或不同接入方式,也要记录各自的配置,帮助解释结果。 还可以把同一经验放到另一个项目,检查其适用条件是否仍成立。将项目规则与个人偏好分开,并使用[项目和用户范围](/cn/memos_cloud/introduction/isolation_filters/)组织检索,能减少把相似背景当成相同要求。 这样得到的选择有明确理由:哪些信息值得压缩复用,哪些需要随时更正,哪些必须保留原文。记忆的价值最终体现在 Agent 下一次工作时少走弯路,也能跟上已经改变的事实。 --- # MemOS 异步写入如何验收?从 task_id 查到下一次回答 (/cn/usecase/blog/memos_async_memory_write_verification) ![MemOS 异步写入验收](https://cdn.memtensor.com.cn/img/1793872182515_ra9zlv_compressed.png) 用户刚把酒店预算从每晚 1200 元改成 800 元,下一句就问“帮我重新推荐”。好的体验,是这次推荐立即采用新预算,用户不必等后台整理,也不必把更正再说一次。 要做到这一点,可以把当前会话中的确认信息与长期记忆衔接起来:先让新预算进入下一轮上下文,同时将这次更正提交给 MemOS。后台处理完成后,后续会话可以检索并使用更新后的记忆。 [MemOS Cloud 的异步模式](/cn/memos_cloud/features/async_mode/)支持在后台处理写入的消息,并提供任务状态查询。应用可以一边继续回应用户,一边跟进记忆处理进度。 ## 当前更正先进入下一轮可用信息 收到明确更正时,先在会话状态中保存用户、项目、预算值和确认顺序。下一轮生成推荐时,将这项当前约束放入上下文,再补充检索到的历史偏好。 如果旧记忆仍写着 1200 元,当前已经确认的 800 元应当拥有更高优先级。这样,后台处理所需的时间就不会变成用户重复解释的负担。 讨论与决定也要分开。“800 元会不会选择太少”是在探讨,“这次就按 800 元”才表达确认。可以为前者保留对话,为后者更新当前约束,避免把每句带金额的话都当成新的预算。 当前会话提供最近确认的信息,长期记忆支持跨会话延续。保存时还要带上适用范围:用户说“这次旅行按每晚 800 元”,应关联到这次旅行;如果用户明确表示以后订酒店都希望控制在这个范围,才可以作为更长期的偏好使用。 更正也可以只覆盖一个字段。预算改成 800 元之后,目的地和交通偏好仍然有效,将它们继续保留,比整份抛弃旧上下文更能维持任务的连续性。 ## 通过 `task_id` 跟进长期记忆处理 在 MemOS Cloud 中,[添加消息默认采用异步模式](/cn/memos_cloud/features/async_mode/)。当前消息先经过初步处理,供后续检索;更细的记忆整理继续在后台进行。因此,消息开始可被检索,与后台任务全部完成,是两个不同的时间点。 应用可以保留返回的 `task_id`,通过 [get/status](/cn/api_docs/message/get_status/) 跟进处理状态。任务完成后,`memory_views` 会汇总新增、更新和删除等变化,并按记忆类别提供相关 ID。应用可以据此进一步查看受影响的记忆,核对预算是否已经更新。 当任务仍在处理中,也可以检查新信息是否已经进入检索,无需为每一轮对话固定等待全部精加工结束。对于依赖完整处理结果的步骤,再等待对应任务完成。 如果某个操作需要在接口返回前等记忆处理完成,也可以在添加消息时选择[同步模式](/cn/memos_cloud/features/async_mode/);需要立即回应用户的场景,则可以继续使用当前会话中已确认的信息。 任务标识应与预算更正的事件关联。一项业务更正可以有进度查询和后续读取,但这些请求仍然围绕同一个变化,便于找到失败或延迟发生的位置。 ## 让新旧信息按确认顺序接续 用户可能先将预算改成 1000 元,随后又改成 800 元。后台处理若耗时不同,完成先后不一定与用户确认的顺序相同。 会话状态应保留最后一次已确认修改。对于同一旅行预算的连续更正,应用可以按确认顺序提交处理,或在相关任务完成后重新核对最新值。 例如,用户先确认 1000 元、随后改成 800 元时,下一轮应继续使用 800 元。如果较早提交的任务晚于后一次任务完成,应用还需要检查长期记忆是否仍采用最新预算;必要时重新提交最新更正。确认相关处理已经接续后,再移除临时记录。 如果写入失败,保留当前更正并安排恢复,不要因为一次后台任务失败,就让下一轮回到旧预算。跨会话使用时,也应保存未完成的更新,或者在继续任务前取得它的最终结果。 写入和检索时,需要保持[项目和用户范围](/cn/memos_cloud/introduction/isolation_filters/)一致;如果应用按 Agent 组织或过滤记忆,也要让相关设置与使用场景对应。会话标识帮助关联当前对话,同一用户标识则有助于在不同入口继续使用该用户的记忆。 ## 用四次提问验收一项更正 先确认原预算,再明确改成 800 元,随后立刻请求推荐,最后换一个会话继续这次旅行。观察推荐是否采用新金额,追问原计划时能否找到之前的信息,以及跨会话是否继续使用当前预算。 还可以连续修改两次,例如先改成 1000 元、再改成 800 元,检查后台任务完成后,后续推荐是否仍以最后确认的金额为准。 若结果不符,可以沿[检索内容](/cn/memos_cloud/mem_operations/search_memory/)、最终模型输入和答案逐步定位。新记录已经找到却仍采用旧预算时,优先检查旧摘要是否覆盖了当前约束;检索尚未取得新信息时,则检查处理进度与范围。 这套设计让异步处理保持效率,也让用户的明确更正在下一次交互中起作用。用户感受到的“记住了”,最终体现在建议真的随他的决定而改变。 --- # 权限撤了,Agent 为什么还记得那份报价? (/cn/usecase/blog/revoked_access_agent_memory) ![企业 Agent 的记忆权限与客户资料管理](https://cdn.memtensor.com.cn/img/1793610733348_azioej_compressed.png) CRM 里的访问权已经撤销,Agent 却还能说出客户的报价。 不一定是 CRM 的权限失效了。也可能是 Agent 之前读过资料,把其中的内容写进了摘要。原文件不能再打开,旧摘要却仍然被放进下一次对话的上下文,Agent 因此可能再次说出其中的内容。 这是企业接入长期记忆时,需要单独检查的一条路径。 随着 Agent 开始跨应用处理工作,如何在延续上下文的同时管理访问权限,也受到越来越多关注。 2026 年 10 月 8 日,Google Cloud 在 Gemini at Work 上介绍 Gemini agent,强调在多个工作应用中延续记忆、技能和控制。10 月 21 日,SentinelOne 发布 Singularity Agentic Detection and Response,以早期访问形式提供 Agent 发现、治理和运行时防护。 跨系统工作需要持续的上下文,也需要持续的权限检查。对记忆来说,问题很直接:当时允许读取的资料,后来谁还能继续用? 接入 MemOS 时,我们建议把这条检查放进日常调用。MemOS 提供记忆的保存、检索、修改和删除操作,让 Agent 能在后续任务中使用已有的客户上下文。企业后端则依据当前业务权限决定谁能调用、能处理哪些资料。这样,客户历史可以继续用于交接,人员权限变化后,应用也能及时调整记忆的使用范围。 ## 人换了,客户历史不该跟着丢 以销售调岗为例。假设一位销售曾用 Agent 整理某客户的报价和谈判进展,后来不再负责这个客户。 原负责人不能继续获取报价,新负责人却还需要知道之前谈到了哪里。为了撤权,把整个客户的记忆清空,会把交接资料一起删掉;只改 CRM 权限,不处理 Agent 已保存的内容,又会留下另一条读取路径。 因此,资料属于哪个客户、当前由谁负责,要分开记录。 企业可以按客户和项目管理共享业务历史,再把当前有权使用这些资料的人映射到对应范围。不要因为某位员工最先输入了报价,就把团队资料当成他的个人偏好;也不要为了方便协作,把它放进所有人都能搜索的公共范围。 在 MemOS Cloud 中,企业可以通过[项目和用户记忆](/cn/memos_cloud/introduction/isolation_filters/)组织不同范围的上下文,也可以使用[知识库](/cn/memos_cloud/features/knowledge_base/)保存需要由多人共同使用的业务资料。客户交接时,新负责人可以在获授权的范围内继续检索相关历史。如果需要交接的内容原本保存在员工个人记忆中,企业也可以将需要共享的业务信息整理到团队可用的范围,再由后端根据权限提供给新负责人。 对更细的范围,MemOS Cloud 支持按来源、标签和业务元信息等条件[过滤记忆](/cn/memos_cloud/features/filters/),再从符合条件的内容中检索与问题相关的信息。应用需要在写入时记录相应的业务字段,并由后端根据可信身份确定检索范围。项目 API Key 也应由后端保管,不接受前端随意指定客户或用户范围。 这里需要两项判断:先确定这名员工能访问哪些资料,再从允许的范围里找与问题相关的记忆。检索过滤负责执行范围,业务授权负责确定范围。 ## 撤权以后,旧对话也要再查一遍 新开一个会话,发现访问被拒绝,还不能说明检查已经结束。 原负责人可能继续使用昨天的对话。报价已经出现在会话摘要、模型上下文或回答缓存里,本次请求甚至不用重新检索,就能再次说出来。 在企业应用中,我们建议把权限检查放到每次构建上下文之前。即使内容来自缓存,也要符合当前的访问规则。权限变更后,让相关缓存失效;已经加载的旧片段,不应继续随对话自动传给模型。 如果一份摘要混入了多个项目的资料,又无法可靠区分各句的来源,应停止复用,并用当前允许访问的材料重新生成。权限检查应发生在内容进入模型之前。 后台任务也要处理。撤权前排队的客户分析任务,执行和返回结果时都应重新检查权限,不能只凭入队时的一次授权继续工作。 读取、修改和删除还应分别授权。一个员工可以查看报价,不代表他可以通过一句“改成这个价格”,影响其他人之后读取的记忆。向 MemOS 提交编辑或自然语言反馈之前,后端要先确认操作权。 企业应用需要把这些检查接入上下文构建和记忆操作流程。撤权无法收回用户已经看过或自行保存的内容,要阻止的是系统在后续交互中继续提供这些资料。 ## 查错时,要知道哪条记忆进了回答 “记忆检索成功”只能证明接口返回过,解释不了为什么 Agent 报出了一个旧价格。 排查时需要沿着请求往回看:调用者是谁,当时获准访问什么,检索返回了哪些记忆,哪些实际进入了模型,以及进入模型的是哪个版本。 应用可能对检索结果做过筛选或摘要,所以返回列表和最终上下文应当分别留记录。可以用一次业务请求的标识,把授权结果、记忆 ID、来源或版本引用,以及后续工具调用串起来。必要的正文证据放在受控存储中,不要把客户资料复制进每一条运行日志。 有权负责人纠正报价后,也可以沿这条记录检查更新结果。MemOS Cloud 支持[直接编辑指定记忆](/cn/memos_cloud/mem_operations/update_memory/),也支持通过[自然语言反馈](/cn/memos_cloud/mem_operations/add_feedback/)提交修正,让系统结合上下文处理相关记忆。应用确认处理完成后,可以在新会话中查询当前报价,核对返回内容。 对会随时间变化的信息,MemOS Cloud 的[时间感知](/cn/memos_cloud/introduction/time_awareness/)还可以帮助检索区分当前信息和历史信息。例如,新负责人查看当前报价时需要最新状态;回顾谈判过程时,则可能需要了解之前的报价。 “建议降到某个价格”和“新报价已经批准”也要分开。保存下来的话即使一字不差,用错它的状态,依然会影响下一步行动。 ## 删除一条记忆,别让旧材料再生成一条 撤权改变谁能使用资料。删除处理的是哪些记录不再保留。两件事不能共用一个含糊的“清理”按钮。 MemOS Cloud 支持[按记忆 ID 删除指定内容](/cn/memos_cloud/mem_operations/delete_memory/),也支持清理某个用户在当前项目中的记忆。后台应根据请求选择范围:只需删除某条报价时,可以定位并删除相关记忆;清理用户在项目中的全部记忆则是另一项操作。 除记忆记录外,还需要检查这次删除范围涉及的原始对话、摘要、缓存和备份等材料,避免旧内容在后续处理时重新进入记忆。 更容易漏掉的,是应用保留的其他副本。 例如,一条记忆删掉了,原始对话还在。夜间任务重新处理这段对话,又把相同信息抽取了一遍。或者在线记录已经清除,恢复备份后,旧版本重新进入检索。 我们建议为删除保留一份处理记录:目标是什么,哪些副本属于这次范围,哪些任务需要取消或排除,哪些环节仍待完成。删除通过授权后,先阻止目标内容继续用于新回答,再执行相应清理。必须保留的业务档案,应限制用途,不能自动回流到记忆抽取流程。 备份按既定规则保留时,也应限制访问。恢复服务前,重新执行仍然有效的删除和权限规则,避免旧数据重新对外可用。 核验要检查目标记录和相关读取路径。问一次没有搜到,只能说明这次没返回,不能证明内容已经删除。 ## 上线前,保留原会话,撤一次权限 针对开头的报价场景,可以用一组测试资料完成下面的检查: | **操作** | **应当看到什么** | | --- | --- | | 有权员工写入、查询客户报价 | 读取范围正确,能追溯到相关记忆和来源 | | 撤销这名员工的权限,继续从原会话追问 | 新检索、旧摘要和缓存不会让系统在后续回答中继续提供该客户报价 | | 换成获授权的新负责人查询 | 仍能使用应保留的客户历史,交接没有因撤权而中断 | | 按约定范围删除资料,并处理后台任务 | 目标内容停止用于回答,不被排队任务重新写回 | | 在隔离环境恢复旧备份 | 服务开放前,适用的删除和授权规则已重新执行 | 采用私有化部署时,再检查一次实际数据去向。记忆抽取、向量化、重排和回答模型都可能有独立端点,日志和备份也可能位于别处。数据库在内网,不代表所有处理都发生在内网。 [MemOS Cloud 与开源自托管](/cn/memos_cloud/getting_started/cloud_and_opensource/)提供不同的接入和部署方式,企业可以结合实际环境,分别检查数据处理链路和记忆操作。 接入可以从一位客户、一次人员交接开始。先检查原负责人失去访问权后,旧对话是否还会提供资料;再确认新负责人能否接着使用需要保留的客户历史。让 MemOS 的记忆操作进入企业已有的管理流程,客户摘要也就能随着人员和业务变化持续维护。 企业希望 Agent 记住之前做过的工作,也需要让记忆的使用范围跟上人员和业务的变化。 --- # ChatGPT 升级后台记忆合成:企业 Agent 为什么需要独立的长期记忆基础设施? (/cn/usecase/blog/chatgpt_dreaming_long_term_memory) > **核心结论:** OpenAI 对 Dreaming 的升级说明,AI 记忆的竞争重点已从“能否保存一条偏好”,转向“能否在多年尺度上持续合成、更新和调用正确的信息”。对企业 Agent 而言,扩大上下文窗口、接入 RAG 或部署向量数据库都不足以独立解决这个问题;生产系统还需要覆盖写入、检索、反馈、更新、删除、权限与审计的长期记忆基础设施。 --- 2026 年 6 月,OpenAI 发布了 Dreaming 的升级架构。Dreaming 并非当月才首次出现:OpenAI 在 2025 年 4 月推出过早期版本,随后针对长期使用中记忆过时、冲突和规模扩展等问题继续重构。新版目标集中在三个方面:延续有价值的上下文,正确遵循用户偏好与约束,并让记忆随时间保持更新。 这次变化的意义不只是 ChatGPT 增加了一项个性化功能。它暴露出一个更普遍的产品问题:当 AI 从一次性问答走向长期陪伴、持续工作和自主执行,真正困难的已不是“有没有记忆”,而是系统如何决定什么值得记住、何时更新、在什么场景调用,以及如何让用户和企业控制这些记忆。 换句话说,AI 记忆正在从产品功能变成独立的基础设施能力。 ## 从“记住几条信息”到管理多年状态 早期 AI 记忆更像一本简化的备忘录。 用户说“记住我不吃辣”,系统保存一条偏好;下一次推荐餐厅时,再把这条信息放进上下文。这类机制可以改善体验,但当使用时间从几天延长到几年、用户数量扩大到数百万甚至更多时,问题会迅速复杂化。 比如: - 用户以前不吃辣,现在改变了偏好,系统应该覆盖旧记忆,还是保留变化过程? - “我下周去上海”在一周后应该如何更新,才能避免系统一直把它当成未来计划? - 一段对话里既有稳定偏好,也有临时情绪,什么值得长期保留? - 同一个用户在工作、家庭和不同设备上的信息,哪些可以关联,哪些必须隔离? - 一条记忆由模型推断得出,而不是用户明确表达,它的可信度应该如何管理? - 当用户要求修改或删除记忆时,系统如何确认相关副本、索引和派生信息已经得到处理? 这些问题无法仅靠扩大上下文窗口解决,也不只是把更多历史文本放进向量数据库。 |技术|主要解决什么|不能单独解决什么| |---|---|---| |上下文窗口|让模型在一次推理中看到当前输入和部分历史|跨会话保存、长期更新、权限与删除| |RAG|从外部知识源检索与当前问题相关的材料|用户状态演化、偏好冲突和记忆生命周期| |向量数据库|存储向量并进行相似度检索|什么该写入、何时遗忘、谁有权调用| |长期记忆系统|管理信息跨会话、跨任务和跨时间的状态|仍需与模型、Agent、业务权限和数据治理体系协同| 对产品负责人而言,问题不应是“要不要再接一个数据库”,而应是:当用户半年后回来,Agent 能否调用仍然有效的信息;当偏好发生变化,旧信息能否被修正;当员工离职或用户要求删除数据,系统能否找到并处理相关记忆;当一条错误信息影响决策,团队能否追溯它从哪里写入、在哪些任务中被使用。 ## Dreaming 升级指向三类系统工程问题 ### 1\. Freshness:记忆如何不过时 时间不会在对话结束时停止。 一次旅行会结束,一项任务会完成,用户偏好会改变,组织规则也会更新。长期记忆系统必须识别新旧信息的关系,对记忆进行更新、降权、归档或遗忘,而不是把每一条历史永久并列保存。 这要求系统具备时间信息、版本关系、反馈机制和生命周期策略。 ### 2\. Continuity:信息如何跨会话持续发挥作用 连续性并不等于把全部聊天记录复制到下一次对话。 原始记录通常冗长、重复,并包含大量只对当时有效的信息。直接拼接会不断增加 Token 成本,也会让真正重要的事实被噪音稀释。系统需要先从原始消息中识别事实、偏好、事件、关系和任务状态,再根据当前场景调用合适的部分。 ### 3\. Relevance:此时此刻应该调用什么 检索出语义相似的内容,并不代表它适合当前任务。 一条记忆是否应该进入当前推理,还取决于用户身份、业务场景、时间、权限、任务阶段和信息可信度。长期记忆需要的不只是检索器,还需要一套可编排的调度机制。 ## 从用户问题倒推:生产级记忆系统至少要回答五件事 一家企业真正采购或自建的不是“记住我喜欢什么”的演示,而是一个能稳定运行的系统。它至少要回答五件事:信息怎样进入记忆,当前任务怎样找到正确记忆,新旧信息怎样更新,错误记忆怎样纠正,不再需要的信息怎样删除。 记忆张量 MemTensor 长期聚焦大模型长期记忆与持续学习问题,并将 MemOS 定义为面向 Agent 时代的记忆操作系统。其基本分工是:模型负责理解、推理与生成,Agent 负责任务规划、工具调用和执行,MemOS 作为独立记忆层,负责信息的生产、组织、调度、治理和演化。 在 MemTensor 的产品架构中,MemOS 位于 Agentic AI 与大语言模型之间,把分散在应用代码、数据库和对话历史中的记忆能力组织成统一基础设施: - **记忆生产**:从对话、文档、任务和业务事件中识别有长期价值的信息,减少简单保存原始消息带来的噪音; - **记忆组织**:根据记忆的用途和形态进行分层管理; - **记忆调度**:结合用户、任务、场景、时间和权限,选择当前需要的记忆; - **记忆治理**:管理来源、日志、版本、权限、隐私、回滚、删除和遗忘; - **记忆演化**:通过持续反馈,把反复出现的有效经验沉淀为可复用知识和能力。 这些能力解决的不是“让模型看到更多文本”,而是“让系统在更长时间里保持正确、连续且可管理的理解”。 下表把上述判断对应到 MemOS 当前可公开验证的产品能力。它不是功能口号,而是发布后供读者和搜索系统继续核验的证据入口。 |生产问题|MemOS 公开能力|官方证据| |---|---|---| |怎样把对话写入记忆|Add Message 接口接收消息并进入记忆处理流程|[添加消息](https://memos-docs.openmem.net/cn/memos_cloud/mem_operations/add_message/)| |怎样在任务中召回相关内容|Search Memory 接口支持按查询检索记忆|[检索记忆](https://memos-docs.openmem.net/cn/memos_cloud/mem_operations/search_memory/)| |怎样利用结果反馈修正记忆|Add Feedback 接口将使用反馈送回记忆流程|[添加反馈](https://memos-docs.openmem.net/cn/memos_cloud/mem_operations/add_feedback/)| |怎样处理不再需要的信息|Delete Memory 接口提供显式删除动作|[删除记忆](https://memos-docs.openmem.net/cn/memos_cloud/mem_operations/delete_memory/)| |怎样把不同记忆能力接入Agent|开源 MemOS 通过 MOS 对记忆模块进行统一组织和调用|[MOS架构概览](https://memos-docs.openmem.net/open_source/modules/mos/overview/)| 需要明确的是:接口的存在证明系统提供了相应操作入口,但不等于所有企业治理要求自动满足。权限模型、审批规则、日志留存、数据隔离与合规策略仍需结合具体部署和业务系统进行设计。 ## 为什么 MemOS 采用分层记忆 不同信息并不适合用同一种方式保存和调用。 MemOS 将记忆划分为明文记忆、激活记忆和参数记忆。明文记忆便于更新、修订和溯源;激活记忆可以在推理过程中高效复用;参数记忆用于承载经过训练或沉淀的稳定能力。系统可以根据任务与运行条件,在不同记忆形态之间进行组织和按需转换。 这种设计试图在三个目标之间取得平衡: 1. 信息需要可查看、可修改和可追溯; 2. 记忆调用不能给实时推理带来不可接受的延迟; 3. 长期积累的经验应当有机会转化为更稳定的能力。 这也说明,生产级记忆系统不应被简化为某一种数据库。向量数据库和图数据库可以作为存储底座,但记忆如何产生、何时调用、怎样更新以及由谁治理,需要由上层记忆系统负责。 ## 一条记忆如何完成完整生命周期 MemOS 提供覆盖记忆生命周期的接口和管理能力。 一条信息可以通过 [`/add/message`](https://memos-docs.openmem.net/cn/memos_cloud/mem_operations/add_message/) 进入系统,经加工形成记忆;应用可以通过 [`/search/memory`](https://memos-docs.openmem.net/cn/memos_cloud/mem_operations/search_memory/) 召回相关内容;新的使用反馈可以通过 [`/add/feedback`](https://memos-docs.openmem.net/cn/memos_cloud/mem_operations/add_feedback/) 进入更新流程;当信息不再有效或用户提出要求时,可以通过 [`/delete/memory`](https://memos-docs.openmem.net/cn/memos_cloud/mem_operations/delete_memory/) 执行删除。 接口本身不是长期记忆的全部,但它让写入、检索、反馈和删除成为可以被应用明确调用和管理的系统动作,而不是隐藏在模型上下文中的不可见过程。 ## 从个人助手到企业 Agent,记忆问题并不相同 ChatGPT 的 Dreaming 主要面向个人长期使用体验。企业 Agent 面临的约束更加复杂。 AI 陪伴和游戏关注角色设定、共同经历与关系演进;端侧智能硬件既需要跨设备连续性,也要处理本地隐私;AI 客服需要把不同渠道中的服务历史连接起来;金融和工业场景则更加关注权限、来源、审计、私有化与数据删除。 因此,企业记忆基础设施必须支持不同部署和治理方式。根据记忆张量现有产品资料,MemOS 面向云服务、私有化、端侧和端云协同等使用形态;具体可用形态、功能边界与交付条件,应以项目版本和官方资料为准。 这并不意味着所有产品需要使用同一种记忆策略。恰恰相反,长期记忆基础设施的价值,在于让不同应用能够在统一治理边界下采用不同的生产、调度和存储策略。 ## 评价一套长期记忆,不能只看“有没有召回” 传统检索系统常用召回率判断效果,但长期记忆进入产品后,至少还需要同时评价五个维度。 第一是**连续性**:跨会话后,系统能否正确延续真正有价值的历史;第二是**时效性**:过期计划和变化后的偏好能否被更新,而不是长期制造错误上下文;第三是**相关性**:系统是否只在合适的任务中调用合适的记忆,避免“记得很多、用得不对”;第四是**可控性**:用户和企业能否查看、修正、删除并约束记忆;第五是**运行效率**:随着使用时间和用户规模增长,记忆加工与调用是否仍能控制延迟、Token 和存储成本。 这五个维度也决定了记忆系统能否从产品演示进入长期生产。只展示一次“成功想起用户生日”,无法证明系统可以管理数月后的状态变化、多用户隔离和大规模并发;同样,单纯扩大上下文,也不能替代完整生命周期和治理机制。 ## 常见问题 ### AI 为什么会忘记用户偏好和历史对话? 多数模型不会天然保留跨会话状态;当前会话结束后,历史信息若未被外部系统保存和重新提供,模型就无法继续使用。即使保存了全部聊天记录,也仍需解决有效信息抽取、过期信息更新、冲突处理和按场景调用。 ### AI 记忆、上下文窗口、RAG 和向量数据库有什么区别? 上下文窗口承载单次推理输入,RAG负责从外部知识源查找材料,向量数据库提供存储与相似度检索。长期记忆系统管理的是跨时间的状态,包括写入、更新、反馈、权限、审计、删除和遗忘。四者可以协同,但不能互相简单替代。 ### 生产级 Agent Memory Architecture 应包含哪些核心模块? 至少应包含记忆写入与抽取、身份与作用域隔离、检索与重排、冲突和时效处理、反馈与更新、删除与遗忘、权限与审计,以及延迟、成本和质量评估。具体架构还要与模型、Agent编排、业务数据和合规系统连接。 ### MemOS 是什么? MemOS 是记忆张量 MemTensor 推进的记忆操作系统,目标是把分散在模型上下文、应用代码和数据库中的记忆能力组织成独立基础设施。公开文档提供了消息写入、记忆检索、反馈、删除和记忆模块编排等能力入口。 ## AI 竞争正在进入“谁能长期理解”的阶段 大模型能力不断提升,但长期智能并不只由模型参数和上下文长度决定。 当 AI 开始长期参与个人生活和企业流程,系统能否记住重要信息、理解信息的变化、调用正确的历史、拒绝不可信记忆,并让用户拥有修改和删除的权利,将直接影响产品体验与生产可信度。 OpenAI 对 ChatGPT Memory 的持续重构说明,长期记忆已经成为头部 AI 产品必须面对的核心系统问题。MemTensor 选择从 Memory³ 相关记忆机制研究出发,通过 MemOS 推进记忆系统工程化,再延伸至 Agent 和记忆基础设施以及记忆原生通用基座模型探索,正是为了回答同一类长期问题: AI 如何从一次性生成,走向持续理解、持续学习与自我进化? 这场变化刚刚开始。未来真正有价值的 AI,不仅需要在一轮对话中回答得更聪明,也需要在更长的时间里理解得更准确、行动得更一致,并对自己的记忆负责。 ## 关于记忆张量MemTensor 记忆张量(上海)科技有限公司(以下简称“记忆张量MemTensor”)是由上海算法创新研究院孵化,并由中国科学院院士担任首席顾问的新一代大模型与长期智能基础设施企业。 公司以“低幻觉、个性化、自我学习进化”为核心,长期聚焦大模型长期记忆与持续学习问题,围绕 Memory³ 相关记忆机制研究、MemOS 记忆操作系统、Agent 和记忆基础设施产品化,以及记忆原生通用基座模型,构建从理论探索、系统工程化到模型层探索的递进式技术路线,推动 AI 从一次性生成走向长期智能。 公司已与招商、海诚、荣耀等重要合作伙伴建立深度协同关系,并在 AI 陪伴、游戏、端侧智能硬件、金融及工业等多个重点行业实现商业化落地,先后累计完成近两亿元融资,由中金、孚腾、华为哈勃、商汤、和玉等众多知名投资机构参投。 --- # Memory Poisoning:企业 Agent 必须建立的六道长期记忆控制 (/cn/usecase/blog/memory_poisoning_controls) > **核心结论:** Memory Poisoning(记忆投毒)不是一次回答出错,而是不可信信息进入持久记忆后,在未来会话、任务或多个 Agent 之间被再次调用。企业不能只在模型输出端拦截风险,还要围绕记忆的来源、写入、更新、隔离、召回和删除建立全生命周期控制。MemOS 可为写入、检索、反馈、删除与记忆编排提供系统入口,但仍需与身份权限、输入验证、审批、监控和安全运营体系协同。 --- 当 AI Agent 只能完成一次性问答时,一次错误回答的影响通常会随着会话结束而停止。但当 Agent 拥有跨会话长期记忆,错误可能被保存、再次调用,甚至在后续任务和多个 Agent 之间继续传播。 2026 年 8 月,Forcepoint 发布《Agentic AI Security Risks: What CISOs Need to Know》,并结合 X\-Labs 的 Agentic AI 威胁研究讨论记忆与上下文被污染后产生的持续风险:如果攻击者把虚假上下文、伪造偏好或错误行为模式写入持久状态,后续依赖这条信息的判断都可能受影响;在多 Agent 架构中,一个 Agent 的污染输出还可能成为另一个 Agent 的输入。 与普通提示词注入相比,Memory Poisoning 更难处理的地方在于:恶意影响不一定立即出现,也不一定停留在发生攻击的那一次会话中。一条错误记忆可能在数周后被触发,以“系统早已知道的事实”重新进入决策过程。 ## 从 Prompt Injection 到 Memory Poisoning,风险发生了什么变化 提示词注入通常试图在当前交互中改变模型行为。例如,一段网页内容包含隐藏指令,诱导 Agent 忽略原有规则或调用不该调用的工具。 如果系统是无状态的,攻击影响可能随着任务结束而终止。但具备持久记忆的 Agent 可能把攻击产生的结果进一步写入长期状态: - 把攻击者提供的虚假联系人保存为可信供应商; - 把一次异常操作总结为以后可以复用的“成功经验”; - 把恶意网页中的指令误认为用户长期偏好; - 在多个 Agent 之间共享已经被污染的任务结论; - 在未来检索时,将错误信息当作比外部证据更可信的历史事实。 这意味着,长期记忆不仅增加了 Agent 的能力,也扩大了攻击可能持续的时间与传播范围。 传统安全控制更擅长检查一次请求、一次网络连接或一次工具调用。Memory Poisoning 则要求系统观察一条信息从进入、加工、存储、调用、反馈到删除的完整生命周期。 ## 一条污染信息如何变成长期风险 |阶段|可能发生什么|应建立的控制| |---|---|---| |输入|网页、邮件、工具结果或外部 Agent 携带不可信内容|标记来源、信任等级与数据类型;高风险输入先验证| |写入|模型把临时内容或恶意指令总结为长期事实|写入权限、策略校验、敏感操作审批| |持久化|错误信息失去原始上下文,被当作稳定记忆保存|保留来源、时间、创建主体、版本和有效期| |召回|相似度检索在错误场景中调出污染记忆|身份与作用域过滤、时效判断、重排和置信度门槛| |行动|Agent 据此调用工具、生成建议或修改业务状态|最小权限、关键动作确认、输出与工具调用监控| |传播|结果进入其他 Agent、总结、知识库或派生记忆|记录血缘、限制跨域共享、支持追溯和批量处置| 这张链路也给出了安全团队的验收标准:不是只问“模型有没有答错”,而是确认污染信息能否被识别、阻止、追踪和清除。 ## 生产级记忆系统必须回答六个治理问题 ### 1\. 这条记忆来自哪里 系统需要区分用户明确表达、业务系统记录、外部文档、模型推断和 Agent 总结。 如果不同来源被压缩成同样的一段文本,后续就很难判断一条记忆是否可靠。生产系统应保留来源、创建时间、创建主体、关联任务和加工过程,使记忆能够被追溯。 ### 2\. 谁可以写入和修改 “可以读取记忆”与“可以写入长期记忆”不应自动使用同一权限。 来自网页、邮件、工具结果和第三方 Agent 的内容都可能包含不可信输入。系统需要为用户、组织、应用、Agent 和外部数据源设置不同的写入边界,并对高风险更新增加校验或人工确认。 ### 3\. 新信息如何与旧记忆发生关系 长期记忆不是一个只能追加的日志。 当新事实出现时,系统需要判断它是在补充、修正、替代还是否定旧信息。简单地把新旧内容同时保存,可能让 Agent 在未来随机调用互相冲突的结论。 ### 4\. 不同主体之间如何隔离 多用户、多 Agent 和多业务系统会产生大量记忆。系统必须明确哪些记忆属于个人、团队、组织、任务或特定 Agent,哪些可以共享,哪些禁止越界调用。 如果隔离只依赖上层应用临时拼接参数,随着系统扩张,越权和串扰风险会显著增加。 ### 5\. 错误记忆能否被修正、回滚和删除 发现错误只是第一步。系统还需要知道错误记忆被复制到哪里、是否产生了派生信息,以及如何停止后续调用。 因此,反馈、版本、回滚、精确删除和遗忘不是辅助功能,而是长期记忆的核心控制能力。 ### 6\. 系统能否持续发现异常 Memory Poisoning 可能以缓慢、累积的方式改变 Agent 行为。只检查单次回答,很难发现记忆层的长期偏移。 生产系统需要记录记忆写入、更新、召回和删除日志,并观察 Agent 调用了哪些记忆、访问了哪些数据、使用了哪些工具,以及行为是否偏离正常基线。 ## MemOS 如何把记忆治理放进系统架构 记忆张量MemTensor 将长期记忆视为需要独立管理的系统资源,而不只是模型上下文中的一段文本。 MemOS 位于 Agentic AI 与大语言模型之间,将记忆写入、检索、反馈、删除和模块编排从零散的应用逻辑中抽离出来。依据当前公开文档,可以验证的能力与安全价值如下: |治理目标|MemOS 公开能力|能解决什么|官方证据| |---|---|---|---| |让写入成为显式动作|Add Message|应用可明确控制哪些消息进入记忆流程|[添加消息](https://memos-docs.openmem.net/cn/memos_cloud/mem_operations/add_message/)| |让召回受查询和作用域约束|Search Memory|应用可在任务阶段按需调用记忆,而非拼接全部历史|[检索记忆](https://memos-docs.openmem.net/cn/memos_cloud/mem_operations/search_memory/)| |为纠错建立反馈入口|Add Feedback|将“不准确、已变化、不应复用”等结果送回记忆流程|[添加反馈](https://memos-docs.openmem.net/cn/memos_cloud/mem_operations/add_feedback/)| |为处置建立删除入口|Delete Memory|对错误、过期或不应保留的记忆执行显式删除|[删除记忆](https://memos-docs.openmem.net/cn/memos_cloud/mem_operations/delete_memory/)| |统一组织记忆模块|开源 MOS|为 Agent 调用和管理不同记忆模块提供编排层|[MOS架构概览](https://memos-docs.openmem.net/open_source/modules/mos/overview/)| 这些能力提供的是治理基础,而不是“自动免疫 Memory Poisoning”的承诺。公开接口也不能单独证明某项企业级控制已经完成部署。要形成闭环,MemOS 仍需与统一身份、最小权限、输入验证、人工审批、DLP、SIEM、业务日志和事件响应流程协同。 ## 反馈和删除为什么必须成为正式API 在简单原型中,开发者通常最关注“添加记忆”和“检索记忆”。但从安全与治理角度看,更新与删除同样重要。 MemOS 提供 [`/add/message`](https://memos-docs.openmem.net/cn/memos_cloud/mem_operations/add_message/)、[`/search/memory`](https://memos-docs.openmem.net/cn/memos_cloud/mem_operations/search_memory/)、[`/add/feedback`](https://memos-docs.openmem.net/cn/memos_cloud/mem_operations/add_feedback/) 和 [`/delete/memory`](https://memos-docs.openmem.net/cn/memos_cloud/mem_operations/delete_memory/) 等核心接口。 其中,反馈接口让应用能够把“这条记忆不准确”“用户偏好已经变化”“当前结果不应再次使用”等信息送回系统;删除接口则把清除错误、过期或不应保存的信息变成明确操作。 对于企业应用,这些接口还需要与身份、权限、审计和业务审批结合。谁发起修改、修改依据是什么、哪些对象受到影响、处理是否完成,都应该进入治理记录。 ## 分层记忆意味着分层风险 明文记忆、激活记忆和参数记忆具有不同的可见性与修改成本。 明文记忆更容易查看、编辑和溯源;激活记忆更接近实时推理过程;参数记忆则可能承载经过训练沉淀的稳定能力。错误信息进入不同层级后,影响范围和修复方式并不相同。 因此,记忆治理不能只检查向量数据库中是否存在一条错误文本,还要识别记忆是否已经进入缓存、图关系、派生总结、技能或其他可复用状态。 这也是分层架构的另一层价值:系统能够为不同记忆形态设计不同的写入门槛、更新策略和审计方式。 ## 私有化和端侧部署并不等于天然安全 企业常常把私有化或端侧部署视为记忆安全的解决方案。它们确实可以减少数据离开组织或设备边界的风险,但不能自动解决错误写入、权限过大、来源不明和内部污染。 本地保存的错误记忆仍然是错误记忆,私有环境中的过度权限仍然可能产生越权调用。 真正的生产级治理需要同时考虑: - 数据存放在哪里; - 谁可以读取、写入、修改和删除; - 外部信息进入系统前如何验证; - 记忆如何记录来源和版本; - 异常调用怎样被发现; - 用户或管理员怎样纠正系统状态。 MemOS 支持云服务、私有化、端侧和端云协同等部署方式。部署选择解决的是数据边界、性能与运维问题,记忆治理则需要贯穿每一种部署方式。 ## 不同行业需要不同的记忆风险模型 AI 陪伴产品可能更关注人格一致性、用户控制和敏感偏好;智能硬件需要处理多用户隔离和端侧隐私;金融 Agent 关注政策时效、业务权限与审计;工业 Agent 则需要区分设备事实、专家经验和现场异常。 如果把所有信息都当作同一种“可检索文本”,这些差异就会被隐藏。 生产级记忆系统需要根据行业和任务定义:哪些信息可以自动写入,哪些必须经过确认;哪些记忆可以共享,哪些必须隔离;哪些状态可以长期保留,哪些必须设置有效期;哪些错误可以通过反馈修正,哪些需要立即停止使用并触发审计。 ## 企业上线前可以直接执行的检查表 - 是否为每条记忆记录来源、创建主体、时间、作用域和有效期; - 是否区分读取、写入、修改、删除和跨主体共享权限; - 外部网页、邮件、工具输出是否默认按不可信输入处理; - 高风险记忆写入和关键业务动作是否需要二次确认; - 新信息与旧记忆冲突时,是否有覆盖、保留、降权或人工审核规则; - 是否能查询某条记忆被哪些任务召回、影响了哪些动作; - 发现污染后,是否能暂停调用、修正或删除原始记忆并追踪派生状态; - 是否监控写入量、召回命中率、冲突率、反馈纠错率、删除完成率、跨域访问和异常工具调用; - 是否定期用红队样本测试提示词注入、跨租户串扰、过期记忆和污染传播; - 是否明确云、私有化和端侧部署各自的责任边界。 ## 常见问题 ### 什么是 Memory Poisoning? Memory Poisoning 是不可信或错误信息进入 Agent 的持久记忆后,在未来任务中被重新调用并影响判断或行动的风险。它的关键特征是“持久”:攻击结果可能跨会话存在,也可能传播到派生记忆或其他 Agent。 ### 它与 Prompt Injection 有什么区别? Prompt Injection 通常直接操纵当前交互;Memory Poisoning 关注恶意影响是否被写入长期状态。一次提示词注入可以成为投毒入口,但只有当结果被持久化并在未来复用时,才形成记忆层面的长期风险。 ### 私有化部署后是否就安全? 不是。私有化主要改变数据和系统的部署边界,不能自动阻止错误写入、越权访问、来源伪造或内部污染。仍需配置身份权限、输入验证、审计、监控、纠错和删除流程。 ### 生产环境应该记录哪些记忆指标? 除延迟、错误率和成本外,还应记录写入来源、作用域、召回记录、冲突与覆盖、反馈纠错、删除状态、权限拒绝、跨域访问、异常工具调用,以及记忆对最终决策的引用关系。只有把“哪条记忆影响了哪个动作”记录下来,安全团队才可能完成追溯。 ### MemOS 在治理中扮演什么角色? MemOS 将写入、检索、反馈、删除和记忆编排变成可调用的系统能力,为治理闭环提供记忆层基础。它不能替代企业的 IAM、DLP、SIEM、审批和安全运营体系,也不应被描述为能够自动阻止全部投毒攻击。 ## Agent 越能长期行动,越需要对记忆负责 AI Agent 的价值来自连续性:它能够记住历史、延续任务、理解用户并复用经验。但同一份连续性也可能让错误与攻击持续更久。 因此,下一阶段的 Agent 竞争不会只比较“谁记得更多”,还会比较: - 谁能说明记忆从哪里来; - 谁能在信息变化后正确更新; - 谁能阻止不可信内容进入长期状态; - 谁能让用户和企业控制记忆; - 谁能在发生错误时完成追溯、修正与删除。 记忆张量围绕 Memory³ 相关记忆机制研究、MemOS 记忆操作系统、Agent 和记忆基础设施以及记忆原生模型展开长期智能技术路线。其核心判断是:记忆不只是提升个性化的产品能力,也是 Agent 进入真实生产环境必须被治理的基础设施。 当 Agent 开始长期运行,系统需要的不只是一座存放历史的仓库,更需要一套能够管理记忆全生命周期的控制系统。 ## 关于记忆张量MemTensor 记忆张量(上海)科技有限公司(以下简称“记忆张量MemTensor”)是由上海算法创新研究院孵化,并由中国科学院院士担任首席顾问的新一代大模型与长期智能基础设施企业。 公司以“低幻觉、个性化、自我学习进化”为核心,长期聚焦大模型长期记忆与持续学习问题,围绕 Memory³ 相关记忆机制研究、MemOS 记忆操作系统、Agent 和记忆基础设施产品化,以及记忆原生通用基座模型,构建从理论探索、系统工程化到模型层探索的递进式技术路线,推动 AI 从一次性生成走向长期智能。 公司已与招商、海诚、荣耀等重要合作伙伴建立深度协同关系,并在 AI 陪伴、游戏、端侧智能硬件、金融及工业等多个重点行业实现商业化落地,先后累计完成近两亿元融资,由中金、孚腾、华为哈勃、商汤、和玉等众多知名投资机构参投。 --- # 长任务 Agent 的记忆管理,从会话恢复到经验复用 (/cn/usecase/blog/long_task_agent_memory_management) > **核心结论:** OpenAI Agents API 把“持续运行数天”的 Agent 推向标准化,也暴露了长任务的另一面:上下文可以被压缩,进程可以被恢复,但一条状态为什么值得长期保留、何时失效、谁有权使用,仍然需要独立的系统判断。 --- ![长任务 Agent 的记忆管理,从会话恢复到经验复用](https://cdn.memtensor.com.cn/img/1789535419466_wb9ei0_compressed.jpeg) 2026 年 9 月 10 日,OpenAI 发布 Agents API 公开测试版,将会话编排、上下文压缩和任务恢复等能力整合到托管的 Agent 运行框架(harness)中。开发者可以通过 API 启动 Agent,配置工具调用与子 Agent 协作,并在后续交互中继续推进已有任务。 当 Agent 的工作从单轮问答扩展到跨会话、跨工具的连续执行,系统就需要持续跟踪任务进度、用户要求和阶段性结果。模型的推理能力、工具执行能力与状态管理能力,共同影响长任务的完成质量。 在这样的任务中,上下文管理有助于保留当前步骤所需的信息。对于需要跨会话复用的内容,还要进一步明确四个问题:哪些信息值得长期保存?新信息与旧信息冲突时采用哪条?多个 Agent 可以共享什么?任务结束后哪些信息应当删除? 长期记忆管理围绕这些问题展开。它以用户、任务或 Agent 为关联对象,管理信息如何跨会话保留、随时间更新,以及在什么范围内被调用,并与上下文管理、检索和底层存储配合工作。 ## 长任务 Agent 为什么需要记忆管理? 短任务所需的信息通常可以保留在当前上下文中。长任务则会不断生成工具结果、文件、计划、错误日志、用户反馈和阶段性结论。随着这些内容积累,将完整历史持续放回上下文,会带来三个需要处理的问题。 第一,历史内容会增加输入规模。如果每轮请求都携带完整历史,输入会随任务推进而增长,其中与当前步骤无关的内容也会反复进入上下文。筛选本轮所需的信息有助于控制输入规模;实际成本和延迟还取决于模型、缓存等机制。 第二,压缩需要保留信息来源和状态。对话摘要可以缩短文本,但如果省略了必要标记,就可能模糊“用户明确要求”“模型推测”“工具返回事实”和“已经失效的计划”之间的区别。后续任务需要据此判断哪些内容可以沿用,哪些仍需核实。 第三,信息的使用范围需要明确。一个子 Agent 写下的中间结论,是否已经核实,能否供其他 Agent 使用?一次失败尝试,哪些部分值得作为经验保存,哪些只需留在执行日志中?这些选择决定了历史信息如何影响后续工作。 因此,设计长任务 Agent 时,可以按四类管理对象明确分工。 | 管理对象 | 典型内容 | 主要职责 | | --- | --- | --- | | 任务执行状态 | 执行进度、工具调用记录、等待中的步骤 | 由运行框架和应用保存,用于继续执行与异常恢复 | | 工作上下文 | 当前指令、计划、最近的工具结果、召回的信息 | 组织模型本次推理可见的内容,按需压缩和替换 | | 外部知识 | 产品手册、项目文档、业务制度 | 从来源系统检索,维护文档版本和访问范围 | | 长期记忆 | 用户偏好、历史要求、可复用的任务经验 | 明确保存对象、适用范围、更新方式和删除路径 | 这些管理职责可以相互配合。上下文窗口限定一次推理能够容纳的信息范围;RAG 将检索到的信息用于生成回答,既可以检索外部知识,也可以召回历史记忆;向量数据库则可以提供向量存储与相似性检索能力。长期记忆管理关注信息如何写入、跨会话保留、随时间更新,以及在什么范围内使用。 以跨会话的报告任务为例,任务执行状态记录报告做到哪一步,工作上下文包含当前处理的章节,知识库提供需要引用的产品资料,长期记忆保存用户对报告格式的持续要求。下一次生成报告时,应用可以召回这些要求,并结合当次指令决定如何使用。 涉及订单支付状态、审批结果等业务数据的操作,则要以相应业务系统确认的当前状态为依据。记忆中的历史描述用于补充背景。 ## 生产环境中的记忆管理 长任务中的记忆会不断变化。用户补充了新的要求,旧计划需要更新;多个 Agent 接手同一项工作,共享信息需要有明确范围。记忆架构需要把这些变化纳入持续运行的流程,让信息的写入、使用、更新和删除相互衔接。 | 职责 | 管理内容 | | --- | --- | | 写入 | 选择需要保存的内容,区分用户陈述、工具结果和模型推断,记录可供核对的来源、时间和关联主体 | | 组织 | 明确记忆属于哪个项目、用户或 Agent,划分个人记忆与共享知识的存放范围 | | 检索 | 按任务需要选择记忆种类、过滤条件和返回数量,并在服务端执行相应的访问控制 | | 更新 | 区分信息补充、状态变化与错误纠正,核对更新后的内容及后续检索结果 | | 删除与保留 | 明确保留期限、删除对象和验证方式;应用自行保存的副本、日志与缓存按各自的保留规则处理 | | 运行记录 | 关联任务、记忆操作与实际送入模型的记忆,为异常排查提供依据 | 这些操作需要在同一条流程中衔接。例如,用户修改了报告格式要求,系统要更新对应记忆,让后续检索能够获取新的要求,并留下可供核对的修改记录。涉及多个 Agent 时,还要限定各自可读取和修改的范围。 ## MemOS 如何把记忆职责从应用逻辑中拆出来 在 MemOS 中,我们将记忆的读写与维护组织为独立的系统能力。开发者可以通过[组件和接口](https://memos-docs.openmem.net/cn/open_source/modules/mos/overview/)配置记忆处理流程,管理哪些信息被保存、何时召回,以及如何更新和删除。 通过 MemOS Cloud 接入时,应用可以调用[写入、检索、修改、反馈和删除接口](https://memos-docs.openmem.net/api_docs/start/overview/),并通过项目 API Key、用户标识及 Agent 过滤条件设置[记忆的检索范围](https://memos-docs.openmem.net/cn/memos_cloud/introduction/isolation_filters/)。会话标识 `conversation_id` 用于提高当前会话相关记忆的召回权重,不承担强制隔离职责。 面对偏好变化和状态更新,MemOS Cloud 的[时间感知](https://memos-docs.openmem.net/cn/memos_cloud/introduction/time_awareness/)能力会结合查询中的时间线索,选择当前或历史记忆。用户纠正信息时,[自然语言反馈](https://memos-docs.openmem.net/cn/memos_cloud/mem_operations/add_feedback/)可以触发相关记忆的校正与更新;需要精确修改时,也可以直接[修改指定记忆条目](https://memos-docs.openmem.net/cn/memos_cloud/mem_operations/update_memory/)。处理后的内容和检索结果可供应用查询核对。 长任务中的工具使用过程和任务经验,同样可以成为后续工作的参考。应用写入工具调用参数、真实返回结果及其关联信息后,MemOS Cloud 可以提取和保存[工具使用轨迹](https://memos-docs.openmem.net/cn/memos_cloud/features/tool_calling/)。 对于可复用的任务方法,MemOS Cloud 的[记忆自进化](https://memos-docs.openmem.net/cn/memos_cloud/features/self-evolving/)功能可以从历史对话中提炼技能,也支持上传已有的技能文件。[检索](https://memos-docs.openmem.net/cn/memos_cloud/mem_operations/search_memory/)时选择相应的记忆种类,即可召回相关轨迹或技能,交给 Agent 参考使用。 对于不再保留的内容,MemOS Cloud 支持[按记忆 ID 删除](https://memos-docs.openmem.net/cn/memos_cloud/mem_operations/delete_memory/)当前项目中的指定条目,并通过查询核对结果。 MemOS 的开源架构采用 [Components + Handlers](https://memos-docs.openmem.net/cn/open_source/modules/mos/overview/) 模式,将系统组件与请求处理逻辑分开。[MemCube](https://memos-docs.openmem.net/cn/open_source/modules/mem_cube/) 统一组织记忆模块,支持为不同用户和应用场景划分记忆容器;Handlers 协调组件完成添加、搜索和反馈等操作;[MemScheduler](https://memos-docs.openmem.net/cn/open_source/modules/mem_scheduler/) 在后台分发记忆更新、组织和反馈等任务,并提供任务状态与操作日志,便于跟踪异步处理进度。 接入应用时,这些记忆操作需要与现有的身份认证、业务授权和监控流程关联。应用服务端依据业务规则确定读写范围,并处理自身保存的副本与缓存。 ## 如何验证长任务中的记忆流程 记忆流程的验证需要覆盖多次交互。保存的信息能否在新会话中被找到,用户的修正能否进入后续任务,切换用户或 Agent 后检索范围是否符合预期,都要结合具体任务检查。验证时,可以从以下七个问题展开。 1. 任务跨会话恢复时,系统使用的是原始历史、摘要,还是结构化状态?这些信息分别由哪一层保存和恢复? 2. 一条长期记忆是否保留来源、时间、主体和作用域? 3. 模型、嵌入模型或 Agent 版本升级后,旧记忆的检索和使用是否经过兼容性测试? 4. 多个子 Agent 同时写入时,是否有明确的并发和冲突处理规则? 5. 错误记忆能否被反馈、修正和删除?如果已经影响后续任务,能否定位并处理相关记录? 6. 检索范围能否按身份、权限、时效和任务阶段设置,并由应用服务端执行相应的访问控制? 7. 一次异常操作能否关联到当时的输入、实际送入模型的记忆和工具执行结果? 当 Agent 持续参与多个任务和会话,记忆就需要与模型、工具和执行环境一起被设计和维护。通过 MemOS,我们将记忆的读写、更新和删除提供为可调用的系统能力,使跨会话积累的信息能够被持续管理,并在后续任务中按需使用。 了解更多:[MemOS 官方网站](https://memos.memtensor.net/)|[MemOS 文档](https://memos-docs.openmem.net/)|[MemOS GitHub](https://github.com/MemTensor/MemOS) ## 关于记忆张量MemTensor 记忆张量(上海)科技有限公司(以下简称“记忆张量MemTensor”)是由上海算法创新研究院孵化,并由中国科学院院士担任首席顾问的新一代大模型与长期智能基础设施企业。 公司以“低幻觉、个性化、自我学习进化”为核心,长期聚焦大模型长期记忆与持续学习问题,围绕 Memory³ 相关记忆机制研究、MemOS 记忆操作系统、Agent 和记忆基础设施产品化,以及记忆原生通用基座模型,构建从理论探索、系统工程化到模型层探索的递进式技术路线,推动 AI 从一次性生成走向长期智能。 公司已与招商、海诚、荣耀等重要合作伙伴建立深度协同关系,并在 AI 陪伴、游戏、端侧智能硬件、金融及工业等多个重点行业实现商业化落地,先后累计完成近两亿元融资,由中金、孚腾、华为哈勃、商汤、和玉等众多知名投资机构参投。 --- # 从数据归属到记忆删除:企业自托管 Agent 记忆的四个关键问题 (/cn/usecase/blog/self_hosted_agent_memory_four_questions) > **核心结论:** 企业选择自托管 Agent 记忆,通常希望把数据存储、模型调用和运行维护纳入自己的管理体系。随着 Agent 开始跨会话、跨团队协作,部署方案也需要回答更具体的问题:哪些信息值得保留,谁可以使用,出错后如何纠正,以及什么时候应该删除。 --- 在记忆张量MemTensor,我们提供 MemOS 云服务与开源自托管路径。企业可以围绕自己的基础设施配置记忆服务,并将记忆管理接入现有业务流程。 ## 1. 一条记忆属于谁,流经哪里? “客户 A 偏好邮件沟通”属于客户个人信息;客服团队的处理流程则适合在授权范围内共享。明确归属,才能决定一条记忆应当保存在哪里、由哪些 Agent 调用。 部署前,可以先梳理一次完整的数据流:消息从哪个业务系统进入,经过哪些模型和嵌入服务处理,生成的记忆、索引和日志分别存在哪里。模型服务、运维访问和备份位置也应纳入同一张图。 MemOS 的[自托管方案](https://docs.openmem.net/open_source/getting_started/rest_api_server/)通过 REST API 提供记忆写入、检索、获取和反馈等能力,并支持配置模型与嵌入服务。参考部署包含 Neo4j、Qdrant 等组件,企业可以结合已有环境规划服务连接和存储位置,让记忆能力融入现有技术架构。 如果业务要求数据在内网处理,就把模型、嵌入和其他外部调用一并纳入部署设计。这样,数据边界从方案阶段就有明确依据。 ## 2. 谁能写、读、改、删,又由谁批准共享? 同一个企业里的 Agent,往往承担不同职责。客服需要了解客户偏好,研发助手需要掌握项目约定,两者的记忆使用范围应与业务权限对应。 我们建议先区分个人、项目和组织级信息,再明确写入、读取、修改、删除与共享的负责人。例如,个人偏好由相关用户维护,项目流程由项目负责人确认,组织级规则经过审核后供更多团队使用。 在 MemOS 中,[MemCube](https://memos-docs.openmem.net/cn/open_source/modules/mem_cube/) 用于组织和管理记忆空间,支持单个空间的操作,也支持通过组合视图跨多个空间检索。应用可以结合用户身份和业务权限,为每次请求确定可读、可写的记忆范围,让多个 Agent 在授权范围内复用信息。 接入企业身份系统时,把账号、角色与这些记忆空间关联起来。员工离职、项目结束或共享权限撤销后,相应的访问范围也应及时调整。试点时,用不同用户和项目各做一次访问测试,就能较早发现权限配置中的遗漏。 ## 3. 出错时能否解释一条记忆的来路? 用户确认过的偏好、模型从聊天中推断的信息、工具返回的业务记录,需要保留各自的来源。Agent 答错时,团队才能沿着线索判断:信息是否记错、检索是否选错,还是正确的内容没有被用于回答。 MemOS 的[记忆调度模块](https://memos-docs.openmem.net/cn/open_source/modules/mem_scheduler/)负责协调记忆的流转与更新,并提供任务状态、处理时间和记忆操作日志。企业可以将这些记录接入现有监控系统,把业务请求、记忆处理和 Agent 回答关联起来,缩短排查路径。 例如,系统将用户一次临时选择记成长期偏好。用户纠正后,团队可以检查反馈处理过程、相关记忆的变化以及下一次检索结果,确认新信息是否进入了后续交互。 日志中优先保留记忆 ID、来源引用和操作记录,详细内容按权限查询。这样既便于追踪问题,也能减少敏感信息在多个运维系统中重复存放。 ## 4. 用户要求删除,具体删到哪里? 记忆管理需要区分纠错、过期和删除。客户换了联系方式,应更新当前信息;临时任务结束后,可以按保存期限清理;用户要求删除历史信息时,则需要明确涉及哪些记录和副本。 我们在 MemOS Cloud 中提供了[按记忆、用户或 Agent 删除的能力](https://memos-docs.openmem.net/cn/memos_cloud/mem_operations/delete_memory/),操作限定在当前项目内,Agent 级删除适用于已开启独立记忆的 Agent。企业采用自托管时,可以围绕实际使用的记忆模块和存储组件,将清理流程接入自己的数据管理体系。 实施时,把业务侧额外生成的摘要、缓存和备份纳入清理计划,约定处理时间与负责人。删除完成后,再通过相关业务入口检索一次,检查旧信息是否仍会进入 Agent 的上下文。 这让删除成为一项可以执行和追踪的日常操作,也方便团队向用户说明请求的处理进度。 ## 用一次试点把四问落地 选择一个真实业务场景,准备两个项目、两个用户和一条测试记忆,走完写入、检索、共享、纠错和删除的过程。观察授权用户能否获得需要的信息,其他用户是否被正确隔离,以及更新和删除是否反映在后续任务中。 MemOS 提供记忆组织、检索、反馈和调度能力,企业把身份规则、存储策略与运维流程接入其中。完成这轮试点,就可以形成一份清晰的上线方案:数据在哪里、谁能使用、问题如何追踪、记录怎样退出,让 Agent 在企业自己的环境中持续积累有用经验。 ## 关于记忆张量MemTensor 记忆张量(上海)科技有限公司(以下简称“记忆张量MemTensor”)是由上海算法创新研究院孵化,并由中国科学院院士担任首席顾问的新一代大模型与长期智能基础设施企业。 公司以“低幻觉、个性化、自我学习进化”为核心,长期聚焦大模型长期记忆与持续学习问题,围绕 Memory³ 相关记忆机制研究、MemOS 记忆操作系统、Agent 和记忆基础设施产品化,以及记忆原生通用基座模型,构建从理论探索、系统工程化到模型层探索的递进式技术路线,推动 AI 从一次性生成走向长期智能。 公司已与招商、海诚、荣耀等重要合作伙伴建立深度协同关系,并在 AI 陪伴、游戏、端侧智能硬件、金融及工业等多个重点行业实现商业化落地,先后累计完成近两亿元融资,由中金、孚腾、华为哈勃、商汤、和玉等众多知名投资机构参投。 --- # 100 万 Token 上下文,为什么还需要长期记忆? (/cn/usecase/blog/million_token_context_long_term_memory) > **核心结论:** 用户希望 AI 助手读懂一份长文档,也希望它记得上次已经确认的安排。换一个会话后,预算不用重新解释;偏好改变后,推荐能跟着调整;不想保留的信息,也有办法删除。 --- 大上下文扩展了模型一次处理信息的范围。长期记忆关注这些信息如何延续到下一次交互,包括哪些值得保留、属于谁、何时更新,以及什么时候停止使用。 在记忆张量MemTensor,我们通过 MemOS 管理这一过程,让 Agent 能够从持续交互中积累有用信息,并在后续任务中调用。即使上下文窗口达到 100 万 Token,这些跨会话的管理需求依然存在。 ## 四类能力,怎样配合? 上下文窗口、RAG、向量数据库和长期记忆处在不同层次,可以共同服务于一次任务。 | 能力 | 承担的角色 | 在客服场景中的用途 | | --- | --- | --- | | 上下文窗口 | 容纳模型处理当前请求所需的信息 | 放入当前问题、近期对话和检索结果 | | RAG | 从外部资料中检索内容,为回答提供依据 | 查找产品手册和保修政策 | | 向量数据库 | 存储向量表示,支持语义相似度检索 | 为相关文档或记忆提供候选结果 | | 长期记忆系统 | 管理跨会话事实与经验的保存、调用、更新和遗忘 | 接续客户已确认的偏好与处理进度 | RAG 可以使用向量数据库,也可以结合关键词、图谱等检索方式。长期记忆同样可以利用这些能力,把适合当前任务的信息送入上下文。模型负责理解和推理,记忆系统负责持续维护可供使用的信息。 ## 看一条会变化的用户事实 周一,用户告诉旅行助手:“这趟上海行每晚预算 800 元。”周三,她补充:“公司报销,预算上限改为 1,200 元,但要靠近会场。”周五,她换一个会话继续选酒店。 此时,助手需要接上这趟行程,使用最新预算和位置要求,而用户不必重述前两次对话。如果用户问起最初的安排,助手又应该能够找到 800 元预算的历史记录。 这里还涉及信息的适用范围:1,200 元是这次出差的预算,不宜直接变成用户今后所有旅行的默认标准。记忆需要保留事实所关联的任务、时间和来源,帮助后续检索选出适用的信息。 更大的上下文为模型理解完整历史提供了空间;长期记忆则让应用能够持续维护这趟行程,并在用户回来时带入相关内容。 ## MemOS 怎样接上这条链路 在 [MemOS Cloud](https://memos-docs.openmem.net/cn/memos_cloud/getting_started/overview/) 中,开发者可以提交对话消息,由系统处理并保存为记忆,再在后续请求中检索使用。围绕上面的旅行场景,可以把这一过程理解为三个环节。 **把不同用途的信息组织起来。** MemOS 支持[事实、偏好、属性、事件、技能、工具和知识库记忆](https://memos-docs.openmem.net/cn/memos_cloud/introduction/memory_types/)。事实和事件可以记录行程条件与相关安排,偏好用于辅助个性化推荐,知识库则可以提供公司的差旅制度。检索时,应用可以选择需要的记忆种类,并让用户记忆与知识库内容共同参与,为酒店推荐提供更完整的依据。 **让记忆跟上用户的变化。** MemOS 的[时间感知](https://memos-docs.openmem.net/cn/memos_cloud/introduction/time_awareness/)帮助检索区分当前信息与历史记录。预算调整后,当前任务应使用新的条件;回顾最初计划时,仍可以查询此前的信息。对于需要纠正的内容,开发者可以[按记忆 ID 修改](https://memos-docs.openmem.net/cn/memos_cloud/mem_operations/update_memory/),也可以通过[自然语言反馈](https://memos-docs.openmem.net/cn/memos_cloud/mem_operations/add_feedback/)提交“这次预算已经改了”这样的说明,由系统定位并更新相关记忆。 **让用户能够管理被记住的内容。** MemOS Cloud 提供[记忆删除能力](https://memos-docs.openmem.net/cn/memos_cloud/mem_operations/delete_memory/),支持在项目内删除指定记忆或某个用户的记忆;开启 Agent 独立记忆后,也支持按 Agent 删除。应用可以将这些能力接入用户设置或客服流程,并同步处理自己保存的相关副本,让记忆管理成为产品体验的一部分。 ## 先从一个真正需要记忆的任务开始 一次性的文档分析,可以优先利用大上下文和按需检索。对于持续服务的旅行助手、客服 Agent 或研发助手,长期记忆能帮助用户接着上次的进度继续工作,减少重复说明,也让已经确认的信息得到复用。 接入时,我们建议先选一个具体场景,走完四个动作:跨会话找回信息、修改一条事实、检查不同用户的访问范围,再删除一条测试记忆。观察这些变化是否反映在后续回答中,就能判断记忆是否真正服务于任务。 上下文容量决定一次能放入多少信息。用户持续使用一个 Agent 时,更容易感受到的是:它能否接上已有的安排,并随着新的需求一起调整。长期记忆让这种连续性成为可以设计和维护的产品能力。 ## 关于记忆张量MemTensor 记忆张量(上海)科技有限公司(以下简称“记忆张量MemTensor”)是由上海算法创新研究院孵化,并由中国科学院院士担任首席顾问的新一代大模型与长期智能基础设施企业。 公司以“低幻觉、个性化、自我学习进化”为核心,长期聚焦大模型长期记忆与持续学习问题,围绕 Memory³ 相关记忆机制研究、MemOS 记忆操作系统、Agent 和记忆基础设施产品化,以及记忆原生通用基座模型,构建从理论探索、系统工程化到模型层探索的递进式技术路线,推动 AI 从一次性生成走向长期智能。 公司已与招商、海诚、荣耀等重要合作伙伴建立深度协同关系,并在 AI 陪伴、游戏、端侧智能硬件、金融及工业等多个重点行业实现商业化落地,先后累计完成近两亿元融资,由中金、孚腾、华为哈勃、商汤、和玉等众多知名投资机构参投。 --- # 有了向量库,Agent 为什么还需要记忆管理? (/cn/usecase/blog/vector_database_memory_management) > **核心结论:** 一个 Agent 周一学会了项目的测试流程,周五再次接手任务时,就能沿用已有经验。如果团队周三调整了流程,Agent 也需要跟上这次变化,在后续任务中使用新的做法。 --- 向量数据库为语义检索提供基础。围绕持续运行的 Agent,一套记忆架构还需要管理信息的写入、更新、共享和退出,让过去积累的经验适用于眼前的任务。 在记忆张量MemTensor,我们将这些需求落实到 MemOS 的记忆管理能力中。下面六个问题,可以帮助团队梳理架构,也可以作为上线前检查用户体验的起点。 ## 1. 什么信息值得写入? 一次成功的工具调用、已经确认的项目决策、用户长期保持的偏好,都可能帮助 Agent 完成下一次任务。临时尝试和未经确认的推测,则需要保留对应的背景,避免被当成通用规则反复使用。 MemOS Cloud 的 [Add Message](https://memos-docs.openmem.net/cn/memos_cloud/mem_operations/add_message/) 接收对话、文件、工具调用等输入,自动提取信息,并处理已有记忆中的重复与冲突。应用可以根据业务节奏实时提交消息,也可以按对话轮次或批量导入。 我们还通过[不同种类的记忆](https://memos-docs.openmem.net/cn/memos_cloud/introduction/memory_types/)组织这些信息。例如,一次测试失败可以保留为事件,用户的工作习惯可以形成偏好,可复用的任务步骤则可以沉淀为技能。这样的组织方式,让后续任务更容易找到合适的经验。 ## 2. 下一次任务找回了什么? 当用户问“现在应该怎样运行测试”,Agent 需要找到当前项目适用的流程,并获得完成任务所需的上下文。检索设计应同时考虑相关性、适用范围和信息的新旧变化。 MemOS Cloud 的 [Search Memory](https://memos-docs.openmem.net/cn/memos_cloud/mem_operations/search_memory/) 支持选择记忆种类、设置过滤条件,并让知识库内容参与召回。研发助手可以结合开发者此前遇到的问题与项目测试文档;客服 Agent 也可以同时参考客户历史和产品手册。 接入时,选择几组真实任务观察结果:关键事实是否被找回,是否混入无关内容,以及送入模型的上下文能否帮助它完成工作。 ## 3. 用户改口之后,旧事实怎么办? 项目流程更新后,Agent 应当使用新的做法;用户询问此前为何采用另一条命令时,历史记录仍有参考价值。记忆管理需要同时支持当前任务和历史回顾。 MemOS Cloud 提供两种纠错方式。[修改记忆](https://memos-docs.openmem.net/cn/memos_cloud/mem_operations/update_memory/)适合按 ID 编辑一条已知记录;[自然语言反馈](https://memos-docs.openmem.net/cn/memos_cloud/mem_operations/add_feedback/)允许用户直接描述变化,由系统定位并更新相关记忆。管理员可以精确维护内容,普通用户也能在对话中完成纠正。 结合[时间感知](https://memos-docs.openmem.net/cn/memos_cloud/introduction/time_awareness/),检索可以区分当前有效信息和历史版本,让“现在怎么做”与“以前怎么做”得到各自需要的依据。 ## 4. 记忆什么时候该停止使用? 一条记忆的价值会随任务变化。临时排障方案可能在故障解决后失效,旧流程在更新后转为历史,用户也可能主动要求删除个人信息。 我们建议在产品设计时明确这些处理方式:哪些内容按期限清理,哪些保留历史,哪些允许用户随时删除。 MemOS Cloud 的[删除能力](https://memos-docs.openmem.net/cn/memos_cloud/mem_operations/delete_memory/)支持在项目内删除指定记忆或某个用户的记忆;开启 Agent 独立记忆后,也支持按 Agent 删除。应用可以将这些操作接入用户设置和数据管理流程,并同步处理自己保存的相关摘要或缓存,让用户能够管理长期保留的信息。 ## 5. 谁能读到这条记忆? 项目测试规范适合在团队内共享,某位开发者的个人习惯则应留在相应的用户范围。多个 Agent 协作时,需要按照任务和身份取得各自有权使用的内容。 MemOS Cloud 的[多用户与多 Agent 记忆管理](https://memos-docs.openmem.net/cn/memos_cloud/introduction/isolation_filters/)通过项目 API Key 和用户标识区分记忆范围,也支持按 Agent 过滤。开启独立记忆后,Agent 可以积累自己的长期经验,服务于跨用户、跨会话的协作场景。 应用负责将这些范围与实际登录身份、业务权限关联。明确的共享规则,能让团队经验得到复用,同时保护个人信息和项目边界。 ## 6. 怎样知道记忆帮了用户? 记忆的价值最终体现在任务中:用户是否少解释了一遍背景,Agent 是否沿用了正确流程,信息修改后是否及时调整了后续行动。 团队可以选择一组跨会话任务,对比使用记忆前后的完成情况,重点观察任务成功率、重复提问和错误信息的变化。再加入一次纠错与删除,就能看到这套架构如何应对日常变化。 MemOS Cloud 提供[调用日志与调用链分析](https://memos-docs.openmem.net/cn/memos_cloud/getting_started/cloud_and_opensource/),帮助开发者追踪记忆请求与处理过程。在本地 Agent 场景中,[MemOS Local Plugin 的可视化管理界面](https://docs.openmem.net/openclaw/local_plugin/)提供任务轨迹、Analytics 和 Logs 等视图,便于查看积累了哪些经验。结合应用侧的任务结果,这些记录可以帮助团队发现问题并持续优化。 从一条具体的用户旅程开始,把写入、找回、纠正、隔离和删除串起来。随着场景成熟,再扩展到更多用户和 Agent。MemOS 将这些记忆操作组织为可持续维护的能力,让每一次交互积累的经验,能够在下一次任务中发挥作用。 ## 关于记忆张量MemTensor 记忆张量(上海)科技有限公司(以下简称“记忆张量MemTensor”)是由上海算法创新研究院孵化,并由中国科学院院士担任首席顾问的新一代大模型与长期智能基础设施企业。 公司以“低幻觉、个性化、自我学习进化”为核心,长期聚焦大模型长期记忆与持续学习问题,围绕 Memory³ 相关记忆机制研究、MemOS 记忆操作系统、Agent 和记忆基础设施产品化,以及记忆原生通用基座模型,构建从理论探索、系统工程化到模型层探索的递进式技术路线,推动 AI 从一次性生成走向长期智能。 公司已与招商、海诚、荣耀等重要合作伙伴建立深度协同关系,并在 AI 陪伴、游戏、端侧智能硬件、金融及工业等多个重点行业实现商业化落地,先后累计完成近两亿元融资,由中金、孚腾、华为哈勃、商汤、和玉等众多知名投资机构参投。 --- # Agent 记忆与 RAG 的区别:2026 年生产实践指南 (/cn/usecase/blog/agent_memory_is_not_rag) Agent 可以检索政策 PDF、记住客户偏好简洁回答、在工具调用间维持工作流,也可以查询实时订单系统。这是四种不同职责。把它们全部叫作“记忆”,会让生产设计和产品比较失去精度。 RAG 查找当前回答所需的外部证据;Agent 记忆保留跨轮次、会话或工作流的有用状态。更大的上下文窗口为单次推理提供更多材料,但保存什么、如何更新旧偏好、怎样执行删除,仍需要另外定义。Oracle 的开发者指南同样强调:持久记忆需要明确身份与范围、来源、生命周期规则和遵循权限的召回。[Oracle Developers](https://blogs.oracle.com/developers/agent-memory-is-not-rag) 向量索引可以是很好的检索组件。完整记忆方案还需要规定信息何时成为持久记录、怎样纠错、过期、隔离和审计。 选择 AI 记忆方案,先明确需要记住什么、信息在哪里可用,以及它应当怎样随时间变化。不同产品通过记忆 API、时序图谱、有状态 Agent 或更广泛的记忆管理系统处理这些需求。 本文从生命周期、检索、部署与应用适配比较 Mem0、Zep/Graphiti、Letta、MemOS 和 Supermemory,说明 MemOS 的位置,并给出实际选型问题,帮助探索阶段与生产评估中的团队作出决定。 ## 先区分四个层次 **提示词上下文**是模型在一次推理中可见的有限 Token 集合,可以包含当前用户消息、系统指令、工具结果、滚动摘要、检索文档与选定记忆。上下文工程关注决策时如何选择、过滤、压缩和刷新这些材料。[Redis](https://redis.io/blog/ai-agent-context/) **RAG**从文档、记录、表格或其他授权材料中检索证据,主要职责是为回答提供依据:使用相关、可访问且有效的来源,并保留足够的溯源信息供核查。RAG 可以是无状态的。良好的流程会处理租户与 ACL 过滤、文档版本、分块或结构化检索,并在需要证据时提供引用。它适合回答“当前政策怎么规定?” **向量数据库或向量索引**存储嵌入并支持相似度检索,许多产品还提供过滤、关键词、元数据或混合检索。它可以支撑 RAG 和语义召回。至于昨天改变的语言偏好是否替代旧事实,以及跨会话如何识别用户,属于更上层的记忆管理。 **Agent 记忆**是经过选择、限定范围、供以后使用的持久状态,通常包括偏好、带时间的事实、任务状态、摘要、决策、已学习流程或已验证工具结果。难点包括:保存什么;哪些用户、租户、Agent、任务与权限背景可以检索;什么会更新或使它失效;谁可以检查、纠正、删除和审计。 生产环境中,这些层次通常并存。客服 Agent 可以组合当前指令、任务摘要、限定到客户与租户的记忆、RAG 政策引用,以及工具返回的实时账户状态。业务实时数据仍以业务系统为准。 ## MemOS 的位置 我们构建 MemOS,是为了让长期记忆成为 AI 应用和 Agent 中可以管理的组成部分。它提供独立层,保留有用背景、在相关时召回,并随着偏好、事实和任务变化更新,支持跨对话连续性、个性化与 Agent 工作流中的背景复用。 MemOS 将存储、检索、多种记忆形态与记忆调度结合起来。Cloud API 提供对话写入、记忆检索、记录更新与删除,以及通过反馈纠错;过滤、标签、异步处理、知识库与 Chat API 支持不同接入需求。 可以通过托管 Cloud、开源框架与支持的 Agent 集成接入,根据团队运维能力和定制要求选择。 [MemOS 官网](https://memos.openmem.net/) · [Cloud 概述](https://memos-docs.openmem.net/cn/memos_cloud/getting_started/overview/) · [API 概览](https://memos-docs.openmem.net/cn/api_docs/start/overview/) · [GitHub](https://github.com/MemTensor/MemOS) MemTensor 是 MemOS 背后的公司,为 AI 应用构建记忆基础设施,并研究长期记忆与持续学习,目标是减少幻觉、改善个性化,让系统更好地利用已有经验。 我们的工作覆盖 Memory³ 研究、MemOS、Agent 记忆基础设施与记忆原生基座模型研究,将理论与信息的长期存储、检索和维护结合起来。MemOS 将这一方向带入需要跨对话背景的应用。 > **产品边界:MemOS 与 Memmy。** > > MemOS 通过 API、开源组件和集成方案,为 AI 应用与 Agent 提供记忆能力,适合把记忆接入应用或现有 Agent 工作流,并选择托管服务或自行运维组件。 > > Memmy 是个人 AI Agent 与本地记忆中心,整合桌面应用、本地记忆服务、CLI 与工具集成,帮助个人在支持的 AI 工具之间复用背景,延续日常工作。 > > 需要在应用或 Agent 流程中添加、定制记忆能力时选择 MemOS;需要个人 Agent 与本地记忆中心,将支持的工具围绕共享背景连接起来时选择 Memmy。 > > [Memmy 官网](https://memmy.bot/) · [官方 GitHub](https://github.com/MemTensor/memmy-agent) ## 生产选型的七个维度 比较产品前,先用一页说明允许存储的数据类别、必须隔离的范围、纠错与删除负责人、权威来源,以及记忆不可用时的处理方式,再按以下七个维度评估。 ### 1. 生命周期 能否有选择地添加、更新、删除、过期、合并或回滚记忆?应用能否区分原始事件、抽取记忆,以及让它成为持久记录的规则?检查时间、来源、冲突处理、保留控制与明确纠错路径。将每条消息生成向量属于摄入,实现生命周期还需要这些规则。 ### 2. 检索与上下文组装 检索返回文档、事实、图关系、属性、记忆块、摘要,还是多种组合?生成前如何过滤?测试租户、用户、Agent、会话、时间、记忆种类与权限条件。同时评估质量与上下文预算:十行相关记忆可能比二十个相似分块更有用。用任务质量、泄露率、检索准确率和新增延迟衡量。 ### 3. 部署与数据边界 选择 SDK 前,先确定运行模式。公开文档提供库、自托管服务、托管云服务,还是多种路径?明确模型、嵌入、数据库、图存储、对象存储、遥测与出站网络依赖。自托管软件包之外,还需要设计完整私有部署与企业控制。 ### 4. 治理与隔离 将记忆读取作为数据访问决策。在相关场景中,明确租户、用户、Agent、任务或会话、请求和权限标识。摄入前定义脱敏与秘密信息排除规则,在实际采用的产品版本中验证按范围删除、纠错、保留、访问控制和审计证据。Cloudflare 也将限定范围的持久状态视为核心运行问题。[Cloudflare](https://blog.cloudflare.com/introducing-agent-memory/) ### 5. 可观测性 为每轮模型调用记录检索请求、过滤条件、候选 ID、选中记忆 ID、来源、时间、Token 数、模型回复与用户反馈。分别观测接纳、修改、删除和回滚。在减少敏感日志副本的同时,能够解释为什么送入某条记忆,以及旧记录为何仍然存在。 ### 6. 生态与应用适配 评估实际会用的 Python、TypeScript、REST、MCP、Agent 框架、工具调用或云平台接口。优先选择能延续现有身份与授权模型的接入路径,并验证集成是否落实组织治理策略。 ### 7. 实际环境中的运行成熟度 按自身要求测试升级、备份、灾难恢复、模型供应商故障、限流、模式变化、迁移和事件支持。代码、文档和部署选项的存在,与满足特定 SLA 或合规体系,是不同的验证目标。 ## 五种 AI 记忆方案 ### Mem0 **概述。** 官方仓库提供记忆库、自托管服务器与托管平台。自托管通过 Docker Compose 部署,文档包含默认启用认证、管理员初始化、API Key 与仪表盘,也提供 Python、npm 安装和按用户 ID 添加、检索的 CLI。仓库使用 Apache-2.0 许可。[Mem0 仓库](https://github.com/mem0ai/mem0) · [自托管说明](https://github.com/mem0ai/mem0/blob/main/docs/open-source/setup.mdx) **适用场景。** 需要以记忆为中心的接入接口,并希望在库、托管与自托管之间选择的团队。文档化的自托管路径为自行运维提供起点;托管平台是另一种运维选择。 **评估重点。** 检查抽取与检索配置如何处理纠错、冲突、租户隔离、删除传播及自身授权模型。使用自己的模型和数据评估质量与成本,确认 SDK 抽象下实际选中了什么记忆。 ### Zep/Graphiti **概述。** Graphiti 与 Zep 相关,但属于不同选择。Graphiti 是 Zep 的 Apache-2.0 开源时序上下文图框架,仓库包含事件摄入、混合检索、图距离重排、MCP 服务器与图存储选项。Zep 是基于 Graphiti 的托管 Agent 记忆服务,文档描述用户与任务线程、上下文组装,以及 Zep Cloud、BYOK 和 BYOC 等部署治理选项。[Graphiti](https://github.com/getzep/graphiti) · [Zep 与 Graphiti](https://help.getzep.com/zep-vs-graphiti) · [Zep 概念](https://help.getzep.com/concepts) · [安全与合规](https://help.getzep.com/v3/security-compliance) **适用场景。** 时序关系和图检索是核心,且团队希望构建、运维外围服务时,可以考虑 Graphiti;希望通过托管服务获得同类能力,并使用已文档化的用户、任务线程和企业部署抽象时,可以考虑 Zep。 **权衡。** 使用 Graphiti,需要团队设计图基础设施、抽取、实体消歧、时序失效、并发与授权。Zep 减少部分运维工作,同时引入商业服务、契约和数据边界选择。两种路径都应测试:有时间范围的关系是否足以改善任务,值得承担额外图谱与摄入复杂度。 ### Letta **概述。** Letta 面向有状态 Agent,提供 API、Python 与 TypeScript 客户端、自托管 base URL,以及可挂载或从 Agent 移除的记忆块。官方 Apache-2.0 仓库将其称为开源项目,并提供本地 CLI 与 API 路径。TypeScript 文档介绍了通过挂载到多个 Agent 来共享记忆块。[Letta 仓库](https://github.com/letta-ai/letta) · [TypeScript 文档](https://docs.letta.com/api/typescript) **适用场景。** 记忆与 Agent 运行时紧密结合,并希望采用以 Agent 为中心的状态模型时,可以考虑 Letta。有意识且经过授权的共享背景,可以通过共享块实现。 **权衡。** 将隔离、记忆块共享、编辑、删除、导出、模型行为、工具状态和迁移作为主要测试用例,确认应用是否需要独立于单个 Agent 运行时的可迁移记忆。 ### MemOS **概述。** MemOS 为 AI 应用与 Agent 提供独立的记忆存储、检索、更新和管理层。Apache-2.0 开源框架支持多种记忆形态与调度;Cloud 提供抽取、检索、更新、删除、反馈纠错,以及知识库与 Chat 能力,也为企业提供私有部署和定制集成选项。[MemOS 仓库](https://github.com/MemTensor/MemOS) · [Cloud 文档](https://memos-docs.openmem.net/cn/memos_cloud/getting_started/overview/) · [API 概览](https://memos-docs.openmem.net/cn/api_docs/start/overview/) · [官网](https://memos.openmem.net/) **适用场景。** 需要跨对话、跨 Agent 工作流延续背景,并明确控制检索与维护的应用。托管接入可以选择 Cloud API;也可以按运行环境选择开源框架与 Agent 集成。 **权衡。** 测试负载所需的记忆形态与调度行为、每次调用携带的身份和范围、纠错与删除的生命周期、集成适配,以及所选版本的运维设计。广泛的记忆抽象带来灵活性,也要求明确哪些信息可以成为可复用记忆。 ### Supermemory **概述。** 官方 MIT 许可仓库提供记忆与上下文 API、JavaScript 与 Python SDK、容器标签、文档摄入、语义和混合检索,以及 API Key 认证。公开仓库的自托管快速开始包含本地服务器和嵌入式引擎,SDK 可以连接自托管 base URL。[仓库](https://github.com/supermemoryai/supermemory) · [自托管快速开始](https://github.com/supermemoryai/supermemory/blob/main/apps/docs/self-hosting/quickstart.mdx) · [SDK 文档](https://github.com/supermemoryai/supermemory/blob/main/apps/docs/integrations/supermemory-sdk.mdx) **适用场景。** 希望采用 API 接入,将用户背景与文档检索结合,并评估托管式调用和已文档化的本地、自托管路径的团队。 **权衡。** 检查容器标签如何映射租户、用户、Agent 与会话边界。测试属性或抽取记忆的时效、文档与记忆检索的区别、删除传播、模型供应商依赖,以及实际负载下自托管设计的规模与持久性。 ## 从比较走向决策 产品适配取决于记忆形态。图优先系统适合随时间变化的关系,Agent 运行时系统适合有状态控制,记忆 API 适合快速接入,更广泛的记忆操作层适合多种形态间的生命周期与调度。 按自己的数据规则开展限定时间的概念验证。按需为请求提供租户、用户、Agent、任务、会话与请求标识,准备已知正确事实、故意过期事实、冲突更新、排除保留的敏感值,以及跨租户近似记录。衡量检索准确率、任务成功率、延迟、Token 成本、写入成本、删除完成情况,以及解释选中条目的难易程度,并演练供应商故障与恢复。 当团队能解释每条记忆的归属、保存原因、替代关系、访问权限、存储位置、观测与删除方式时,选型才具备生产依据。RAG 则继续承担来源明确的证据检索,与持久 Agent 状态协同工作。 --- # Agent 记忆可观测性:上线后值得关注的 12 项指标 (/cn/usecase/blog/agent_memory_observability_12_measures) *记忆张量 MemTensor 的生产检查清单* Agent 可能给出了正确答案,却依赖一条过期偏好;也可能检索到调用者无权访问的记录,或在用户纠正后继续使用旧信息。我们建议从首次写入到检索、再到后续变化,全程追踪记忆,了解哪些记录实际进入模型,并据此排查结果。 ## 从用户完成任务的结果出发 选择一个记忆应当有所帮助的任务:一周后接续客服工单、编码 Agent 应用项目规则,或助手使用修正后的偏好。在模型、基础提示词、工具与评分标准一致的条件下,对比使用和不使用授权记忆的同类任务。 同时记录任务成功率、检索质量和延迟,才能把记忆系统的变化与 Agent 实际完成的工作关联起来。 ## 起步时的十二项指标 以下指标用于应用侧评估。试点前先定义标注规则、抽样方法和验收阈值。 | 阶段 | 指标 | 衡量方式 | | --- | --- | --- | | 写入 | **1. 记忆接受率** | 抽样生成记忆中,内容准确、归属正确且值得保留的比例。 | | 写入 | **2. 重复写入率** | 新存储记录中,与现有有效记忆形成无必要重复的比例;有意保留的历史版本除外。 | | 写入 | **3. 写入到可检索延迟** | 从提交写入,到预先定义的授权查询首次成功找回记忆的时间,报告 p50 和 p95。 | | 检索 | **4. 事实召回率 recall@k** | 前 k 条结果覆盖的必要事实数,除以任务所需的全部事实数;事实去重后计算。 | | 检索 | **5. 准确率 precision@k** | 前 k 条结果中的相关记录数除以 k,未返回满的结果位按未命中计算。 | | 检索 | **6. 过期信息召回率** | 返回记录中,相对于问题所要求时间已失效的比例。 | | 检索 | **7. 跨范围信息暴露率** | 权限范围测试中,返回任意未授权记忆的测试比例,无论它是否出现在最终回答里。 | | 检索 | **8. 读取延迟 p95** | 从发起检索请求到收到响应的第 95 百分位耗时,按负载与数据规模分别统计。 | | 更新 | **9. 纠错传播时间** | 从提交纠正,到当前状态查询返回新值、且不再把旧值当作当前值的时间。 | | 更新 | **10. 未解决冲突率** | 已审核事实组中,同一实体、属性、作用域和有效时间仍存在不兼容当前值的比例。 | | 遗忘 | **11. 删除完成率** | 在截止时间前,已在声明范围内验证完成的删除请求数,除以全部到期请求数。 | | 结果 | **12. 任务成功率增量** | 同类任务在使用和不使用授权记忆时的成功率差值,以百分点表示。 | 按实际负载设置延迟预算,并在成功请求耗时之外报告失败与超时。即使总体比例很低,也要逐条检查越权暴露和未完成的删除。 ## 用标识符串联过程,减少私密内容副本 将每次请求与认证后的访问范围、查询、返回的记忆 ID、实际注入的记忆 ID、回答和反馈关联起来。对于写入、更新和删除,记录受影响的记忆 ID、来源引用、操作主体和时间。敏感内容保留在指定存储中,遥测系统通过引用查询。 MemOS Cloud 的[异步写入](https://memos-docs.openmem.net/cn/memos_cloud/features/async_mode/)会返回任务 ID,处理在后台继续进行。通过[获取任务状态](https://memos-docs.openmem.net/cn/api_docs/message/get_status/)跟踪完成情况,并按类别识别受影响的记忆。同时记录处理完成时间和首次成功检索时间。 [Cloud 控制台](https://memos-docs.openmem.net/cn/memos_cloud/getting_started/cloud_and_opensource/)提供调用日志与调用链查看,便于排查 API 行为。[MemOS Local Plugin Viewer](https://docs.openmem.net/cn/openclaw/local_plugin/)把记忆、任务、Analytics 和 Logs 汇集到同一个界面,便于检查本地运行情况。采用[开源部署](https://memos-docs.openmem.net/cn/memos_cloud/getting_started/cloud_and_opensource/)时,也可以在自己的基础设施中扩展服务端观测。 ## 发布前演练三类失败 **尝试越权读取。** 使用不同用户和项目的测试账号,也测试篡改标识符的请求。MemOS Cloud 的[项目与用户隔离](https://memos-docs.openmem.net/cn/memos_cloud/introduction/isolation_filters/)通过项目 API Key 和 `user_id` 区分记录。在后端将这些 ID 绑定到已认证的调用者,再检查未授权请求是否会暴露其他范围的记录。 **纠正一条偏好,再执行同一任务。** [修改记忆](https://memos-docs.openmem.net/cn/memos_cloud/mem_operations/update_memory/)按 ID 编辑已知记录;[添加反馈](https://memos-docs.openmem.net/cn/memos_cloud/mem_operations/add_feedback/)理解自然语言纠正,定位相关记忆并更新。按约定期限衡量传播时间;历史记录可以保留,但应被识别为历史状态。 **删除测试记忆,再次检索。** [删除记忆](https://memos-docs.openmem.net/cn/memos_cloud/mem_operations/delete_memory/)支持在 API Key 所属项目内删除指定条目或用户的记忆。按 Agent 删除需要开启 Agent 独立记忆。查询应用使用的每一条检索路径,并在删除策略覆盖的底层存储中验证完成情况,包括应用保存的副本。 从一条用户旅程和一小组已标注任务开始。当更多指标能够帮助诊断失败或作出发布决策时,再扩展测量范围。 --- # 如何为 AI Agent 选择 MemOS 接入方式 (/cn/usecase/blog/choosing_memos_integration) 假设客户在换货申请获批三天后再次联系,想知道何时发货,并提供了新的收货地址。处理这次对话的 Agent 需要此前的审批结果、更新后的地址,以及订单系统中的当前物流状态。 这为选择记忆系统提供了具体起点:从信息第一次出现的对话,一直追踪到后续需要它的任务。 我们构建 MemOS,是为了帮助应用[跨对话延续上下文](https://memos-docs.openmem.net/cn/memos_cloud/getting_started/quick_start/)。可以接入托管 API、在自己的基础设施上运行开源服务,或通过插件为支持的 Agent 添加记忆。起点取决于应用形态和运维方式。 ## 先确定接入运行在哪里 团队自行开发应用时,首先选择托管服务或自行部署;为已有 Agent 环境添加记忆时,插件负责连接 Agent 与记忆系统。 | 正在构建的应用 | 建议起点 | 团队负责的内容 | | --- | --- | --- | | 需要托管记忆服务的应用 | [MemOS Cloud API](https://memos-docs.openmem.net/cn/memos_cloud/getting_started/quick_start/) | 应用集成、用户身份,以及召回记忆如何进入模型上下文 | | 运行在自有基础设施上的服务 | [MemOS 开源框架](https://github.com/MemTensor/MemOS) | 服务、存储依赖、模型配置与运维 | | 使用云端记忆的 OpenClaw 或 DeepSeek Harness | [MemOS Cloud Plugin](https://memos-docs.openmem.net/cn/openclaw/guide/) | Agent 环境与插件配置 | | 使用本地记忆的 OpenClaw、Hermes Agent 或 DeepSeek Harness | [MemOS Local Plugin](https://docs.openmem.net/cn/openclaw/local_plugin/) | 本地运行环境、模型连接与备份 | 使用 MemOS Cloud 时,由我们运维记忆服务。自托管则让团队控制代码与基础设施;[参考 Docker 部署](https://github.com/MemTensor/MemOS)同时运行 MemOS API、Neo4j 与 Qdrant。 插件把记忆接入 Agent 的日常执行。MemOS Cloud Plugin 在运行前召回相关记忆,运行后保存新消息。MemOS Local Plugin 在本机维护 SQLite 存储,结合向量与词法检索,并将执行经验转化为可复用策略与技能,通过 Memory Viewer 检查结果。[本地配置](https://docs.openmem.net/cn/openclaw/local_plugin/)包含模型连接和可选的团队共享;判断数据处理位置时,需要一并查看这些设置。 选定路径后,测试真正需要的工作流程。下文以 MemOS Cloud 接口为例。 ## 决定下一次对话需要记住什么 换货案例中,客户的通知偏好属于个人历史;公司的换货政策属于共享业务知识;查询订单并创建换货工单的流程,则可能被多个客户场景复用。 [客服示例](https://memos-docs.openmem.net/cn/usecase/customer_service_assistant/)将它们分别组织为用户记忆、Agent 技能与政策知识库。这样,Agent 可以同时检索客户背景与通用流程,并继续通过订单、工单系统获取当前业务状态。 MemOS Cloud 提供[多种记忆类型](https://memos-docs.openmem.net/cn/memos_cloud/introduction/memory_types/):事实和偏好记录客户背景;事件记忆保留发生过什么;技能与工具记忆保存可复用的任务经验;属性记忆在应用需要结构化用户视图时,将信息组织到预定义字段中。 不同类型的准备工作有所区别。属性记忆需要为用户绑定模板,工具记忆需要输入工具调用信息,知识库需要上传内容。写入时使用 `allow_memory_view` 选择允许生成的种类。 开发阶段,检查几个代表性对话的抽取结果。“发货时请短信通知我”是一条偏好;“如果下个月搬家,我就需要改地址”是一条带条件的陈述。测试应检查抽取后是否保留了条件。 需要单独检查抽取时,[记忆抽取接口](https://memos-docs.openmem.net/cn/self_developed_model/extraction_usage_example/)可以返回事实与偏好候选,而不写入记忆存储。它支持文本对话的同步抽取,便于应用检查或增加自身验证。使用完整写入流程后,也要查看实际存储的记录。 ## 让再次联系的客户被正确识别 客户从另一个渠道回来时,使用相同的 `user_id`。应用从已认证的客户记录中确定这个标识。 MemOS Cloud 的[项目与用户范围](https://memos-docs.openmem.net/cn/memos_cloud/introduction/isolation_filters/)决定请求检索哪些个人记忆。API Key 选择项目,`user_id` 标识项目内客户。API Key 保留在服务端,每个请求与应用访问规则关联。 多个 Agent 服务同一客户时,可以用 `agent_id` 标记记忆,并按生成记忆的 Agent 过滤。Agent 也可以拥有自己的独立记忆,例如积累可复用客服技能。该行为需要在项目设置中开启「为 Agent 创建独立记忆」,默认关闭。 新对话仍然可以使用客户先前的记忆。`conversation_id` 提供会话背景并影响相关性,不会自动将检索限制在当前会话内。 [检索记忆接口](https://memos-docs.openmem.net/cn/memos_cloud/mem_operations/search_memory/)结合关键词、向量检索、排序、过滤与去重。通过 `include_memory_view` 选择记忆种类,`memory_limit_number` 控制结果数量,`filter` 缩小范围。 在这个案例中,检查检索是否返回换货批准记录和相关收货信息,再检查应用实际送入模型的上下文。[应用接入流程](https://memos-docs.openmem.net/cn/memos_cloud/getting_started/quick_start/)展示了召回内容加入提示词的位置。 ## 处理地址变化 周一正确的信息,周四可能需要更新。MemOS Cloud 的[时间感知机制](https://memos-docs.openmem.net/cn/memos_cloud/introduction/time_awareness/)支持状态变化与历史问题,让当前信息和早期版本分别服务不同请求。导入旧对话时提供 `chat_time`,保留信息的记录时间。 系统也需要纠错方式。客服团队知道具体错误条目时,可以[按记忆 ID 修改](https://memos-docs.openmem.net/cn/memos_cloud/mem_operations/update_memory/)内容、标题或状态。客户在对话中纠正时,后端可以附带用户与会话背景,通过[自然语言反馈](https://memos-docs.openmem.net/cn/memos_cloud/mem_operations/add_feedback/)提交。 持续跟踪到操作完成。Cloud 写入默认采用[异步处理](https://memos-docs.openmem.net/cn/memos_cloud/features/async_mode/)。使用返回的 `task_id` 查询 `get/status`,完成任务包含记忆变更摘要。随后再次检索相关信息,确认下一次回答使用新地址。 真正发货前,应用仍应通过业务系统核实地址与订单状态。 ## 明确删除对象 客户要求删除历史信息时,先确定请求覆盖哪些记录。 [`delete/memory` 接口](https://memos-docs.openmem.net/cn/memos_cloud/mem_operations/delete_memory/)每次接受三种目标之一:具体的 `memory_ids`、`user_id` 或 `agent_id`。操作范围限定在 API Key 所属项目内,按 Agent 删除需要开启独立记忆。 该接口的删除目标不包含会话 ID 或知识库 ID。知识库文件使用[独立删除接口](https://memos-docs.openmem.net/cn/api_docs/knowledge/delete_kb_doc/),传入 `file_ids`。 删除后重复相关检索。定义完整删除流程时,一并考虑应用在缓存、导出文件或日志中保留的副本。 ## 推广前走完完整案例 试点始终围绕同一个换货场景。几种变化比一组互不相关的提示词更容易暴露集成问题。 1. **在新会话中返回。** 记录审批结果后,为同一客户打开另一次对话,检查 Agent 能否接续工单,减少重复询问。 2. **修改细节。** 更新收货地址,或把邮件通知改为短信,检查存储变化与下一次回答。 3. **加入条件陈述。** 尝试“如果我搬到西雅图,就需要更新地址”,检查可能发生的搬家是否被误记成已确认地址变更。 4. **换一个客户账号。** 以不同用户重复提问,检查请求的身份映射,并确认原客户的个人信息没有出现。 5. **删除测试记录。** 删除目标记忆后再次检索。流程涉及知识库文件时,单独测试文件删除。 记录新信息变得可检索所需的时间,以及 p95 延迟、Token 用量和失败排查耗时。对比有无记忆时的任务结果:Agent 是否给出正确下一步,客户重复解释的次数,以及纠正是否延续到后续对话。 简要保存配置、结果和待解决问题,让团队能够说明所选部署为何适合应用。 [Cloud 快速开始](https://memos-docs.openmem.net/cn/memos_cloud/getting_started/quick_start/)介绍首次写入和检索;自行部署时,从[自托管说明](https://github.com/MemTensor/MemOS)开始。先完成一个客户案例,再扩展到更多工作流。 --- # Claude 让记忆可编辑,生产 Agent 仍需要可治理的记忆层 (/cn/usecase/blog/claude_editable_memory_governed_layer) Claude 的记忆更新标志着 AI 产品的一项变化:记忆开始可见、分类、可编辑,并提供明确的敏感主题设置。这改善了用户控制,也提醒我们,生产 Agent 需要在模型内置记忆之外,建立可治理的记忆层。 助手的内置记忆帮助它在应用内保留背景。这里的可治理记忆层,是指明确规定保存什么、谁可以检索、如何更新和删除的服务。多用户或多租户应用还可能需要与这些边界对应的访问控制和变更历史。 Anthropic 的发布说明给出了具体变化。2026 年 7 月 10 日,Claude 记忆从每日摘要改为单独分类的条目,由 Claude 在对话中读取和更新。8 月 25 日,记忆扩展到云端 Chat 与 Cowork,用户可以按 Topics 编辑或删除;健康与信仰等内容在开启敏感主题前不被保留;Free、Pro 和 Max 默认开启,Team 与 Enterprise 组织默认关闭。这些都是实质控制。[Anthropic 发布说明](https://support.claude.com/en/articles/12138966-release-notes)记录了公开宣布的行为。 可编辑能力本身仍不足以构成可迁移的企业记忆层。生产系统可能同时使用多种模型、Agent 框架、工具、知识来源、身份系统和部署环境,需要在保留背景的同时,明确每段历史的使用范围和期限。因此,实现问题还包括:组织能否管理被记住状态的完整生命周期? ## 可编辑性为什么改变了讨论 过去,记忆常被当作后台机制:有效时有帮助,失效时难以检查。可编辑 Topics 改变了这种预期,承认了三个运行事实。 第一,记忆可能出错。偏好会改变,项目决策可能被推翻,自动摘要也可能丢失重要条件。编辑和删除使记忆可以纠正。 第二,记忆的敏感程度不同。Anthropic 的敏感主题设置说明,应用需要明确哪些信息可以长期保存,哪些需要额外同意,哪些应当排除。 第三,组织默认设置很重要。个人觉得有用的能力,在企业中仍需要管理员控制起点、明确归属,并提供检索遵循边界的证据。Team 与 Enterprise 的默认设置,说明记忆决策也属于组织管理。 这一方向有价值。生产系统还需要处理记忆跨 Agent 共享、连接工具,以及保留时间超过单次对话后产生的问题。 ## 从产品功能走向可治理的数据层 这里的“可迁移”,意味着组织能够通过明确接口与策略,独立于某个聊天界面或模型运行环境管理记忆。当 Agent 更换、会话结束或模型供应商变化时,记忆边界与处理规则仍然清晰。 Oracle 的开发者指南区分了 RAG 与 Agent 记忆:RAG 检索文档或数据,为回答提供依据;记忆保存跨交互的有用状态。RAG 应保留来源证据,记忆则可在有效且获准的前提下,保留限定范围的偏好、决策、摘要、任务状态和工具结果。Oracle 还强调记忆应可纠正、可删除,作用域应使用明确的用户、租户、Agent 与会话标识。[Oracle Developers 的《Agent Memory Is Not RAG》](https://blogs.oracle.com/developers/agent-memory-is-not-rag)说明了这种区别及其运行影响。 这形成一条实际规则: > 用 RAG 获取有来源依据的证据与当前知识;用持久记忆保存经过明确选择、仍有价值且允许召回的限定范围状态。 两者可以配合。Agent 准备客服回复时,通过 RAG 读取当前政策,从记忆中召回已批准的沟通偏好,再向实时系统查询订单状态。如果统一称为“上下文”,就容易忽略它们各自的更新、来源与授权规则。 ## 添加持久记忆前,先定义什么 以下是应用设计的参考流程。实际采用时,需要核实所选产品提供哪些控制,以及应用负责哪些部分。 ```text 对话或工具结果 | v 决定保存什么 |----> 丢弃、脱敏,或仅保留在本会话 v 已存储记忆 (内容、归属、来源、时间、状态) | |----> 按应用规则更新或删除 v 在调用者获准范围内检索 | v Agent 上下文 ``` 记录入口承担筛选职责。生产设计应区分临时观察、候选记忆与已批准的持久记录。例如,“用户今天心情不好”可能具有临时性和敏感性;“用户喜欢每周用通俗语言总结项目”则可能在明确范围和审核规则下持续有用。 记录需要内容与向量以外的信息,至少包括记忆 ID、归属与租户,相关 Agent、任务或会话范围,分类、来源、创建时间、最后确认时间、状态、保留或过期规则,以及召回所需的权限背景。纠正应留下可识别的生命周期事件,便于解释早期事实为何曾被使用。删除请求应能从发起追踪到移除或删除标记,并覆盖适用的派生索引。 召回时,相关性只是条件之一。检索路径先确定调用者权限与用途,再在允许范围内检索,并说明选中了什么记忆、为什么选中。这样,系统才能解释实际注入行动的状态。 ## 按生命周期管理记忆 长期 Agent 记忆有明确的生命周期,可以减少意外遗忘和无意积累。 1. **记录。** 接收对话事件或工具结果,同时保留产生它的身份和会话背景。 2. **分类。** 区分偏好、任务状态、决策、已验证事实、摘要,以及敏感或临时内容。 3. **接纳或拒绝。** 按持久性、敏感性、同意和预期价值筛选。部分信息只留在会话中,密钥等秘密信息留在专门的安全存储中。 4. **限定范围并标注。** 绑定获准的用户、租户、Agent、任务、会话或业务域,附带来源和时间。 5. **按需检索。** 在允许的记忆中匹配当前任务,控制噪声、延迟与跨边界暴露。 6. **纠正、替代或反馈。** 授权用户与运维人员可以修订错误、过时状态,并保留足够的事件历史解释变化。 7. **过期或删除。** 对记忆的可用表达落实保留规则和删除请求。 8. **审计与测量。** 记录写入、召回、策略结果与生命周期动作,评估收益是否足以支持成本和风险。 Oracle 的建议与此一致:持久保存需要明确选择,记忆需要来源与时间;在接入 Agent 循环前,先定义存储范围,以及接纳、更新、删除和检索规则。[相关实现建议](https://blogs.oracle.com/developers/agent-memory-is-not-rag)也适用于不同底层平台。 ## Claude 公开宣布了什么,还有什么需要核实 发布说明展示产品行为,完整架构需要进一步核实。下表区分已宣布行为和生产采购仍需追问的问题。 | Anthropic 已公开宣布 | 所引发布说明尚未确立 | | --- | --- | | 2026 年 7 月 10 日,分类记忆条目替代每日摘要 | 跨供应商或跨模型的导出与迁移契约 | | 记忆在云端 Chat 与 Cowork 之间使用 | 组织可独立于 Claude 产品界面运行的企业记忆结构 | | 用户可以编辑或删除记住的 Topics | 外部生产流程所需的完整保留、删除传播、审计与来源语义 | | 敏感主题在用户开启设置前被排除 | 适用于各组织数据分类与业务用途的通用策略引擎 | | Team 与 Enterprise 默认关闭记忆 | 具体组织应如何按自身风险配置记忆 | 右栏并不判定这些能力在 Anthropic 其他产品或文档中不存在,只说明本篇引用的发布说明尚未提供相关依据。架构与采购决策应结合已核实文档、契约和限定范围的技术评估。 ## MemTensor 与 MemOS 在其中的角色 MemTensor 为 AI 应用构建记忆基础设施,并研究长期记忆与持续学习。工作包括 Memory³ 研究、MemOS 记忆系统,以及记忆原生基座模型研究,目标是帮助应用保留有用背景、支持个性化,并持续利用信息。 MemOS 面向跨对话、跨任务的背景保留。Cloud API 支持从对话生成记忆、检索相关信息、更新和删除记录,以及通过反馈纠正记忆。这些能力帮助应用记住偏好,将相关背景带入后续交互。MemOS 同时提供托管 Cloud 与开源部署方案,公开能力见 [MemOS Cloud 概述](https://memos-docs.openmem.net/cn/memos_cloud/getting_started/overview/)和 [API 概览](https://memos-docs.openmem.net/cn/api_docs/start/overview/)。 对用户而言,良好的记忆管理意味着减少重复说明,并随着偏好与项目变化保持连续性。独立记忆层则为应用提供明确的检索、更新与删除操作,持续管理这些背景。 ## 生产 Agent 的治理检查清单 启用持久记忆前,团队应当能够书面回答: - **用途:** 每类记忆服务什么决策或流程?哪些信息排除在保留范围外? - **范围:** 哪些用户、租户、Agent、项目、任务与会话组合可以写入和召回? - **接纳:** 谁可以把交互转为持久记忆?适用什么审核或置信度规则? - **来源:** 运维人员能否找到来源事件、工具结果、策略版本、时间与最后确认记录? - **权限:** 召回是否使用与底层业务数据一致的身份和授权背景? - **敏感性:** 密钥、受监管字段与敏感个人主题如何排除、脱敏或获得明确同意? - **纠正:** 相关用户或授权人员能否编辑、替代或质疑记忆,并保持状态一致? - **删除与保留:** 保留期限是什么,如何验证记录、索引、缓存与下游表达的删除? - **可观测性:** 写入、检索与策略拒绝是否有日志,可重建 Agent 动作? - **评估:** 是否同时衡量召回收益,以及过期、无关召回与范围泄露? 这些检查直接面向运行。用户体验可以简洁,底层处理需要精确。 ## Claude 更新带来的启示 Claude 的可编辑记忆让用户更接近被记住的状态,也把记忆作为一组条目来管理。这一方向提高了 Agent 体验的基准。 AI 进入日常工作后,有用的记忆可以减少重复,并长期保留相关背景。Claude 展示了易于管理的价值,MemOS 则向其他 AI 应用提供跨交互保留与复用背景的记忆能力。实际问题始终是:应用记住什么、在哪里使用,以及用户如何让它保持准确。 --- # 如何让错误假设远离 Agent 记忆 (/cn/usecase/blog/keep_bad_assumptions_out_of_agent_memory) > **导读:** 写入时就有误的记忆,很难靠检索质量补救。生产 Agent 需要在信息成为长期记忆前,区分用户陈述、环境事实、模型推断、操作流程和高影响状态。记忆张量 MemTensor 的 MemOS 提供系统层架构,让这些生命周期控制成为明确的操作。 --- Agent 可能把一次任务中的错误假设带入下一次任务。检查它学到了什么、保留来源,并在条件变化后重新审视记忆,有助于阻止错误传播。MemOS 提供从处理新信息到纠正已有记忆的工具,支持这一过程。 Agent 答错时,人们通常先检查召回内容。但问题可能更早就已出现:记忆建立在不完整观察上,或保存了一条从未验证过的结论。 在论文 [*Grounding Agent Memory: Environment-Probing Curation for Enterprise Agents*](https://arxiv.org/html/2609.11060v1) 中,微软研究人员让记忆整理组件在任务结束后以只读方式访问环境。它可以核查存疑陈述,在后续任务使用前修改或跳过相应记录。 在论文包含模式变更的 40 道 CLBench 问题实验中,研究者使用 GPT-5.4 和 GitHub Copilot SDK 运行框架。记忆加环境探查系统的平均通过率为 73%,仅使用记忆为 70%,无记忆基线为 39%。加入探查后,每题平均查询次数从 5.6 降至 4.7,任务 Agent 成本从 1.99 美元降至 1.68 美元;这些成本未包含单独的蒸馏与整理阶段。 这些结果对应研究者的具体设置,也引出一个实际问题:Agent 把学到的内容传给下一次任务前,应该先核查什么? ## 一次有用观察,怎样变成误导性规则 假设数据库 Agent 在 `customers_current` 表中找到所需记录,完成任务后保存了一条说明:“查询活跃账户时使用 customers_current。” 这次查询可能只适用于某个地区或报告周期。保存的说明省略了条件,另一个 Agent 就可能将它用于更广泛的问题。检查表定义与相关业务规则,可以帮助明确建议的适用范围。 即使核查仔细,说明也可能过时。一个月后,这张表可能被更新频率更低的兼容视图替代。后续 Agent 需要识别变化并更新记忆。 类似问题还包括:接口已修复却继续推荐临时绕行方案;把临时审批流程保存为永久流程;把失败命令记成成功方案。政策可能在摘要时丢失生效日期,针对一个客户的规则也可能被推广到所有客户。 这些记忆都缺少后续任务所需的证据、条件或更新。检索能找到说明,但 Agent 还需要足够的信息判断它是否适用。 ## 让结论可复用前,先核查内容 常见记忆流程从对话或任务历史出发,抽取有用信息并保存,供以后检索。在结论成为可复用建议之前,可以增加验证步骤。 原始对话和工具结果仍可作为证据保留。需要决定的是:哪些结论供未来任务使用,以及附带什么限制。保留这一区别,也便于团队在出错后检查摘要如何生成。 核查方式应与信息类型匹配。 | 信息 | 核查内容 | | --- | --- | | 用户陈述或偏好 | 保留谁在何时、何种背景下说过。“我喜欢简洁的周报摘要”可以直接记录,并在用户修改时更新。 | | 环境事实 | 检查相应系统,如数据库模式、代码仓库、API 规格或政策文档,并记录观察的版本或时间。 | | Agent 推断 | 保留证据并标记为推断。“这位客户可能对价格敏感”应与客户明确表达的内容区分。 | | 流程或技能 | 保留前提条件与成功证据,采用适合该流程的测试或验收条件。 | 敏感程度与影响范围适用于以上所有类别。报告长短偏好所需的审核,可以少于一条可能改变访问权限或授权支付的流程。 只读检查往往足以消除疑问。编码 Agent 可以查看符号定义,数据库 Agent 可以检查模式或查询有限样本。有副作用的流程,则需要适当测试环境或其他成功证据。 ## MemOS 如何支持这一流程 [MemOS](https://github.com/MemTensor/MemOS)提供添加、查找、纠正和删除记忆的操作。开发者可以将这些操作与自己的业务系统核查结合起来。应用选择权威来源,并实现前文所述的环境检查。 ### 让记忆保留来源 开源服务中的 [MemReader](https://memos-docs.openmem.net/cn/open_source/modules/mem_reader/)将对话、文档与图片处理为带来源信息的记忆条目。开发者可以使用添加接口的[元数据](https://memos-docs.openmem.net/cn/api-reference/add-memories/)附带来源位置、应用提供的验证结果等信息。 对数据库示例,可以记录数据库模式版本、核查时间,以及这张表适用的业务背景。后续回答异常时,团队就有排查起点。 验证应覆盖抽取后的结论。仅检查输入文档,可能遗漏从文档生成短记忆时引入的错误。 ### 区分偏好与推断 MemOS Cloud 的[记忆抽取接口](https://memos-docs.openmem.net/cn/api_docs/core/extract_memory/)区分明确偏好与根据行为推断的偏好,并返回推断依据。 这样,应用可以分别处理“我喜欢经济型酒店”和根据一次预订作出的猜测。开发者可判断推断是否适合推荐,或是否需要用户确认后再用于影响更大的操作。 ### 信息变化时更新记忆 MemOS Cloud 在[记忆维护](https://memos-docs.openmem.net/cn/changelog/)中支持冲突与重复处理。[时间感知机制](https://memos-docs.openmem.net/cn/memos_cloud/introduction/time_awareness/)保留变化状态,帮助检索区分当前事实与早期记录。 这些能力处理已经进入记忆系统的变化。数据库示例中,应用仍需发现模式变更或提供新证据,再通过[反馈](https://memos-docs.openmem.net/cn/memos_cloud/mem_operations/add_feedback/)纠正建议,或使用相应记忆操作更新、删除受影响条目。 ### 确定记忆可以在哪里使用 开源服务通过 [MemCube](https://memos-docs.openmem.net/cn/open_source/modules/mos/overview/)组织记忆。请求可以指定读取或写入的空间,让应用隔离项目记忆,或向多个 Agent 开放选定信息。应用负责将这些选择与授权规则关联。 会话上下文承担不同职责。在开源[检索接口](https://memos-docs.openmem.net/cn/api-reference/search-memories/)中,`session_id` 帮助优先返回相关记忆,不构成会话间的强制隔离边界。 ### 检查后台处理结果 记忆写入和纠错可以在后台运行。开源服务提供[调度与状态操作](https://memos-docs.openmem.net/cn/open_source/modules/mos/overview/)来跟踪处理。MemOS Cloud 的[任务状态接口](https://memos-docs.openmem.net/cn/api_docs/message/get_status/)报告处理状态,并在完成后返回受影响的记忆 ID 与变更摘要。 应用由此可以从提交跟踪到结果,再查看受影响条目,核对后续检索返回的内容。 ## 把核查接入实际流程 先选择一种准确性对任务有重要影响的记忆,例如数据库使用建议或经常复用的客服流程。 1. **抽取候选内容。** 识别值得保存的结论或流程,保留来源。 2. **核查证据。** 检查权威系统,验证候选内容依赖的条件。证据不完整时,缩小结论范围或转交审核。 3. **同时保存适用条件。** 记录适用范围、核查时间,以及再次核查的触发条件,让已通过审核的候选内容参与复用。 4. **检查结果。** 写入或纠正后,检查操作结果,以及后续任务能取得的记录。 5. **来源变化后重新审视。** 数据库迁移、政策修订或 API 变化,应触发相关记忆的复核。 对 `customers_current`,有用的记录应包含适用地区与报告周期、建议依据,以及已核查的模式版本。涉及这张表的迁移,为复核提供了具体触发条件。 ## 追踪记忆如何进入下一次任务 团队也需要观察流程是否有效。以下问题可指导应用与记忆服务之间的监测。 | 阶段 | 检查内容 | | --- | --- | | 候选审核 | 候选来自哪些来源,核查了什么证据,为什么接受、修订或拒绝 | | 写入 | 添加或修改了哪些记录,存在哪里,处理是否完成 | | 检索 | 返回了哪些记忆,哪些实际进入模型上下文 | | 使用 | 任务完成情况、重复错误、用户纠正,以及与无记忆基线的对比 | | 维护 | 哪些条目受来源变化影响,哪些核查已逾期,纠正是否进入后续检索 | | 删除 | 记忆存储与应用管理的副本、缓存是否完成删除 | 关联这些记录有助于排查失败。召回的记忆可能从未进入模型,进入提示词的记忆也未必能解释后续动作。追踪记录提供证据,确认因果仍需要测试。 首次评估可以先保存一条核查过的记忆,在后续任务中使用,再修改底层信息。确认纠正在后续检索中出现,Agent 也能用新信息完成任务。这检验了持续工作中最有价值的部分:把有用知识带向未来,并持续允许纠正。 ## 关于 MemTensor 与 MemOS MemTensor 为 AI 应用与 Agent 开发记忆基础设施,工作覆盖 [Memory³ 研究、MemOS、Agent 记忆基础设施和记忆原生模型研究](https://memos-docs.openmem.net/cn/usecase/blog/agent_memory_is_not_rag/)。MemOS 通过 API、开源组件和集成方案,将这些工作用于跨任务的信息存储、检索与维护。 --- # 持久化 Agent 记忆,应当让下一次任务更轻松 (/cn/usecase/blog/persistent_agent_memory_next_task) *记忆张量 MemTensor 如何看待连续性、纠错与边界* 假设团队周二发现,只有先启动数据库,集成测试才能通过。周五,另一个 Agent 接手相关任务,需要找到已经确认的准备步骤,以及它适用的条件。团队调整步骤后,保存的说明也需要同步更新。 这就是我们希望通过 MemOS 实现的体验:有用的知识能够延续到后续任务,并随时接受纠正。 ## 大上下文仍然需要记忆策略 更大的上下文窗口让 Agent 能阅读更多材料。应用仍需决定哪些值得保留、谁可以复用,以及怎样处理更新。 在测试示例中,失败是一次事件;已经确认的准备顺序则是可复用流程,需要附带适用的环境与条件。 MemOS Cloud [按种类组织记忆](https://memos-docs.openmem.net/cn/memos_cloud/introduction/memory_types/),让这些记录分别发挥作用。事件记忆保留发生时间等细节,技能记录可复用的任务步骤,事实与偏好提供用户背景。应用可以控制生成哪些种类,以及检索时包含哪些种类。 ## 用四步衔接持续工作 **记录。** 通过[添加消息](https://memos-docs.openmem.net/cn/memos_cloud/mem_operations/add_message/),MemOS Cloud 从对话中抽取记忆,检查重复与冲突,必要时更新已有记录。使用 `info` 可以附带来源、环境等自定义元数据。对周二的测试,应提交确认准备步骤及适用范围的讨论;元数据也为后续过滤提供字段。 **检索。** [检索记忆](https://memos-docs.openmem.net/cn/memos_cloud/mem_operations/search_memory/)结合关键词与向量检索,按相关性排序并移除重复结果。过滤条件可按标签、时间、Agent 或自定义元数据缩小范围;选择记忆种类可包含技能,返回数量限制则控制结果条数。周五接手任务时,检索相关测试说明,与当前请求一起送入模型。 **纠正。** 假设团队增加了自动启动数据库的脚本。如果知道需要更改的记录,可以通过[修改记忆](https://memos-docs.openmem.net/cn/memos_cloud/mem_operations/update_memory/)按 ID 编辑;用户也可以用[自然语言反馈](https://memos-docs.openmem.net/cn/memos_cloud/mem_operations/add_feedback/)描述新流程,由 MemOS 定位并更新相关记忆。对于变化中的事实与偏好,[时间感知机制](https://memos-docs.openmem.net/cn/memos_cloud/introduction/time_awareness/)维护历史版本,并结合查询中的时间线索区分当前信息和早期状态。 **停止使用或删除。** 过时流程可以通过更新接口归档。[删除记忆](https://memos-docs.openmem.net/cn/memos_cloud/mem_operations/delete_memory/)支持删除指定条目,或清除 API Key 所属项目内某个用户的记忆。删除流程也应覆盖应用缓存或摘要中保存的副本。 ## 共享需要维护者 把流程共享给多个 Agent 前,先明确谁负责维护,以及哪些用户或项目可以使用。 MemOS Cloud 的[隔离能力](https://memos-docs.openmem.net/cn/memos_cloud/introduction/isolation_filters/)按项目与用户划分记忆范围。Agent 过滤条件可以进一步筛选某个用户在指定 Agent 下的记录;开启 Agent 独立记忆后,Agent 则拥有跨用户、跨会话的长期记忆。后端应把 `user_id` 映射到已认证用户。`conversation_id` 影响检索上下文,不承担访问控制职责。 对于共享的环境准备说明,[知识库](https://memos-docs.openmem.net/cn/memos_cloud/features/knowledge_base/)将上传文档转化为可检索记忆,并与用户记忆共同召回。一项任务就能同时参考团队文档和此前交互的背景。 在支持的 Agent 宿主中,[MemOS Local Plugin](https://docs.openmem.net/cn/openclaw/local_plugin/)把记忆存入本地 SQLite 数据库,并将记录与检索接入宿主的任务生命周期。任务完成后记录对话、工具调用和反馈,在下一次任务前提供相关上下文。反复出现的有效方法可以沉淀为可复用技能。 验证时使用三个会话:先确认流程,再由有权限的 Agent 应用,最后修改流程并重新提问。切换到另一个项目,以及删除后,也各重复一次请求。同时检查召回的记忆、实际送入模型的上下文和最终回答,发现过期说明或访问范围错误。