Customers ask the same questions again and again. What are your opening hours? Do gift cards expire? If the prompt is identical, why pay the model to answer it twice? A cache remembers answers, and returns them instantly.
Set LLM cache turns on caching for every model in the program. In memory cache keeps answers in memory, while the program runs. We ask the same question twice, and time each call. Run it. The first call goes to the model. The second is answered from the cache, in almost no time, and costs nothing.
cache.pypython
import timefrom langchain.chat_models import init_chat_modelfrom langchain_core.caches import InMemoryCachefrom langchain_core.globals import set_llm_cacheset_llm_cache(InMemoryCache())model = init_chat_model("google_genai:gemini-flash-lite-latest", temperature=0)for attempt in [1, 2]: start = time.perf_counter() reply = model.invoke("Suggest one classic novel for a long train journey. Title only.") print(f"call {attempt}: {time.perf_counter() - start:.2f}s {reply.text.strip()}")
Output
call 1: 0.88s Murder on the Orient Express
call 2: 0.00s Murder on the Orient Express
A cache only helps when the prompt is exactly the same, so it suits fixed questions, and temperature zero. The in memory cache is lost when the program stops. For a shared, lasting cache, LangChain also has caches backed by SQLite, and Redis.
A cache returns stored answers for repeated prompts, instantly and for free. Turn it on with set LLM cache. Next, staying under a provider's rate limits.