Skip to main content

Semantic Cache

Calls to an LLM are slow and cost money, and people ask the same thing in different words. A semantic cache stores each response in Redis and finds it again by the meaning of the prompt, so "What's the capital city of France?" can reuse the answer to "What is the capital of France?".

Quick Start​

import { createClient } from 'redis';
import { HuggingFaceVectorizer, SemanticCache } from 'redis-vl';

const client = createClient();
await client.connect();

const cache = await SemanticCache.create({
client,
vectorizer: new HuggingFaceVectorizer({ model: 'Xenova/all-MiniLM-L6-v2' }),
ttl: 3600, // entries expire after an hour
});

async function answer(question: string) {
// Look in the cache first
const [hit] = await cache.check({ prompt: question });
if (hit) {
return hit.response;
}

// Nothing close enough: ask the LLM, and cache its answer
const response = await askTheLlm(question);
await cache.store({ prompt: question, response });
return response;
}

SemanticCache.create() creates the cache and its search index in Redis, if they do not exist yet.

Choosing a Vectorizer​

The vectorizer turns each prompt into a vector, and the cache compares vectors to decide what is similar. Pass any vectorizer as vectorizer.

If you leave it out, the cache uses HuggingFaceVectorizer with the redis/langcache-embed-v2 model. That needs @huggingface/transformers installed, and the first use downloads the model, which is about 600 MB.

The size of the vectors is fixed when the index is created. create() finds it by embedding one short text, so the first call with a local model can take a moment.

Storing Responses​

store() caches a response and returns the Redis key of the entry:

const key = await cache.store({
prompt: 'What is the capital of France?',
response: 'Paris',
metadata: { model: 'gpt-4o', tokens: 12 },
});
OptionDescription
promptThe prompt to cache. Required.
responseThe response to cache. Required.
vectorThe embedding of the prompt, if you already have it. Skips the vectorizer.
metadataAnything JSON can hold. It comes back unchanged with a hit.
filtersValues for the cache's filterable fields, such as { user: 'alice' }.
ttlSeconds until this entry expires, instead of the cache's TTL.

An entry's id is a hash of the prompt and its filters. Storing the same prompt with the same filters again replaces the earlier entry instead of adding a duplicate.

Checking the Cache​

check() looks up the nearest entries and keeps those that are close enough. It returns an empty array on a miss:

const hits = await cache.check({ prompt: "What's the capital city of France?" });

for (const hit of hits) {
console.log(hit.response, hit.vectorDistance); // the cached answer, and how far away its prompt was
}
OptionDescription
promptThe prompt to look up. Give prompt or vector.
vectorThe embedding of the prompt, if you already have it.
numResultsHow many entries to return at most. Default 1.
filterOnly consider entries that match this filter.
distanceThresholdOverrides the cache's threshold for this call.
refreshTtlOverrides whether this call resets the expiry of the hits.

Each hit has these fields:

FieldDescription
keyThe full Redis key of the entry.
entryIdThe entry's id, which is the key without the cache name.
promptThe prompt that was cached.
responseThe cached response.
vectorDistanceCosine distance between your prompt and the cached prompt.
insertedAtWhen the entry was first stored, in Unix seconds.
updatedAtWhen the entry last changed, in Unix seconds.
metadataThe metadata given to store(), if any.
filtersThe filter values of the entry, if any.

The Distance Threshold​

The threshold decides what counts as a match. It is a cosine distance from 0 (the same meaning) up to 2 (opposite), and lower is stricter. An entry matches when its distance is at most the threshold. A threshold of 0 matches identical prompts only.

The default is 0.1. How far apart paraphrases land depends on the model, so tune the threshold on prompts from your own application. Set it when creating the cache, change it later, or override it for one call:

const cache = await SemanticCache.create({ client, vectorizer, distanceThreshold: 0.2 });

cache.setThreshold(0.15);

await cache.check({ prompt: question, distanceThreshold: 0.05 }); // strict for this call only

Filters​

Filters keep entries apart, for example so that each user only gets answers cached for them. Declare the fields when creating the cache, give their values when storing, and filter on them when checking:

import { Tag } from 'redis-vl';

const cache = await SemanticCache.create({
client,
vectorizer,
filterableFields: [{ name: 'user', type: 'tag' }],
});

await cache.store({
prompt: 'What is the best programming language?',
response: 'TypeScript',
filters: { user: 'alice' },
});

const hits = await cache.check({
prompt: 'Which programming language is best?',
filter: Tag('user').eq('alice'),
});

filters on store() writes values onto an entry. filter on check() narrows the search to entries that carry them.

Filter values are part of an entry's id, so the same prompt can be cached once per filter value.

A filterable field cannot be named entry_id, prompt, response, inserted_at, updated_at, metadata, prompt_vector or key, because the cache uses those itself.

Expiry​

Give the cache a ttl in seconds, and every entry expires that long after it is stored. Without a TTL, entries stay until you remove them.

const cache = await SemanticCache.create({ client, vectorizer, ttl: 3600 });

await cache.store({ prompt, response, ttl: 60 }); // this entry expires sooner

cache.setTtl(7200); // new entries, and later hits, use two hours
cache.setTtl(undefined); // stop expiring entries

A cache hit resets the entry's expiry to the cache's TTL, so answers that keep being used stay cached. Turn that off for the whole cache with refreshTtlOnHit: false, or for one call with refreshTtl:

await cache.check({ prompt: question, refreshTtl: false });

Updating and Removing Entries​

// Change fields of an entry, using the key from store() or a hit
await cache.update(key, { response: 'Paris, France', metadata: { reviewed: true } });

// Remove entries by id, by full key, or both. Returns how many were deleted
await cache.drop({ ids: [hit.entryId] });
await cache.drop({ keys: [key] });

// Remove every entry and keep the index
await cache.clear();

// Remove the index together with all of its entries
await cache.delete();

update() can set prompt, response, metadata or a filterable field. It also moves updatedAt forward and resets the entry's expiry.

Reopening a Cache​

Creating a cache with the name of an existing one reuses its index and entries. Nothing is recreated.

If the existing index holds vectors of a different size than your vectorizer produces, create() refuses with an error that explains it, because mixing sizes would silently stop entries from being searchable. To switch to a vectorizer with a different vector size, delete() the old cache first and create a new one.

Pass overwrite: true to recreate the index, for example to add a filterable field. The entries stay in Redis.

Good to Know​

  • Redis indexes a new entry a moment after it is written, so a check() made within milliseconds of the matching store() can still miss.
  • Documents that expire while a search is running are skipped.
  • cache.index gives you the underlying SearchIndex, for example to inspect entries yourself.

Next Steps​