OpenAI 429:rate_limit_exceeded と insufficient_quota の違いと対処
OpenAI API の HTTP 429 Too Many Requests には、まったく異なる 2 つの原因があります。1 分あたりのレート制限(rate_limit_exceeded)と、残高・月次上限の枯渇(insufficient_quota)です。前者はリトライで回復しますが、後者は何回再送しても成功しません。
結論(最短切り分け)
レスポンス JSON の error.code を確認してください:
rate_limit_exceeded(RPM / TPM / RPD 制限):retry-afterヘッダーと指数バックオフ+ジッターでリトライし、過大なmax_completion_tokens/max_output_tokensを下げて TPM 予約を抑えます。insufficient_quota(You exceeded your current quota):リトライを即停止し、API プリペイド残高・組織の月次上限・トークン上限を確認します。
2 種類の 429 を見分ける
| 項目 | rate_limit_exceeded(一時的な速度制限) | insufficient_quota(残高・上限枯渇) |
|---|---|---|
error.code | rate_limit_exceeded | insufficient_quota |
error.type | requests または tokens | insufficient_quota |
| リトライ可否 | 可(Retry-After / バックオフ後) | 不可(即時停止して課金設定を確認) |
対処 1:error.code で分岐して Retry-After を守る
python
import random
import time
from openai import OpenAI, RateLimitError
client = OpenAI()
def call_with_backoff(messages, model="gpt-6-sol", max_attempts=5):
for attempt in range(max_attempts):
try:
return client.chat.completions.create(
model=model,
messages=messages,
max_completion_tokens=1024,
)
except RateLimitError as exc:
if getattr(exc, "code", None) == "insufficient_quota":
raise RuntimeError("残高またはクォータ上限に達しました。") from exc
if attempt == max_attempts - 1:
raise
retry_after = exc.response.headers.get("retry-after") if exc.response else None
delay = float(retry_after) if retry_after else min(2 ** attempt, 30)
time.sleep(delay + random.uniform(0.1, 0.5))対処 2:max_completion_tokens の過大予約を防ぐ
OpenAI はリクエスト前に input_tokens + max_completion_tokens(Responses API では max_output_tokens)で TPM を予約します。短い分類タスクに 32768 を指定すると即座に 429 に達します。必要な上限に近い値へ絞ってください。
対処 3:insufficient_quota の確認ポイント
- API 用のプリペイド残高があるか確認する(ChatGPT Plus/Pro 購読には API クレジットは含まれません)。
- 組織の月次ハードリミットやプロジェクト予算を確認する。
- シェルに古い
OPENAI_API_KEYが残っていないか確認する(OpenAI 401 invalid_api_key)。 - ゲートウェイ経由の場合は 402 / insufficient_quota 確認手順 も参照してください。