跳到主要内容

ResponseCache

ResponseCache 是一种输入 Processor,在 Agent 循环内的请求/响应边界缓存 LLM 响应。它接入 processLLMRequest 以查找缓存,并在命中时短路返回。它使用 processLLMResponse 写入完整响应。

缓存键派生自 Mastra 即将发送给模型的已解析 LanguageModelV2Prompt(即在内存加载完毕且更早的输入 Processor 已转换提示词_之后_),因此拥有不同内存上下文的两个用户会生成不同的缓存键。Agent Tool 循环中的每个步骤都会独立缓存。

响应缓存没有 Agent 级选项。请在 inputProcessors 上显式注册 ResponseCache。每次调用的覆盖项通过 ResponseCache.context()ResponseCache.applyContext(),经由 RequestContext 传递。

用法示例
用法示例的直接链接

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 }),
})

有关概念概述、作用域规则和推荐的部署模式,请参阅响应缓存

构造函数参数
构造函数参数的直接链接

cache:

MastraServerCache
缓存后端。必填。可传入任意 MastraServerCache 实现——本地开发使用 InMemoryServerCache,生产环境使用 @mastra/redis 中的 RedisCache,也可以为自定义后端传入自己的子类。

ttl?:

number
= 300
此 Processor 所写条目的存活时间(秒)。默认为 300 秒(5 分钟),与 OpenRouter 的参考实现一致。

scope?:

string | null
追加到缓存键的租户作用域。null 表示不使用作用域。省略时,Processor 会回退到从请求上下文(MASTRA_RESOURCE_ID_KEY)解析出的 resource id,以自动实现按用户隔离。

key?:

string | (inputs: ResponseCacheKeyInputs) => string | Promise<string>
覆盖自动派生的缓存键。传入字符串可固定缓存键,或传入接收 { agentId, scope, model, prompt, stepNumber } 并返回缓存键的函数。如果函数抛出错误,Processor 会回退到确定性哈希,使调用仍可使用缓存。

bust?:

boolean
= false
强制每次调用缓存未命中:跳过读取,但仍在完成时写入。适用于显式刷新路径。

agentId?:

string
= 'mastra-response-cache'
缓存键命名空间中使用的逻辑 id。默认为 'mastra-response-cache'。如果希望缓存条目按 Agent 划分作用域,请将其设置为所属 Agent 的 id。

静态辅助函数
静态辅助函数的直接链接

ResponseCache 提供两个静态辅助函数,用于在 RequestContext 上设置每次调用的覆盖项。这些辅助函数会将底层上下文键保留为私有实现细节:应优先使用它们,而不是直接读写原始键。

ResponseCache.context(options)
responsecachecontextoptions的直接链接

构建一个预先加载了每次调用响应缓存覆盖项的新 RequestContext

await agent.stream('hello', {
requestContext: ResponseCache.context({ key: 'custom', bust: true }),
})

ResponseCache.applyContext(requestContext, options)
responsecacheapplycontextrequestcontext-options的直接链接

将每次调用的响应缓存覆盖项合并到现有 RequestContext 中。返回同一个上下文以便链式调用。

const ctx = new RequestContext()
ctx.set('caller-meta', { userId: 'u-123' })
ResponseCache.applyContext(ctx, { bust: true })
await agent.stream('hello', { requestContext: ctx })

ResponseCacheContextOptions
ResponseCacheContextOptions的直接链接

传递给 ResponseCache.context() / ResponseCache.applyContext() 的数据结构。

key?:

string | (inputs: ResponseCacheKeyInputs) => string | Promise<string>
仅为此请求覆盖自动派生的缓存键。

scope?:

string | null
仅为此请求覆盖租户作用域。null 表示不使用作用域。

bust?:

boolean
跳过缓存读取,但仍在完成时写入。

cachettlagentId 特意不允许按调用覆盖:它们属于实例级关注点,不应因请求而异。

ResponseCacheKeyInputs
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:默认 ttl300)。
  • RESPONSE_CACHE_CONTEXT_KEY:静态辅助函数写入的 RequestContext 键。为高级场景公开(例如在管道中途清除覆盖项)。请优先使用辅助函数。