このガイドは、Claude APIの基本的な使用方法をClaudeに教えるために設計されています。モデルID/基本的なメッセージAPI、ツール使用、ストリーミング、拡張思考の説明と例を提供し、それ以外は何もありません。
最も高性能なモデル: Claude Opus 4.7: claude-opus-4-7
高性能モデル: Claude Sonnet 4.6: claude-sonnet-4-6
高速で費用効果的なタスク向け: 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-4-7",
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-4-7",
"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-4-7",
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から単一の多肢選択回答を取得します。
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 ("},
],
)Claudeはリクエストでテキストと画像の両方を読むことができます。画像にはbase64とurlソースタイプの両方がサポートされており、image/jpeg、image/png、image/gif、およびimage/webpメディアタイプがサポートされています。
拡張思考は、Claudeが非常に難しいタスクを実行するのに役立つことがあります。Claude Opus 4.7より前のモデルでは、拡張思考が有効な場合、温度を1に設定する必要があります。
拡張思考は以下のモデルでサポートされています:
claude-opus-4-1-20250805)claude-opus-4-20250514)claude-sonnet-4-6)claude-sonnet-4-5-20250929)拡張思考がオンになると、Claudeは内部推論を出力するthinkingコンテンツブロックを作成します。APIレスポンスにはthinkingコンテンツブロックが含まれ、その後にtextコンテンツブロックが続きます。
import anthropic
client = anthropic.Anthropic()
response = client.messages.create(
model="claude-opus-4-7",
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?",
}
],
)
# The response will contain summarized thinking blocks and text blocks
for block in response.content:
if block.type == "thinking":
print(f"\nThinking summary: {block.thinking}")
elif block.type == "text":
print(f"\nResponse: {block.text}")budget_tokensパラメータは、Claudeが内部推論プロセスに使用できるトークンの最大数を決定します。Claude 4モデルでは、この制限は完全な思考トークンに適用され、要約された出力には適用されません。より大きな予算は、複雑な問題に対してより徹底的な分析を可能にすることで、レスポンスの品質を向上させることができます。1つのルール: max_tokensの値はbudget_tokensの値より厳密に大きくなければならないため、Claudeは思考が完了した後にレスポンスを書く余地があります。
拡張思考はツール使用と一緒に使用でき、Claudeがツール選択と結果処理を推論できます。
重要な制限事項:
tool_choice: {"type": "auto"} (デフォルト) または tool_choice: {"type": "none"} のみをサポートします。thinkingブロックをAPIに渡す必要があります。Claude 4モデルでのツール使用を伴う拡張思考は、インターリーブされた思考をサポートしており、Claudeがツール呼び出し間で考えることができます。Claude 4、4.5、およびSonnet 4.6モデルで有効にするには、ベータヘッダーinterleaved-thinking-2025-05-14をAPIリクエストに追加します。
インターリーブされた思考を使用する場合、そしてインターリーブされた思考のみを使用する場合(通常の拡張思考ではない)、budget_tokensはmax_tokensパラメータを超えることができます。この場合、budget_tokensは1つのアシスタントターン内のすべての思考ブロック全体の総予算を表します。
Claude Opus 4.6の場合、インターリーブされた思考は適応的思考(thinking: {type: "adaptive"})を使用する場合に自動的に有効になります。ベータヘッダーは不要です。Sonnet 4.6は、手動拡張思考と適応的思考の両方でinterleaved-thinking-2025-05-14ベータヘッダーをサポートしています。
クライアントツールは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が提供されたツールの1つを使用する必要があることを示します。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停止理由の処理ツール使用中にmax_tokens制限に達したためにClaudeのレスポンスが切断された場合、より高いmax_tokens値でリクエストを再試行します。
pause_turn停止理由の処理Webサーチなどのサーバーツールを使用する場合、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を設定して、サーバー送信イベント(SSE)を使用してレスポンスを段階的にストリーミングできます。
各サーバー送信イベントには、名前付きイベントタイプと関連するJSONデータが含まれます。各ストリームは以下のイベントフローを使用します:
message_start: 空のcontentを持つMessageオブジェクトを含みます。content_block_start、1つ以上のcontent_block_deltaイベント、およびcontent_block_stopを持ちます。message_deltaイベント。最終的なMessageオブジェクトへのトップレベルの変更を示します。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-4-7", "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?
import anthropic
import base64
import httpx
# Option 1: Base64-encoded image
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-4-7",
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?"},
],
}
],
)
# Option 2: URL-referenced image
message_from_url = anthropic.Anthropic().messages.create(
model="claude-opus-4-7",
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?"},
],
}
],
)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}
# First request - Claude responds with thinking and tool request
response = client.messages.create(
model="claude-opus-4-7",
max_tokens=16000,
thinking={"type": "adaptive", "display": "summarized"},
tools=[weather_tool],
messages=[{"role": "user", "content": "What's the weather in Paris?"}],
)
# Extract thinking block and tool use block
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
)
# Second request - Include thinking block and tool result
continuation = client.messages.create(
model="claude-opus-4-7",
max_tokens=16000,
thinking={"type": "adaptive", "display": "summarized"},
tools=[weather_tool],
messages=[
{"role": "user", "content": "What's the weather in Paris?"},
# Notice that the thinking_block is passed in as well as the 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",
}
],
},
],
)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"],
)import anthropic
client = anthropic.Anthropic()
with client.messages.stream(
max_tokens=1024,
messages=[{"role": "user", "content": "Hello"}],
model="claude-opus-4-7",
) as stream:
for text in stream.text_stream:
print(text, end="", flush=True)