You ask the model the same question twice. Your app makes two network calls and pays for two answers. Sometimes that is exactly what you want. Sometimes a cache is a better fit.

Microsoft.Extensions.AI lets you add distributed caching to an IChatClient pipeline.

Try It

This example uses Ollama and an in memory distributed cache. Add the packages:

Terminal window
dotnet add package Microsoft.Extensions.AI
dotnet add package Microsoft.Extensions.Caching.Memory
dotnet add package OllamaSharp

With Ollama running locally and the llama3.1 model available, try this in a .NET 10 console app:

using Microsoft.Extensions.AI;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Options;
using OllamaSharp;
var model = new OllamaApiClient(
new Uri("http://localhost:11434"),
"llama3.1");
IChatClient chatClient = new ChatClientBuilder(model)
.UseDistributedCache(new MemoryDistributedCache(
Options.Create(new MemoryDistributedCacheOptions())))
.Build();
string[] prompts =
[
"What is a .NET assembly?",
"What is a .NET assembly?"
];
foreach (var prompt in prompts)
{
var response = await chatClient.GetResponseAsync(prompt);
Console.WriteLine(response.Text);
}

The second identical prompt can be served from the cache instead of asking the model again.

The Big Gotcha

The cache only helps when the request matches what was cached. A slightly different prompt, model configuration, or relevant chat history can mean a different answer.

Be careful with personalized prompts and private data. Don’t let one user’s cached response become another user’s answer. For longer conversations, caching a prompt without its conversation context would be the wrong shortcut.

The sample uses memory, so entries disappear when the process stops and are not shared with other app instances. Use a real distributed cache when that is what your deployment needs.

When Not to Use It

Skip response caching when answers need to be fresh, the model uses randomness that matters to your experience, or user context makes safe cache keys difficult.

Key Takeaway

UseDistributedCache adds caching to an AI client pipeline. It can save repeated calls, but only when the request is genuinely reusable and the cache boundary respects user privacy.