All Products
Search
Document Center

:Long-term memory

Last Updated:Aug 21, 2026

Long-term memory enables Agents to retain user preferences and interaction history across sessions. Once enabled, the Agent uses vector search to retrieve relevant memories and deliver personalized responses.

What is long-term memory

Long-term memory persists user data across sessions. Each memory is stored as text and associated with a specific User ID, Agent ID, and an optional Run ID, supporting rapid retrieval through vector search.

Long-term memory is one of three sub-modules of the memory storage feature:

  • long-term memory

  • conversation history

  • conversation state

Use cases

  • Remember user preferences: Remember user settings, such as language preferences, and automatically apply them in future conversations.

  • Review interaction history: Retrieve past conversation content across sessions to avoid repetitive questions.

  • Personalized recommendations: Provide tailored recommendations and suggestions based on a user's historical behavior and preferences.

Prerequisites

  • You have created a memory storage instance. For more information, see Create and manage memory storage.

  • Long-term memory requires a configured large language model (LLM) and a vector model (embedder), meaning both llmConfig and embedderConfig must not be empty.

Note

If you did not configure an LLM and a vector model when creating the memory storage instance, go to the Overview page, find the Long-Term Memory card, and click Enable Long-Term Memory. In the panel that appears, enter the LLM and vector model information.

Limitations

Item

Description

Default list loading limit

A maximum of 200 memories are displayed by default. To find more memories, use the search feature.

Search requirements

You must provide both a search keyword and at least one ID (User ID, Agent ID, or Run ID).

Supported vector databases

Long-term memory supports two vector database types: Tablestore and RDS (MySQL).

Billing

The long-term memory feature is free, but you are billed for the resources it consumes:

  • LLM calls: Used for generating and processing memory content. Billed by the large language model service.

  • vector search: Triggered during memory searches. Billed by the vector model service.

  • Storage resources: Tablestore or RDS MySQL. Billed by each product for storage and read/write capacity.

For detailed pricing, see the billing documentation for each product.

Manage memories

On the details page of your memory storage instance, select the Long-Term Memory tab to manage memory entries. For information on how to use memory capabilities, see Integration and use.

Add a memory

  1. Go to the details page of the memory storage instance and select the Long-Term Memory tab.

  2. Click Add Memory to open the Add User Memory form.

  3. Enter the memory information:

    Field

    Description

    Example

    User ID

    Required. The identifier for the user who owns the memory.

    test-user-001

    Memory Content

    Required. The specific content of the memory.

    Lives in Hangzhou

    Metadata

    Optional. Custom key-value pairs. Click Add Metadata to add more.

    {"category": "food"}

  4. Click Save and wait for the memory to be created.

Note

The first API call might experience a cold start delay. If this happens, wait 10 to 30 seconds and try again.

After a memory is successfully created, it appears in the memory list, displaying information such as the User ID, creation time, and memory content. Each memory card includes View Details, Edit, View History, and Delete buttons.

Memory list

The memory list displays up to 200 memories by default. Each memory card contains the following information:

  • First line: The User ID in bold. In search mode, a similarity score tag is also displayed.

  • Second line: The original memory content.

  • Third line: Metadata in the format {Agent ID} · {Run ID} · {Date}. The Agent ID and Run ID are optional and are omitted if not set.

You can select multiple memory entries using the checkboxes. When one or more items are selected, a Batch Delete button appears in the upper-right corner of the list.

Search and filter memories

If you have more than 200 memories, use the search feature to find specific entries. When searching, you must provide both keywords and at least one ID (User ID, Agent ID, or Run ID).

Important

If you enter only keywords, the system returns an error: "Please open Advanced Filter and provide at least one of User ID, Agent ID, or Run ID." If you enter only an ID without keywords, the system returns an error: "Please enter a search query."

Advanced filter conditions

Filter

Placeholder

Description

User ID

Enter a user ID

Filter by user identifier.

Agent ID

Enter an Agent ID

Filter by Agent identifier.

Run ID

Enter a Run ID

Filter by Run identifier.

You can enter multiple IDs to filter the results, but you must provide at least one. Click Apply to apply the filter or Reset to clear the conditions.

Memory details

  1. In the memory list, click the view icon (an eye) on the right side of a memory card.

  2. The details drawer displays the following information:

    • Memory ID, User ID, Agent ID (a hyphen '-' is displayed if empty), Run ID (a hyphen '-' is displayed if empty), and creation time.

    • The Memory Content area, which preserves the original line breaks.

    • The Metadata area (if available), displayed in JSON format.

    • The Tags area (if metadata.tags exists), displayed as blue rounded-corner tags.

Edit memory

  1. In the memory list, click the edit icon on the right side of the target memory.

  2. In the edit form, modify the Memory Content field.

  3. Click Save Changes.

Read-only information such as the User ID, Agent ID, Run ID, creation time, and update time is displayed at the bottom of the edit form.

Delete memory

Single delete

  1. In the memory list, click the delete icon on the right side of the target memory.

  2. In the confirmation dialog box, review the memory content preview and click Confirm Delete.

Batch delete

  1. In the list, select the checkboxes for multiple memories, or click the select-all checkbox.

  2. Click the Batch Delete button above the list.

  3. Click Confirm in the confirmation dialog box.

Note

The selected memories are deleted in parallel. If some deletions fail, a message indicates the number of successful and failed operations. This action is irreversible.

Memory history

A memory's version history tracks all changes from add, update, and delete operations.

  1. In the memory details drawer, click the View History button.

  2. The history list is sorted in reverse chronological order. Each record includes:

    • Version information: Version number + "Current Version" tag (for the latest version) + event type (ADD/UPDATE/DELETE).

    • Timestamp: In YYYY/MM/DD HH:mm:ss format.

    • Actor: actor_id + role (if available).

    • Memory Content: The memory text for that version.

    • Change details (if applicable): A comparison between the old value (red background) and the new value (green background).

Event type

Tag color

Description

ADD

Green

A new memory is created.

UPDATE

Blue

The memory content or metadata is modified.

DELETE

Red

A memory is deleted.

Integration and use

MCP integration

Integrate memory capabilities into an Agent through the MCP (Model Context Protocol) service. On the MCP integration tab, you can start or stop the MCP service, get the service URL, view the dynamic configuration, and connect the service to an Agent.

MCP service status

The MCP service can have the following statuses:

Status

Description

Actions

Stopped

The MCP service has not been started.

Click Start Service.

Starting

The service is being deployed. Wait for the deployment to complete.

No action is required. Wait for the status to change to Running or Failed to start.

Running

The MCP service is ready and can be used.

View the MCP configuration or click Disable Service.

Failed to start

The service failed to deploy, usually due to insufficient permissions or configuration errors.

Check your permissions or configuration, and then click Start Service Configuration again.

Start MCP service

  1. On the details page of the memory storage instance, select the Long-Term Memory tab, then switch to the MCP Integration tab.

  2. If the MCP service status is Stopped, click Start Service Configuration.

  3. Check permissions: The system requires the AliyunFCFunctionAIServicesDeployPolicy policy. If a permission error is displayed, go to the RAM console to grant this policy to your account, then return and click Start Service Configuration again.

  4. Wait for the system to automatically install the Toolset and monitor its status until it reaches a final state:

    • If the Toolset status is Installed and internetUrl exists, the service status changes to Running.

    • If the Toolset status is Failed, the service status changes to Failed to start.

  5. After the service starts successfully, two sub-tabs are displayed:

    • Configure MCP Server: Displays the dynamically generated MCP configuration in JSON format. It includes the MCP service URL and tool definitions, which you can copy directly into your Agent configuration.

    • Use MCP Tool: Provides a JavaScript code example that shows how to call the MCP tool in your code.

MCP service URL

The MCP service URL is the endpoint your Agent uses to connect to the memory storage. After the service starts, find this URL in the configuration JSON on the Configure MCP Server tab. The URL is derived from the toolset.status.outputs.urls.internetUrl field after the toolset is deployed.

Dynamic MCP configuration

After the service starts, the Configure MCP Server tab displays a dynamically generated JSON configuration. This configuration includes the MCP service URL and available tool definitions, updated in real time based on the service status. Copy this configuration into your Agent's MCP settings to access memory storage through the MCP tool.

Stop MCP service

  1. On the MCP Integration page, click the Disable Service button.

  2. In the Confirm MCP Server Shutdown dialog box, click Confirm Shutdown. The system then deletes the toolset.

Warning

Stopping the service deletes the toolset. This action is irreversible. You must restart the service to use the MCP feature again.

After the service is stopped successfully, its status changes to Stopped, and the Configure MCP Server and Use MCP Tool tabs are no longer displayed.

Connect to an Agent

After the MCP service is running, select your memory storage instance in the Memory setting when creating an Agent, and enable the MCP option. The Agent can then access the memory storage through the MCP tool.

Code Integration

Integrate the memory storage feature using the AgentRun SDK. The following example retrieves memory storage metadata using MemoryCollection and converts it into a mem0 Memory client for memory operations.

Prerequisites

  1. Install the AgentRun SDK:

    pip install agentrun
  2. Configure access credentials. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables are set. The SDK automatically reads these credentials for authentication.

  3. Replace the memory storage name mem-OGzJ in the sample code with the name of your own memory storage instance. You can find the instance name on the memory storage list page.

Note

If your memory storage uses an RDS (MySQL) vector database, you must set the AGENTRUN_MYSQL_PUBLIC_HOST environment variable to the public endpoint of your MySQL instance for local debugging. You also need to add your local public IP address to the RDS IP address whitelist. Otherwise, the connection will fail.

from agentrun.memory_collection import MemoryCollection

# Get the memory storage metadata
memory_collection = MemoryCollection.get_by_name("mem-OGzJ")
print(f"Successfully retrieved: {memory_collection}")

# Convert to a mem0_memory client
memory = MemoryCollection.to_mem0_memory("mem-OGzJ")

# Use the mem0ai Memory client to perform operations
user_id = "user123"

# Add a memory
result = memory.add(
    "I like to eat apples and bananas",
    user_id=user_id,
    metadata={"category": "food"},
)
for idx, res in enumerate(result.get("results", []), 1):
    print(f" {idx}. ID: {res.get('id')}, Event: {res.get('event')}")

# Search memories
search_results = memory.search("What fruit does the user like to eat?", user_id=user_id)
for idx, result in enumerate(search_results.get("results", []), 1):
    print(
        f" {idx}. Content: {result.get('memory')}, Similarity: {result.get('score', 0):.4f}"
    )

Ecosystem Integration

Memory storage integrates with open-source Agent development frameworks like LangChain to build memory-based conversational systems. The following example integrates memory storage into a LangChain conversational chain to deliver personalized responses based on historical memory.

Note

Before you run the following example, complete the prerequisite steps, such as installing the SDK and configuring access credentials. For more information, see Prerequisites. You also need to replace the memory storage name in the example code with the name of your own instance.

from typing import List, Dict
from langchain_core.messages import SystemMessage, HumanMessage
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
from agentrun.integration.langchain import model
from agentrun.memory_collection import MemoryCollection

# Create from model name
llm = model("qwen3-max")
# Create from memory storage name
mem0 = MemoryCollection.to_mem0_memory("mem-OGzJ")


prompt = ChatPromptTemplate.from_messages([
    SystemMessage(content="""You are a helpful travel agent AI. Use the provided context to personalize your responses and remember user preferences and past interactions.
    Provide travel recommendations, itinerary suggestions, and answer questions about destinations.
    If you don't have specific information, you can make general suggestions based on common travel knowledge."""),
    MessagesPlaceholder(variable_name="context"),
    HumanMessage(content="{input}")
])

def retrieve_context(query: str, user_id: str) -> List[Dict]:
    """Retrieve relevant context from Mem0"""
    try:
        memories = mem0.search(query, user_id=user_id)
        memory_list = memories['results']
        print(f"Memory search successfully: {memory_list}")
        serialized_memories = ' '.join([mem["memory"] for mem in memory_list])
        context = [
            {
                "role": "system",
                "content": f"Relevant information: {serialized_memories}"
            },
            {
                "role": "user",
                "content": query
            }
        ]
        return context
    except Exception as e:
        print(f"Error retrieving memories: {e}")
        # Return empty context if there's an error
        return [{"role": "user", "content": query}]

def generate_response(input: str, context: List[Dict]) -> str:
    """Generate a response using the language model"""
    chain = prompt | llm
    response = chain.invoke({
        "context": context,
        "input": input
    })
    return response.content

def save_interaction(user_id: str, user_input: str, assistant_response: str):
    """Save the interaction to Mem0"""
    try:
        interaction = [
            {
              "role": "user",
              "content": user_input
            },
            {
                "role": "assistant",
                "content": assistant_response
            }
        ]
        result = mem0.add(interaction, user_id=user_id)
        print(f"Memory saved successfully: {len(result.get('results', []))} memories added")
    except Exception as e:
        print(f"Error saving interaction: {e}")

def chat_turn(user_input: str, user_id: str) -> str:
    # Retrieve context
    context = retrieve_context(user_input, user_id)

    # Generate response
    response = generate_response(user_input, context)

    # Save interaction
    save_interaction(user_id, user_input, response)

    return response

if __name__ == "__main__":
    print("Welcome to your personal Travel Agent Planner! How can I assist you with your travel plans today?")
    user_id = "alice"

    while True:
        user_input = input("You: ")
        if user_input.lower() in ['quit', 'exit', 'bye']:
            print("Travel Agent: Thank you for using our travel planning service. Have a great trip!")
            break

        response = chat_turn(user_input, user_id)
        print(f"Travel Agent: {response}")

Troubleshooting

Failed to enable long-term memory

Symptom

Possible cause

Solution

Cannot select a large language model or a vector model.

You have not created a model service.

Create a model service using the Add Model feature, and then enable long-term memory.

Cannot select an execution role.

The RAM role is not authorized to access Tablestore or AgentRun.

In the RAM console, attach the AliyunOTSFullAccess and AliyunAgentRunFullAccess policies to the role.

MCP service failed to start

Symptom

Possible cause

Solution

The MCP service status is displayed as Failed to start.

Your account does not have the required AliyunFCFunctionAIServicesDeployPolicy policy.

Go to the RAM console and grant this policy to your account. Then, return to the MCP integration page and click Start Service Configuration again.

The MCP service status is displayed as Failed to start.

The memory storage configuration is invalid (for example, the LLM or vector model is not configured correctly).

On the Overview page of the memory storage instance, confirm that long-term memory is configured correctly, and then restart the MCP service.

Failed to add a memory

Symptom

Possible cause

Solution

The first attempt to add a memory times out or returns an error.

The service may experience a cold start on the first call.

Wait 10 to 30 seconds and try again.

An error message indicates that the User ID cannot be empty.

The User ID field is empty.

Enter a valid User ID and submit again.

An error message indicates that the memory content cannot be empty.

The memory content field is empty.

Enter valid memory content and submit again.

Failed to search memories

Symptom

Possible cause

Solution

An error message appears: "Please open Advanced Filter and provide at least one of User ID, Agent ID, or Run ID."

Only keywords were entered, without any ID.

Expand the Advanced Filter panel and enter at least one ID (User ID, Agent ID, or Run ID).

An error message appears: "Please enter a search query."

Only an ID was entered, without any search keywords.

Enter search keywords in the search box.