Smart Caching for Memory and Tool Outputs

FreeAPIOpenAIKey · Updated 2026-11-24 · 11 min read

Glass jar with labeled data cards representing cached memory
Organized storage for efficient memory retrieval.

Agentic workflows consume tokens at a rate that can quickly exceed daily limits, especially when agents loop through multiple reasoning steps or tool calls. Each iteration sends the full conversation history to the model, meaning memory grows linearly with every action. Without intervention, a simple task can balloon into a massive context window, driving up costs and latency significantly.

Caching memory is not just about storing chat logs; it is about recognizing when the state has not changed enough to warrant a fresh inference. By intercepting repeated queries or tool outputs, you can serve cached results instantly, bypassing the expensive API call entirely. This approach preserves the agent's ability to reason while drastically cutting the number of tokens sent to the model, which is critical for budget management.

This guide outlines how to implement caching strategies specifically for agentic systems. We will cover how to structure memory, detect redundancy, and integrate caches into your workflow. Whether you are using a lightweight endpoint or a commercial provider, these techniques help you manage context windows and reduce the overall cost of running autonomous agents. The site is not affiliated with OpenAI, ensuring you get unbiased advice on cost reduction.

Frequently asked questions

What is agentic memory caching?

Agentic memory caching stores the results of previous agent actions or reasoning steps. When the agent encounters a similar state or query, it retrieves the cached result instead of making a new API call. This reduces token usage by reusing computed outcomes rather than re-inferencing them from scratch.

How does caching differ from standard conversation history?

Standard history keeps every message in the context window, growing indefinitely. Caching stores specific outcomes or tool responses separately. The agent references the cache to save tokens, while the history remains lightweight. This distinction allows you to manage context size more effectively than just appending messages.

Which is better: caching tool outputs or reasoning steps?

Caching tool outputs is generally more effective because tool calls often involve expensive external API requests or complex computations. Reasoning steps are cheaper to re-run but can still benefit from caching if the logic is deterministic. Prioritize caching high-cost operations first for maximum savings.

What happens if the cached data becomes stale?

Stale data occurs when the underlying state changes but the cache returns an old result. To prevent this, use time-to-live (TTL) values or invalidation triggers based on state changes. For example, if a file is modified, clear the cache for that file's path to ensure fresh data is fetched.

How do I handle unique queries in a cache?

Use a hashing function to generate a unique key for each query. If the key does not exist in the cache, the agent performs the inference and stores the result. This ensures that every unique interaction is processed correctly while avoiding redundant calls for identical or near-identical inputs.

Does caching affect the agent's reasoning quality?

Caching generally improves consistency because the same input yields the same output. However, it may reduce adaptability if the context changes slightly but the cache returns an identical result. Monitor for edge cases where cached responses might be slightly outdated due to subtle state changes in the environment.

How much can I save by caching memory?

Savings depend on the frequency of repeated queries and the cost of the API. In high-loop scenarios, caching can reduce token usage by 30-50%. The more deterministic the agent's actions, the higher the cache hit rate, leading to greater cost reductions and faster response times.

Can I cache memory across different agent sessions?

Yes, if you use a persistent storage backend like Redis or a database. This allows agents to remember past interactions even after sessions end. However, ensure that the cache is scoped correctly to avoid cross-contamination between different users or projects, which could lead to incorrect context retrieval.

Step by step

  1. Identify Cacheable Actions — Analyze your agent's workflow to identify repeated tool calls and reasoning steps. Focus on deterministic actions that produce consistent outputs for the same input.
  2. Design Cache Structure — Choose a caching strategy, such as dictionary, Redis, or database. Define cache keys based on input parameters or context hashes to ensure accurate retrieval.
  3. Implement Cache Logic — Write code to check the cache before making API calls. If the result is cached, return it; otherwise, make the call, store the result, and return it.
  4. Monitor and Optimize — Track cache hit rates, latency, and token savings. Adjust TTLs and eviction policies based on performance metrics to optimize your caching strategy.

Understanding the Cost of Agentic Loops

Agentic workflows often involve multiple rounds of reasoning and tool usage. Each round sends the entire conversation history to the model, including the initial prompt, previous turns, and the current query. As the agent performs more actions, the context window grows, and so does the cost. This linear growth can quickly become unsustainable for long-running tasks.

The primary cost driver is the input tokens, which include the history. If an agent loops five times, each iteration includes the previous four turns. This means the fifth turn is significantly more expensive than the first. Caching helps by reducing the need to re-process the same information, thereby flattening the cost curve.

The Token Growth Problem

Every additional turn in an agentic workflow adds the previous history to the context. This means the token count increases quadratically in some scenarios, especially if the agent recalls previous tool outputs. Understanding this growth pattern is crucial for estimating costs and designing efficient caching strategies.

Why Caching Matters for Agents

Caching is essential for agents because it breaks the linear cost model. By storing repeated results, you avoid sending the same data to the model multiple times. This not only reduces costs but also improves latency, as cached responses are served instantly without waiting for model inference.

  • Input tokens include history, prompts, and current query.
  • Output tokens are generated per inference step.
  • Caching reduces input tokens by reusing results.
  • Latency improves as cache hits bypass inference.
import hashlib

def get_cache_key(prompt):
    return hashlib.md5(prompt.encode()).hexdigest()

# Example: Generate a unique key for a prompt
key = get_cache_key("What is the capital of France?")
print(f"Cache Key: {key}")

Strategies for Caching Tool Outputs

Tool outputs are a prime candidate for caching because they often involve external API calls or complex computations. If an agent calls a weather API or a database query, the result is likely to be the same for the same input. Caching these outputs can save significant tokens and reduce latency.

To implement this, identify the tool calls that are deterministic or have predictable outputs. Store the result of these calls in a cache with a unique key based on the input parameters. When the agent makes the same call again, retrieve the cached result instead of making a new request.

Identifying Cacheable Tools

Not all tools are suitable for caching. Focus on those with deterministic outputs, such as database queries, API calls, or file operations. Avoid caching tools with side effects, like writing to a file, unless you also handle cache invalidation properly to prevent stale data.

Implementing Tool Caching

Use a dictionary or a database to store tool outputs. Generate a unique key for each input and store the result. When the tool is called, check the cache first. If the key exists, return the cached result; otherwise, make the API call and store the result for future use.

  • Cache deterministic tool outputs.
  • Use input parameters as cache keys.
  • Handle cache invalidation for stateful tools.
  • Prioritize high-cost tool calls.
cache = {}

def call_tool(tool_name, params):
    key = f"{tool_name}:{hashlib.md5(str(params).encode()).hexdigest()}"
    if key in cache:
        return cache[key]
    result = simulate_api_call(tool_name, params)
    cache[key] = result
    return result
Flowchart with cache icon for agentic workflows
Flowchart demonstrating caching logic in agent loops.

Caching Reasoning Steps

Reasoning steps involve the model's internal thought process, which can be expensive to re-run. If the agent reaches the same conclusion multiple times, caching these steps can save tokens. However, reasoning is less deterministic than tool outputs, so caching requires careful consideration of context changes.

To cache reasoning, store the final conclusion or summary of a reasoning step. Use a hash of the input context and the current state to generate the cache key. If the agent encounters a similar situation, retrieve the cached reasoning to avoid re-inferencing.

When to Cache Reasoning

Cache reasoning when the agent repeats similar logical steps. This is common in planning tasks where the agent evaluates multiple options. If the context and options are identical, the reasoning will likely be the same, making it a good candidate for caching.

Managing Reasoning Cache Size

Reasoning caches can grow large if not managed properly. Use a least recently used (LRU) eviction policy to remove old entries when the cache reaches its size limit. This ensures that the most relevant reasoning steps are retained while freeing up space for new data.

  • Cache final conclusions of reasoning steps.
  • Use context hashes for cache keys.
  • Apply LRU eviction to manage size.
  • Monitor cache hit rates for reasoning.
from collections import OrderedDict

class LRUCache(OrderedDict):
    def __init__(self, capacity):
        super().__init__()
        self.capacity = capacity

    def get(self, key):
        if key not in self:
            return -1
        self.move_to_end(key)
        return self[key]

    def put(self, key, value):
        if key in self:
            self.move_to_end(key)
        self[key] = value
        if len(self) > self.capacity:
            oldest = next(iter(self))
            del self[oldest]

Handling Context Window Constraints

Context windows are limited, and agentic workflows can quickly exceed these limits. Caching helps by reducing the amount of data sent to the model, but it also requires careful management of what is stored in the context. Prioritize recent and relevant information while archiving older data.

Use caching to offload historical data from the context window. Store older interactions in a cache and only retrieve them when needed. This keeps the context window lean, reducing costs and improving inference speed. It also prevents the model from being overwhelmed by irrelevant information.

Optimizing Context Size

Reduce context size by summarizing older interactions. Store these summaries in a cache and reference them when needed. This allows the agent to maintain a long-term memory without filling the context window with detailed history, saving tokens and improving performance.

Dynamic Context Management

Implement dynamic context management by adjusting the context window size based on the task. For simple tasks, use a smaller context; for complex tasks, allow a larger window. Caching helps by providing access to historical data without including it in the active context.

  • Summarize older interactions for caching.
  • Use dynamic context window sizes.
  • Archive historical data to save tokens.
  • Reference cached summaries when needed.
def summarize_history(history):
    # Placeholder for summarization logic
    return "Summary of past interactions"

cached_summary = summarize_history(history)
cache.put("summary", cached_summary)
Stack of books with magnifying glass
Searching for cached information efficiently.

Implementing Cache Invalidation

Cache invalidation is critical to ensure that stale data does not affect the agent's decisions. If the state changes, the cache must be updated to reflect the new reality. This can be done using time-to-live (TTL) values or event-driven invalidation.

Use TTLs to automatically expire cache entries after a certain period. This is useful for time-sensitive data, such as weather forecasts or stock prices. For stateful data, use event-driven invalidation to clear the cache when a relevant event occurs, such as a file modification or user action.

Time-to-Live (TTL) Strategy

TTLs are simple and effective for time-sensitive data. Set a TTL for each cache entry based on how long the data remains relevant. After the TTL expires, the cache entry is removed, and the next request will fetch fresh data from the source.

Event-Driven Invalidation

Event-driven invalidation is more precise than TTLs. Listen for events that indicate a state change, such as a file write or a database update. When an event occurs, clear the relevant cache entries to ensure the agent uses the latest data.

  • Use TTLs for time-sensitive data.
  • Clear cache on state changes.
  • Combine TTL and event-driven strategies.
  • Monitor cache freshness to avoid stale data.
import time

cache = {}

def set_with_ttl(key, value, ttl):
    cache[key] = {"value": value, "expiry": time.time() + ttl}

def get_cache(key):
    if key in cache and cache[key]["expiry"] > time.time():
        return cache[key]["value"]
    return None

Monitoring and Debugging Cache Performance

Monitoring cache performance is essential to ensure that caching is delivering the expected benefits. Track metrics such as cache hit rates, latency improvements, and token savings. Use these metrics to optimize your caching strategy and identify areas for improvement.

Debugging cache issues involves checking for stale data, incorrect cache keys, and performance bottlenecks. Use logging to trace cache hits and misses, and compare the cached results with fresh API responses to ensure accuracy. Adjust your caching strategy based on these insights.

Key Metrics to Track

Track cache hit rates to measure effectiveness. A high hit rate indicates that caching is reducing API calls. Also monitor latency improvements and token savings to quantify the cost benefits. These metrics help you understand the impact of caching on your workflow.

Debugging Cache Issues

Debug cache issues by logging cache operations and comparing results. Check for incorrect cache keys that may cause misses, or stale data that may lead to incorrect outcomes. Use these insights to refine your caching strategy and improve reliability.

  • Track cache hit rates and latency.
  • Monitor token savings from caching.
  • Log cache operations for debugging.
  • Compare cached vs. fresh results.
import logging

logger = logging.getLogger(__name__)

def get_cache(key):
    result = cache.get(key)
    if result:
        logger.info(f"Cache hit for key: {key}")
        return result
    logger.info(f"Cache miss for key: {key}")
    return None
Network diagram with connected nodes
Network diagram showing interconnected data and caching.

Advanced Caching Techniques

Advanced caching techniques include using semantic caching, where similar queries are matched based on meaning rather than exact text. This can significantly increase cache hit rates by capturing variations in user input. It also allows for more flexible and robust caching strategies.

Another advanced technique is hierarchical caching, where data is cached at multiple levels. For example, cache tool outputs at one level and reasoning steps at another. This allows you to optimize caching for different types of data, improving efficiency and reducing costs.

Semantic Caching

Semantic caching uses embeddings to match similar queries. This allows the cache to return results for queries that are semantically similar but not identical. It increases hit rates and reduces the need for new inferences, especially in conversational agents.

Hierarchical Caching

Hierarchical caching organizes data at multiple levels, such as tool outputs, reasoning steps, and summaries. This allows you to optimize caching for different types of data, improving efficiency and reducing costs. It also makes it easier to manage cache size and invalidation.

  • Use embeddings for semantic matching.
  • Organize cache by data type.
  • Optimize for different data levels.
  • Improve hit rates with semantic caching.
from sklearn.feature_extraction.text import TfidfVectorizer
import numpy as np

vectorizer = TfidfVectorizer()

def get_similarity(query1, query2):
    vectors = vectorizer.fit_transform([query1, query2])
    return np.dot(vectors[0], vectors[1].T)[0][0]

# Example: Check similarity between queries
similarity = get_similarity("What is the weather?", "How's the weather?")
print(f"Similarity: {similarity}")

Integrating Caching with Agentic Frameworks

Integrating caching with agentic frameworks like Langchain or OpenAI's API requires careful consideration of the framework's architecture. You need to intercept tool calls and reasoning steps to apply caching without disrupting the workflow. This ensures that the agent can leverage cached results seamlessly.

For Langchain, you can create custom tools that check the cache before making API calls. For OpenAI's API, you can implement caching at the application level, storing results and retrieving them when needed. This approach allows you to customize caching to fit your specific needs.

Caching in Langchain

In Langchain, create custom tools that check the cache before executing. This allows you to intercept tool calls and return cached results when possible. You can also cache reasoning steps by storing the output of each chain and retrieving it when needed.

Caching with OpenAI API

With the OpenAI API, implement caching at the application level. Store the results of each API call and retrieve them when the same query is made. This approach gives you full control over caching logic and allows you to optimize for your specific use case.

  • Create custom tools for Langchain caching.
  • Implement application-level caching for OpenAI.
  • Intercept tool calls to check cache.
  • Store and retrieve reasoning steps.
from langchain.tools import tool

@tool
def cached_tool(query: str) -> str:
    key = get_cache_key(query)
    result = cache.get(key)
    if result:
        return result
    # Call API and cache result
    result = api_call(query)
    cache.put(key, result)
    return result
Clock with gear mechanism for cache invalidation
Clock representing time-based cache invalidation.
Try the free API

Test the free endpoint now to see how tokens are counted before you commit to a paid plan.

Read also