Loading...
  • ビルド
  • 管理
  • モデルと料金
  • クライアントSDK
  • APIリファレンス
Search...
⌘K
Log in
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...

Solutions

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

Partners

  • Amazon Bedrock
  • Google Cloud's Vertex AI

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 APIの基本的な使用方法をClaudeに教えるために設計されています。モデルID/基本的なメッセージAPI、ツール使用、ストリーミング、拡張思考の説明と例を提供し、それ以外は何もありません。

Claude向けAPI使用入門

このガイドは、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-20251001

APIの呼び出し

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

import 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)
Output
{
  "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のレスポンスの一部を事前入力できます。これは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 (claude-opus-4-1-20250805)
  • Claude Opus 4 (非推奨) (claude-opus-4-20250514)
  • Claude Sonnet 4.6 (claude-sonnet-4-6)
  • Claude Sonnet 4.5 (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がツール選択と結果処理を推論できます。

重要な制限事項:

  1. ツール選択の制限: tool_choice: {"type": "auto"} (デフォルト) または tool_choice: {"type": "none"} のみをサポートします。
  2. 思考ブロックの保持: ツール使用中に、最後のアシスタントメッセージの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"]
  }
}

Claudeの出力の制御

ツール使用の強制

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

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

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

  • autoはClaudeが提供されたツールを呼び出すかどうかを決定することを許可します(デフォルト)。
  • anyはClaudeが提供されたツールの1つを使用する必要があることを示します。
  • toolはClaudeに常に特定のツールを使用するよう強制します。
  • noneはClaudeがツールを使用することを防止します。

JSON出力

ツールは必ずしもクライアント関数である必要はありません。モデルが提供されたスキーマに従う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: ツールに渡される入力を含むオブジェクト。

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

  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停止理由の処理

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)を使用してレスポンスを段階的にストリーミングできます。

SDKを使用したストリーミング

イベントタイプ

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

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

  • APIの呼び出し
  • Claudeの口に言葉を入れる
  • Claudeの出力の制御
  • JSON出力
  • max_tokens停止理由の処理
  • pause_turn停止理由の処理
  • SDKを使用したストリーミング
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)