CostGuardProcessor
CostGuardProcessor 會在 Agent 迴圈中強制套用費用上限,並在超過可設定的費用門檻時封鎖或發出警告。
它會使用 processInputStep,在每次呼叫 LLM 前檢查費用上限。所有範圍的費用資料都會從可觀測性儲存 API(getMetricAggregate)查詢。對於 resource 與 thread 範圍,它會在可設定的時間範圍內,彙總多次執行的費用(預設為 7 天)。對於 run 範圍,它會查詢目前 Trace 的費用。
若要設定以 token 為基礎的上限,請改用 TokenLimiterProcessor。
支援三種範圍模式:
- 執行範圍:透過 Trace ID 追蹤單次 Agent 執行內的費用
- 資源範圍(預設):依
resourceId追蹤多次執行的累計費用 - 討論串範圍:依
threadId追蹤多次執行的累計費用
概略費用防護。 費用資料會透過可觀測性管線中的緩衝匯出器,以非同步方式保存。快速執行的 Agent 可能在指標可供查詢前,就已超過設定的上限。請將
maxCost視為概略門檻;快速執行的 Agent 可能會超過此門檻。
使用範例「使用範例」的直接連結
追蹤每個資源的累計費用(預設範圍):
import { CostGuardProcessor } from '@mastra/core/processors'
const costGuard = new CostGuardProcessor({
maxCost: 1.0,
})
以 24 小時的時間範圍追蹤每個討論串的累計費用:
import { CostGuardProcessor } from '@mastra/core/processors'
const costGuard = new CostGuardProcessor({
maxCost: 5.0,
scope: 'thread',
window: '24h',
})
附加至 Agent,並設定 onViolation 回呼函式:
import { Agent } from '@mastra/core/agent'
import { CostGuardProcessor } from '@mastra/core/processors'
const costGuard = new CostGuardProcessor({
maxCost: 5.0,
scope: 'resource',
window: '30d',
})
costGuard.onViolation = ({ detail }) => {
console.log(`Cost exceeded for ${detail.scopeKey}: $${detail.usage}/$${detail.limit}`)
}
const agent = new Agent({
id: 'my-agent',
name: 'my-agent',
model: 'openai/gpt-5-nano',
processors: {
input: [costGuard],
},
})
建構函式參數「建構函式參數」的直接連結
maxCost:
scope?:
window?:
strategy?:
message?:
執行個體屬性「執行個體屬性」的直接連結
id:
name:
onViolation?:
processInputStep:
錯誤行為「錯誤行為」的直接連結
啟用 block 策略(預設)時,若超過費用上限,CostGuardProcessor 會以 retry: false 呼叫 abort()。TripWire 中繼資料包含:
processorId:'cost-guard'usage:目前的累計用量(estimatedCost、costUnit)maxCost:設定的費用上限scope:目前使用的範圍('run'、'resource'或'thread')scopeKey:資源/討論串範圍的範圍識別碼(如適用)
範圍行為「範圍行為」的直接連結
| 範圍 | 跨執行追蹤 | 篩選條件 | 必要內容 |
|---|---|---|---|
run | 否 | 目前 span 的 traceId | 追蹤內容(自動) |
resource | 是 | resourceId + 時間範圍 | RequestContext 中的 resourceId |
thread | 是 | threadId + 時間範圍 | RequestContext 中的 threadId |
所有範圍都需要支援 getMetricAggregate 的可觀測性儲存空間。若 Mastra 執行個體未設定可觀測性儲存空間,系統會在註冊時擲回錯誤。
對於 run 範圍,處理器會從目前 span 的追蹤內容讀取 Trace ID。若沒有可用的追蹤內容,則會略過檢查(fail-open)。
對於 resource 與 thread 範圍,若執行階段缺少必要的內容 ID,則會略過檢查。可觀測性查詢失敗時會採取 fail-open 策略:若查詢失敗,費用會視為零。
關於指標保存延遲。 可觀測性管線使用緩衝匯出器,以非同步方式清空並匯出指標。LLM 呼叫完成後,需要一小段時間,才能查詢其費用指標。當 Agent 高頻率執行時,費用防護可能要等到實際費用超過門檻後的一或多個步驟,才會偵測到超出上限。