Claude向けAPI使用入門
このガイドは、ClaudeにClaude APIの使用に関する基本を提供することを目的としています。モデルID/基本的なMessages API、ツール使用、ストリーミング、思考についての説明と例を提供し、それ以外は扱いません。
Claude向けAPI使用入門
このガイドは、ClaudeにClaude APIの使用に関する基本を提供することを目的としています。モデルID/基本的なMessages API、ツール使用、ストリーミング、思考についての説明と例を提供し、それ以外は扱いません。
モデル
Recommended default for most work, including complex agentic coding: Claude Opus 5.5: claude-opus-5-5
Step up for the hardest long-running agentic and research tasks, at 2.5x Claude Opus 5.5 pricing: Claude Fable 5.1: claude-fable-5-1
Previous Opus model: Claude Opus 5: claude-opus-5
Smart model: Claude Sonnet 5.5: claude-sonnet-5-5
Previous Sonnet model: Claude Sonnet 5: claude-sonnet-5
For fast, cost-effective tasks: Claude Haiku 5.5: claude-haiku-5-5
Previous Haiku model: Claude Haiku 4.5: claude-haiku-4-5-20251001APIの呼び出し
基本的なリクエストとレスポンス
import anthropic
message = anthropic.Anthropic().messages.create(
model="claude-opus-5-5",
max_tokens=1024,
messages=[{"role": "user", "content": "Hello, Claude"}],
)
print(message){
"id": "msg_01XFDUDYJgAACzvnptvVoYEL",
"type": "message",
"role": "assistant",
"content": [
{
"type": "text",
"text": "Hello!"
}
],
"model": "claude-opus-5-5",
"stop_reason": "end_turn",
"stop_sequence": null,
"usage": {
"input_tokens": 12,
"output_tokens": 6
}
}複数の会話ターン
Messages APIは「stateless」(ステートレス)です。つまり、常に会話履歴全体をAPIに送信します。このパターンを使用して、時間をかけて会話を構築できます。以前の会話ターンは、必ずしも実際にClaudeから生成されたものである必要はありません。合成のassistantメッセージを使用できます。
ベータ版のメッセージスレッドを使用すると、APIが会話を保持できるため、以降の各リクエストでは新しいメッセージのみを送信すれば済みます。スレッドの有効期限は最後のリクエストから5分後に切れ、スレッドは最後の使用から1時間以内に削除されます。
import anthropic
message = anthropic.Anthropic().messages.create(
model="claude-opus-5-5",
max_tokens=1024,
messages=[
{"role": "user", "content": "Hello, Claude"},
{"role": "assistant", "content": "Hello!"},
{"role": "user", "content": "Can you describe LLMs to me?"},
],
)
print(message)Claudeの応答のプリフィル
入力メッセージリストの最後の位置で、Claudeの応答の一部を「prefill」(プリフィル)できます。この手法を使用してClaudeの応答を形作ります。次の例では、"max_tokens": 1を使用してClaudeから単一の多肢選択式の回答を取得します。
import anthropic
message = anthropic.Anthropic().messages.create(
model="claude-sonnet-4-5",
max_tokens=1,
messages=[
{
"role": "user",
"content": "What is latin for Ant? (A) Apoidea, (B) Rhopalocera, (C) Formicidae",
},
{"role": "assistant", "content": "The answer is ("},
],
)
print(message.content[0].text)ビジョン
Claudeはリクエスト内のテキストと画像の両方を読み取ることができます。画像についてはbase64とurlの両方のソースタイプがサポートされており、image/jpeg、image/png、image/gif、image/webpのメディアタイプに対応しています。
import anthropic
import base64
import httpx2
# オプション 1: Base64 エンコードされた画像
image_url = "https://platform.claude.com/docs/images/vision-example.jpg"
image_media_type = "image/jpeg"
image_data = base64.standard_b64encode(httpx2.get(image_url).content).decode("utf-8")
message = anthropic.Anthropic().messages.create(
model="claude-opus-5-5",
max_tokens=1024,
messages=[
{
"role": "user",
"content": [
{
"type": "image",
"source": {
"type": "base64",
"media_type": image_media_type,
"data": image_data,
},
},
{"type": "text", "text": "What is in the above image?"},
],
}
],
)
print(next(block.text for block in message.content if block.type == "text"))
# オプション 2: URL で参照する画像
message_from_url = anthropic.Anthropic().messages.create(
model="claude-opus-5-5",
max_tokens=1024,
messages=[
{
"role": "user",
"content": [
{
"type": "image",
"source": {
"type": "url",
"url": "https://platform.claude.com/docs/images/vision-example.jpg",
},
},
{"type": "text", "text": "What is in the above image?"},
],
}
],
)
print(next(block.text for block in message_from_url.content if block.type == "text"))思考
思考は、非常に難しいタスクでClaudeの助けになることがあります。現在のメカニズムは「adaptive thinking」(適応型思考)(thinking: {"type": "adaptive"})です。Claudeがいつ、どの程度思考するかを判断し、トークン予算ではなくeffortパラメータで思考の深さを調整します。適応型思考は、Claude 4.6以降のモデルおよびClaude Mythos Previewでサポートされています。Claude 5以降のモデルおよびClaude Mythos Previewでは、thinkingパラメータを省略した場合、思考はデフォルトでオンになります。
思考は次のモデルでサポートされています:
- Claude Opus 5.5(
claude-opus-5-5、適応型思考のみ、常にオン) - Claude Sonnet 5.5(
claude-sonnet-5-5、適応型思考のみ、デフォルトでオン。thinking: {"type": "disabled"}は400エラーを返すため、事前の思考をオフにするにはthinking: {"type": "between_tools"}を送信してください) - Claude Haiku 5.5(
claude-haiku-5-5、適応型思考のみ、デフォルトでオン) - Claude Fable 5.1(
claude-fable-5-1、適応型思考のみ、常にオン) - Claude Mythos 5.1(
claude-mythos-5-1、適応型思考のみ、常にオン) - Claude Fable 5(
claude-fable-5、適応型思考のみ、常にオン) - Claude Mythos 5(
claude-mythos-5、適応型思考のみ、常にオン) - Claude Opus 5(、適応型思考のみ、デフォルトでオン)
- Claude Sonnet 5(
claude-sonnet-5、適応型思考のみ、デフォルトでオン) - Claude Opus 4.8(、適応型思考のみ)
- Claude Opus 4.7(
claude-opus-4-7、適応型思考のみ) - Claude Opus 4.6(
claude-opus-4-6、適応型思考またはレガシーの手動思考) - Claude Sonnet 4.6(
claude-sonnet-4-6、適応型思考またはレガシーの手動思考) - Claude Opus 4.5(
claude-opus-4-5-20251101、レガシーの手動思考のみ) - Claude Sonnet 4.5(
claude-sonnet-4-5-20250929、非推奨、レガシーの手動思考のみ) - Claude Haiku 4.5(
claude-haiku-4-5-20251001、レガシーの手動思考のみ)
思考の仕組み
思考がオンの場合、Claudeは内部の推論を出力するthinkingコンテンツブロックを作成します。APIレスポンスにはthinkingコンテンツブロックが含まれ、その後にtextコンテンツブロックが続きます。
import anthropic
client = anthropic.Anthropic()
response = client.messages.create(
model="claude-opus-5-5",
max_tokens=16000,
thinking={"type": "adaptive", "display": "summarized"},
messages=[
{
"role": "user",
"content": "Are there an infinite number of prime numbers such that n mod 4 == 3?",
}
],
)
# レスポンスには要約された思考ブロックとテキストブロックが含まれます
for block in response.content:
match block.type:
case "thinking":
print(f"\nThinking summary: {block.thinking}")
case "text":
print(f"\nResponse: {block.text}")手動の「extended thinking」(拡張思考)(thinking: {"type": "enabled", "budget_tokens": N})はレガシーのメカニズムです。これは思考をサポートするClaude 4から4.6までのモデルでのみ機能します。Claude 4.7以降のモデルはtype: enabledを400エラーで拒否し、代わりに適応型思考を使用します。手動の拡張思考では、budget_tokensはClaudeが内部の推論プロセスに使用できるトークンの最大数を設定します。この制限は要約された出力ではなく、完全な思考トークンに適用されます。インターリーブ思考を使用している場合を除き、思考の完了後にClaudeが応答を書くための余地を確保するため、budget_tokensはmax_tokensより小さくする必要があります。
ツール使用を伴う思考
思考はツール使用と併用でき、Claudeがツールの選択と結果の処理について推論できるようになります。
重要な制限事項:
- ツール選択の制限: 手動の拡張思考(
thinking: {"type": "enabled"})では、tool_choice: {"type": "auto"}(デフォルト)またはtool_choice: {"type": "none"}のみがサポートされます。適応型思考は強制的なツール使用を受け付けますが、ツール使用の強制に記載されているモデルは例外です。受け付けられる場合、強制されたツール呼び出しは思考をスキップします。レスポンスはツール呼び出しから始まり、thinkingブロックは含まれません。 - 思考ブロックの保持: ツール使用中は、最後のアシスタントメッセージの
thinkingブロックをAPIに返す必要があります。
思考ブロックの保持
import anthropic
client = anthropic.Anthropic()
weather_tool = {
"name": "get_weather",
"description": "Get the current weather for a location.",
"input_schema": {
"type": "object",
"properties": {"location": {"type": "string", "description": "The city name."}},
"required": ["location"],
},
}
weather_data = {"temperature": 72}
# 最初のリクエスト - Claude は思考とツールリクエストで応答します
response = client.messages.create(
model="claude-opus-5-5",
max_tokens=16000,
thinking={"type": "adaptive", "display": "summarized"},
tools=[weather_tool],
messages=[{"role": "user", "content": "What's the weather in Paris?"}],
)
# 思考ブロックとツール使用ブロックを抽出します
thinking_block = next(
(block for block in response.content if block.type == "thinking"), None
)
tool_use_block = next(
(block for block in response.content if block.type == "tool_use"), None
)
# 2回目のリクエスト - 思考ブロックとツール結果を含めます
continuation = client.messages.create(
model="claude-opus-5-5",
max_tokens=16000,
thinking={"type": "adaptive", "display": "summarized"},
tools=[weather_tool],
messages=[
{"role": "user", "content": "What's the weather in Paris?"},
# tool_use_block だけでなく thinking_block も渡されている点に注意してください
{"role": "assistant", "content": [thinking_block, tool_use_block]},
{
"role": "user",
"content": [
{
"type": "tool_result",
"tool_use_id": tool_use_block.id,
"content": f"Current temperature: {weather_data['temperature']}°F",
}
],
},
],
)
for block in continuation.content:
if block.type == "text":
print(block.text)インターリーブ思考
「interleaved thinking」(インターリーブ思考)により、Claudeはツール呼び出しの間に思考し、次のステップを決定する前にツールの結果について推論できます。
手動の拡張思考を使用する古いモデル(Claude 4、4.5、およびSonnet 4.6モデル)では、APIリクエストにベータヘッダーinterleaved-thinking-2025-05-14を追加してインターリーブ思考を有効にします:
import anthropic
client = anthropic.Anthropic()
calculator_tool = {
"name": "calculator",
"description": "Perform arithmetic calculations.",
"input_schema": {
"type": "object",
"properties": {
"expression": {
"type": "string",
"description": "The math expression to evaluate.",
}
},
"required": ["expression"],
},
}
database_tool = {
"name": "database_query",
"description": "Query the product database.",
"input_schema": {
"type": "object",
"properties": {
"query": {"type": "string", "description": "The database query."}
},
"required": ["query"],
},
}
response = client.beta.messages.create(
model="claude-sonnet-4-6",
max_tokens=16000,
thinking={"type": "enabled", "budget_tokens": 10000},
tools=[calculator_tool, database_tool],
messages=[
{
"role": "user",
"content": "What's the total revenue if we sold 150 units of product A at $50 each?",
}
],
betas=["interleaved-thinking-2025-05-14"],
)
for block in response.content:
match block.type:
case "thinking":
print(f"Thinking: {block.thinking}")
case "tool_use":
print(f"Tool call: {block.name}({block.input})")
case "text":
print(f"Response: {block.text}")インターリーブ思考の場合に限り(通常の手動の拡張思考ではなく)、budget_tokensはmax_tokensパラメータを超えることができます。この場合のbudget_tokensは、1つのアシスタントターン内のすべての思考ブロックにわたる合計予算を表すためです。
ツール使用
クライアントツールの指定
クライアントツールは、APIリクエストのtoolsトップレベルパラメータで指定します。各ツール定義には以下が含まれます:
| パラメータ | 説明 |
|---|---|
name | ツールの名前。正規表現^[a-zA-Z0-9_-]{1,128}$に一致する必要があります。 |
description | ツールが何をするのか、いつ使用すべきか、どのように動作するのかについての詳細なプレーンテキストの説明。 |
input_schema | ツールに期待されるパラメータを定義するJSON Schemaオブジェクト。 |
{
"name": "get_weather",
"description": "Get the current weather in a given location",
"input_schema": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "The city and state, e.g. San Francisco, CA"
},
"unit": {
"type": "string",
"enum": ["celsius", "fahrenheit"],
"description": "The unit of temperature, either 'celsius' or 'fahrenheit'"
}
},
"required": ["location"]
}
}ツール定義のベストプラクティス
非常に詳細な説明を提供してください。 これはツールのパフォーマンスにおいて圧倒的に最も重要な要素です。説明では、ツールに関するあらゆる詳細を説明する必要があります。これには以下が含まれます:
- ツールが何をするのか
- いつ使用すべきか(そしていつ使用すべきでないか)
- 各パラメータが何を意味し、ツールの動作にどのように影響するか
- 重要な注意事項や制限事項
複雑なツールにはinput_examplesの使用を検討してください。 ネストされたオブジェクト、オプションのパラメータ、または形式に敏感な入力を持つツールの場合、input_examplesフィールド(ベータ)を使用して具体的な例を提供できます。これにより、Claudeに期待される入力パターンを示すことができます。詳細については、ツール使用の例の提供を参照してください。
良いツール説明の例:
{
"name": "get_stock_price",
"description": "Retrieves the current stock price for a given ticker symbol. The ticker symbol must be a valid symbol for a publicly traded company on a major US stock exchange like NYSE or NASDAQ. The tool will return the latest trade price in USD. It should be used when the user asks about the current or most recent price of a specific stock. It will not provide any other information about the stock or company.",
"input_schema": {
"type": "object",
"properties": {
"ticker": {
"type": "string",
"description": "The stock ticker symbol, e.g. AAPL for Apple Inc."
}
},
"required": ["ticker"]
}
}Claudeの出力の制御
ツール使用の強制
tool_choiceフィールドでツールを指定することで、Claudeに特定のツールの使用を強制できます:
tool_choice = {"type": "tool", "name": "get_weather"}tool_choiceパラメータを使用する場合、4つのオプションがあります:
autoは、提供されたツールを呼び出すかどうかをClaudeが判断できるようにします(デフォルト)。anyは、提供されたツールのいずれかを使用しなければならないことをClaudeに伝えます。toolは、Claudeに常に特定のツールを使用するよう強制します。noneは、Claudeがツールを使用することを防ぎます。
Claude Opus 5.5、Claude Sonnet 5.5、Claude Fable 5.1、およびClaude Mythos 5.1では、anyとtoolは400エラーを返します。tool_choiceをautoのままにし、ツール定義で"strict": trueを設定することで、Claudeが行う呼び出しがツールのinput_schemaに一致することを保証できます。厳格なツール使用を参照してください。
JSON出力
ツールは必ずしもクライアント関数である必要はありません。提供されたスキーマに従うJSON出力をモデルに返させたい場合は、いつでもツールを使用できます。
並列ツール使用
デフォルトでは、Claudeはユーザーのクエリに回答するために複数のツールを使用する場合があります。disable_parallel_tool_use=trueを設定することで、この動作を無効にできます。
ツール使用およびツール結果のコンテンツブロックの処理
クライアントツールからの結果の処理
レスポンスにはtool_useのstop_reasonと、以下を含む1つ以上のtool_useコンテンツブロックが含まれます:
id:この特定のツール使用ブロックの一意の識別子。name:使用されているツールの名前。input:ツールに渡される入力を含むオブジェクト。
{
"role": "assistant",
"content": [
{
"type": "tool_use",
"id": "toolu_01A09q90qw90lq917835lq9",
"name": "get_weather",
"input": { "location": "San Francisco, CA" }
}
]
}ツール使用のレスポンスを受け取ったら、次のことを行う必要があります:
tool_useブロックからname、id、inputを抽出します。- そのツール名に対応する実際のツールをコードベースで実行します。
tool_resultを含む新しいメッセージを送信して会話を続けます:
{
"role": "user",
"content": [
{
"type": "tool_result",
"tool_use_id": "toolu_01A09q90qw90lq917835lq9",
"content": "15 degrees"
}
]
}max_tokens停止理由の処理
ツール使用中にmax_tokensの制限に達してClaudeの応答が途中で切れた場合は、より大きなmax_tokens値でリクエストを再試行してください。
pause_turn停止理由の処理
ウェブ検索などのサーバーツールを使用する場合、APIはpause_turn停止理由を返すことがあります。一時停止されたレスポンスを後続のリクエストでそのまま返すことで、会話を続けてください。
エラーのトラブルシューティング
ツール実行エラー
ツール自体が実行中にエラーをスローした場合は、"is_error": trueとともにエラーメッセージを返してください:
{
"role": "user",
"content": [
{
"type": "tool_result",
"tool_use_id": "toolu_01A09q90qw90lq917835lq9",
"content": "ConnectionError: the weather service API is not available (HTTP 500)",
"is_error": true
}
]
}無効なツール名
Claudeが試みたツールの使用が無効な場合(たとえば、必須パラメータが欠落している場合)は、ツール定義のdescription値をより詳細にしてリクエストを再試行してください。
メッセージのストリーミング
Messageを作成する際に、"stream": trueを設定すると、「server-sent events」(サーバー送信イベント)、すなわちSSEを使用してレスポンスを段階的にストリーミングできます。
SDKを使用したストリーミング
import anthropic
client = anthropic.Anthropic()
with client.messages.stream(
max_tokens=1024,
messages=[{"role": "user", "content": "Hello"}],
model="claude-opus-5-5",
) as stream:
for text in stream.text_stream:
print(text, end="", flush=True)イベントタイプ
各サーバー送信イベントには、名前付きのイベントタイプと関連するJSONデータが含まれます。各ストリームは次のイベントフローを使用します:
message_start:空のcontentを持つMessageオブジェクトを含みます。- 一連のコンテンツブロック。それぞれに
content_block_start、1つ以上のcontent_block_deltaイベント、およびcontent_block_stopがあります。 - 最終的な
Messageオブジェクトへのトップレベルの変更を示す1つ以上のmessage_deltaイベント。 - 最後の
message_stopイベント。
警告: message_deltaイベントのusageフィールドに表示されるトークン数は累積です。
コンテンツブロックのデルタタイプ
テキストデルタ
{
"type": "content_block_delta",
"index": 0,
"delta": { "type": "text_delta", "text": "Hello frien" }
}入力JSONデルタ
tool_useコンテンツブロックの場合、デルタは部分的なJSON文字列です:
{"type": "content_block_delta","index": 1,"delta": {"type": "input_json_delta","partial_json": "{\"location\": \"San Fra"}}}思考デルタ
ストリーミングで思考を使用する場合:
{
"type": "content_block_delta",
"index": 0,
"delta": {
"type": "thinking_delta",
"thinking": "Let me solve this step by step..."
}
}基本的なストリーミングリクエストの例
event: message_start
data: {"type": "message_start", "message": {"id": "msg_1nZdL29xx5MUA1yADyHTEsnR8uuvGzszyY", "type": "message", "role": "assistant", "content": [], "model": "claude-opus-5-5", "stop_reason": null, "stop_sequence": null, "usage": {"input_tokens": 25, "output_tokens": 1}}}
event: content_block_start
data: {"type": "content_block_start", "index": 0, "content_block": {"type": "text", "text": ""}}
event: content_block_delta
data: {"type": "content_block_delta", "index": 0, "delta": {"type": "text_delta", "text": "Hello"}}
event: content_block_delta
data: {"type": "content_block_delta", "index": 0, "delta": {"type": "text_delta", "text": "!"}}
event: content_block_stop
data: {"type": "content_block_stop", "index": 0}
event: message_delta
data: {"type": "message_delta", "delta": {"stop_reason": "end_turn", "stop_sequence":null}, "usage": {"output_tokens": 15}}
event: message_stop
data: {"type": "message_stop"}このページは役に立ちましたか?