以编程方式使用文档

消费策略为特定范围(组织、工作区、API 密钥或用户)在时间窗口(每月、每周、每天或每小时)内定义成本上限。 LLM 网关 实时追踪费用并阻止任何会使支出超过上限的请求,返回 402 response:

API Error: 402 request blocked by gateway policies: R&D Spend Cap

被阻止的请求会被追踪到 LangSmith,策略违规记录为元数据,因此您可以准确了解被阻止的内容和原因。

策略维度

消费策略从最广泛到最具体进行评估。所有匹配的策略都会被检查,如果任何一个返回阻止,则请求被拒绝。您可以将策略设置为默认(对所有工作区、用户或 API 密钥应用统一的支出上限)或粒化策略(个人限制或一组实体的限制)。

范围限制内容示例
**组织**Total spend across all workspaces in the org"The entire org cannot spend more than $10,000/month on LLM calls"
**工作区**Total spend within a single workspace or group of workspaces"The workspaces related to R&D cannot spend more than $2,000/month"
**API 密钥**Spend by a single API key or group of API keys (maps to a service or agent)"The customer support agent keys cannot spend more than $500/month cumulatively"
**用户**Spend by a single user or group of users (resolved from the API key's identity)"No individual developer can spend more than $50/day"

冲突解决

By default, LLM Gateway assesses the broadest scope first. If a granular policy applies, the most restrictive policy wins. Narrower scopes can only tighten limits, never loosen them. If an org-level policy caps spend at \$10,000/month and a workspace-level policy caps at \$15,000/month, the $10,000 org cap still applies.

默认策略与粒化策略

消费策略有两个方面:

  1. **跨维度汇总:** the total cap for that scope. Example: "This workspace's total spend cannot exceed $5,000/month."
  2. **每个维度成员的默认设置:** a base limit that applies to every API key or user within a scope unless overridden. Example: "Each API key in this workspace gets a $200/month default cap." Individual API keys can receive additional policies that raise their specific limit, but no policy can loosen a cap set at a broader scope.

时间窗口

窗口重置时间使用场景
**每月**每月第一天预算对齐、整体成本控制
**每周**每周周一 UTC 零点每周预算
**每天**UTC 零点防止单日成本激增(例如,编码代理在夜间重试循环中)
**每小时**每小时整点快速捕获失控代理

You can apply multiple time windows to the same scope. For example, a workspace can have both a \$5,000/month cap and a \$500/day cap. Both are enforced independently.

创建消费策略

  1. Go to **设置 → 网关 → LLM 网关**.
  2. 点击 **创建策略**.
  3. 选择范围(组织、工作区、API 密钥或用户)。
  4. 设置时间窗口(每月、每周、每天或每小时)。
  5. 以美元设置支出上限。
  6. Save.

策略立即生效。网关在每个传入请求上评估这些策略,执行延迟低于一秒。

查看支出

支出可见性仪表板显示实时成本汇总,以便您了解 LLM 预算的去向,而不会达到限额。

从网关设置页面,您可以查看每个策略相对于其上限的支出情况。

与 LangSmith Engine 集成

当消费策略阻止某个请求时,违规行为会作为元数据记录在追踪中。这些违规会在 LangSmith Engine中显示为问题,你可以从问题点击进入追踪,了解代理在达到限制时正在做什么。

这对于诊断被阻止的请求是代表真正的成本问题(处于重试循环中的编码代理)还是需要调整的策略(超出其上限的合法工作负载)非常有用。

后续步骤