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',
})
連同 onViolation 回呼函式附加至 Agent:
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 | Tracing context(自動) |
resource | 是 | resourceId + 時間範圍 | RequestContext 中的 resourceId |
thread | 是 | threadId + 時間範圍 | RequestContext 中的 threadId |
所有範圍均須使用支援 getMetricAggregate 的可觀測性儲存空間。如 Mastra 實例未設定可觀測性儲存空間,系統會在註冊時拋出錯誤。
對於 run 範圍,處理器會從目前 span 的 Tracing context 讀取 Trace ID。如沒有可用的 Tracing context,便會跳過檢查(fail-open)。
對於 resource 及 thread 範圍,如執行時缺少所需的 context ID,便會跳過檢查。可觀測性查詢失敗時會採用 fail-open 策略:如查詢失敗,成本會視為零。
關於指標保存延誤。 可觀測性管道使用緩衝匯出器,以非同步方式清空並匯出指標。LLM 呼叫完成後,其成本指標需要短暫時間才可供查詢。在 Agent 高頻執行期間,成本防護可能要到實際成本超出門檻後的一個或多個步驟,才偵測到超出上限。