CostGuardProcessor
CostGuardProcessor 在 agentic loop 中实施费用上限,并在超出可配置的费用阈值时阻止执行或发出警告。
它使用 processInputStep 在每次 LLM 调用前检查费用上限。对于所有作用域,费用数据都通过可观测性存储 API(getMetricAggregate)查询。对于 resource 和 thread 作用域,它会在可配置的时间窗口内汇总多次运行的费用(默认为 7 天)。对于 run 作用域,它会查询当前 trace 的费用。
如需基于 token 的限制,请改用 TokenLimiterProcessor。
支持三种作用域模式:
- 运行作用域:通过 trace ID 跟踪单次 Agent 运行中的费用
- 资源作用域(默认):按
resourceId跟踪多次运行的累计费用 - 线程作用域:按
threadId跟踪多次运行的累计费用
近似费用保护。 费用数据通过可观测性管道中的缓冲 exporter 异步持久化。在指标可供查询之前,快速运行的 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 会调用 abort() 并设置 retry: false。TripWire metadata 包括:
processorId:'cost-guard'usage:当前累计用量(estimatedCost、costUnit)maxCost:配置的费用上限scope:当前作用域('run'、'resource'或'thread')scopeKey:resource/thread 作用域的作用域标识符(如适用)
作用域行为作用域行为的直接链接
| 作用域 | 跨运行跟踪 | 筛选条件 | 所需上下文 |
|---|---|---|---|
run | 否 | 当前 span 中的 traceId | tracing context(自动) |
resource | 是 | resourceId + 时间窗口 | RequestContext 中的 resourceId |
thread | 是 | threadId + 时间窗口 | RequestContext 中的 threadId |
所有作用域都要求可观测性存储支持 getMetricAggregate。如果 Mastra 实例未配置可观测性存储,会在注册时抛出错误。
对于 run 作用域,Processor 会从当前 span 的 tracing context 中读取 trace ID。如果 tracing context 不可用,则跳过检查(fail-open)。
对于 resource 和 thread 作用域,如果运行时缺少所需的上下文 ID,则跳过检查。可观测性查询失败时采用 fail-open 策略:如果查询失败,费用会被视为零。
关于指标持久化延迟的说明。 可观测性管道使用缓冲 exporter 异步刷新指标。从一次 LLM 调用完成到其费用指标可供查询之间存在短暂延迟。在高频执行 Agent 时,费用保护可能要等到实际费用超出阈值一个或多个步骤后,才能检测到超限。