Caching and Performance
Relevant source files
The following files were used as context for generating this wiki page:
Caching is a critical feature in LangChain for enhancing performance and reducing costs associated with repeated calls to Large Language Models (LLMs) and embedding providers. By storing the results of previous computations, LangChain can retrieve them from a cache instead of re-computing them, leading to faster response times and lower API usage bills.
The framework provides a flexible caching system with multiple backend implementations, ranging from simple in-memory stores to persistent database-backed solutions. This allows developers to choose the appropriate caching strategy based on their application's needs, whether it's for a single session or across multiple users and runs. Caching is available for both LLM generations and text embeddings.
Core Caching Abstractions
The foundation of LangChain's caching system is built upon a set of abstract base classes defined in langchain_core. These interfaces ensure a consistent API for all cache implementations.
Sources: libs/core/langchain_core/caches.py
Key Classes
| Class | Description |
|---|---|
BaseCache | The fundamental abstract base class for all cache implementations. It defines the core methods lookup, update, clear. |
Cache | A synchronous version of the cache interface that inherits from BaseCache. |
AsyncCache | An asynchronous version of the cache interface, providing alookup and aupdate methods for non-blocking operations. |
The following diagram illustrates the inheritance structure of the core caching classes.
Global Cache Management
LangChain provides a global mechanism to set and retrieve a cache instance that can be used throughout an application. This simplifies configuration by allowing a single cache to be configured once and used implicitly by various components.
Sources: libs/langchain/langchain/globals.py
Global Cache Functions
The langchain.globals module contains functions to manage the global cache instance.
| Function | Description |
|---|---|
set_llm_cache(cache: Optional[BaseCache]) | Sets the global cache for LLMs. Accepts an instance of a BaseCache implementation or None to disable it. |
get_llm_cache() -> Optional[BaseCache] | Retrieves the currently set global LLM cache. |
set_embedding_cache(cache: Optional[BaseCache]) | Sets the global cache for embeddings. |
get_embedding_cache() -> Optional[BaseCache] | Retrieves the currently set global embedding cache. |
Global Cache Flow
The following diagram shows the flow of setting and using the global cache.
Cache Implementations
LangChain offers several built-in cache implementations to suit different needs.
Sources: libs/langchain/langchain/cache.py
| Class | Description | Persistence | Backend |
|---|---|---|---|
InMemoryCache | A basic cache that stores data in a dictionary in memory. | No | In-Memory Dictionary |
FullLLMCache | A more advanced in-memory cache that stores full Generation objects. | No | In-Memory Dictionary |
SQLAlchemyCache | A persistent cache that uses a SQLAlchemy-compatible database as a backend. | Yes | SQL Database |
RedisCache | A cache that uses a Redis server for storage. | Yes | Redis |
GPTCache | An integration with GPTCache for semantic caching. | Yes | Various (via GPTCache) |
MongoDBCache | A cache that uses a MongoDB collection for storage, often for semantic caching. | Yes | MongoDB |
SQLAlchemyCache
The SQLAlchemyCache provides a persistent caching layer by storing LLM generations in a SQL database. It uses a single table to store the prompt, the LLM string identifier, and the response.
The schema for the cache table is defined as follows:
To use it, you need to instantiate it with a SQLAlchemy engine and optionally a session.
# Example of initializing SQLAlchemyCache
from sqlalchemy import create_engine
from langchain.cache import SQLAlchemyCache
# An in-memory SQLite database
engine = create_engine("sqlite:///:memory:")
cache = SQLAlchemyCache(engine)
Sources: libs/langchain/langchain/cache.py:134-140
Semantic Caching with MongoDB
Semantic caching goes beyond exact string matching for prompts. It stores embeddings of prompts and retrieves cached results for semantically similar new prompts. The mongodb-langchain-cache-memory.ipynb cookbook demonstrates this using MongoDBCache and MongoDBAtlasVectorSearch. This approach is powerful for handling variations in user queries that have the same intent.
Sources: cookbook/mongodb-langchain-cache-memory.ipynb
Embedding Caching
Similar to LLM caching, LangChain provides a mechanism to cache text embeddings to avoid re-computing them, which saves time and cost. This is primarily achieved through the CacheBackedEmbeddings class.
Sources: libs/langchain/langchain/embeddings/cache.py, libs/langchain/tests/unit_tests/embeddings/test_caching.py
CacheBackedEmbeddings
This class acts as a wrapper around an embedding model. It uses a key-value store to cache the embeddings. When asked to embed a document, it first checks the cache. If the embedding is found, it's returned immediately. If not, it calls the underlying embedding model, stores the result in the cache, and then returns it.
The keys for the cache are generated from the text and the class name of the underlying embedder, ensuring that caches are not mixed between different embedding models.
Sources: libs/langchain/langchain/embeddings/cache.py:31-43
The following sequence diagram illustrates the workflow for both a cache hit and a cache miss.
Here is a code example demonstrating its usage:
from langchain.embeddings import CacheBackedEmbeddings
from langchain.storage import InMemoryStore
from langchain.embeddings.fake import FakeEmbeddings
# Initialize the underlying embedder and the cache store
underlying_embedder = FakeEmbeddings(size=10)
store = InMemoryStore()
# Create the cached embedder
embedder = CacheBackedEmbeddings.from_bytes_store(
underlying_embedder, store, namespace=underlying_embedder.model
)
# First call: embeds and caches the result
embeddings1 = embedder.embed_documents(["hello", "goodbye"])
# Second call: retrieves from cache
embeddings2 = embedder.embed_documents(["hello", "goodbye"])
Sources: libs/langchain/tests/unit_tests/embeddings/test_caching.py:27-44
Conclusion
LangChain's caching system is a powerful tool for optimizing LLM and embedding-based applications. By providing a simple set of abstractions, a global configuration mechanism, and a variety of backend implementations (from in-memory to persistent SQL and NoSQL databases), it offers developers the flexibility to significantly improve performance and reduce operational costs. Whether using simple key-value caching for LLM prompts or more advanced semantic and embedding caching, these features are essential for building scalable and efficient applications.