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 实现——本地开发使用 InMemoryServerCache,生产环境使用 @mastra/redis 中的 RedisCache,也可以为自定义后端传入自己的子类。ttl?:
scope?:
null 表示不使用作用域。省略时,Processor 会回退到从请求上下文(MASTRA_RESOURCE_ID_KEY)解析出的 resource id,以自动实现按用户隔离。key?:
{ agentId, scope, model, prompt, stepNumber } 并返回缓存键的函数。如果函数抛出错误,Processor 会回退到确定性哈希,使调用仍可使用缓存。bust?:
agentId?:
'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 })
ResponseCacheContextOptionsResponseCacheContextOptions的直接链接
传递给 ResponseCache.context() / ResponseCache.applyContext() 的数据结构。
key?:
scope?:
null 表示不使用作用域。bust?:
cache、ttl 和 agentId 特意不允许按调用覆盖:它们属于实例级关注点,不应因请求而异。
ResponseCacheKeyInputsResponseCacheKeyInputs的直接链接
传递给 key 函数(构造函数或每次调用)的参数。默认情况下,所有字段都会参与确定性哈希的计算。
agentId:
scope?:
null。model:
prompt:
stepNumber:
辅助导出辅助导出的直接链接
buildResponseCacheKey(inputs):默认使用的确定性哈希。可重新导出它以覆盖个别字段,同时保留标准缓存键结构的其余部分。DEFAULT_RESPONSE_CACHE_TTL_SECONDS:默认ttl(300)。RESPONSE_CACHE_CONTEXT_KEY:静态辅助函数写入的RequestContext键。为高级场景公开(例如在管道中途清除覆盖项)。请优先使用辅助函数。