> Discover all available pages from the documentation index: https://mastra.zisheng.pro/llms.txt # ResponseCache `ResponseCache` 是一种输入 Processor,在 Agent 循环内的请求/响应边界缓存 LLM 响应。它接入 `processLLMRequest` 以查找缓存,并在命中时短路返回。它使用 `processLLMResponse` 写入完整响应。 缓存键派生自 Mastra 即将发送给模型的已解析 `LanguageModelV2Prompt`(即在内存加载完毕且更早的输入 Processor 已转换提示词\_之后\_),因此拥有不同内存上下文的两个用户会生成不同的缓存键。Agent Tool 循环中的每个步骤都会独立缓存。 响应缓存没有 Agent 级选项。请在 `inputProcessors` 上显式注册 `ResponseCache`。每次调用的覆盖项通过 [`ResponseCache.context()`](#static-helpers) 和 [`ResponseCache.applyContext()`](#static-helpers),经由 `RequestContext` 传递。 ## 用法示例 ```typescript import { Agent } from '@mastra/core/agent' import { InMemoryServerCache } from '@mastra/core/cache' import { ResponseCache } from '@mastra/core/processors' const cache = new InMemoryServerCache() const agent = new Agent({ id: 'search-agent', name: 'Search Agent', instructions: 'You answer questions concisely.', model: 'openai/gpt-5', inputProcessors: [new ResponseCache({ cache, ttl: 600 })], }) // First call hits the LLM and writes to the cache. await agent.generate('What is the capital of France?') // Second identical call replays the cached response. await agent.generate('What is the capital of France?') // Force a fresh call but still update the cache. await agent.generate('What is the capital of France?', { requestContext: ResponseCache.context({ bust: true }), }) ``` 有关概念概述、作用域规则和推荐的部署模式,请参阅[响应缓存](https://mastra.zisheng.pro/docs/agents/processors)。 ## 构造函数参数 **cache** (`MastraServerCache`): 缓存后端。必填。可传入任意 MastraServerCache 实现——本地开发使用 InMemoryServerCache,生产环境使用 @mastra/redis 中的 RedisCache,也可以为自定义后端传入自己的子类。 **ttl** (`number`): 此 Processor 所写条目的存活时间(秒)。默认为 300 秒(5 分钟),与 OpenRouter 的参考实现一致。 (Default: `300`) **scope** (`string | null`): 追加到缓存键的租户作用域。null 表示不使用作用域。省略时,Processor 会回退到从请求上下文(MASTRA\_RESOURCE\_ID\_KEY)解析出的 resource id,以自动实现按用户隔离。 **key** (`string | (inputs: ResponseCacheKeyInputs) => string | Promise`): 覆盖自动派生的缓存键。传入字符串可固定缓存键,或传入接收 { agentId, scope, model, prompt, stepNumber } 并返回缓存键的函数。如果函数抛出错误,Processor 会回退到确定性哈希,使调用仍可使用缓存。 **bust** (`boolean`): 强制每次调用缓存未命中:跳过读取,但仍在完成时写入。适用于显式刷新路径。 (Default: `false`) **agentId** (`string`): 缓存键命名空间中使用的逻辑 id。默认为 'mastra-response-cache'。如果希望缓存条目按 Agent 划分作用域,请将其设置为所属 Agent 的 id。 (Default: `'mastra-response-cache'`) ## 静态辅助函数 `ResponseCache` 提供两个静态辅助函数,用于在 `RequestContext` 上设置每次调用的覆盖项。这些辅助函数会将底层上下文键保留为私有实现细节:应优先使用它们,而不是直接读写原始键。 ### `ResponseCache.context(options)` 构建一个预先加载了每次调用响应缓存覆盖项的新 `RequestContext`。 ```typescript await agent.stream('hello', { requestContext: ResponseCache.context({ key: 'custom', bust: true }), }) ``` ### `ResponseCache.applyContext(requestContext, options)` 将每次调用的响应缓存覆盖项合并到现有 `RequestContext` 中。返回同一个上下文以便链式调用。 ```typescript const ctx = new RequestContext() ctx.set('caller-meta', { userId: 'u-123' }) ResponseCache.applyContext(ctx, { bust: true }) await agent.stream('hello', { requestContext: ctx }) ``` ## ResponseCacheContextOptions 传递给 `ResponseCache.context()` / `ResponseCache.applyContext()` 的数据结构。 **key** (`string | (inputs: ResponseCacheKeyInputs) => string | Promise`): 仅为此请求覆盖自动派生的缓存键。 **scope** (`string | null`): 仅为此请求覆盖租户作用域。null 表示不使用作用域。 **bust** (`boolean`): 跳过缓存读取,但仍在完成时写入。 `cache`、`ttl` 和 `agentId` 特意不允许按调用覆盖:它们属于实例级关注点,不应因请求而异。 ## ResponseCacheKeyInputs 传递给 `key` 函数(构造函数或每次调用)的参数。默认情况下,所有字段都会参与确定性哈希的计算。 **agentId** (`string`): 用于为缓存键划分命名空间的逻辑 Processor id。 **scope** (`string | null | undefined`): 为此请求解析出的作用域;禁用作用域时为 null。 **model** (`{ provider?: string; modelId?: string; specVersion?: string }`): Provider/模型标识。不同模型会生成不同响应。 **prompt** (`LanguageModelV2Prompt`): Provider 将收到的确切提示词,即内存加载以及所有会修改提示词的输入 Processor 处理之后的结果。 **stepNumber** (`number`): Agent 循环中从 0 开始的步骤编号。Tool 步骤的编号大于零。 ## 辅助导出 - `buildResponseCacheKey(inputs)`:默认使用的确定性哈希。可重新导出它以覆盖个别字段,同时保留标准缓存键结构的其余部分。 - `DEFAULT_RESPONSE_CACHE_TTL_SECONDS`:默认 `ttl`(`300`)。 - `RESPONSE_CACHE_CONTEXT_KEY`:静态辅助函数写入的 `RequestContext` 键。为高级场景公开(例如在管道中途清除覆盖项)。请优先使用辅助函数。 ## 相关内容 - [响应缓存](https://mastra.zisheng.pro/docs/agents/processors) - [Processors](https://mastra.zisheng.pro/docs/agents/processors) - [Processor 接口](https://mastra.zisheng.pro/reference/processors/processor-interface)