

Le traduzioni sono generate tramite traduzione automatica. In caso di conflitto tra il contenuto di una traduzione e la versione originale in Inglese, quest'ultima prevarrà.

# ElastiCache Configurazione di Valkey come archivio vettoriale per la memoria agentica
<a name="agentic-memory-setup"></a>

La seguente procedura dettagliata mostra come creare un agente AI abilitato alla memoria utilizzando Mem0 con Valkey come archivio vettoriale. ElastiCache

## Passaggio 1: creare un agente di base senza memoria
<a name="agentic-memory-step1"></a>

Innanzitutto, installa Strands Agents e crea un agente di base:

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

Inizializza un agente di base con uno strumento HTTP per la navigazione web:

```
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)
```

Senza memoria, l'agente esegue ripetutamente le stesse attività di ricerca per ogni richiesta. Durante il test, l'agente effettua tre chiamate allo strumento per rispondere alla richiesta, utilizzando circa 70.000 token e impiegando più di 9 secondi per il completamento.

## Passaggio 2: configura Mem0 con per Valkey ElastiCache
<a name="agentic-memory-step2"></a>

Installa la libreria Mem0 con il connettore Valkey Vector Store:

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

Configura Valkey come archivio vettoriale. ElastiCache for Valkey supporta le funzionalità di ricerca vettoriale a partire dalla versione 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)
```

Sostituiscilo {{your-elasticache-cluster.cache.amazonaws.com}} con l'endpoint del tuo ElastiCache cluster. Per istruzioni su come trovare l'endpoint del cluster, consulta [Accesso al ElastiCache ](accessing-elasticache.md) cluster.

## Fase 3: Aggiungere strumenti di memoria all'agente
<a name="agentic-memory-step3"></a>

Create strumenti di memoria che l'agente possa utilizzare per archiviare e recuperare informazioni. Il `@tool` decoratore trasforma le normali funzioni di Python in strumenti che l'agente può invocare:

```
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])
```

## Fase 4: Testare l'agente abilitato alla memoria
<a name="agentic-memory-step4"></a>

Con la memoria abilitata, l'agente archivia le informazioni dalle sue interazioni e le recupera nelle richieste successive:

```
# 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)
```

Alla seconda richiesta, l'agente recupera le informazioni dalla memoria anziché effettuare chiamate agli strumenti Web. Nei test, ciò ha ridotto l'utilizzo dei token da circa 70.000 a 6.300 (una riduzione di 12 volte) e ha migliorato il tempo di risposta da 9,25 secondi a 2 secondi (oltre 3 volte più veloce).

## Come funziona sotto il cofano
<a name="agentic-memory-valkey-commands"></a>

La tabella seguente mostra i comandi Valkey che Mem0 utilizza internamente per implementare la memoria agentica. ElastiCache Mem0 astrae questi comandi tramite la sua API: lo schema esatto e la denominazione delle chiavi possono variare a seconda della versione e della configurazione di Mem0:


| Operation | Comando Valkey | Description | 
| --- | --- | --- | 
| Crea un indice vettoriale | FT.CREATE agent\_memory SCHEMA embedding VECTOR HNSW 6 TYPE FLOAT32 DIM 1024 DISTANCE\_METRIC COSINE | Crea un indice vettoriale per la ricerca nella memoria semantica | 
| Memorizza memoria | HSET mem:{id} memory "..." embedding [bytes] user\_id "user\_123" created\_at "..." | Memorizza una memoria con il suo incorporamento vettoriale | 
| Cerca ricordi | FT.SEARCH agent\_memory "\*=>[KNN 5 @embedding $query\_vec]" PARAMS 2 query\_vec [bytes] DIALECT 2 | Trova i ricordi semanticamente più simili | 
| Imposta la scadenza | EXPIRE mem:{id} 86400 | Imposta il TTL per le voci di memoria | 