AI Hints
Home›LangChain Tutorial›Cache, Limits and Timeouts
LangChain · Lesson 82 of 120

Caching Model Calls

Pay once.

⏱ 2 min read▶ Video at 1:32:58🎓 Free
Watch this lesson in the LangChain courseWatch on YouTube ↗Full LangChain course

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.

Caching Model Calls
From the video: Caching Model Calls
  • Same questions, again and again
  • Why pay twice?
  • A cache remembers

An in-memory cache

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 time
from langchain.chat_models import init_chat_model
from langchain_core.caches import InMemoryCache
from langchain_core.globals import set_llm_cache

set_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

Caching tips

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.

keyvalue
Matchesexact same prompt
Best withtemperature 0
InMemoryCachelost on restart
LastingSQLite, Redis caches

Summary

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.

Key takeaways
  • set_llm_cache
  • InMemoryCache
  • Exact prompts only
Next up: Rate Limiting — staying under limits