Caching saves previous results so you don't pay or wait for the same work twice. It helps reduce costs and speeds up your app.
Caching strategies for cost reduction in LangChain
Start learning this pattern below
Jump into concepts and practice - no test required
from langchain.cache import InMemoryCache cache = InMemoryCache() # Use cache to store and retrieve results result = cache.get_or_set(key, lambda: expensive_function(input))
Use get_or_set to check cache first, then run function if missing.
LangChain supports different cache backends like memory, Redis, or custom stores.
from langchain.cache import InMemoryCache cache = InMemoryCache() key = 'user_question_1' result = cache.get_or_set(key, lambda: llm.generate('What is AI?'))
from langchain.cache import RedisCache cache = RedisCache(redis_url='redis://localhost:6379') key = 'expensive_call' result = cache.get_or_set(key, lambda: expensive_api_call())
This example shows caching an expensive calculation. The first call runs the function and caches the result. The second call returns the cached result instantly without running the function again.
from langchain.cache import InMemoryCache cache = InMemoryCache() # Simulate an expensive function def expensive_function(x): print('Running expensive function...') return x * x key = 'square_4' # First call runs the function result1 = cache.get_or_set(key, lambda: expensive_function(4)) print('First call result:', result1) # Second call uses cache, no print from function result2 = cache.get_or_set(key, lambda: expensive_function(4)) print('Second call result:', result2)
Cache keys should be unique and descriptive to avoid collisions.
Cached data may become stale; consider cache expiration if needed.
Choose cache backend based on your app scale and persistence needs.
Caching stores results to avoid repeated work and reduce costs.
Use get_or_set to check cache before running expensive calls.
Pick the right cache type for your app, like in-memory or Redis.
Practice
Solution
Step 1: Understand caching purpose
Caching saves results from previous operations to reuse them later.Step 2: Connect caching to cost reduction
By reusing stored results, it avoids repeated expensive API calls, lowering costs.Final Answer:
It stores previous results to avoid repeated expensive calls -> Option BQuick Check:
Caching = Avoid repeated calls [OK]
- Thinking caching increases API calls
- Believing caching deletes data immediately
- Confusing caching with version upgrades
get_or_set method?Solution
Step 1: Recall
The method takes a key and a function to call if the key is missing.get_or_setsyntaxStep 2: Match correct argument order
Correct usage iscache.get_or_set(key, lambda: expensive_call())to delay call until needed.Final Answer:
cache.get_or_set(key, lambda: expensive_call()) -> Option AQuick Check:
Correct method and argument order = B [OK]
- Swapping key and function arguments
- Calling expensive function immediately instead of lazy
- Using wrong method names like set_or_get
cache = InMemoryCache()
result1 = cache.get_or_set('key1', lambda: 'data1')
result2 = cache.get_or_set('key1', lambda: 'data2')
What will be the value of result2?Solution
Step 1: Understand
If the key exists, it returns cached value without calling the function.get_or_setbehaviorStep 2: Apply to given code
First call caches 'data1' under 'key1'. Second call finds 'key1' and returns 'data1', ignoring 'data2'.Final Answer:
'data1' -> Option CQuick Check:
Cache returns stored value, not new function result [OK]
- Assuming second lambda runs and returns 'data2'
- Expecting None if key exists
- Thinking it raises an error on duplicate keys
cache = RedisCache()
result = cache.get_or_set('key', expensive_call())
What is the likely cause of the error?Solution
Step 1: Check get_or_set argument types
get_or_set expects a key and a function to call if missing, not the function result.Step 2: Identify error cause
Passing expensive_call() calls it immediately, causing error or unwanted behavior.Final Answer:
You passed the result of expensive_call() instead of a function -> Option AQuick Check:
Pass function, not result, to get_or_set [OK]
- Calling function instead of passing it
- Assuming RedisCache lacks get_or_set
- Using wrong key types
Solution
Step 1: Understand multi-server caching needs
Multiple servers require a shared cache to avoid duplicate expensive calls.Step 2: Evaluate cache types
In-memory caches are local to each server; Redis is a shared external cache accessible by all servers.Final Answer:
Use a Redis cache shared by all servers -> Option DQuick Check:
Shared cache for multi-server = Redis [OK]
- Using local in-memory cache for multi-server apps
- Disabling caching unnecessarily
- Relying on local files which are not shared
