跳至主要內容

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
快取後端。此參數為必填。可傳入任何 MastraServerCache 實作:本機開發可使用 InMemoryServerCache,正式環境可使用 @mastra/redisRedisCache,也可以建立自己的子類別作為自訂後端。

ttl?:

number
= 300
此處理器所寫入項目的存留時間(秒)。預設為 300 秒(5 分鐘),與 OpenRouter 的參考實作相同。

scope?:

string | null
附加至快取鍵的租戶範圍。null 表示不使用範圍。省略時,處理器會改用從請求情境解析的資源 ID(MASTRA_RESOURCE_ID_KEY),自動依使用者隔離。

key?:

string | (inputs: ResponseCacheKeyInputs) => string | Promise<string>
覆寫自動衍生的快取鍵。傳入字串可固定快取鍵;也可傳入函式,函式會接收 { agentId, scope, model, prompt, stepNumber } 並回傳快取鍵。若函式擲回錯誤,處理器會改用確定性雜湊,讓該次呼叫仍可受益於快取。

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
用來區分快取鍵命名空間的邏輯處理器 ID。

scope?:

string | null | undefined
此請求解析後的範圍;停用範圍時為 null

model:

{ provider?: string; modelId?: string; specVersion?: string }
Provider/模型識別資訊。不同模型會產生不同回應。

prompt:

LanguageModelV2Prompt
Provider 實際會收到的提示詞,位於記憶體載入及所有會修改提示詞的輸入處理器執行之後。

stepNumber:

number
Agent 迴圈中從 0 開始的步驟編號。Tool 步驟會大於 0。

匯出的輔助項目
「匯出的輔助項目」的直接連結

  • buildResponseCacheKey(inputs):預設使用的確定性雜湊。可重新匯出它,覆寫個別欄位,同時保留其餘標準快取鍵結構。
  • DEFAULT_RESPONSE_CACHE_TTL_SECONDS:預設 ttl300)。
  • RESPONSE_CACHE_CONTEXT_KEY:靜態輔助函式寫入的 RequestContext 鍵。此項目是為進階情況公開(例如在管線中途清除覆寫值)。請優先使用輔助函式。