|
| 1 | +--- |
| 2 | +title: "Response caching | Agents" |
| 3 | +description: "Cache identical agent calls to skip the LLM, return responses instantly, and avoid duplicate spend." |
| 4 | +packages: |
| 5 | + - "@mastra/core" |
| 6 | +--- |
| 7 | + |
| 8 | +# Response caching |
| 9 | + |
| 10 | +Response caching skips the LLM call and replays a previously cached response when an agent receives an identical request. Use it to drop latency to single-digit milliseconds and avoid paying for repeated calls. |
| 11 | + |
| 12 | +Caching is implemented as the [`ResponseCache`](/reference/processors/response-cache) input processor. There is no agent-level option — to enable caching, register the processor explicitly. This keeps the API surface small while we collect feedback; per-call overrides flow through `RequestContext`. |
| 13 | + |
| 14 | +## When to use response caching |
| 15 | + |
| 16 | +Reach for it when the same request shape repeats across users or sessions, for example prompt templates, suggested-prompt buttons, agentic search re-asks, or guardrail LLMs that classify the same input over and over. Skip it when calls trigger external side effects through tools, since cache hits replay tool calls without re-executing them. |
| 17 | + |
| 18 | +## Quickstart |
| 19 | + |
| 20 | +Add a `ResponseCache` to the agent's `inputProcessors` and pass any `MastraServerCache` as the backend. For development, `InMemoryServerCache` works out of the box: |
| 21 | + |
| 22 | +```typescript title="src/mastra/agents/search-agent.ts" |
| 23 | +import { Agent } from '@mastra/core/agent' |
| 24 | +import { InMemoryServerCache } from '@mastra/core/cache' |
| 25 | +import { ResponseCache } from '@mastra/core/processors' |
| 26 | + |
| 27 | +const cache = new InMemoryServerCache() |
| 28 | + |
| 29 | +export const searchAgent = new Agent({ |
| 30 | + name: 'Search Agent', |
| 31 | + instructions: 'You answer questions concisely.', |
| 32 | + model: 'openai/gpt-5', |
| 33 | + inputProcessors: [new ResponseCache({ cache, ttl: 600 })], // 10 minutes |
| 34 | +}) |
| 35 | +``` |
| 36 | + |
| 37 | +The first call runs the LLM normally and writes the response to the cache. Subsequent calls with an identical resolved prompt return the cached response without invoking the LLM. |
| 38 | + |
| 39 | +## Per-call overrides via RequestContext |
| 40 | + |
| 41 | +Per-call config flows through `RequestContext`. Use `ResponseCache.context()` to build a fresh context, or `ResponseCache.applyContext()` to merge into one you already have: |
| 42 | + |
| 43 | +```typescript title="src/example.ts" |
| 44 | +import { ResponseCache } from '@mastra/core/processors' |
| 45 | +import { RequestContext } from '@mastra/core/request-context' |
| 46 | + |
| 47 | +// Fresh context with the override |
| 48 | +await agent.stream('hello', { |
| 49 | + requestContext: ResponseCache.context({ key: 'custom-key', bust: true }), |
| 50 | +}) |
| 51 | + |
| 52 | +// Or merge into an existing context |
| 53 | +const ctx = new RequestContext() |
| 54 | +ctx.set('caller-meta', { userId: 'u-123' }) |
| 55 | +ResponseCache.applyContext(ctx, { bust: true }) |
| 56 | +await agent.stream('hello', { requestContext: ctx }) |
| 57 | +``` |
| 58 | + |
| 59 | +Three fields are overridable per call: |
| 60 | + |
| 61 | +- `key` — string or function. Overrides the auto-derived cache key for this request only. |
| 62 | +- `scope` — string or `null`. Overrides the tenant/user scope for this request only. `null` opts out of scoping. |
| 63 | +- `bust` — boolean. Skips the cache read but still writes on completion (useful for "force refresh" buttons). |
| 64 | + |
| 65 | +`cache`, `ttl`, and `agentId` stay on the constructor — they are instance-level concerns and not safe to vary per call. |
| 66 | + |
| 67 | +## Tenant scoping |
| 68 | + |
| 69 | +By default, `ResponseCache` looks up `MASTRA_RESOURCE_ID_KEY` on the request context and uses it as the cache scope. This means an agent that already populates the resource id (e.g. via memory) gets per-user isolation automatically — two users never see each other's cached responses. |
| 70 | + |
| 71 | +Override explicitly when you need a different scope: |
| 72 | + |
| 73 | +```typescript title="src/mastra/agents/scoped-agent.ts" |
| 74 | +new Agent({ |
| 75 | + // ... |
| 76 | + inputProcessors: [ |
| 77 | + new ResponseCache({ |
| 78 | + cache, |
| 79 | + scope: 'org-123', // explicit tenant scope |
| 80 | + }), |
| 81 | + ], |
| 82 | +}) |
| 83 | +``` |
| 84 | + |
| 85 | +Pass `scope: null` to deliberately share entries across all callers — only use this for known-public, non-personalized content. |
| 86 | + |
| 87 | +## Custom cache backend |
| 88 | + |
| 89 | +`ResponseCache` accepts any `MastraServerCache`. For production, use `RedisCache` from `@mastra/redis`: |
| 90 | + |
| 91 | +```typescript title="src/mastra/agents/cached-agent.ts" |
| 92 | +import { Agent } from '@mastra/core/agent' |
| 93 | +import { ResponseCache } from '@mastra/core/processors' |
| 94 | +import { RedisCache } from '@mastra/redis' |
| 95 | + |
| 96 | +const cache = new RedisCache({ url: process.env.REDIS_URL }) |
| 97 | + |
| 98 | +export const agent = new Agent({ |
| 99 | + name: 'Cached Agent', |
| 100 | + instructions: '...', |
| 101 | + model: 'openai/gpt-5', |
| 102 | + inputProcessors: [new ResponseCache({ cache })], |
| 103 | +}) |
| 104 | +``` |
| 105 | + |
| 106 | +For a custom backend, extend `MastraServerCache` and implement its abstract methods (the processor only calls `get` and `set`). |
| 107 | + |
| 108 | +## How caching is implemented |
| 109 | + |
| 110 | +`ResponseCache` hooks into `processLLMRequest` (cache lookup, short-circuits on hit) and `processLLMResponse` (cache write on completion). Both run inside the agentic loop _after_ memory has loaded and earlier input processors have transformed the prompt. |
| 111 | + |
| 112 | +This means the cache key is derived from the resolved `LanguageModelV2Prompt` Mastra is about to send to the model — i.e. _after_ memory has loaded and earlier input processors have run — and each step in an agentic tool loop is independently cached. |
| 113 | + |
| 114 | +## What's in the cache key |
| 115 | + |
| 116 | +When you don't supply `key`, the processor derives one deterministically from the inputs that change the LLM's response at this step: `agentId`, `stepNumber` (so each step in a tool loop has its own cache entry), `scope`, model identity (`provider`, `modelId`, spec version), and the resolved `prompt` (post-memory + post-processors). Any change to these inputs automatically invalidates the cache. |
| 117 | + |
| 118 | +### Customize the cache key |
| 119 | + |
| 120 | +Pass `key` as a function on the constructor or per-call to derive your own cache key from any subset of those inputs. The function receives the same inputs the deterministic hash would have consumed and returns a string (or a `Promise<string>`): |
| 121 | + |
| 122 | +```typescript title="src/example.ts" |
| 123 | +import { ResponseCache, buildResponseCacheKey } from '@mastra/core/processors' |
| 124 | + |
| 125 | +await agent.stream(input, { |
| 126 | + requestContext: ResponseCache.context({ |
| 127 | + // Cache only on the model id and the resolved prompt tail — ignore |
| 128 | + // step number, scope, etc. |
| 129 | + key: ({ model, prompt }) => `qa:${model.modelId}:${JSON.stringify(prompt).slice(-200)}`, |
| 130 | + }), |
| 131 | +}) |
| 132 | + |
| 133 | +// Or reuse the deterministic helper while overriding individual fields: |
| 134 | +await agent.stream(input, { |
| 135 | + requestContext: ResponseCache.context({ |
| 136 | + key: inputs => buildResponseCacheKey({ ...inputs, scope: 'global' }), |
| 137 | + }), |
| 138 | +}) |
| 139 | +``` |
| 140 | + |
| 141 | +If the function throws, the processor falls back to the default key derivation so the call still benefits from caching. |
| 142 | + |
| 143 | +## How cache hits work |
| 144 | + |
| 145 | +When the processor finds a cache hit, it short-circuits the LLM call by returning the cached chunks from `processLLMRequest`. The agentic loop synthesizes a stream from those chunks instead of calling the model. `agent.generate()` collects them into a `FullOutput`; `agent.stream()` returns a `MastraModelOutput` whose chunks come from the cached buffer, so consumers iterating `fullStream` or awaiting `text`, `usage`, and `finishReason` see the cached values. |
| 146 | + |
| 147 | +Cache writes happen after the response completes. Failed runs (errors, tripwire activations) are not cached, so the next call retries cleanly. |
| 148 | + |
| 149 | +## Related |
| 150 | + |
| 151 | +- [`ResponseCache` reference](/reference/processors/response-cache) |
| 152 | +- [Processors](/docs/agents/processors) |
| 153 | +- [Guardrails](/docs/agents/guardrails) |
| 154 | +- [Agent.stream()](/reference/streaming/agents/stream) |
| 155 | +- [Agent.generate()](/reference/agents/generate) |
0 commit comments