AI業務活用 2026.04.23

Anthropic APIアカウント停止時の対応|影響確認コードと復旧手順【完全ガイド】

タグ:Claude / API / エラー / トラブルシューティング / Anthropic

停止の影響範囲は3つで独立している

Anthropicのアカウント停止(ban)は、以下の3つが独立して影響を受ける場合があります:

Anthropic アカウント停止の影響
├─ Webダッシュボード(Claude.ai)
│   └─ ログインできない・UIが使えない
├─ APIキー
│   └─ 既存キーが即時無効化 or 新規発行のみ制限
└─ 課金システム
    └─ 課金情報が個別に凍結される可能性

これを理解していないと「APIは止まっているのにダッシュボードはアクセスできる」という混乱が起きます。

Step 1:影響範囲を確認するコード

# check_api_status.py
import anthropic
import os
import sys

def check_api_health() -> dict:
    """APIの状態を確認して影響範囲を特定する"""
    api_key = os.environ.get("ANTHROPIC_API_KEY")
    
    if not api_key:
        return {"status": "error", "reason": "ANTHROPIC_API_KEY 環境変数が未設定"}
    
    client = anthropic.Anthropic(api_key=api_key)
    
    try:
        # 最小限のテストリクエスト
        response = client.messages.create(
            model="claude-haiku-4-5-20251001",
            max_tokens=5,
            messages=[{"role": "user", "content": "ping"}]
        )
        return {
            "status": "ok",
            "model": response.model,
            "usage": {"input": response.usage.input_tokens, "output": response.usage.output_tokens}
        }
    
    except anthropic.AuthenticationError as e:
        # 401: APIキーが無効
        return {
            "status": "auth_error",
            "code": 401,
            "reason": "APIキーが無効または期限切れです",
            "action": "console.anthropic.comで新しいAPIキーを発行してください",
            "raw_error": str(e)
        }
    
    except anthropic.PermissionDeniedError as e:
        # 403: アカウント停止の可能性が高い
        return {
            "status": "suspended",
            "code": 403,
            "reason": "アカウントが停止されているか、アクセス権限がありません",
            "action": "1. console.anthropic.comにログインして通知を確認\n"
                     "2. support.anthropic.comからサポートに連絡",
            "raw_error": str(e)
        }
    
    except anthropic.RateLimitError as e:
        # 429: 停止ではなくレート制限
        return {
            "status": "rate_limited",
            "code": 429,
            "reason": "レート制限に達しました(停止ではありません)",
            "action": "数分待って再試行してください",
            "raw_error": str(e)
        }
    
    except anthropic.APIConnectionError as e:
        # 接続エラー
        return {
            "status": "connection_error",
            "reason": "ネットワークまたはAPIサーバーへの接続失敗",
            "action": "status.anthropic.comでサービス状態を確認してください",
            "raw_error": str(e)
        }

if __name__ == "__main__":
    result = check_api_health()
    
    print(f"API状態: {result['status']}")
    if result['status'] != 'ok':
        print(f"原因: {result.get('reason', '不明')}")
        print(f"対応: {result.get('action', '—')}")
    else:
        print(f"✅ 正常稼働中 (model: {result['model']})")
    
    # 停止の場合は終了コード1で終了(CI/CDで検知できるように)
    if result['status'] in ('suspended', 'auth_error'):
        sys.exit(1)

Step 2:エラーコード別の対応フロー

APIエラーコード判別:

401 Unauthorized
  └─ APIキーが無効 or 期限切れ
  └─ 対応: console.anthropic.com → API Keys → Create Key

403 Forbidden
  └─ アカウント停止の可能性大
  └─ console.anthropic.comにログインして通知確認
  └─ 停止通知メールをチェック

429 Too Many Requests
  └─ レート制限(停止ではない)
  └─ ヘッダーのretry-after秒後に再試行
  └─ 長期的: APIティアをアップグレード

500/503
  └─ Anthropicサーバー障害
  └─ status.anthropic.comで確認
  └─ 指数バックオフで再試行

Step 3:停止理由別の対応

支払い問題による停止

# 支払い問題の確認ポイント
# 1. console.anthropic.com → Billing → Check status
# 2. クレジットカードの有効期限・残高を確認
# 3. 新しいカードを追加して既存を削除
# 支払い問題確認後のAPI動作テスト
def verify_billing_fixed():
    """課金情報更新後にAPIが復旧したか確認"""
    import time
    
    max_attempts = 5
    wait_seconds = 60
    
    for attempt in range(max_attempts):
        result = check_api_health()
        if result['status'] == 'ok':
            print(f"✅ {attempt+1}回目で復旧確認")
            return True
        
        print(f"❌ {attempt+1}/{max_attempts} - まだ停止中。{wait_seconds}秒後に再確認...")
        time.sleep(wait_seconds)
    
    print("課金情報更新後もサポートへの連絡が必要です")
    return False

利用規約違反による停止

# よくある違反原因と予防策

COMMON_VIOLATIONS = {
    "急激なリクエスト増加": {
        "症状": "短時間に通常の10倍以上のリクエスト",
        "対策": "実装: Semaphoreで最大並行数を制限"
    },
    "コンテンツポリシー違反": {
        "症状": "不適切なコンテンツ生成・プロンプトインジェクション",
        "対策": "システムプロンプトにコンテンツ制限を明示"
    },
    "APIキーの共有・流出": {
        "症状": "複数の地理的ロケーションから同一キーでアクセス",
        "対策": "定期的なAPIキーローテーション・環境変数での管理"
    }
}

# レート制限遵守の実装例
import asyncio
import anthropic

async def rate_limited_requests(prompts: list[str], max_concurrent: int = 5) -> list[str]:
    """レート制限を守った並行リクエスト"""
    client = anthropic.AsyncAnthropic()
    semaphore = asyncio.Semaphore(max_concurrent)  # 同時接続数を制限
    
    async def single_request(prompt: str) -> str:
        async with semaphore:
            response = await client.messages.create(
                model="claude-haiku-4-5-20251001",
                max_tokens=512,
                messages=[{"role": "user", "content": prompt}]
            )
            return response.content[0].text
    
    results = await asyncio.gather(*[single_request(p) for p in prompts])
    return results

Step 4:サポートへの申請(Appeal)

Anthropic サポート連絡先: support.anthropic.com

申請に含める情報:
□ 停止通知メールのスクリーンショット
□ アカウント登録メールアドレス
□ APIキー(最初の8文字のみ: sk-ant-api03-XXXX...)
□ チームID(Teamプランの場合)
□ 停止に至った経緯の説明
□ 今後の再発防止策

英語での申請が推奨(返答が早い):

Subject: Account Suspension Appeal - [your email]

I am writing to appeal the suspension of my Anthropic account.

Account email: [your@email.com]
Date of suspension: [date]

Situation: [短い説明]
Why I believe this was an error: [理由]
Steps taken to prevent recurrence: [対策]

再発防止の実装

# monitoring.py - APIの健全性を定期監視してSlackに通知

import anthropic
import requests
import os
from datetime import datetime

def notify_slack(message: str, webhook_url: str) -> None:
    requests.post(webhook_url, json={"text": message})

def monitor_api_health(
    webhook_url: str,
    check_interval_seconds: int = 300  # 5分ごと
) -> None:
    """APIの健全性を監視して問題があればSlackに通知"""
    import time
    
    previous_status = "ok"
    
    while True:
        result = check_api_health()
        current_status = result['status']
        
        if current_status != previous_status:
            if current_status != 'ok':
                notify_slack(
                    f"🚨 Anthropic API障害検知 [{datetime.now().strftime('%H:%M')}]\n"
                    f"状態: {current_status}\n"
                    f"原因: {result.get('reason', '不明')}\n"
                    f"対応: {result.get('action', '—')}",
                    webhook_url
                )
            else:
                notify_slack(
                    f"✅ Anthropic API復旧確認 [{datetime.now().strftime('%H:%M')}]",
                    webhook_url
                )
            
            previous_status = current_status
        
        time.sleep(check_interval_seconds)

# APIキーローテーションの例
def rotate_api_key_reminder():
    """APIキーを定期的にローテーションする reminder"""
    # 90日ごとにAPIキーを更新する運用を推奨
    # 1. console.anthropic.com → API Keys → Create new key
    # 2. 全サービスの環境変数を更新
    # 3. 旧キーを削除
    pass

あわせて読みたい

参考ソース