Claude API Python チュートリアル 2026 | APIMaster.ai
PythonでClaude APIを使用する方法。Anthropic SDKとOpenAI互換クライアントを使用した完全な例(チャット、ストリーミング、ビジョン、関数呼び出し)をAPIMaster.ai経由で紹介します。
Claude API Python チュートリアル
このガイドでは、ネイティブのAnthropic SDKとOpenAI互換クライアントの両方を使用して、PythonでClaude APIを使用する方法を説明します。すべての例はAPIMaster.aiで動作します。ご自身のベースURLとAPIキーに置き換えてください。
インストール
pip install anthropic # ネイティブAnthropic SDK
pip install openai # OpenAI互換(オプション)
基本設定
import anthropic
client = anthropic.Anthropic(
api_key="YOUR_APIMASTER_KEY",
base_url="https://apimaster.ai", # Anthropic SDKでは/v1は不要
)
またはOpenAI SDKを使用する場合(すでにOpenAIを使用している場合はより簡単です):
from openai import OpenAI
client = OpenAI(
api_key="YOUR_APIMASTER_KEY",
base_url="https://apimaster.ai/v1",
)
最初のClaude API呼び出し
import anthropic
client = anthropic.Anthropic(
api_key="YOUR_APIMASTER_KEY",
base_url="https://apimaster.ai",
)
message = client.messages.create(
model="claude-sonnet-4-6",
max_tokens=1024,
messages=[
{"role": "user", "content": "Pythonにおけるリストとタプルの違いを説明してください。"}
],
)
print(message.content[0].text)
システムプロンプト
response = client.messages.create(
model="claude-sonnet-4-6",
max_tokens=512,
system="あなたはシニアPythonエンジニアです。簡潔に、コード例を使って説明してください。",
messages=[
{"role": "user", "content": "ネストされたリストを平坦化する最速の方法は?"}
],
)
print(response.content[0].text)
マルチターン会話
conversation = []
def chat(user_message):
conversation.append({"role": "user", "content": user_message})
response = client.messages.create(
model="claude-sonnet-4-6",
max_tokens=1024,
messages=conversation,
)
assistant_message = response.content[0].text
conversation.append({"role": "assistant", "content": assistant_message})
return assistant_message
print(chat("Pythonのデコレータとは何ですか?"))
print(chat("実用的な例を見せてもらえますか?"))
ストリーミングレスポンス
ストリーミングはトークンが生成されるたびに返します。長い出力に対してより良いUXを提供します:
with client.messages.stream(
model="claude-sonnet-4-6",
max_tokens=1024,
messages=[{"role": "user", "content": "requestsとBeautifulSoupを使ったPythonのWebスクレイパーを書いてください。"}],
) as stream:
for text in stream.text_stream:
print(text, end="", flush=True)
print() # 末尾に改行
ビジョン:画像分析
Claude SonnetとOpusは画像入力(base64またはURL)をサポートしています:
import base64
with open("chart.png", "rb") as f:
image_data = base64.standard_b64encode(f.read()).decode("utf-8")
response = client.messages.create(
model="claude-sonnet-4-6",
max_tokens=512,
messages=[
{
"role": "user",
"content": [
{
"type": "image",
"source": {
"type": "base64",
"media_type": "image/png",
"data": image_data,
},
},
{"type": "text", "text": "このチャートが示している内容を要約してください。"},
],
}
],
)
print(response.content[0].text)
ツール使用(関数呼び出し)
tools = [
{
"name": "get_weather",
"description": "都市の現在の天気を取得する",
"input_schema": {
"type": "object",
"properties": {
"city": {"type": "string", "description": "都市名"},
},
"required": ["city"],
},
}
]
response = client.messages.create(
model="claude-sonnet-4-6",
max_tokens=256,
tools=tools,
messages=[{"role": "user", "content": "東京の天気は?"}],
)
# Claudeがツールを呼び出そうとしているか確認
if response.stop_reason == "tool_use":
tool_call = next(b for b in response.content if b.type == "tool_use")
print(f"ツール: {tool_call.name}, 入力: {tool_call.input}")
非同期使用
import asyncio
import anthropic
async def main():
client = anthropic.AsyncAnthropic(
api_key="YOUR_APIMASTER_KEY",
base_url="https://apimaster.ai",
)
response = await client.messages.create(
model="claude-sonnet-4-6",
max_tokens=256,
messages=[{"role": "user", "content": "こんにちは!"}],
)
print(response.content[0].text)
asyncio.run(main())
エラーハンドリング
import anthropic
try:
response = client.messages.create(
model="claude-sonnet-4-6",
max_tokens=256,
messages=[{"role": "user", "content": "こんにちは"}],
)
except anthropic.AuthenticationError:
print("無効なAPIキー")
except anthropic.RateLimitError:
print("レート制限—リトライロジックを追加してください")
except anthropic.APIStatusError as e:
print(f"APIエラー {e.status_code}: {e.message}")
Pythonプロジェクトに適したClaudeモデルの選択
| タスク | モデル | 理由 |
|---|---|---|
| チャットボット、Q&A | claude-haiku-4-5 | 高速+低コスト |
| コード生成 | claude-sonnet-4-6 | 最適なバランス |
| 複雑な推論 | claude-opus-4-8 | 最高の精度 |
| ドキュメント分析 | claude-sonnet-4-6 | 100万トークンのコンテキスト |
Claude APIアクセスの取得
よくある質問
Claude API Pythonライブラリをインストールするにはどうすればよいですか?
公式SDKを使用するには pip install anthropic を実行するか、APIMasterのOpenAI互換エンドポイントをClaudeモデルで使用するには pip install openai を実行します。
Claude APIにはどのPython SDKを使用すべきですか?
anthropic SDKが公式の選択肢であり、すべてのClaude固有機能(ツール使用、ビジョン、ストリーミング)をサポートしています。openai SDKはAPIMasterの互換レイヤーを介して動作します。すでにOpenAIを使用していてモデルを切り替えたい場合に便利です。
PythonでClaude APIレスポンスをストリーミングするにはどうすればよいですか?
openai ライブラリでは stream=True を渡すか、anthropic SDKでは client.messages.stream() を使用します。上記のストリーミングの例を参照してください。
Claude APIは関数呼び出し(ツール使用)をサポートしていますか?
はい。ClaudeはネイティブのAnthropic SDKと、APIMasterのOpenAI互換エンドポイントの両方で、標準の tools パラメータを使用したツール使用をサポートしています。
PythonでのClaudeの最大コンテキストウィンドウはどのくらいですか?
Claude Sonnet 4.6とOpus 4.8はそれぞれ100万トークンをサポートしています。非常に長いドキュメントも messages 配列に直接渡すことができます。
APIMaster.aiに登録して、統合エンドポイント、リアルタイム価格、フィンガープリント検証データを通じてClaude APIアクセスを取得してください。
関連情報: Claude API料金 · Claude APIキーの取得方法