Semantic Caching for LLMs#

RedisVL provides an SemanticCache interface utilize Redis’ built-in caching capabilities AND vector search in order to store responses from previously-answered questions. This reduces the number of requests and tokens sent to the Large Language Models (LLM) service, decreasing costs and enhancing application throughput (by reducing the time taken to generate responses).

This notebook will go over how to use Redis as a Semantic Cache for your applications

First, we will import OpenAI to use their API for responding to user prompts. We will also create a simple ask_openai helper method to assist.

import os
import openai
import getpass
import time

import numpy as np

os.environ["TOKENIZERS_PARALLELISM"] = "False"

api_key = os.getenv("OPENAI_API_KEY") or getpass.getpass("Enter your OpenAI API key: ")

openai.api_key = api_key

def ask_openai(question: str) -> str:
    response = openai.Completion.create(
    return response.choices[0].text.strip()
# Test
print(ask_openai("What is the capital of France?"))
The capital of France is Paris.

Initializing SemanticCache#

SemanticCache will automatically create an index within Redis upon initialization for the semantic cache content.

from redisvl.extensions.llmcache import SemanticCache

llmcache = SemanticCache(
    name="llmcache",                     # underlying search index name
    prefix="llmcache",                   # redis key prefix for hash entries
    redis_url="redis://localhost:6379",  # redis connection url string
    distance_threshold=0.1               # semantic cache distance threshold
# look at the index specification created for the semantic cache lookup
!rvl index info -i llmcache
Index Information:
│ Index Name   │ Storage Type   │ Prefixes     │ Index Options   │   Indexing │
│ llmcache     │ HASH           │ ['llmcache'] │ []              │          0 │
Index Fields:
│ Name          │ Attribute     │ Type   │ Field Option   │   Option Value │
│ prompt        │ prompt        │ TEXT   │ WEIGHT         │              1 │
│ response      │ response      │ TEXT   │ WEIGHT         │              1 │
│ prompt_vector │ prompt_vector │ VECTOR │                │                │

Basic Cache Usage#

question = "What is the capital of France?"
# Check the semantic cache -- should be empty
if response := llmcache.check(prompt=question):
    print("Empty cache")
Empty cache

Our initial cache check should be empty since we have not yet stored anything in the cache. Below, store the question, proper response, and any arbitrary metadata (as a python dictionary object) in the cache.

# Cache the question, answer, and arbitrary metadata
    metadata={"city": "Paris", "country": "france"}

Now we will check the cache again with the same question and with a semantically similar question:

# Check the cache again
if response := llmcache.check(prompt=question, return_fields=["prompt", "response", "metadata"]):
    print("Empty cache")
[{'id': 'llmcache:115049a298532be2f181edb03f766770c0db84c22aff39003fec340deaec7545', 'vector_distance': '8.34465026855e-07', 'prompt': 'What is the capital of France?', 'response': 'Paris', 'metadata': {'city': 'Paris', 'country': 'france'}}]
# Check for a semantically similar result
question = "What actually is the capital of France?"

Customize the Distance Threshhold#

For most use cases, the right semantic similarity threshhold is not a fixed quantity. Depending on the choice of embedding model, the properties of the input query, and even business use case – the threshhold might need to change.

Fortunately, you can seamlessly adjust the threshhold at any point like below:

# Widen the semantic distance threshold
# Really try to trick it by asking around the point
# But is able to slip just under our new threshold
question = "What is the capital city of the country in Europe that also has a city named Nice?"
# Invalidate the cache completely by clearing it out

# should be empty now

Utilize TTL#

Redis uses TTL policies (optional) to expire individual keys at points in time in the future. This allows you to focus on your data flow and business logic without bothering with complex cleanup tasks.

A TTL policy set on the SemanticCache allows you to temporarily hold onto cache entries. Below, we will set the TTL policy to 5 seconds.

llmcache.set_ttl(5) # 5 seconds"This is a TTL test", "This is a TTL test response")

# confirm that the cache has cleared by now on it's own
result = llmcache.check("This is a TTL test")

# Reset the TTL to null (long lived data)

Simple Performance Testing#

Next, we will measure the speedup obtained by using SemanticCache. We will use the time module to measure the time taken to generate responses with and without SemanticCache.

def answer_question(question: str) -> str:
    """Helper function to answer a simple question using OpenAI with a wrapper
    check for the answer in the semantic cache first.

        question (str): User input question.

        str: Response.
    results = llmcache.check(prompt=question)
    if results:
        return results[0]["response"]
        answer = ask_openai(question)
        return answer
start = time.time()
# asking a question -- openai response time
question = "What was the name of the first US President?"
answer = answer_question(question)
end = time.time()

print(f"Without caching, a call to openAI to answer this simple question took {end-start} seconds.")

# add the entry to our LLM cache, response="George Washington")
Without caching, a call to openAI to answer this simple question took 0.984370231628418 seconds.
# Calculate the avg latency for caching over LLM usage
times = []

for _ in range(10):
    cached_start = time.time()
    cached_answer = answer_question(question)
    cached_end = time.time()

avg_time_with_cache = np.mean(times)
print(f"Avg time taken with LLM cache enabled: {avg_time_with_cache}")
print(f"Percentage of time saved: {round(((end - start) - avg_time_with_cache) / (end - start) * 100, 2)}%")
Avg time taken with LLM cache enabled: 0.5094501972198486
Percentage of time saved: 48.25%
# check the stats of the index
!rvl stats -i llmcache
│ Stat Key                    │ Value       │
│ num_docs                    │ 0           │
│ num_terms                   │ 19          │
│ max_doc_id                  │ 5           │
│ num_records                 │ 36          │
│ percent_indexed             │ 1           │
│ hash_indexing_failures      │ 0           │
│ number_of_uses              │ 40          │
│ bytes_per_record_avg        │ 5.27778     │
│ doc_table_size_mb           │ 0           │
│ inverted_sz_mb              │ 0.000181198 │
│ key_table_size_mb           │ 0           │
│ offset_bits_per_record_avg  │ 8           │
│ offset_vectors_sz_mb        │ 3.33786e-05 │
│ offsets_per_term_avg        │ 0.972222    │
│ records_per_doc_avg         │ inf         │
│ sortable_values_size_mb     │ 0           │
│ total_indexing_time         │ 3.074       │
│ total_inverted_index_blocks │ 19          │
│ vector_index_sz_mb          │ 0.000389099 │
# Clear the cache AND delete the underlying index