Learn how to create a caching middleware for local development.
When developing AI applications, you'll often find yourself repeatedly making the same API calls during development. This can lead to increased costs and slower development cycles. A caching middleware allows you to store responses locally and reuse them when the same inputs are provided.
This approach is particularly useful in two scenarios:
Iterating on UI/UX - When you're focused on styling and user experience, you don't want to regenerate AI responses for every code change.
Working on evals - When developing evals, you need to repeatedly test the same prompts, but don't need new generations each time.
In this implementation, you create a JSON file to store responses. When a request is made, you first check if you have already seen this exact request. If you have, you return the cached response immediately (as a one-off generation or chunks of tokens). If not, you trigger the generation, save the response, and return it.
Make sure to add the path of your local cache to your .gitignore so you do
not commit it.
For regular generations, you store and retrieve complete responses. Instead, the streaming implementation captures each token as it arrives, stores the full sequence, and on cache hits uses the SDK's simulateReadableStream utility to recreate the token-by-token streaming experience at a controlled speed (defaults to 10ms between chunks).
This approach gives you the best of both worlds:
Instant responses for repeated queries
Preserved streaming behavior for UI development
The middleware handles all transformations needed to make cached responses indistinguishable from fresh ones, including normalizing tool calls and fixing timestamp formats.
When using this caching middleware, keep these points in mind:
Development Only - This approach is intended for local development, not production environments
Cache Invalidation - You'll need to clear the cache (delete the cache file) when you want fresh responses
Multi-Step Flows - When using stopWhen, be aware that caching occurs at the individual language model response level, not across the entire execution flow. This means that while the model's generation is cached, the tool call is not and will run on each generation.