Source: https://aiprimetech.io/ja/learn/anthropic-python-sdk/ [ホーム](/ja/) / [学習](/ja/learn/) / Anthropic Python SDK:インストール、base_urlの設定、ストリーミング、エラー処理 # Anthropic Python SDK:インストール、base_urlの設定、ストリーミング、エラー処理 この anthropic パッケージは、Claude API向けのAnthropic公式Pythonクライアントです。認証、再試行、ストリーミング、型付きエラーを処理し、どのAnthropic互換エンドポイントでも変更せずに動作します。設定するのは base_url (または ANTHROPIC_BASE_URL)だけで、残りのコードはそのまま使えます。 ## インストール ターミナルコピー ``` pip install anthropic ``` 1.xリリースは、次の環境で動作します: httpx2 また、Python 3.10以降が必要です。独自のHTTPクライアントを渡す場合は、SDKの次のものを使ってください: DefaultHttpxClient これにより、デフォルトのタイムアウトと接続数制限が維持されます。 ## クライアントを作成する app.pyコピー ``` import anthropic client = anthropic.Anthropic( api_key="your_key", # default: ANTHROPIC_API_KEY base_url="https://aiprimetech.io", # default: ANTHROPIC_BASE_URL, else https://api.anthropic.com ) ``` base_url はホストのルートです。SDKが次のパスを追加します: /v1/messages この追加はSDK自身が行うため、 https://aiprimetech.io/v1 を指定すると、次のようになります: /v1/v1/messages および 404 page not found。両方の変数を環境に設定してあれば、 anthropic.Anthropic() に引数を渡す必要はまったくありません: ターミナルコピー ``` export ANTHROPIC_API_KEY=your_key export ANTHROPIC_BASE_URL=https://aiprimetech.io ``` ## メッセージを送信する app.pyコピー ``` message = client.messages.create( model="claude-sonnet-5", max_tokens=1024, messages=[{"role": "user", "content": "Summarise TCP slow start in two sentences."}], ) for block in message.content: if block.type == "text": print(block.text) print(message.usage.input_tokens, message.usage.output_tokens) print(message._request_id) # log this with any failure report ``` content はブロック(テキスト、思考、ツール使用)のリストなので、次を確認してください: block.type 次を無条件に読み取るのではなく、 content[0].text 内容を確認してください。 ## レスポンスをストリーミングする stream.pyコピー ``` with client.messages.stream( model="claude-sonnet-5", max_tokens=16000, messages=[{"role": "user", "content": "Write a short story about a lighthouse."}], ) as stream: for text in stream.text_stream: print(text, end="", flush=True) final = stream.get_final_message() ``` 入力が長い場合、出力が長い場合、または次の値が大きい場合は、ストリーミングを使ってください: max_tokens:単一の非ストリーミングリクエストはタイムアウト時間内に完了する必要がありますが、ストリーミングではその必要はありません。 messages.create(..., stream=True) は、ヘルパーが不要な場合に生のイベントイテレーターを提供します。 ## 非同期クライアント async_app.pyコピー ``` import asyncio, anthropic client = anthropic.AsyncAnthropic(base_url="https://aiprimetech.io") limit = asyncio.Semaphore(3) # stay within your key's concurrency async def ask(question: str) -> str: async with limit: msg = await client.messages.create( model="claude-haiku-4-5", max_tokens=512, messages=[{"role": "user", "content": question}], ) return next(b.text for b in msg.content if b.type == "text") async def main(): answers = await asyncio.gather(*(ask(q) for q in ["What is DNS?", "What is BGP?"])) print(answers) asyncio.run(main()) ``` セマフォは重要です。次を使って数百件のリクエストを一度に送信すると、 asyncio.gather 次のエラーの最も一般的な原因になります: Concurrency limit exceeded これは、Pythonクライアントでよく見られるエラーです。 ## タイムアウトとリトライ デフォルト設定:リクエストごとのタイムアウトは10分、指数バックオフによる自動再試行は2回です。SDKは接続エラー、408、409、429、および5xxレスポンスを再試行します。タイムアウトも再試行されるため、最悪の場合の実経過時間は、タイムアウト時間に試行回数を掛けた値になります。 app.pyコピー ``` client = anthropic.Anthropic(base_url="https://aiprimetech.io", timeout=60.0, max_retries=4) # override for one call only client.with_options(timeout=300.0).messages.create( model="claude-opus-5-5", max_tokens=4000, messages=[{"role": "user", "content": "Review this design doc..."}], ) ``` ## エラー処理 | 状態 | 例外 | リトライするか | 400 | anthropic.BadRequestError | いいえ:リクエストを修正 | 401 | anthropic.AuthenticationError | いいえ:キーが不正または未設定 | 403 | anthropic.PermissionDeniedError | なし | 404 | anthropic.NotFoundError | いいえ:モデルIDまたはURLを確認 | 429 | anthropic.RateLimitError | はい:しばらく待ってから | 5xx(529の過負荷エラーを含む) | anthropic.InternalServerError | はい | ネットワーク障害 | anthropic.APIConnectionError | はい | タイムアウト | anthropic.APITimeoutError | はい、またはストリーミングを使用 errors.pyコピー ``` try: message = client.messages.create(model="claude-sonnet-5", max_tokens=1024, messages=[{"role": "user", "content": "Hi"}]) except anthropic.NotFoundError as e: print("Bad model ID or URL:", e.message) except anthropic.RateLimitError as e: print("Rate limited, retry after", e.response.headers.get("retry-after")) except anthropic.APIStatusError as e: print(e.status_code, e.type, e.message) except anthropic.APIConnectionError: print("Network problem") ``` まず具体的なクラスを捕捉し、 APIStatusError は最後に捕捉してください。広範囲をまとめて捕捉する単一の except では、再試行する価値のあるエラーと、コードの変更が必要なエラーの違いが分からなくなります。 e.type は、次のようなAPIのエラー種別文字列を返します: rate_limit_error または overloaded_error. ## モデルID | モデルID | 用途 | claude-sonnet-5 | コーディングとエージェント作業の標準モデル:高速、高性能、中程度の価格。 | claude-opus-5-5 | より難しい推論、大規模なリファクタリング、長時間のエージェント実行。 | claude-fable-5-1 | 最も高性能で最も高価。最も難しいタスクに絞って使いましょう。 | claude-haiku-4-5 | 低価格で高速:タイトル、要約、分類、小さな処理。 client.models.list() は、エンドポイントが提供するモデルを返すため、使用前にIDを確認できます。IDは記載どおりに使い、日付の接尾辞は付けないでください。 ## ゲートウェイでのトラブルシューティング | 表示される内容 | 原因 | 対処方法 | NotFoundError 置き換え先: 404 page not found | /v1 の提供先: base_url | ホストのルートを使用 | AuthenticationError | プロセスにキーが設定されていない、または空白を含めて貼り付けられている | 表示する値: len(os.environ["ANTHROPIC_API_KEY"]) | RateLimitError: Concurrency limit exceeded for user | 同時実行中のリクエストが多すぎる | 使用するもの: asyncio.Semaphore 上記のとおり | APITimeoutError 長時間の処理で発生 | 非ストリーミングリクエストがタイムアウト時間を超えて実行されている | ストリーミングを使うか、次の値を増やす: timeout | InternalServerError: No available accounts | 上流サービスの一時的な処理能力不足 | SDKに再試行させる。次の値を増やす: max_retries | Insufficient account balance | 残高不足 | [チャージ](/ja/topup/) モデル側のエラーについて詳しくは、こちらをご覧ください: [Claude APIエラーガイド](/ja/learn/claude-api-errors-troubleshooting/). ## よくある質問 Anthropic Python SDKをインストールするには? pip install anthropicを実行します。バージョン1.xにはPython 3.10以降が必要です。 Anthropic Python SDKでカスタムベースURLを設定するには? anthropic.Anthropic()にbase_urlを渡すか、ANTHROPIC_BASE_URLを設定します。ホストのルートを指定してください。SDKが/v1/messagesを追加します。 デフォルトのタイムアウトと再試行回数は? リクエストごとに10分、指数バックオフによる再試行は2回です。接続エラー、408、409、429、および5xxが対象です。 Python SDKでストリーミングするには? with client.messages.stream(...) as stream:を使い、stream.text_streamを反復処理します。stream.get_final_message()は完全なメッセージを返します。 数分でClaudeの利用を開始 APIキーを取得 — Anthropicアカウントもウェイトリストへの登録も不要です。[APIキーを取得](/register) AI Prime Techは独立したAPIゲートウェイです。Anthropicとの提携関係はなく、同社の承認を受けておらず、同社の再販業者でもありません。Claudeおよび関連するモデル名は、それぞれの所有者の商標です。 ## Claude APIのその他のガイド [Claude APIキーの取得方法](/ja/learn/how-to-get-a-claude-api-key/)[Claude API の料金を解説](/ja/learn/claude-api-pricing-explained/)[Claude APIを最も安く利用する方法](/ja/learn/cheapest-way-to-use-claude-api/)[Claude APIでCursorを無制限に利用](/learn/use-claude-api-with-cursor/)[Claude Codeへの無制限アクセス](/ja/learn/use-claude-api-with-claude-code/)[Claude APIゲートウェイとAnthropicへの直接接続の比較](/ja/learn/claude-api-vs-anthropic-direct/)[OpenAI互換API経由でClaudeを使う](/ja/learn/openai-compatible-claude-api/)[Claude モデルを解説:Claude Opus、Sonnet、Haiku、Fable のモデル比較 — すべての Claude API モデル、Anthropic のモデル名と料金(2026)](/ja/learn/claude-api-models-compared/)[暗号資産でClaude APIの料金を支払う](/ja/learn/claude-api-with-crypto-payment/)[ウェイティングリストなしでClaude APIを利用](/ja/learn/claude-api-without-waitlist/)[Claudeのトークン使用量を削減する方法](/ja/learn/how-to-reduce-claude-token-usage/)[Claude APIでClineを無制限に利用](/ja/learn/use-claude-api-with-cline/)[Claude APIでRoo Codeを無制限に利用](/ja/learn/use-claude-api-with-roo-code/)[JetBrains IDEでClaudeを無制限に利用](/ja/learn/use-claude-api-with-jetbrains/)[Claude APIでAiderを無制限に使う](/ja/learn/use-claude-api-with-aider/)[VS CodeでClaudeを無制限に利用](/ja/learn/use-claude-api-with-vscode/)[Claude向けのOpenCode設定:opencode.jsonの設定、モデル、よくあるエラー](/ja/learn/use-claude-api-with-opencode/)[ClaudeでHermesエージェントを無制限に実行する](/ja/learn/run-hermes-agent-with-claude-api/)[ClaudeでOpenClawを無制限に実行](/ja/learn/run-openclaw-with-claude-api/)[Anthropic互換APIとは](/ja/learn/anthropic-compatible-api/)[Claude CodeのAPIキー — ANTHROPIC_API_KEY:取得方法、設定方法、代わりにclaude setup-tokenを使うべき場合](/ja/learn/claude-code-api-key-setup/)[Claude Code APIのコスト — 料金と削減方法](/ja/learn/claude-code-api-costs/)[Claude APIエラーを解説:サーバーエラー500、過負荷529、レート制限429、不正なリクエスト400 — それぞれの解決方法](/ja/learn/claude-api-errors-troubleshooting/)[Claude APIクレジットの購入方法 — Claudeクレジットがどの「Claudeアカウント購入」のオファーよりも優れている理由](/ja/learn/buy-claude-api-credits/)[Claudeの無料API:無料のClaude APIキーはあるのか、2026に実際に無料で使えるものは?](/ja/learn/claude-api-free-trial/)[Claude APIとClaude Pro/Maxサブスクリプション — どちらを選ぶべきか](/ja/learn/claude-api-vs-subscription/)[ClaudeでCodex CLIを実行する](/ja/learn/use-claude-api-with-codex/)[Claudeをn8nに接続する](/ja/learn/use-claude-api-with-n8n/)[LiteLLMからClaudeへのルーティング](/ja/learn/use-claude-api-with-litellm/)[Kilo CodeでClaudeを使う](/ja/learn/use-claude-api-with-kilo-code/)[GitHub CopilotにClaudeを導入する](/ja/learn/use-claude-api-with-github-copilot/)[ゲートウェイ経由でZedをClaudeに接続する](/ja/learn/use-claude-api-with-zed/)[Cherry StudioをClaudeに接続](/ja/learn/use-claude-api-with-cherry-studio/)[LangChainのChatAnthropic:インポート、base_url、ストリーミング、ツール、エラー](/ja/learn/use-claude-api-with-langchain/)[Vercel AI SDKでClaudeを使用:createAnthropicのbaseURL、ストリーミング、問題の修正](/ja/learn/use-claude-api-with-vercel-ai-sdk/)[ClaudeでFactory Droidを実行](/ja/learn/use-claude-api-with-factory-droid/)[Claude Code APIの仕組みを解説](/ja/learn/claude-code-api/)[アプリケーションへのClaude APIの統合](/ja/learn/claude-api-integration/)[Claudeを無制限に利用する方法 — 「Claude Codeのクラック版」が存在しない理由](/ja/learn/get-unlimited-claude-usage/)