

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# 將 ElastiCache for Valkey 設定為代理記憶體的向量存放區
<a name="agentic-memory-setup"></a>

下列逐步解說說明如何使用 Mem0 搭配 ElastiCache for Valkey 作為向量存放區來建置啟用記憶體的 AI 代理程式。

## 步驟 1：建立沒有記憶體的基本代理程式
<a name="agentic-memory-step1"></a>

首先，安裝 Strands 代理程式並建立基本代理程式：

```
pip install strands-agents strands-agents-tools strands-agents-builder
```

使用用於 Web 瀏覽的 HTTP 工具初始化基本代理程式：

```
from strands import Agent
from strands.tools import http_request

# Initialize agent with access to the tool to browse the web
agent = Agent(tools=[http_request])

# Format messages as expected by Strands
formatted_messages = [
    {
        "role": "user",
        "content": [{"text": "What is the URL for the project mem0 and its most important metrics?"}]
    }
]

result = agent(formatted_messages)
```

如果沒有記憶體，代理程式會為每個請求重複執行相同的研究任務。在測試中，客服人員使用大約 70，000 個字符進行三次工具呼叫來回應請求，並花費超過 9 秒的時間來完成請求。

## 步驟 2：使用 ElastiCache for Valkey 設定 Mem0
<a name="agentic-memory-step2"></a>

使用 Valkey 向量存放區連接器安裝 Mem0 程式庫：

```
pip install mem0ai "mem0ai[vector_stores]"
```

將 Valkey 設定為向量存放區。ElastiCache for Valkey 支援從 8.2 版開始的向量搜尋功能：

```
from mem0 import Memory

# Configure Mem0 with ElastiCache for Valkey
config = {
    "vector_store": {
        "provider": "valkey",
        "config": {
            "valkey_url": "your-elasticache-cluster.cache.amazonaws.com:6379",
            "index_name": "agent_memory",
            "embedding_model_dims": 1024,
            "index_type": "flat"
        }
    }
}

m = Memory.from_config(config)
```

將 {{your-elasticache-cluster.cache.amazonaws.com}} 取代為您的 ElastiCache 叢集的端點。如需尋找叢集端點的指示，請參閱[存取 ElastiCache 叢集](accessing-elasticache.md)。

## 步驟 3：將記憶體工具新增至代理程式
<a name="agentic-memory-step3"></a>

建立 代理程式可用來存放和擷取資訊的記憶體工具。`@tool` 裝飾項目會將一般 Python 函數轉換為代理程式可以叫用的工具：

```
from strands import Agent, tool
from strands.tools import http_request

@tool
def store_memory_tool(information: str, user_id: str = "user") -> str:
    """Store important information in long-term memory."""
    memory_message = [{"role": "user", "content": information}]

    # Create new memories using Mem0 and store them in Valkey
    m.add(memory_message, user_id=user_id)

    return f"Stored: {information}"

@tool
def search_memory_tool(query: str, user_id: str = "user") -> str:
    """Search stored memories for relevant information."""

    # Search memories using Mem0 stored in Valkey
    results = m.search(query, user_id=user_id)
    if results['results']:
        return "\n".join([r['memory'] for r in results['results']])
    return "No memories found"

# Initialize Strands agent with memory tools
agent = Agent(tools=[http_request, store_memory_tool, search_memory_tool])
```

## 步驟 4：測試啟用記憶體的代理程式
<a name="agentic-memory-step4"></a>

啟用記憶體後，代理程式會儲存來自其互動的資訊，並在後續請求中擷取資訊：

```
# First request - agent searches the web and stores results in memory
formatted_messages = [
    {
        "role": "user",
        "content": [{"text": "What is the URL for the project mem0 and its most important metrics?"}]
    }
]
result = agent(formatted_messages)

# Second request (same question) - agent retrieves from memory
result = agent(formatted_messages)
```

在第二個請求上，代理程式會從記憶體擷取資訊，而不是進行 Web 工具呼叫。在測試中，這將字符用量從大約 70，000 減少到 6，300 （減少 12 倍），並將回應時間從 9.25 秒縮短到 2 秒 （加快 3 倍以上）。

## 它在幕後的運作方式
<a name="agentic-memory-valkey-commands"></a>

下表顯示 Mem0 在內部用來使用 ElastiCache 實作代理式記憶體的 Valkey 命令。Mem0 透過其 API 抽象化這些命令，確切的結構描述和金鑰命名可能會因 Mem0 版本和組態而有所不同：


| 作業 | Valkey 命令 | Description | 
| --- | --- | --- | 
| 建立向量索引 | FT.CREATE agent\_memory SCHEMA embedding VECTOR HNSW 6 TYPE FLOAT32 DIM 1024 DISTANCE\_METRIC COSINE | 建立向量索引以進行語意記憶體搜尋 | 
| 存放記憶體 | HSET mem:{id} memory "..." embedding [bytes] user\_id "user\_123" created\_at "..." | 存放具有向量內嵌的記憶體 | 
| 搜尋記憶體 | FT.SEARCH agent\_memory "\*=>[KNN 5 @embedding $query\_vec]" PARAMS 2 query\_vec [bytes] DIALECT 2 | 尋找語意最相似的記憶 | 
| 設定過期時間 | EXPIRE mem:{id} 86400 | 設定記憶體項目的 TTL | 