コアガイド

エージェントが対応可能なエラー

エラーコード、リトライタイミング、モデルの提案を活用し、プロセスの解析を回避する

このページはアプリやコーディングエージェント向けの、機械可読な公開 API エラーについて説明します。ワークスペースの調査やサポートへの権限を付与するものではありません。自分のリクエストはトラブルシューティングから調べてください。

OpenAI互換のTokenLabエラーには、エージェントやアプリケーション向けの構造化されたヒントが含まれる場合があります。これらのフィールドが存在する場合はそれを使用し、人間が読むための message を解析して動作を決定しないでください。

Anthropic Messages APIおよびGemini APIは独自のネイティブなエラー形式を維持しているため、このページで説明する拡張機能はOpenAI互換のChat CompletionsおよびResponsesエラーにのみ適用されます。

オプションのエラーフィールド

以下のすべてのフィールドは error オブジェクト内に含まれ、存在しない場合もあります。

フィールド型用途
did_you_meanstring最も近い利用可能なモデルID
suggestionsarrayリクエストに適している可能性のあるモデル
hintstring短い説明または推奨されるアクション
retryableboolean同じリクエストが後で成功する可能性があるかどうか
retry_afternumber再試行までに待機すべき秒数
balance_usdnumber現在の残高(USD)
estimated_cost_usdnumber拒否されたリクエストの推定コスト(USD)

クライアントは引き続き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

これには、最初のリクエスト、一般的なエンドポイント、モデルフィルター、およびエラーハンドリングのガイダンスが含まれています。

リクエストを再送せずにエラーを扱う

この例はリクエストを 1 回だけ送り、選択したモデルを維持して構造化されたエラー情報を表示します。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

このページの内容