> Discover all available pages from the documentation index: https://mastra.zisheng.pro/zh-HK/llms.txt # CostGuardProcessor `CostGuardProcessor` 會在整個 Agent 循環中限制金錢成本,並在超出可設定的成本門檻時封鎖或發出警告。 它會使用 `processInputStep`,在每次呼叫 LLM 前檢查成本上限。所有範圍的成本資料均透過可觀測性儲存 API(`getMetricAggregate`)查詢。對於 `resource` 及 `thread` 範圍,它會在可設定的時間範圍內彙總多次執行的成本(預設為 7 日)。對於 `run` 範圍,它會查詢目前 Trace 的成本。 如要使用以 token 為基礎的限制,請改用 `TokenLimiterProcessor`。 支援三種範圍模式: - **執行範圍**:透過 Trace ID 追蹤單次 Agent 執行內的成本 - **資源範圍**(預設):按 `resourceId` 追蹤多次執行的累計成本 - **執行緒範圍**:按 `threadId` 追蹤多次執行的累計成本 > **近似成本防護。** 成本資料會透過可觀測性管道中的緩衝匯出器,以非同步方式保存。快速執行的 Agent 可能會在指標可供查詢前,已超出設定上限。請將 `maxCost` 視為快速執行的 Agent 可能會超出的近似門檻。 ## 使用範例 按資源追蹤累計成本(預設範圍): ```typescript import { CostGuardProcessor } from '@mastra/core/processors' const costGuard = new CostGuardProcessor({ maxCost: 1.0, }) ``` 在 24 小時時間範圍內,按執行緒追蹤累計成本: ```typescript import { CostGuardProcessor } from '@mastra/core/processors' const costGuard = new CostGuardProcessor({ maxCost: 5.0, scope: 'thread', window: '24h', }) ``` 連同 `onViolation` 回呼函式附加至 Agent: ```typescript 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** (`number`): 允許的估算成本上限(例如 0.50 代表 0.50 美元)。必須為正數。使用可觀測性指標中的成本資料。由於指標保存存在延誤,這是近似上限。 **scope** (`'run' | 'resource' | 'thread'`): 成本追蹤範圍。'run' 透過 Trace ID 追蹤目前 Agent 執行內的成本。'resource' 按 resourceId 追蹤多次執行的累計成本(預設)。'thread' 按 threadId 追蹤多次執行的累計成本。所有範圍均須使用支援 getMetricAggregate 的可觀測性儲存空間。 (Default: `'resource'`) **window** (`'1h' | '6h' | '24h' | '7d' | '30d' | '365d'`): 使用 'resource' 或 'thread' 範圍時,用於彙總成本的時間範圍。只適用於非執行範圍。 (Default: `'7d'`) **strategy** (`'block' | 'warn'`): 超出成本上限時採用的策略。'block' 會以 TripWire 錯誤中止;'warn' 會記錄警告,但允許繼續執行該步驟。 (Default: `'block'`) **message** (`string`): 中止原因的自訂訊息範本。支援 {usage} 及 {limit} 預留位置。 (Default: `'Cost guard: cost limit exceeded ({usage}/{limit})'`) ## 實例屬性 **id** (`'cost-guard'`): 處理器識別碼。 **name** (`'Cost Guard'`): 處理器顯示名稱。 **onViolation** (`(violation: ProcessorViolation) => void | Promise`): 偵測到成本違規時呼叫的回呼函式,不受策略影響。這是通用 Processor 介面的一部分。可用於發出警報、記錄至外部系統或向用戶傳送電郵等副作用。此回呼函式拋出的錯誤會被靜默攔截。 **processInputStep** (`(args: ProcessInputStepArgs) => Promise`): 在每次呼叫 LLM 前,將累計估算成本與 maxCost 比較。它會向可觀測性儲存空間查詢成本資料:執行範圍按 Trace ID 篩選,資源/執行緒範圍則配合時間範圍,按各自的 ID 篩選。超出上限時會呼叫 abort()(block 策略),或記錄警告(warn 策略)。由於指標保存存在延誤,成本檢查只屬近似值。 ## 錯誤行為 使用 `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 高頻執行期間,成本防護可能要到實際成本超出門檻後的一個或多個步驟,才偵測到超出上限。