このガイドは、ClaudeにClaude APIの基本を伝えるために設計されています。モデルID/基本的なMessages API、ツール使用、ストリーミング、思考の説明と例を提供し、それ以外は含みません。
For complex agentic coding and enterprise work: Claude Opus 5: claude-opus-5
Previous Opus model: Claude Opus 4.8: claude-opus-4-8
Smart model: Claude Sonnet 5: claude-sonnet-5
For fast, cost-effective tasks: Claude Haiku 4.5: claude-haiku-4-5-20251001import anthropic
import os
message = anthropic.Anthropic(
api_key=os.environ.get("ANTHROPIC_API_KEY")
).messages.create(
model="claude-opus-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",
"stop_reason": "end_turn",
"stop_sequence": null,
"usage": {
"input_tokens": 12,
"output_tokens": 6
}
}Messages APIはステートレスです。つまり、常に完全な会話履歴をAPIに送信します。このパターンを使用して、時間をかけて会話を構築できます。以前の会話ターンは、必ずしも実際にClaudeから生成されたものである必要はありません。合成のassistantメッセージを使用できます。
import anthropic
message = anthropic.Anthropic().messages.create(
model="claude-opus-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の応答を形作ることができます。次の例では、"max_tokens": 1を使用して、Claudeから単一の多肢選択式の回答を取得します。
Claude 4.6以降のモデルおよびClaude Mythos Previewは、アシスタントメッセージのプレフィルをサポートしていません。これらのモデルへのリクエストは、ユーザーメッセージで終わる必要があります。以下の例では、プレフィルをサポートするモデルを使用しています。
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 httpx
# オプション1: Base64エンコードされた画像
image_url = "https://upload.wikimedia.org/wikipedia/commons/a/a7/Camponotus_flavomarginatus_ant.jpg"
image_media_type = "image/jpeg"
image_data = base64.standard_b64encode(httpx.get(image_url).content).decode("utf-8")
message = anthropic.Anthropic().messages.create(
model="claude-opus-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",
max_tokens=1024,
messages=[
{
"role": "user",
"content": [
{
"type": "image",
"source": {
"type": "url",
"url": "https://upload.wikimedia.org/wikipedia/commons/a/a7/Camponotus_flavomarginatus_ant.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を助けることがあります。現在のメカニズムは適応的思考(thinking: {"type": "adaptive"})です。Claudeがいつ、どれだけ思考するかを決定し、トークン予算ではなくeffortパラメータで思考の深さを調整します。適応的思考は、Claude 4.6以降のモデルおよびClaude Mythos Previewでサポートされています。Claude 5モデルおよびClaude Mythos Previewでは、thinkingパラメータが省略された場合、思考はデフォルトでオンになります。
すべてのモデルにおいて、思考が有効な場合は温度を1に設定する(または未設定のままにする)必要があります。Claude 4.7以降のモデルおよびClaude Mythos Previewでは、temperatureは非推奨であり、思考がオフの場合でもデフォルト値のみが受け入れられます。
思考は以下のモデルでサポートされています。
claude-sonnet-5、適応的思考のみ、デフォルトでオン)claude-opus-4-7、適応的思考のみ)claude-opus-4-6、適応的思考またはレガシーの手動思考)claude-sonnet-4-6、適応的思考またはレガシーの手動思考)claude-opus-4-5-20251101、レガシーの手動思考のみ)claude-sonnet-4-5-20250929、レガシーの手動思考のみ)claude-haiku-4-5-20251001、レガシーの手動思考のみ)Claude 4.7以降のモデルでは、手動の拡張思考(budget_tokens値を伴うtype: enabled)はサポートされておらず、400エラーを返します。代わりに適応的思考(type: adaptive)を使用してください。
思考がオンの場合、Claudeは内部の推論を出力するthinkingコンテンツブロックを作成します。APIレスポンスにはthinkingコンテンツブロックが含まれ、その後にtextコンテンツブロックが続きます。
import anthropic
client = anthropic.Anthropic()
response = client.messages.create(
model="claude-opus-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:
if block.type == "thinking":
print(f"\nThinking summary: {block.thinking}")
elif block.type == "text":
print(f"\nResponse: {block.text}")手動の拡張思考(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がツールの選択と結果の処理について推論できるようになります。
重要な制限事項:
tool_choice: {"type": "auto"}(デフォルト)またはtool_choice: {"type": "none"}のみをサポートします。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",
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",
max_tokens=16000,
thinking={"type": "adaptive", "display": "summarized"},
tools=[weather_tool],
messages=[
{"role": "user", "content": "What's the weather in Paris?"},
# thinking_blockとtool_use_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)インターリーブ思考により、Claudeはツール呼び出しの間に思考し、次のステップを決定する前にツールの結果について推論できます。
適応的思考(thinking: {type: "adaptive"})を備えたモデルでは、インターリーブ思考は自動的に有効になります。ベータヘッダーは不要です。Sonnet 4.6は、手動の拡張思考を伴うinterleaved-thinking-2025-05-14ベータヘッダーと適応的思考の両方をサポートしています。
手動の拡張思考を使用する古いモデル(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:
if block.type == "thinking":
print(f"Thinking: {block.thinking}")
elif block.type == "tool_use":
print(f"Tool call: {block.name}({block.input})")
elif block.type == "text":
print(f"Response: {block.text}")インターリーブ思考を使用する場合、かつインターリーブ思考の場合のみ(通常の手動の拡張思考ではなく)、budget_tokensはmax_tokensパラメータを超えることができます。この場合のbudget_tokensは、1つのアシスタントターン内のすべての思考ブロックにわたる合計予算を表すためです。
クライアントツールは、APIリクエストのtoolsトップレベルパラメータで指定します。各ツール定義には以下が含まれます。
| パラメータ | 説明 |
|---|---|
name | ツールの名前。正規表現^[a-zA-Z0-9_-]{1,64}$に一致する必要があります。 |
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"]
}
}tool_choiceフィールドでツールを指定することで、Claudeに特定のツールの使用を強制できます。
tool_choice = {"type": "tool", "name": "get_weather"}tool_choiceパラメータを使用する場合、4つのオプションがあります。
autoは、提供されたツールを呼び出すかどうかをClaudeが決定できるようにします(デフォルト)。anyは、提供されたツールのいずれかを使用しなければならないことをClaudeに伝えます。toolは、Claudeに常に特定のツールを使用させます。noneは、Claudeがツールを使用することを防ぎます。ツールは必ずしもクライアント関数である必要はありません。提供されたスキーマに従うJSON出力をモデルに返させたい場合はいつでもツールを使用できます。
ツールを使用する際、Claudeはしばしば「思考の連鎖」、つまり問題を分解してどのツールを使用するかを決定するために使用する段階的な推論を示します。
{
"role": "assistant",
"content": [
{
"type": "text",
"text": "<thinking>To answer this question, I will: 1. Use the get_weather tool to get the current weather in San Francisco. 2. Use the get_time tool to get the current time in the America/Los_Angeles timezone, which covers San Francisco, CA.</thinking>"
},
{
"type": "tool_use",
"id": "toolu_01A09q90qw90lq917835lq9",
"name": "get_weather",
"input": { "location": "San Francisco, CA" }
}
]
}デフォルトでは、Claudeはユーザーのクエリに答えるために複数のツールを使用する場合があります。disable_parallel_tool_use=trueを設定することで、この動作を無効にできます。
レスポンスにはtool_useのstop_reasonと、以下を含む1つ以上のtool_useコンテンツブロックがあります。
id: この特定のツール使用ブロックの一意の識別子。name: 使用されているツールの名前。input: ツールに渡される入力を含むオブジェクト。ツール使用レスポンスを受け取ったら、次のことを行う必要があります。
tool_useブロックからname、id、inputを抽出します。tool_resultを含む新しいメッセージを送信して会話を続けます。{
"role": "user",
"content": [
{
"type": "tool_result",
"tool_use_id": "toolu_01A09q90qw90lq917835lq9",
"content": "15 degrees"
}
]
}max_tokens停止理由の処理ツール使用中にClaudeの応答がmax_tokensの制限に達して途切れた場合は、より大きな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値をより詳細にしてリクエストを再試行してください。
メッセージを作成する際、"stream": trueを設定すると、「server-sent events」(サーバー送信イベント)、すなわちSSEを使用してレスポンスを段階的にストリーミングできます。
import anthropic
client = anthropic.Anthropic()
with client.messages.stream(
max_tokens=1024,
messages=[{"role": "user", "content": "Hello"}],
model="claude-opus-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" }
}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", "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"}Was this page helpful?