TokenLab

核心指南

代理可處理的錯誤

使用錯誤代碼、重試時間與模型建議,無需解析文字說明

本頁介紹供應用程式和編程 Agent 讀取的公開 API 錯誤,不授予工作區請求調查或客服權限。排查自己的請求,請從請求疑難排解開始。

與 OpenAI 相容的 TokenLab 錯誤可能包含供代理或應用程式使用的結構化提示。請在這些欄位存在時使用它們;請勿解析人類可讀的 message 來決定後續操作。

Anthropic Messages 和 Gemini API 保留其原生的錯誤格式,因此本頁面的擴充功能僅適用於與 OpenAI 相容的 Chat Completions 和 Responses 錯誤。

選用錯誤欄位

下方所有欄位皆出現在 error 物件中,且可能不存在。

欄位類型用途
did_you_meanstring最接近的可用模型 ID
suggestionsarray可能適合該請求的模型
hintstring簡短說明或建議操作
retryableboolean相同的請求稍後是否可能成功
retry_afternumber再次嘗試前需等待的秒數
balance_usdnumber目前餘額(美元)
estimated_cost_usdnumber被拒絕請求的預估成本(美元)

您的客戶端仍應根據 HTTP 狀態碼和 code 來處理每個錯誤。請將這些額外欄位視為有用的上下文,而非必要欄位。

未知模型

拼寫錯誤或不可用的模型會回傳 400 model_not_found。如果 did_you_mean 存在,請將其顯示給使用者,或僅在您的產品已獲准變更所選模型時才進行重試。

{
  "error": {
    "message": "Model not found: please check the model name",
    "type": "invalid_request_error",
    "param": "model",
    "code": "model_not_found",
    "did_you_mean": "gpt-5.6-terra",
    "suggestions": [
      {"id": "gpt-5.6-terra"},
      {"id": "gpt-5.6-luna"}
    ],
    "hint": "Did you mean 'gpt-5.6-terra'? Use GET https://api.tokenlab.sh/v1/models to list all available models."
  }
}

餘額不足

402 insufficient_balance 可能包含目前餘額與所需的預估金額。您的應用程式可以提供儲值連結、建議較便宜的模型,或發送較小的請求。

{
  "error": {
    "message": "Insufficient balance: need ~$0.3500 for claude-sonnet-4-6, but balance is $0.1200.",
    "type": "insufficient_balance",
    "code": "insufficient_balance",
    "balance_usd": 0.12,
    "estimated_cost_usd": 0.35,
    "suggestions": [
      {"id": "gpt-5.6-luna"},
      {"id": "deepseek-v3-2"}
    ],
    "hint": "Try a cheaper model, or top up at https://tokenlab.sh/dashboard/billing."
  }
}

模型無法使用

503 all_channels_failed 或 503 delivery_tier_unavailable 不一定是暫時性故障。如果所選 Delivery 層級沒有支援目前操作的供應,retryable 為 false,且不回傳 retry_after,請勿原樣重試。更換模型前,透過 GET /v1/models 檢查對應操作和 Delivery 的可用性。名稱相近不代表可用;未經驗證的替代模型不會列出。

{
  "error": {
    "message": "This model is unavailable for the requested operation and Delivery tier.",
    "type": "all_channels_failed",
    "code": "all_channels_failed",
    "retryable": false,
    "hint": "Check the model's operation and Delivery availability with GET /v1/models. Repeating the same request will not resolve this."
  }
}

速率限制

對於 429 rate_limit_exceeded,請等待 retry_after 秒數,或使用標準的 Retry-After 回應標頭。

{
  "error": {
    "message": "Rate limit: 1000 rpm exceeded",
    "type": "rate_limit_exceeded",
    "code": "rate_limit_exceeded",
    "retryable": true,
    "retry_after": 8,
    "hint": "Retry after 8s."
  }
}

上下文過長

400 context_length_exceeded 無法透過再次發送相同請求來解決。請縮短輸入內容,或讓使用者選擇具有更大上下文視窗的模型。

{
  "error": {
    "message": "This model's maximum context length is 128000 tokens...",
    "type": "invalid_request_error",
    "code": "context_length_exceeded",
    "retryable": false,
    "suggestions": [
      {"id": "gemini-2.5-pro"},
      {"id": "claude-sonnet-5"}
    ],
    "hint": "Reduce your input or switch to a model with a larger context window."
  }
}

尋找正確的 API 格式

在使用特定模型 API 之前,請先從 GET /v1/models/{model} 讀取 tokenlab.accepted_request_formats。

值端點
openai_chat_completions/v1/chat/completions
openai_responses/v1/responses
anthropic_messages/v1/messages
gemini_generate_content/v1beta/models/{model}:generateContent

接受的格式確認了端點。個別工具和欄位仍可能因模型而異;在依賴它們之前,請先查看模型頁面。

依任務尋找模型

Models API 可以回傳非聊天任務的當前精選清單:

curl "https://api.tokenlab.sh/v1/models?recommended_for=image"

有效的 recommended_for 值包括 image、video、music、3d、tts、stt、embedding、rerank 和 translation。請在建立請求時明確發送所選的模型 ID。TokenLab 不會自動將其替換為其他模型。

機器可讀概覽

代理可以在以下位置讀取精簡的 API 概覽:

GET https://api.tokenlab.sh/llms.txt

其中包含首次請求、常用端點、模型篩選器以及錯誤處理指南。

讀取錯誤,不自動重送請求

此範例只傳送一次請求,保留選定模型並回報結構化錯誤資訊。SDK 自動重試已關閉,由應用程式判斷是否可安全重試。模型建議須由使用者明確選擇;已受理或逾時的生成請求不可自動重送。

import os
from openai import OpenAI, APIStatusError

with OpenAI(
    api_key=os.environ["TOKENLAB_API_KEY"],
    base_url="https://api.tokenlab.sh/v1",
    timeout=30.0,
    max_retries=0,
) as client:
    try:
        response = client.chat.completions.create(
            model="gpt-5.6-terra",
            messages=[{"role": "user", "content": "Reply only with OK."}],
        )
        print(response.choices[0].message.content)
    except APIStatusError as exc:
        body = exc.body if isinstance(exc.body, dict) else {}
        error = body.get("error", body)
        if not isinstance(error, dict):
            error = {}
        print({
            "status": exc.status_code,
            "request_id": exc.request_id,
            "code": error.get("code"),
            "hint": error.get("hint"),
            "suggested_model": error.get("did_you_mean"),
            "retry_after": exc.response.headers.get("Retry-After") or error.get("retry_after"),
        })
        raise

本頁內容