

As traduções são geradas por tradução automática. Em caso de conflito entre o conteúdo da tradução e da versão original em inglês, a versão em inglês prevalecerá.

# Implementando um cache semântico com ElastiCache for Valkey
<a name="semantic-caching-implementation"></a>

O passo a passo a seguir mostra como implementar um cache semântico de leitura usando o ElastiCache Valkey com o Amazon Bedrock.

## Etapa 1: criar um cluster ElastiCache for Valkey
<a name="semantic-caching-step1"></a>

Crie um cluster ElastiCache for Valkey com a versão 8.2 ou posterior usando: AWS CLI

```
aws elasticache create-replication-group \
  --replication-group-id "valkey-semantic-cache" \
  --cache-node-type cache.r7g.large \
  --engine valkey \
  --engine-version 8.2 \
  --num-node-groups 1 \
  --replicas-per-node-group 1
```

## Etapa 2: conectar-se ao cluster e configurar as incorporações
<a name="semantic-caching-step2"></a>

A partir do código do seu aplicativo em execução na sua instância do Amazon EC2, conecte-se ao ElastiCache cluster e configure o modelo de incorporação:

```
from valkey.cluster import ValkeyCluster
from langchain_aws import BedrockEmbeddings

# Connect to ElastiCache for Valkey
valkey_client = ValkeyCluster(
    host="mycluster.xxxxxx.clustercfg.use1.cache.amazonaws.com",  # Your cluster endpoint
    port=6379,
    decode_responses=False
)

# Set up Amazon Bedrock Titan embeddings
embeddings = BedrockEmbeddings(
    model_id="amazon.titan-embed-text-v2:0",
    region_name="us-east-1"
)
```

Substitua o valor do host pelo endpoint de configuração do seu ElastiCache cluster. Para obter instruções sobre como encontrar seu endpoint de cluster, consulte [Como acessar seu ElastiCache cluster](accessing-elasticache.md).

## Etapa 3: criar o índice vetorial para o cache semântico
<a name="semantic-caching-step3"></a>

Configure um ValkeyStore que incorpore consultas automaticamente usando um índice HNSW com distância COSINE para pesquisa vetorial:

```
from langgraph_checkpoint_aws import ValkeyStore
from hashlib import md5

store = ValkeyStore(
    client=valkey_client,
    index={
        "collection_name": "semantic_cache",
        "embed": embeddings,
        "fields": ["query"],           # Fields to vectorize
        "index_type": "HNSW",          # Vector search algorithm
        "distance_metric": "COSINE",   # Similarity metric
        "dims": 1024                   # Titan V2 produces 1024-d vectors
    }
)
store.setup()

def cache_key_for_query(query: str):
    """Generate a deterministic cache key for a query."""
    return md5(query.encode("utf-8")).hexdigest()
```

**nota**  
ElastiCache for Valkey usa um índice para fornecer uma pesquisa vetorial rápida e precisa. O `FT.CREATE` comando cria o índice subjacente. Para obter mais informações, consulte [Pesquisa vetorial por ElastiCache](search.md).

## Etapa 4: Implementar funções de pesquisa e atualização de cache
<a name="semantic-caching-step4"></a>

Crie funções para pesquisar consultas semanticamente semelhantes no cache e armazenar novos pares de consultas e respostas:

```
def search_cache(user_message: str, k: int = 3, min_similarity: float = 0.8):
    """Look up a semantically similar cached response from ElastiCache."""
    hits = store.search(
        namespace="semantic-cache",
        query=user_message,
        limit=k
    )
    if not hits:
        return None

    # Sort by similarity score (highest first)
    hits = sorted(hits, key=lambda h: h["score"], reverse=True)
    top_hit = hits[0]
    score = top_hit["score"]

    if score < min_similarity:
        return None  # Below similarity threshold

    return top_hit["value"]["answer"]  # Return cached answer


def store_cache(user_message: str, result_message: str):
    """Store a new query-response pair in the semantic cache."""
    key = cache_key_for_query(user_message)
    store.put(
        namespace="semantic-cache",
        key=key,
        value={
            "query": user_message,
            "answer": result_message
        }
    )
```

## Etapa 5: Implementar o padrão de cache de leitura contínua
<a name="semantic-caching-step5"></a>

Integre o cache ao tratamento de solicitações do seu aplicativo:

```
import time

def handle_query(user_message: str) -> dict:
    """Handle a user query with read-through semantic cache."""
    start = time.time()

    # Step 1: Search the semantic cache
    cached_response = search_cache(user_message, min_similarity=0.8)

    if cached_response:
        # Cache hit - return cached response
        elapsed = (time.time() - start) * 1000
        return {
            "response": cached_response,
            "source": "cache",
            "latency_ms": round(elapsed, 1),
        }

    # Step 2: Cache miss - invoke LLM
    llm_response = invoke_llm(user_message)  # Your LLM invocation function

    # Step 3: Store the response in cache for future reuse
    store_cache(user_message, llm_response)

    elapsed = (time.time() - start) * 1000
    return {
        "response": llm_response,
        "source": "llm",
        "latency_ms": round(elapsed, 1),
    }
```

## Comandos subjacentes do Valkey
<a name="semantic-caching-valkey-commands"></a>

A tabela a seguir mostra os comandos Valkey usados para implementar o cache semântico:


| Operation | Comando Valkey | Latência típica | 
| --- | --- | --- | 
| Criar índice | FT.CREATE semantic\_cache SCHEMA query TEXT answer TEXT embedding VECTOR HNSW 6 TYPE FLOAT32 DIM 1024 DISTANCE\_METRIC COSINE | One-time configuração | 
| Pesquisa de cache | FT.SEARCH semantic\_cache "\*=>[KNN 3 @embedding $query\_vec]" PARAMS 2 query\_vec [bytes] DIALECT 2 | Microssegundos | 
| Resposta da loja | HSET cache:{hash} query "..." answer "..." embedding [bytes] | Microssegundos | 
| Definir TTL | EXPIRE cache:{hash} 82800 | Microssegundos | 
| Inferência LLM (senhorita) | Chamada de API externa para o Amazon Bedrock | 500—6000 ms | 