

기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.

# 에이전트 메모리의 벡터 저장소로 ElastiCache for Valkey 설정
<a name="agentic-memory-setup"></a>

다음 연습에서는 ElastiCache for Valkey와 함께 Mem0을 벡터 스토어로 사용하여 메모리 지원 AI 에이전트를 빌드하는 방법을 보여줍니다.

## 1단계: 메모리 없이 기본 에이전트 생성
<a name="agentic-memory-step1"></a>

먼저 Strands 에이전트를 설치하고 기본 에이전트를 생성합니다.

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

웹 브라우징을 위한 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단계: Valkey용 ElastiCache를 사용하여 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)
```

두 번째 요청에서 에이전트는 웹 도구 호출 대신 메모리에서 정보를 검색합니다. 테스트에서 토큰 사용량을 약 70,000에서 6,300으로 줄이고(12배 감소) 응답 시간을 9.25초에서 2초로 개선했습니다(3배 이상 빠름).

## 후드 아래에서 작동하는 방식
<a name="agentic-memory-valkey-commands"></a>

다음 표에는 Mem0이 ElastiCache를 사용하여 에이전트 메모리를 구현하는 데 내부적으로 사용하는 Valkey 명령이 나와 있습니다. Mem0은 API를 통해 이러한 명령을 추상화합니다. 정확한 스키마 및 키 이름 지정은 Mem0 버전 및 구성에 따라 다를 수 있습니다.


| 연산 | Valkey 명령 | 설명 | 
| --- | --- | --- | 
| 벡터 인덱스 생성 | 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을 설정합니다. | 