ResponseCache
ResponseCache 是一種輸入處理器,會在 Agent 迴圈內的請求/回應邊界快取 LLM 回應。它會掛接 processLLMRequest 以查找快取,並在命中時直接回傳;接著使用 processLLMResponse 寫入已完成的回應。
快取鍵衍生自 Mastra 即將傳送給模型、已解析的 LanguageModelV2Prompt(也就是在記憶體載入完成,且先前的輸入處理器已轉換提示詞之後),因此記憶體情境不同的兩位使用者會產生不同的快取鍵。Agent Tool 迴圈中的每個步驟都會獨立快取。
目前沒有 Agent 層級的回應快取選項。請明確將 ResponseCache 註冊至 inputProcessors。每次呼叫的覆寫值會透過 RequestContext,經由 ResponseCache.context() 與 ResponseCache.applyContext() 傳遞。
使用範例「使用範例」的直接連結
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 表示不使用範圍。省略時,處理器會改用從請求情境解析的資源 ID(MASTRA_RESOURCE_ID_KEY),自動依使用者隔離。key?:
{ agentId, scope, model, prompt, stepNumber } 並回傳快取鍵。若函式擲回錯誤,處理器會改用確定性雜湊,讓該次呼叫仍可受益於快取。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 })
ResponseCacheContextOptions「ResponseCacheContextOptions」的直接連結
傳入 ResponseCache.context()/ResponseCache.applyContext() 的資料結構。
key?:
scope?:
null 表示不使用範圍。bust?:
cache、ttl 和 agentId 刻意不允許每次呼叫覆寫:它們是執行個體層級的考量,不應隨請求而變動。
ResponseCacheKeyInputs「ResponseCacheKeyInputs」的直接連結
傳入 key 函式(建構函式或每次呼叫)的引數。預設情況下,所有欄位都會納入確定性雜湊。
agentId:
scope?:
null。model:
prompt:
stepNumber:
匯出的輔助項目「匯出的輔助項目」的直接連結
buildResponseCacheKey(inputs):預設使用的確定性雜湊。可重新匯出它,覆寫個別欄位,同時保留其餘標準快取鍵結構。DEFAULT_RESPONSE_CACHE_TTL_SECONDS:預設ttl(300)。RESPONSE_CACHE_CONTEXT_KEY:靜態輔助函式寫入的RequestContext鍵。此項目是為進階情況公開(例如在管線中途清除覆寫值)。請優先使用輔助函式。