
AI API 額度、限流與錯誤處理
解析 OpenRouter 平台的額度控制、預算限制與請求限流機制,涵蓋 402、403、429 錯誤的成因、識別方式與應對策略,協助開發者穩定呼叫 API 並合理規劃資源消耗。
- 呼叫前主動查詢密钥狀態,避免因額度或預算耗尽導致請求失敗。
- 根據 error.metadata 中的 limit_source 欄位精準判斷錯誤來源,而非依赖提示文字。
- 在途支出預算僅影響余額較低或新帳戶,大額預存帳戶通常不受此限制。
- 預算重置時間基於 UTC,需提前規劃任務執行窗口,避免跨窗口失敗。
- 流式介面錯誤處理需兼容 HTTP 狀態碼與 SSE 事件两種形態。
AI API 額度、限流與錯誤處理
- 1total spending capacity of an account is shaped by three distinct credit controls. The first is the account balance, which represents the aggregate of all prepaid credits available across the platform. If this balance falls below zero, even requests to free models will be rejected with a 402 status. The second control is the per-key credit limit, an optional cap that can be applied to an individual API key. This limit is defined by three fields in the key metadata: `limit` sets the total cap, `limit_reset` indicates when the cap will refresh, and `limit_remaining` shows how much of the cap is still available. The third control is the in-flight spending budget, a mechanism designed to prevent concurrent requests from collectively exceeding the account's balance before any of them have finished processing.
- 2請求限流的規則與響應頭
- 3402 錯誤的诊斷與緩解手段
- 4403 錯誤的來源與預算耗尽處理
- 5429 錯誤的重試機制與流式中斷應對
- 6AI API 額度、限流與錯誤處理的落地取舍
total spending capacity of an account is shaped by three distinct credit controls. The first is the account balance, which represents the aggregate of all prepaid credits available across the platform. If this balance falls below zero, even requests to free models will be rejected with a 402 status. The second control is the per-key credit limit, an optional cap that can be applied to an individual API key. This limit is defined by three fields in the key metadata: `limit` sets the total cap, `limit_reset` indicates when the cap will refresh, and `limit_remaining` shows how much of the cap is still available. The third control is the in-flight spending budget, a mechanism designed to prevent concurrent requests from collectively exceeding the account's balance before any of them have finished processing.
The in-flight spending budget operates by estimating the token cost of a request before it is sent to a provider. This estimate is calculated using the input tokens plus the completion tokens allowed by the `max_tokens` parameter, up to a fixed per-request ceiling if `max_tokens` is not specified. Only token prices are factored into this calculation; per-request fees, plugin charges, and image pricing are excluded. If a request has no token component, no hold is placed on the budget. The estimated cost is held against the account while the request is active. Once the request completes or fails, the hold is replaced by the actual cost for a brief settlement period before being released. The total amount that can be held at once is determined by a fraction of the current credit balance, capped at a fixed maximum. If a new request's estimated cost cannot fit within this budget alongside existing active and recently completed requests, it is rejected with a 402 error before reaching a provider. The error metadata will specify whether the budget is exhausted due to existing requests (`in_flight_budget_exhausted`) or because the single request is too expensive (`weight_exceeds_budget`). In the former case, a `Retry-After` header is provided, as the condition is transient. In the latter, reducing the prompt size or `max_tokens` is the only viable solution without adding credits. This budget only applies to prepaid accounts with balances below a certain threshold or newer accounts without a established spending history. Accounts with balances above the threshold, as well as enterprise or invoice-billed accounts, are exempt.
Budget controls are organized into a hierarchy of spending caps, checked in a specific sequence on every paid request. The first layer consists of guardrail budgets, which are defined by a `limit_usd` and a `reset_interval`. These are applied at the workspace default level, the member level, and the individual API key level. The spend is tracked against the combined total of the member and then against the key's own spend. The second layer is workspace budgets, which cap the total spend of an entire workspace per interval. The third layer is the key's own limit, which is the `limit` field mentioned earlier, enforced once its specific time window is exhausted. All time intervals are based on UTC. A daily budget resets at 00:00 UTC, a weekly budget on Monday at 00:00 UTC, and a monthly budget on the first day of the month at 00:00 UTC. A lifetime workspace budget does not reset.
To inspect these budgets, the `GET /api/v1/key` endpoint provides a `budgets` array. This array lists every applicable budget, showing the enforcement count, the remaining amount in USD, and the reset time. The `effective_budget` field identifies which budget will block a request first. If a budget is already spent, it is the one that triggers the rejection. If no budget is fully spent, the entry with the least `remaining_usd` is considered the effective budget. When a request is blocked by a budget, it fails with a 403 status before reaching a provider. The error message names the budget and includes the relevant figures. The `error.metadata` object provides structured details: `limit_source` identifies the type of budget (guardrail, workspace, or key limit), `scope` matches the scope value from the `budgets` array, and `resets_at` gives the ISO 8601 UTC timestamp for the window rollover, or `null` for a lifetime budget. Since the wait time is typically hours or days, no `Retry-After` header is sent. Proactive monitoring of `effective_budget.remaining_usd` via the key endpoint is recommended to avoid mid-task failures.
請求限流的規則與響應頭
OpenRouter 的請求限流主要針對两類場景:免費模型的使用額度和 DDoS 防護。免費模型變體(ID 以 `:free` 結尾)受两個維度限制:每分鐘請求數和每日請求數。具體阈值取決於帳戶累計購買的代币數量。若累計購買少於 10 個代币,每分鐘最多 20 次請求,每日最多 50 次;若累計購買達到或超過 10 個代币,每日上限提升至 1000 次,每分鐘限制仍為 20 次。值得注意的是,系統在實際執行時會略有寬容:當帳戶累計購買達到 9 個代币時,即按高額度策略處理,但介面回傳的 `is_free_tier` 欄位可能仍顯示為 `false`,同時回傳較高的每日限額值。
這些限制通過 HTTP 響應頭中的 `X-RateLimit-*` 系列欄位暴露給呼叫方。當請求触發限流時,伺服器回傳 HTTP 429 狀態碼,並在響應頭中附帶目前限額、剩余配額、重置時間等資訊。呼叫方應優先讀取 `Retry-After` 頭部,該欄位明確指示了需要等待的秒數。對於免費模型,每分鐘的限流值不會在 `GET /api/v1/key` 介面的響應中直接體現,僅能通過實際請求被拒後的響應頭獲取。
DDoS 防護由 Cloudflare 層面執行,當請求頻率或模式被判定為異常時,會直接拦截並回傳 429。這類拦截通常沒有明確的配額說明,響應頭中可能不包含標準的限流元資料。此時應降低請求頻率,避免短時間內集中發送大量請求。
當限流發生時,錯誤響應體遵循標準錯誤格式。若限流來自 OpenRouter 平台自身,`error.metadata` 中會包含具體原因;若來自上游服務商,则 `error.metadata.provider_code` 會携帶服務商回傳的原始錯誤碼。對於服務商侧的限流,系統會自動嘗試 fallback 路由,將請求切換至其他可用服務商,只有當所有候選服務商均不可用時,才會將 429 回傳給呼叫方。
在流式響應場景下,若限流發生在資料传輸過程中,錯誤不會以 HTTP 429 形式回傳,而是通過 SSE 事件流中的 `finish_reason: "error"` 传递。這是因為伺服器已發送 HTTP 200 狀態碼,無法再更改響應狀態。呼叫方需在流式處理逻辑中監聽該欄位,及時終止連接並触發重試機制。
402 錯誤的诊斷與緩解手段
402 錯誤表示請求因額度或預算問題被拒绝,通常在請求到達上游服務商之前就被 OpenRouter 拦截。诊斷時應首先檢查響應體中的 `error.metadata` 欄位,其中 `limit_source` 欄位是關鍵線索。若其值為 `openrouter_in_flight_budget`,說明目前執行中及 recently completed 的請求已耗尽 in-flight spending budget。這是一種瞬時狀態,即使目前沒有活躍請求也可能發生,因為系統正在處理近期請求的結算。此時響應頭中會包含 `Retry-After`,建議等待指定時間後重試。
若 `limit_source` 為 `openrouter_credits`,则表示帳戶余額不足以覆蓋目前請求的預估費用,或單個請求的預估成本超出了 in-flight budget 的總額。前者需要充值以提升余額,後者则需降低請求規模,例如减少輸入 token 數或調低 `max_tokens` 參數。若 `limit_source` 為 `openrouter_key_limit`,则說明該 API key 的獨立額度已用尽,應檢查 `GET /api/v1/key` 回傳中的 `limit_remaining` 欄位,並根據 `limit_reset` 時間等待額度重置,或提升該 key 的額度上限。
in-flight spending budget 的計算機制是:系統在請求開始時,根據輸入 token 數和 `max_tokens`(若未設定则使用預設上限)預估總 token 成本,並按目前定價計算費用。該預估金額會被暂時锁定,作為“占用額度”,直到請求完成或失敗後,系統在短暂的結算窗口內將占用額度替換為實際費用,隨後釋放。總占用額度受帳戶余額的一定比例限制,且有固定上限。余額低於特定阈值的帳戶,或新註冊且無歷史消費紀錄的帳戶,才會啟用該機制;余額充足或有穩定消費歷史的帳戶不受此限。免費模型請求、完全使用自有 provider key 且未啟用付費外掛程式的請求,以及企業帳戶、付費訂閱帳戶、發票結算帳戶,均不触發 in-flight budget 檢查。
緩解 402 錯誤的手段包含:主動呼叫 `GET /api/v1/key` 介面,持續監控 `limit_remaining` 和 `effective_budget.remaining_usd`,在請求量較大前預判額度狀態;合理規劃請求並發量,避免短時間內發起大量高成本請求;對於頻繁触發 in-flight budget 的場景,可考虑分批處理任務,或在任務間隙插入延遲;若問題持續存在,應優先充值以提升余額,從而提高 in-flight budget 的上限。對於單個請求成本過高的情況,應最佳化 prompt 設計,减少冗余上下文,或調整 `max_tokens` 參數,使預估費用控制在預算範圍內。

403 錯誤的來源與預算耗尽處理
403 錯誤在 OpenRouter 的體系中屬於預算管控類問題,它與額度限制(402)不同,不直接由帳戶余額或單次請求的預估成本触發,而是由組織或工作區管理員預先設定的支出上限所導致。當一笔付費請求在到達上游模型服務商之前,被系統檢測到其累計支出已触及某一層級的預算红線,就會立即回傳 403,不會產生任何實際的模型呼叫開销。這種機制的目的是防止團隊或專案的支出失控,屬於一種事前拦截而非事後結算。
預算的檢查順序是固定的,系統會逐層比對,最先被耗尽的那一層即為拦截源。第一層是防護預算(Guardrail Budgets),它可能绑定在工作區預設設定、成員帳戶或具體的 API 密钥上,統計口径可以是該成員的總支出,也可以是該密钥自身的支出。第二層是工作區預算(Workspace Budgets),它針對整個工作區在某一周期內的總支出設限。第三層是密钥自身的額度限制(Key Limit),即為該密钥單獨設定的周期性消費上限。每一層預算都有一個重置周期,採用 UTC 時間:每日預算在 00:00 UTC 重置,每週一在 00:00 UTC 重置,每月在第一天 00:00 UTC 重置,而終身預算则從不重置。
當請求被 403 拦截時,響應體中的 `error.metadata` 欄位會明確指出拦截來源。`limit_source` 的取值可以是 `openrouter_guardrail_budget`(表示防護預算拦截)、`openrouter_workspace_budget`(工作區預算拦截)或 `openrouter_key_limit`(密钥自身額度拦截)。同時,`scope` 欄位會對應 `GET /api/v1/key` 介面回傳的 `budgets` 數組中的某一項,協助開發者精確定位是哪一個具體預算條目触發了拦截。`resets_at` 欄位则提供該預算窗口的下一次重置時間,格式為 ISO 8601 UTC 時間戳;對於終身預算,該欄位為 `null`。需要注意的是,403 響應中通常不包含 `Retry-After` 頭部,因為距离預算重置往往還有數小時甚至數天,簡單地等待几秒後重試毫無意義。
要有效處理 403 錯誤,關鍵在於預防而非補救。在執行任何長時間執行的任務之前,應當先呼叫 `GET /api/v1/key` 介面,檢查回傳體中的 `effective_budget.remaining_usd` 欄位。這個欄位反映了目前最紧迫的預算限制及其剩余金額,是判斷是否會中途触發 403 的最直接依據。如果發現剩余金額不足以支撑整個任務的預估開销,就應當提前調整任務粒度、申請更高的預算額度,或將任務拆分為多個在不同預算周期內執行的子任務。一旦在任務執行過程中遭遇 403,根據 `limit_source` 確定具體的預算類型後,唯一的解決途径就是等待該預算窗口重置,或由組織管理員临時提升該預算的上限。在預算重置之前,任何重試請求都會繼續回傳 403,因此盲目重試只會浪費用戶端的請求配額。
429 錯誤的重試機制與流式中斷應對
429 錯誤表示請求頻率超出了系統允許的阈值,其來源分為两類:一類是 OpenRouter 平台自身的限制,另一類是上游模型服務商施加的限制。平台侧的限制主要針對免費模型變體(模型 ID 以 `:free` 結尾),根據帳戶累計購買的信用點數劃分不同的請求頻次上限。購買信用點數少於 10 的帳戶,每分鐘最多 20 次請求,每天最多 50 次;購買信用點數達到或超過 10 的帳戶,每分鐘仍為 20 次,但每天的上限提升至 1000 次。此外,Cloudflare 的 DDoS 防護機制也會對異常高頻的請求模式進行拦截,這種拦截通常沒有固定的配額,而是基於行為模式的異常檢測。當請求被上游服務商限流時,`error.metadata` 中會包含 `provider_code` 欄位,紀錄服務商回傳的原始錯誤碼,此時 OpenRouter 的回退路由機制會自動嘗試呼叫其他可用的提供商來服務同一模型,只有在所有候選提供商均不可用時,才會將 429 錯誤回傳給用戶端。
針對 429 錯誤的處理,核心策略是引入指數退避的重試機制。由於限流狀態是暂時的,立即重試只會加剧擁堵並可能触發更严格的拦截。用戶端應當在捕獲 429 響應後,解析響應頭中的 `Retry-After` 欄位(如果存在),獲取系統建議的等待時長;若該欄位不存在,则採用預設的退避算法,例如首次等待 1 秒,隨後依次翻倍為 2 秒、4 秒、8 秒,同時結合隨機抖動以避免多個用戶端在同一時刻同時重試。對於使用免費模型變體的場景,若頻繁触發 429,根本解決辦法是購買至少 10 個信用點以提升每日請求上限,或切換至該模型的付費變體,後者不受平台級請求配額的限制。若 429 來自上游服務商,则可以通過設定模型回退清單(Fallback Models),在首選模型的所有提供商均回傳 429 時,自動嘗試其他兼容的模型,或放寬提供商路由偏好,增加可選服務商的範圍以提高請求成功的概率。
流式传輸過程中的限流處理與普通請求不同。當請求已成功建立連接並開始回傳 SSE(伺服器發送事件)流後,HTTP 狀態碼已經發送為 200,此時若触發限流,系統無法再回傳 429 狀態碼,而是會在 SSE 事件流中插入一個特殊的錯誤事件。該事件的 `finish_reason` 欄位會被設定為 `"error"`,並在事件负載中包含具體的錯誤資訊和元資料。用戶端需要具備解析 SSE 流的能力,在接收到 `finish_reason: "error"` 的事件時,立即終止目前流的處理,並根據錯誤類型決定是否重試。由於流式中斷發生在資料传輸中途,重試時應當從斷點處重新發起請求,而不是從頭開始,以避免重複传輸已接收的資料。對於關鍵業務場景,建議在用戶端實現流狀態的持久化和斷點續传機制,確保在遭遇流式中斷後能夠無缝恢複資料传輸,而不丢失已积累的上下文。
AI API 額度、限流與錯誤處理的落地取舍
在實際串接 AI API 時,額度、限流與錯誤處理不是三個獨立模塊,而是同一套資源約束在不同維度的體現。落地取舍的核心在於:你愿意用多少成本換取多少穩定性,以及你能否承受請求失敗時的延遲與資料不一致。
額度限制的本質是“你能花多少钱”,但它並不只看帳戶余額。平台通常會預估每個請求的 token 成本,並在請求真正完成前就占用一部分額度,這就是所谓的“在途預算”。如果你的帳戶余額偏低,或屬於新帳戶、缺乏歷史消費紀錄,平台會啟用更严格的在途預算控制。這意味着即使帳戶裡還有余額,也可能因為多個請求同時執行、累計預估成本超過阈值而被提前拒绝。這種機制防止了“並發請求把帳戶刷爆”的風險,但也要求開發者必須理解:余額為正不等於請求一定能通過。應對方式是降低單次請求的 token 預估,比如减少輸入長度或限制最大輸出 token 數,或主動轮詢帳戶狀態,在請求發起前確認額度充足。
限流则關注“你能在單位時間內發多少請求”。免費模型通常有严格的每分鐘和每日請求上限,且這些上限與帳戶累計充值金額挂钩。例如,累計充值不足 10 個信用點的帳戶,每日免費請求上限為 50 次;達到 10 個信用點以上,上限提升至 1000 次。這種設計是為了防止濫用,但也意味着如果你的業務依赖高頻呼叫免費模型,必須提前規劃充值節奏,或直接切換到付費模型以繞過平台級限流。此外,DDoS 防護機制會拦截異常高頻的請求,這通常不是業務逻辑問題,而是流量模式被判定為攻击,需要調整請求間隔或串接更進階別的防護策略。
錯誤處理的關鍵在於區分錯誤來源。402 錯誤通常與額度或在途預算有關,403 錯誤與組織或密钥級別的預算上限有關,429 錯誤则可能來自平台限流或上游服務商的临時過載。每種錯誤的響應體中都會携帶元資料,比如 `limit_source` 欄位,明確指出是哪個層級的限制触發了拒绝。開發者應根據這個欄位做分支處理,而不是依赖錯誤提示文字。例如,當 `limit_source` 為 `openrouter_in_flight_budget` 時,說明是並發請求占满了在途預算,此時應等待 `Retry-After` 頭指定的時間後重試;如果是 `openrouter_credits`,则說明單個請求的成本超過了帳戶余額或預算上限,需要調整請求參數或充值。
對於流式響應,限流問題可能以更隱蔽的方式出現。如果在資料传輸過程中触發限流,平台不會回傳 HTTP 429,而是通過 SSE 事件發送 `finish_reason: "error"`,因為 HTTP 狀態碼已經在響應開始時設定為 200。這種情況下,用戶端需要監聽流中的錯誤事件,並根據錯誤類型決定是否重試、是否切換模型或是否暂停發送新請求。處理流式中斷時,不能簡單地重連並從頭開始,因為這可能導致重複計費或資料重複;應紀錄已接收的片段,並在恢複時從斷點繼續,或在業務層做好幂等設計。
在落地取舍上,最現實的權衡是“主動監控 vs 被動重試”。主動呼叫 `GET /api/v1/key` 獲取額度、預算和限流狀態,虽然增加了請求開销,但能避免業務高峰時的批次失敗。被動重試则依赖錯誤響應中的 `Retry-After` 頭或指數退避策略,適合對延遲不敏感或流量波動大的場景。另一個取舍是“單一模型 vs 多模型回退”。當主模型因限流或配額耗尽不可用時,設定備用模型可以提高系統的可用性,但也會增加成本和複雜度。尤其要注意的是,備用模型的 token 價格可能高於主模型,如果回退逻辑不考虑成本,可能在“救火”的同時烧掉了更多預算。
最後,所有機制的有效性都依赖於對元資料的正確解析。平台提供的 `error.metadata` 欄位包含了錯誤原因、限制來源、重置時間等關鍵資訊,但這些欄位的結構和語義可能隨平台迭代而變化。開發者應定期審查介面文件,確保錯誤處理逻辑與平台最新行為一致,避免因欄位變更而導致的靜默失敗或误判。
參考來源
本文由 AI X Tool 基於公開資料研究後原創整理,發布日期與產品資訊可能變化,請以來源網站最新內容為準。