All Products
Search
Document Center

Agent Run:Memory storage

Last Updated:Aug 24, 2026

Memory storage provides persistence for Agents. It saves and retrieves contextual data, such as user interaction history and preferences, across sessions. Using vector retrieval, an Agent can provide personalized responses based on historical memory to ensure session continuity. You can integrate memory storage into a quick-start Agent using the MCP tool or with open source frameworks such as LangChain.

Getting started

After you create a memory storage instance, you can create, search, and manage memories in the console or using an SDK.

Create a memory storage instance

  1. Log in to the AgentRun console and click Others in the top menu bar.

  2. In the navigation pane on the left, click Memory Storage to view the memory storage list.

  3. Click the Add Memory Storage button to open the creation form.

  4. Enter the basic information:

    • Name: The system automatically generates a unique identifier, such as mem-OGzJ. You can also specify a custom name.

    • Description: (Optional) Enter a description for the memory storage.

    • Execution Role: Select an authorized RAM role from the drop-down list. The role must have access permissions for Tablestore and AgentRun, such as AliyunAgentRunDefaultRole.

    • Large Language Model: From the drop-down list, select a large language model, such as qwen3-max.

      Or, click Add Model. For more information, see Large language models.
    • Vector Model: Select a created vector model from the drop-down list, such as text-embedding-v4.

      Alternatively, click Add Model. For more information, see Vector models.
  5. Configure the vector database:

    • One-click configuration (Recommended): Automatically creates and configures a Tablestore instance without requiring manual setup.

    • Custom configuration: Select an existing Alibaba Cloud Tablestore instance.

      • From the drop-down list, select an existing Tablestore (OTS) instance in the current region. If no instance is available in the list, click the image button on the right. For more information, see Create an OTS instance.

      • Enter a name for the table that will be used to store vector data.

      • Set the dimensions of the vector data.

  6. Set the network policy:

    • Public mode: Allows access over the public network.

    • Private mode: Requires a VPC ID, a security group, and a subnet ID.

  7. Click Start Deployment. Wait about 10 seconds for the status to change to Running.

After the deployment is complete, you can manage memories, search memories, view observability metrics, or configure MCP and code integrations on the instance details page.

Memory management

Create a memory

On the memory storage instance product page, click the Memory Management tab to open the memory list. By default, the list displays 200 memories. To find more memories, use the search feature.

  1. Click the Create Memory button to open the Add User Memory dialog box.

  2. Enter the memory information:

    • User ID (Required): The user who owns the memory, such as test-user-001.

    • Memory Content (Required): The content for the memory, such as lives in Hangzhou.

    • Metadata (Optional): Click Add Metadata to configure custom fields.

  3. Click the Save button and wait for the creation to complete. The first call may trigger a cold start.

After the memory is created, it appears in the memory list. The list shows information such as the user ID, creation time, and memory content. Each memory card provides buttons for operations such as View Details, Edit, View History, and Delete.

Search memories

On the memory storage instance details page, click the Search Memories tab to go to the memory search page.

  1. Enter the search criteria:

    • Search Query (Required): Enter a search query, such as Hangzhou.

    • User ID, Agent ID, or Run ID (Specify at least one): Filters memories for a specific user or session. For example, enter the user ID test-user-001 to search for memories that match the keywords for that user.

  2. Click the Search button. The search results will load in about 5 seconds.

  3. View the search results: The results list shows the matching memory content, user ID, similarity score, ID, hash, creation time, and other information.

The search results are sorted by similarity from high to low. A higher similarity score indicates a higher relevance to the query.

Delete a memory

On the memory list page, find the memory that you want to delete, click Delete, and then confirm the operation.

Modify a memory

On the memory list page, find the memory that you want to modify, click Edit, modify the memory content, and then save your changes.

Observability

On the product page for your memory storage instance, click the Observability tab to view real-time key metrics for memory operations.

Create memory operation metrics

  • Number of create memory operations: The total number of create memory operations.

  • Average latency of create memory operations: The overall response time for create memory operations.

  • Failure rate of create memory operations: The percentage of failed create memory operations.

Search memory operation metrics

  • Number of search memory operations: The total number of search memory operations.

  • Average latency of memory retrieval: The overall response time for memory retrieval operations.

  • Failure rate of memory retrieval: The percentage of failed memory retrieval operations.

Monitoring charts

The observability page provides the following monitoring charts:

  • Queries per second (QPS): Displays total QPS, 2xx QPS, 4xx QPS, 5xx QPS, and 429 QPS.

  • Average access latency: Displays the trend of request latency.

  • Row statistics: Displays the total number of rows and the number of failed rows.

  • Traffic statistics: Displays public network inbound, public network outbound, private network inbound, private network outbound, and free public network outbound traffic.

  • Capacity unit statistics: Displays read CU, write CU, internal read CU, and internal write CU.

  • Request status statistics: Displays execution status classifications (such as Request successful, Parameter error, Request throttled, and Server error) along with their statistical values and percentages.

You can filter the view by switching the time range (for example, 1 day or 7 days) and the operation type (Create memory operation or Search memory operation).

Ecosystem integration

MCP integration

You can integrate memory storage into a quick-start Agent using the MCP tool.

  1. On the memory storage instance product page, on the Integration and Cases tab, select the MCP Integration sub-tab.

  2. View the MCP Server status:

    • If the status is "Not started", click the Start Service Configuration button to start the MCP Server.

    • After the service starts, the status changes to Processing.

  3. On the Quick Start for Agent (No-Code) page, for the Memory configuration item, select your memory storage instance and enable the MCP option.

After you enable it, the Agent can access memory storage through the MCP tool at runtime. This allows the Agent to create, search, and manage memories, which provides persistence.

Code integration

You can integrate the memory storage feature using the AgentRun SDK.

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 for 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}"
    )

LangChain integration

You can integrate memory storage with open source Agent developer frameworks, such as LangChain, to create memory-based conversational systems. The following example shows how to integrate memory storage into a LangChain conversational chain to achieve personalized responses based on historical memory.

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 the model name
llm = model("qwen3-max")
# Create from the 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}")