AI / LangGraph LangChain Interview questions II
How do you implement caching in LangChain?
LangChain supports LLM response caching at the global level, so any chain that calls an LLM automatically benefits from cache hits without modifying individual chains. The cache key is the serialised prompt plus model parameters — if the same prompt is sent twice, the second call returns the cached response without hitting the API.
In-memory cache — fastest, lost on process restart, suitable for development and single-request deduplication:
from langchain.globals import set_llm_cache from langchain_community.cache import InMemoryCache set_llm_cache(InMemoryCache())
SQLite cache — persists across restarts, suitable for single-process production servers or CLIs:
from langchain_community.cache import SQLiteCache set_llm_cache(SQLiteCache(database_path=".langchain_cache.db"))
Semantic cache — uses embedding similarity to serve cached responses for queries that are semantically equivalent but not character-identical:
from langchain_community.cache import GPTCache # Or use RedisSemanticCache: from langchain_community.cache import RedisSemanticCache from langchain_openai import OpenAIEmbeddings set_llm_cache(RedisSemanticCache( redis_url="redis://localhost:6379", embedding=OpenAIEmbeddings(), score_threshold=0.1, ))
Caching is most effective for knowledge base Q&A where many users ask similar questions, and for evaluation pipelines where the same prompts are run repeatedly.
More Related questions...