Claude Platform Docs
  • メッセージ
  • マネージドエージェント
  • 管理

Search...
⌘K

Log in
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Claude Platform Docs

Solutions

  • AI agents
  • Code modernization
  • Coding
  • Customer support
  • Education
  • Financial services
  • Government
  • Life sciences

Partners

  • Claude on AWS
  • Claude on Google Cloud

Learn

  • Blog
  • Courses
  • Use cases
  • Connectors
  • Customer stories
  • Engineering at Anthropic
  • Events
  • Powered by Claude
  • Service partners
  • Startups program

Company

  • Anthropic
  • Careers
  • Economic Futures
  • Research
  • News
  • Responsible Scaling Policy
  • Security and compliance
  • Transparency

Learn

  • Blog
  • Courses
  • Use cases
  • Connectors
  • Customer stories
  • Engineering at Anthropic
  • Events
  • Powered by Claude
  • Service partners
  • Startups program

Help and security

  • Availability
  • Status
  • Support
  • Discord

Terms and policies

  • Privacy policy
  • Responsible disclosure policy
  • Terms of service: Commercial
  • Terms of service: Consumer
  • Usage policy
Documentation

Claude向けAPI使用入門

このガイドは、ClaudeにClaude APIの基本的な使い方を伝えることを目的としています。モデルID、基本的なMessages API、ツール使用、ストリーミング、拡張思考についての説明と例を提供し、それ以外の内容は含みません。

Claude向けAPI使用入門

このガイドは、ClaudeにClaude APIの基本的な使い方を伝えることを目的としています。モデルID、基本的なMessages API、ツール使用、ストリーミング、拡張思考についての説明と例を提供し、それ以外の内容は含みません。

モデル

Smartest model: Claude Opus 4.8: claude-opus-4-8
Smart model: Claude Sonnet 4.6: claude-sonnet-4-6
For fast, cost-effective tasks: Claude Haiku 4.5: claude-haiku-4-5-20251001

APIの呼び出し

基本的なリクエストとレスポンス

import anthropic
import os

message = anthropic.Anthropic(
    api_key=os.environ.get("ANTHROPIC_API_KEY")
).messages.create(
    model="claude-opus-4-8",
    max_tokens=1024,
    messages=[{"role": "user", "content": "Hello, Claude"}],
)
print(message)
Output
{
  "id": "msg_01XFDUDYJgAACzvnptvVoYEL",
  "type": "message",
  "role": "assistant",
  "content": [
    {
      "type": "text",
      "text": "Hello!"
    }
  ],
  "model": "claude-opus-4-8",
  "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-8",
    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の応答の一部を事前に入力できます。これを使用して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 ("},
    ],
)
print(message.content[0].text)

ビジョン

Claudeはリクエスト内のテキストと画像の両方を読み取ることができます。画像にはbase64とurlの両方のソースタイプがサポートされており、image/jpeg、image/png、image/gif、image/webpのメディアタイプに対応しています。

拡張思考

「extended thinking」(拡張思考)は、非常に難しいタスクにおいてClaudeを支援できる場合があります。Claude Opus 4.7より前のモデルでは、拡張思考を有効にする場合、temperatureを1に設定する必要があります。

拡張思考は以下のモデルでサポートされています。

  • Claude Opus 4.8(claude-opus-4-8、適応型思考のみ)
  • Claude Opus 4.7(claude-opus-4-7)
  • Claude Opus 4.6(claude-opus-4-6)
  • Claude Opus 4.5(claude-opus-4-5-20251101)
  • Claude Sonnet 4.6(claude-sonnet-4-6)
  • Claude Sonnet 4.5(claude-sonnet-4-5-20250929)
  • Claude Haiku 4.5(claude-haiku-4-5-20251001)


Claude Opus 4.8およびClaude Opus 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-4-8",
    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}")

手動の拡張思考(type: enabled)を使用する場合、budget_tokensパラメータは、Claudeが内部推論プロセスに使用できるトークンの最大数を決定します。Claude 4以降のモデルでは、この制限は要約された出力ではなく、完全な思考トークンに適用されます。予算を大きくすると、複雑な問題に対してより徹底的な分析が可能になり、応答の品質が向上する場合があります。インターリーブ思考を使用していない限り、思考が完了した後にClaudeが応答を書くためのスペースを確保するため、budget_tokensはmax_tokensより小さくする必要があります。

ツール使用を伴う拡張思考

拡張思考はツール使用と併用でき、Claudeがツールの選択と結果の処理について推論できるようになります。

重要な制限事項:

  1. ツール選択の制限: tool_choice: {"type": "auto"}(デフォルト)またはtool_choice: {"type": "none"}のみをサポートします。
  2. 思考ブロックの保持: ツール使用中は、最後のアシスタントメッセージのthinkingブロックをAPIに返す必要があります。

思考ブロックの保持

インターリーブ思考

Claude 4モデルでのツール使用を伴う拡張思考は、「interleaved thinking」(インターリーブ思考)をサポートしており、Claudeがツール呼び出しの間に思考できるようになります。Claude 4、4.5、およびSonnet 4.6モデルで有効にするには、APIリクエストにベータヘッダーinterleaved-thinking-2025-05-14を追加してください。

インターリーブ思考の場合、かつインターリーブ思考の場合のみ(通常の拡張思考ではなく)、budget_tokensはmax_tokensパラメータを超えることができます。この場合のbudget_tokensは、1つのアシスタントターン内のすべての思考ブロックにわたる合計予算を表すためです。



Claude Opus 4.8、Claude Opus 4.7、および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"]
  }
}

Claudeの出力の制御

ツール使用の強制

tool_choiceフィールドでツールを指定することで、Claudeに特定のツールの使用を強制できます。

tool_choice = {"type": "tool", "name": "get_weather"}

tool_choiceパラメータを使用する場合、4つのオプションがあります。

  • autoは、提供されたツールを呼び出すかどうかをClaudeに判断させます(デフォルト)。
  • anyは、提供されたツールのいずれかを使用する必要があることをClaudeに伝えます。
  • toolは、Claudeに常に特定のツールを使用するよう強制します。
  • noneは、Claudeがツールを使用することを防ぎます。

JSON出力

ツールは必ずしもクライアント関数である必要はありません。提供されたスキーマに従うJSON出力をモデルに返させたい場合はいつでも、ツールを使用できます。

思考の連鎖

ツールを使用する際、Claudeは多くの場合「chain of thought」(思考の連鎖)、つまり問題を分解してどのツールを使用するかを決定するために使用する段階的な推論を示します。

{
  "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:ツールに渡される入力を含むオブジェクト。

ツール使用レスポンスを受け取ったら、以下を行う必要があります。

  1. tool_useブロックからname、id、inputを抽出します。
  2. そのツール名に対応するコードベース内の実際のツールを実行します。
  3. 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でのストリーミング

イベントタイプ

各サーバー送信イベントには、名前付きのイベントタイプと関連するJSONデータが含まれます。各ストリームは以下のイベントフローを使用します。

  1. message_start:空のcontentを持つMessageオブジェクトを含みます。
  2. 一連のコンテンツブロック。それぞれにcontent_block_start、1つ以上のcontent_block_deltaイベント、およびcontent_block_stopがあります。
  3. 最終的なMessageオブジェクトへのトップレベルの変更を示す、1つ以上のmessage_deltaイベント。
  4. 最後の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-4-8", "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?

  • モデル
  • APIの呼び出し
  • 基本的なリクエストとレスポンス
  • 複数の会話ターン
  • Claudeの発言を事前に設定する
  • ビジョン
  • 拡張思考
  • 拡張思考の仕組み
  • ツール使用を伴う拡張思考
  • 思考ブロックの保持
  • インターリーブ思考
  • ツール使用
  • クライアントツールの指定
  • ツール定義のベストプラクティス
  • Claudeの出力の制御
  • ツール使用の強制
  • JSON出力
  • 思考の連鎖
  • 並列ツール使用
  • ツール使用とツール結果コンテンツブロックの処理
  • クライアントツールからの結果の処理
  • max_tokens停止理由の処理
  • pause_turn停止理由の処理
  • エラーのトラブルシューティング
  • ツール実行エラー
  • 無効なツール名
  • ストリーミングメッセージ
  • SDKでのストリーミング
  • イベントタイプ
  • コンテンツブロックデルタタイプ
  • 基本的なストリーミングリクエストの例
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-4-8",
    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(message.content[0].text)

# オプション2:URLで参照される画像
message_from_url = anthropic.Anthropic().messages.create(
    model="claude-opus-4-8",
    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(message_from_url.content[0].text)
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-4-8",
    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-4-8",
    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)
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}")
import anthropic

client = anthropic.Anthropic()

with client.messages.stream(
    max_tokens=1024,
    messages=[{"role": "user", "content": "Hello"}],
    model="claude-opus-4-8",
) as stream:
    for text in stream.text_stream:
        print(text, end="", flush=True)