AI API を本番環境に統合する際、エラー処理は避けて通れない重要な課題です。ネットワーク障害、レート制限、認証エラーなど、様々な要因でリクエストが失敗します。私は複数のAI APIサービスを使い分けてきた経験から、各状態碼への適切な対処法を体系的に解説します。
HolySheep vs 公式API vs 他のリレーサービス:比較表
| 比較項目 | HolySheep AI | 公式OpenAI API | 他のリレーサービス |
|---|---|---|---|
| コスト | ¥1 = $1(85%節約) | ¥7.3 = $1 | ¥4〜6 = $1 |
| レイテンシ | <50ms | 100〜300ms | 80〜200ms |
| 対応支払い | WeChat Pay / Alipay / クレジットカード | クレジットカードのみ | 限定的な支払い方法 |
| GPT-4.1 出力料金 | $8/MTok | $8/MTok | $8〜10/MTok |
| Claude Sonnet 4.5 出力 | $15/MTok | $15/MTok | $15〜18/MTok |
| DeepSeek V3.2 出力 | $0.42/MTok | N/A(中國無法使用) | $0.50〜0.80/MTok |
| 429再試行 | 自動バックオフ対応 | 手動実装が必要 | 不安定 |
| 無料クレジット | 登録時付与 | $5〜18無料枠 | 限定的な無料枠 |
今すぐ登録して、85%のコスト削減と<50msの低レイテンシを体感してください。
HTTP 状態碼の基礎知識
AI API は RESTful な設計を採用しており、HTTP 状態碼でリクエストの結果を表現します。主な状態碼とその意味は以下の通りです。
- 200番台:成功(200 OK, 201 Created)
- 400番台:クライアントエラー(入力問題)
- 429:レート制限(Too Many Requests)
- 500番台:サーバーエラー(インフラ問題)
実践的なエラー処理コード
以下は HolySheep AI API 用の包括的なエラー処理クラスです。私は実際のプロジェクトで3ヶ月以上運用して改良を重ねてきました。
Python での包括的エラーハンドリング
import requests
import time
import json
from typing import Optional, Dict, Any
from datetime import datetime
class HolySheepAIClient:
"""HolySheep AI API 用エラーハンドリングクライアント"""
def __init__(self, api_key: str, base_url: str = "https://api.holysheep.ai/v1"):
self.api_key = api_key
self.base_url = base_url
self.session = requests.Session()
self.session.headers.update({
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json"
})
def _handle_status_code(self, response: requests.Response) -> Dict[str, Any]:
"""HTTP状態碼に応じたエラー処理"""
status = response.status_code
if 200 <= status < 300:
return {"success": True, "data": response.json()}
error_detail = response.json() if response.text else {}
error_type = error_detail.get("error", {}).get("type", "unknown")
error_message = error_detail.get("error", {}).get("message", response.text)
# 400 Bad Request - 入力パラメータエラー
if status == 400:
raise ValueError(f"リクエストパラメータエラー: {error_message}")
# 401 Unauthorized - APIキー不正
elif status == 401:
raise AuthenticationError(
f"APIキー認証失敗: {error_message}\n"
f"APIキーの有効性を確認してください: https://api.holysheep.ai/v1/account"
)
# 403 Forbidden - アクセス権限なし
elif status == 403:
raise PermissionError(f"アクセス権限エラー: {error_message}")
# 404 Not Found - リソース不存在
elif status == 404:
raise NotFoundError(f"リソースが見つかりません: {error_message}")
# 429 Too Many Requests - レート制限
elif status == 429:
retry_after = int(response.headers.get("Retry-After", 60))
raise RateLimitError(
f"レート制限に達しました。{retry_after}秒後に再試行してください。",
retry_after=retry_after
)
# 500 Internal Server Error - サーバーエラー
elif status == 500:
raise ServerError(f"HolySheep AI サーバーエラー: {error_message}")
# 502/503/504 - ゲートウェイ/メンテナンスエラー
elif status in (502, 503, 504):
raise ServiceUnavailableError(
f"サービス一時停止中 ({status}): {error_message}"
)
else:
raise APIError(f"予期しないエラー (HTTP {status}): {error_message}")
def chat_completions(
self,
model: str,
messages: list,
max_retries: int = 3,
timeout: int = 60
) -> Dict[str, Any]:
"""Chat completions API呼び出し(自動再試行付き)"""
endpoint = f"{self.base_url}/chat/completions"
payload = {
"model": model,
"messages": messages,
"temperature": 0.7
}
for attempt in range(max_retries):
try:
response = self.session.post(
endpoint,
json=payload,
timeout=timeout
)
result = self._handle_status_code(response)
print(f"[成功] Attempt {attempt + 1}: {model}")
return result
except RateLimitError as e:
wait_time = e.retry_after or (2 ** attempt)
print(f"[レート制限] {wait_time}秒待機... (Attempt {attempt + 1}/{max_retries})")
time.sleep(wait_time)
except (ServerError, ServiceUnavailableError) as e:
wait_time = 2 ** attempt
print(f"[サーバーエラー] {wait_time}秒待機... (Attempt {attempt + 1}/{max_retries})")
time.sleep(wait_time)
except (AuthenticationError, PermissionError, ValueError) as e:
# これらのエラーは再試行しても解決しない
raise
raise APIError(f"{max_retries}回の再試行後も失敗しました")
カスタム例外クラス
class AuthenticationError(Exception):
"""認証エラー"""
pass
class RateLimitError(Exception):
"""レート制限エラー"""
def __init__(self, message, retry_after=None):
super().__init__(message)
self.retry_after = retry_after
class ServerError(Exception):
"""サーバーエラー"""
pass
class ServiceUnavailableError(Exception):
"""サービス停止エラー"""
pass
class APIError(Exception):
"""一般的なAPIエラー"""
pass
使用例
if __name__ == "__main__":
client = HolySheepAIClient(api_key="YOUR_HOLYSHEEP_API_KEY")
try:
result = client.chat_completions(
model="gpt-4.1",
messages=[
{"role": "system", "content": "あなたは有用なアシスタントです。"},
{"role": "user", "content": "エラー処理のベストプラクティスを教えてください。"}
]
)
print(result["data"]["choices"][0]["message"]["content"])
except AuthenticationError as e:
print(f"認証エラー: {e}")
print("→ APIキーを確認してください")
except RateLimitError as e:
print(f"レート制限: {e}")
print("→ リクエスト間隔を調整してください")
except Exception as e:
print(f"エラー: {e}")
TypeScript での非同期エラー処理
interface HolySheepError {
type: string;
message: string;
code?: string;
}
interface APIError extends Error {
statusCode: number;
error: HolySheepError;
retryAfter?: number;
}
class HolySheepTSClient {
private apiKey: string;
private baseURL: string = "https://api.holysheep.ai/v1";
constructor(apiKey: string) {
this.apiKey = apiKey;
}
private async handleResponse(response: Response): Promise {
const status = response.status;
if (status >= 200 && status < 300) {
return await response.json();
}
const errorData = await response.json().catch(() => ({}));
const error: HolySheepError = errorData?.error || {
type: "unknown",
message: response.statusText
};
const apiError: APIError = new Error(error.message) as APIError;
apiError.statusCode = status;
apiError.error = error;
switch (status) {
case 400:
apiError.message = リクエストパラメータエラー: ${error.message};
break;
case 401:
apiError.message = APIキー認証失敗: ${error.message};
break;
case 403:
apiError.message = アクセス権限エラー: ${error.message};
break;
case 404:
apiError.message = リソースが見つかりません: ${error.message};
break;
case 429:
apiError.retryAfter = parseInt(response.headers.get("Retry-After") || "60");
apiError.message = レート制限: ${apiError.retryAfter}秒後に再試行;
break;
case 500:
case 502:
case 503:
case 504:
apiError.message = サーバーエラー (${status}): ${error.message};
break;
}
throw apiError;
}
async chatCompletions(
model: string,
messages: Array<{ role: string; content: string }>,
options: {
maxRetries?: number;
timeout?: number;
backoffBase?: number;
} = {}
): Promise {
const {
maxRetries = 3,
timeout = 60000,
backoffBase = 1000
} = options;
for (let attempt = 0; attempt <= maxRetries; attempt++) {
try {
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), timeout);
const response = await fetch(${this.baseURL}/chat/completions, {
method: "POST",
headers: {
"Authorization": Bearer ${this.apiKey},
"Content-Type": "application/json"
},
body: JSON.stringify({ model, messages }),
signal: controller.signal
});
clearTimeout(timeoutId);
return await this.handleResponse(response);
} catch (error: any) {
const isLastAttempt = attempt === maxRetries;
if (error.name === "AbortError") {
console.error([タイムアウト] Attempt ${attempt + 1}/${maxRetries + 1});
if (isLastAttempt) throw new Error("リクエストがタイムアウトしました");
}
if (error.statusCode === 429) {
const waitMs = error.retryAfter * 1000 || backoffBase * Math.pow(2, attempt);
console.log([レート制限] ${waitMs}ms待機中... (${attempt + 1}/${maxRetries + 1}));
await this.sleep(waitMs);
continue;
}
if (error.statusCode >= 500) {
const waitMs = backoffBase * Math.pow(2, attempt);
console.log([サーバーエラー ${error.statusCode}] ${waitMs}ms待機... (${attempt + 1}/${maxRetries + 1}));
await this.sleep(waitMs);
continue;
}
// 400, 401, 403, 404 は再試行不要
throw error;
}
}
}
private sleep(ms: number): Promise {
return new Promise(resolve => setTimeout(resolve, ms));
}
}
// 使用例
async function main() {
const client = new HolySheepTSClient("YOUR_HOLYSHEEP_API_KEY");
try {
const result = await client.chatCompletions(
"gpt-4.1",
[
{ role: "system", content: "あなたは有用なアシスタントです。" },
{ role: "user", content: "TypeScriptでのエラーハンドリングを教えて" }
],
{ maxRetries: 3, timeout: 60000 }
);
console.log("成功:", result.choices[0].message.content);
} catch (error: any) {
console.error("APIエラー発生:");
console.error(- ステータス: ${error.statusCode});
console.error(- メッセージ: ${error.message});
if (error.retryAfter) {
console.error(- リトライ間隔: ${error.retryAfter}秒);
}
}
}
main();
よくあるエラーと対処法
エラー1: 401 Unauthorized - APIキー認証失敗
原因:APIキーが無効、有効期限切れ、またはリクエストヘッダーが不正です。
# 誤った例(キーが空または未設定)
headers = {
"Authorization": f"Bearer " # APIキー未設定
}
正しい例
headers = {
"Authorization": f"Bearer {api_key}", # 有効なAPIキーを設定
"Content-Type": "application/json"
}
キーの有効性を確認するエンドポイント
response = requests.get(
"https://api.holysheep.ai/v1/account",
headers={"Authorization": f"Bearer {api_key}"}
)
解決方法:
- APIキーを正しく設定しているか確認する
- キーを再生成して.envファイルに安全に保存する
- 先頭の
sk-プレフィックスを含む完全キーをコピーする
エラー2: 429 Too Many Requests - レート制限超過
原因:短时间内でのリクエスト过多、またはプランの上限に達しています。
# 指数バックオフを使用したレート制限対処
import time
import random
def call_with_backoff(client, payload, max_retries=5):
for attempt in range(max_retries):
response = client.chat_completions(**payload)
if response.status_code != 429:
return response
# Retry-Afterヘッダーがある場合はそれを使用
retry_after = int(response.headers.get("Retry-After", 60))
# 指数バックオフ + ジッター
wait_time = retry_after * (2 ** attempt) + random.uniform(0, 1)
print(f"レート制限: {wait_time:.1f}秒待機...")
time.sleep(wait_time)
raise Exception("最大再試行回数を超過")
別の方法:リクエスト間隔を制御する
from collections import deque
import threading
class RateLimiter:
def __init__(self, max_calls: int, period: float):
self.max_calls = max_calls
self.period = period
self.calls = deque()
self.lock = threading.Lock()
def wait(self):
with self.lock:
now = time.time()
# 期間内の古いリクエストを削除
while self.calls and self.calls[0] < now - self.period:
self.calls.popleft()
if len(self.calls) >= self.max_calls:
sleep_time = self.calls[0] + self.period - now
time.sleep(sleep_time)
self.calls.append(time.time())
使用
limiter = RateLimiter(max_calls=60, period=60) # 1分間に60リクエスト
for message in messages:
limiter.wait()
response = client.chat_completions(message)
解決方法:
- リクエスト間に適切な間隔を設定する
- バッチ処理を検討してリクエスト数を最適化する
- より上位のプランにアップグレードする
- DeepSeek V3.2($0.42/MTok)などコスト効率の良いモデルに切り替えも検討
エラー3: 400 Bad Request - 入力パラメータエラー
原因:リクエストボディの形式が不正、または必須パラメータが欠落しています。
# 誤った例
payload = {
"model": "gpt-4.1",
"messages": "こんにちは" # 文字列ではなくリストである必要がある
}
正しい例
payload = {
"model": "gpt-4.1",
"messages": [
{"role": "user", "content": "こんにちは"}
],
"max_tokens": 1000, # オプション
"temperature": 0.7 # オプション
}
入力検証を行うラッパー関数
def validate_chat_request(model: str, messages: list, **kwargs) -> dict:
valid_models = [
"gpt-4.1", "gpt-4-turbo", "gpt-3.5-turbo",
"claude-sonnet-4.5", "claude-opus-4",
"gemini-2.5-flash", "deepseek-v3.2"
]
if model not in valid_models:
raise ValueError(f"無効なモデル: {model}. 選択可能: {valid_models}")
if not messages or not isinstance(messages, list):
raise ValueError("messagesは空でないリストである必要があります")
for msg in messages:
if "role" not in msg or "content" not in msg:
raise ValueError("各メッセージにはroleとcontentが必要です")
if msg["role"] not in ["system", "user", "assistant"]:
raise ValueError(f"無効なrole: {msg['role']}")
# temperature検証
temperature = kwargs.get("temperature", 0.7)
if not 0 <= temperature <= 2:
raise ValueError("temperatureは0〜2の間である必要があります")
return {
"model": model,
"messages": messages,
**{k: v for k, v in kwargs.items() if k in ["max_tokens", "temperature", "top_p"]}
}
使用
validated = validate_chat_request(
model="gpt-4.1",
messages=[{"role": "user", "content": "Hello"}],
temperature=0.5
)
response = client.chat_completions(**validated)
解決方法:
- リクエストボディのJSON形式を検証する
- 必須パラメータ(model, messages)が存在するか確認する
- APIドキュメントでサポートされているモデル・パラメータを確認する
エラー4: 500 Internal Server Error - サーバー側エラー
原因