モデルの選択

複雑なツールと曖昧なクエリには、最新のClaude Sonnet(4.5)またはClaude Opus(4.1)モデルの使用をお勧めします。これらは複数のツールをより適切に処理し、必要に応じて明確化を求めます。 シンプルなツールにはClaude Haikuモデルを使用してください。ただし、不足しているパラメータを推測する可能性があることに注意してください。
Claude でツール使用と拡張思考を使用する場合は、詳細についてはこちらのガイドを参照してください。

クライアントツールの指定

クライアントツール(Anthropic定義とユーザー定義の両方)は、APIリクエストのtoolsトップレベルパラメータで指定されます。各ツール定義には以下が含まれます:
パラメータ説明
nameツールの名前。正規表現^[a-zA-Z0-9_-]{1,64}$に一致する必要があります。
descriptionツールが何をするか、いつ使用すべきか、どのように動作するかについての詳細なプレーンテキスト説明。
input_schemaツールの予想されるパラメータを定義するJSON Schemaオブジェクト。
JSON
{
  "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"]
  }
}
このツール(get_weatherという名前)は、必須のlocation文字列と、「celsius」または「fahrenheit」のいずれかである必須ではないunit文字列を含む入力オブジェクトを期待します。

ツール使用システムプロンプト

toolsパラメータを使用してClaude APIを呼び出すと、ツール定義、ツール設定、およびユーザー指定のシステムプロンプトから特別なシステムプロンプトが構築されます。構築されたプロンプトは、指定されたツールを使用するようにモデルに指示し、ツールが適切に動作するために必要なコンテキストを提供するように設計されています:
In this environment you have access to a set of tools you can use to answer the user's question.
{{ FORMATTING INSTRUCTIONS }}
String and scalar parameters should be specified as is, while lists and objects should use JSON format. Note that spaces for string values are not stripped. The output is not expected to be valid XML and is parsed with regular expressions.
Here are the functions available in JSONSchema format:
{{ TOOL DEFINITIONS IN JSON SCHEMA }}
{{ USER SYSTEM PROMPT }}
{{ TOOL CONFIGURATION }}

ツール定義のベストプラクティス

Claudeでツールを使用する際に最高のパフォーマンスを得るには、以下のガイドラインに従ってください:
  • 非常に詳細な説明を提供してください。 これはツールのパフォーマンスにおいて最も重要な要素です。説明には、以下を含むツールに関するすべての詳細を説明する必要があります:
    • ツールが何をするか
    • いつ使用すべきか(そしていつ使用すべきでないか)
    • 各パラメータが何を意味し、ツールの動作にどのように影響するか
    • ツール名が不明な場合、ツールが返さない情報など、重要な注意事項や制限事項。Claudeに提供できるコンテキストが多いほど、ツールをいつどのように使用するかを決定するのに役立ちます。ツール説明ごとに少なくとも3~4文を目指し、ツールが複雑な場合はそれ以上を目指してください。
  • 説明を例より優先してください。 ツールの使用方法の例をその説明またはそれに付随するプロンプトに含めることができますが、これはツールの目的とパラメータの明確で包括的な説明を持つことほど重要ではありません。説明を完全に充実させた後にのみ例を追加してください。
JSON
{
  "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"]
  }
}
JSON
{
  "name": "get_stock_price",
  "description": "Gets the stock price for a ticker.",
  "input_schema": {
    "type": "object",
    "properties": {
      "ticker": {
        "type": "string"
      }
    },
    "required": ["ticker"]
  }
}
良い説明は、ツールが何をするか、いつ使用するか、どのデータを返すか、tickerパラメータが何を意味するかを明確に説明しています。不適切な説明は短すぎて、ツールの動作と使用方法についてClaudeに多くの未解決の質問を残します。

ツールランナー(ベータ版)

ツールランナーは、Claudeでツールを実行するためのすぐに使用できるソリューションを提供します。ツール呼び出し、ツール結果、会話管理を手動で処理する代わりに、ツールランナーは自動的に以下を実行します:
  • Claudeがツールを呼び出すときにツールを実行する
  • リクエスト/レスポンスサイクルを処理する
  • 会話状態を管理する
  • 型安全性と検証を提供する
ほとんどのツール使用実装にはツールランナーの使用をお勧めします。
ツールランナーは現在ベータ版であり、PythonおよびTypeScript SDKでのみ利用可能です。

基本的な使用方法

@beta_toolデコレータを使用してツールを定義し、client.beta.messages.tool_runner()を使用してそれらを実行します。
非同期クライアントを使用している場合は、@beta_tool@beta_async_toolに置き換え、関数をasync defで定義してください。
import anthropic
import json
from anthropic import beta_tool

# Initialize client
client = anthropic.Anthropic()

# Define tools using the decorator
@beta_tool
def get_weather(location: str, unit: str = "fahrenheit") -> str:
    """Get the current weather in a given location.

    Args:
        location: The city and state, e.g. San Francisco, CA
        unit: Temperature unit, either 'celsius' or 'fahrenheit'
    """
    # In a full implementation, you'd call a weather API here
    return json.dumps({"temperature": "20°C", "condition": "Sunny"})

@beta_tool
def calculate_sum(a: int, b: int) -> str:
    """Add two numbers together.

    Args:
        a: First number
        b: Second number
    """
    return str(a + b)

# Use the tool runner
with client.beta.messages.tool_runner(
    model="claude-sonnet-4-5",
    max_tokens=1024,
    tools=[get_weather, calculate_sum],
    messages=[
        {"role": "user", "content": "What's the weather like in Paris? Also, what's 15 + 27?"}
    ]
) as runner:
    for message in runner:
        print(message.content[0].text)
デコレートされた関数は、テキスト、画像、またはドキュメントブロックを含むコンテンツブロックまたはコンテンツブロック配列を返す必要があります。これにより、ツールはリッチなマルチモーダルレスポンスを返すことができます。返された文字列はテキストコンテンツブロックに変換されます。 構造化されたJSONオブジェクトをClaudeに返したい場合は、返す前にJSON文字列にエンコードしてください。数値、ブール値、またはその他の非文字列プリミティブも文字列に変換する必要があります。@beta_toolデコレータは関数の引数とdocstringを検査して、指定された関数のJSON スキーマ表現を抽出します。上記の例では、calculate_sumは以下に変換されます:
{
  "name": "calculate_sum",
  "description": "Adds two integers together.",
  "input_schema": {
    "additionalProperties": false,
    "properties": {
      "left": {
        "description": "The first integer to add.",
        "title": "Left",
        "type": "integer"
      },
      "right": {
        "description": "The second integer to add.",
        "title": "Right",
        "type": "integer"
      }
    },
    "required": ["left", "right"],
    "type": "object"
  }
}
SDK ツールランナーはベータ版です。このドキュメントの残りの部分は、手動ツール実装をカバーしています。

Claudeの出力の制御

ツール使用の強制

場合によっては、Claudeが特定のツールを使用してユーザーの質問に答えるようにしたいことがあります。これは、Claudeがツールを使用せずに答えを提供できると考えている場合でも同様です。これは、tool_choiceフィールドでツールを指定することで実行できます:
tool_choice = {"type": "tool", "name": "get_weather"}
tool_choiceパラメータを使用する場合、4つの可能なオプションがあります:
  • autoを使用すると、Claudeは提供されたツールを呼び出すかどうかを決定できます。これはtoolsが提供されるときのデフォルト値です。
  • anyは、Claudeが提供されたツールの1つを使用する必要があることを示していますが、特定のツールを強制しません。
  • toolを使用すると、Claudeが常に特定のツールを使用するように強制できます。
  • noneは、Claudeがツールを使用することを防ぎます。これはtoolsが提供されないときのデフォルト値です。
プロンプトキャッシングを使用する場合、tool_choiceパラメータへの変更はキャッシュされたメッセージブロックを無効にします。ツール定義とシステムプロンプトはキャッシュされたままですが、メッセージコンテンツは再処理される必要があります。
このダイアグラムは、各オプションがどのように機能するかを示しています:
tool_choiceanyまたはtoolの場合、アシスタントメッセージをプリフィルして、ツールの使用を強制することに注意してください。これは、明示的に要求された場合でも、モデルがtool_useコンテンツブロックの前に自然言語応答または説明を発行しないことを意味します。
拡張思考をツール使用と一緒に使用する場合、tool_choice: {"type": "any"}およびtool_choice: {"type": "tool", "name": "..."}はサポートされておらず、エラーが発生します。tool_choice: {"type": "auto"}(デフォルト)およびtool_choice: {"type": "none"}のみが拡張思考と互換性があります。
当社のテストでは、これはパフォーマンスを低下させないことが示されています。モデルが特定のツールの使用を要求しながら、自然言語コンテキストまたは説明を提供するようにしたい場合は、tool_choice{"type": "auto"}(デフォルト)を使用し、userメッセージに明示的な指示を追加できます。例えば:What's the weather like in London? Use the get_weather tool in your response.

JSON出力

ツールは必ずしもクライアント関数である必要はありません。提供されたスキーマに従うJSON出力をモデルに返させたい場合はいつでも、ツールを使用できます。例えば、特定のスキーマを持つrecord_summaryツールを使用する場合があります。完全に機能する例については、Claudeでのツール使用を参照してください。

ツールを使用したモデルレスポンス

ツールを使用する場合、Claudeはしばしば実行している内容についてコメントしたり、ツールを呼び出す前にユーザーに自然に応答したりします。 例えば、プロンプト「サンフランシスコの現在の天気は何ですか、そしてそこの時刻は何ですか?」が与えられた場合、Claudeは以下のように応答する可能性があります:
JSON
{
  "role": "assistant",
  "content": [
    {
      "type": "text",
      "text": "I'll help you check the current weather and time in San Francisco."
    },
    {
      "type": "tool_use",
      "id": "toolu_01A09q90qw90lq917835lq9",
      "name": "get_weather",
      "input": {"location": "San Francisco, CA"}
    }
  ]
}
この自然な応答スタイルは、ユーザーがClaudeが何をしているかを理解するのに役立ち、より会話的なインタラクションを作成します。システムプロンプトを通じてこれらの応答のスタイルとコンテンツをガイドし、プロンプトで<examples>を提供することで、これを行うことができます。 Claudeが実行内容を説明する際にさまざまなフレーズとアプローチを使用する可能性があることに注意することが重要です。コードはこれらの応答を他のアシスタント生成テキストと同様に扱い、特定のフォーマット規則に依存しないようにしてください。

並列ツール使用

デフォルトでは、Claudeはユーザークエリに答えるために複数のツールを使用する場合があります。この動作は以下によって無効にできます:
  • tool_choiceタイプがautoの場合にdisable_parallel_tool_use=trueを設定すると、Claudeが最大1つのツールを使用することが保証されます
  • tool_choiceタイプがanyまたはtoolの場合にdisable_parallel_tool_use=trueを設定すると、Claudeが正確に1つのツールを使用することが保証されます
ツールランナーでより簡単に: 以下の例は手動の並列ツール処理を示しています。ほとんどのユースケースでは、ツールランナーがはるかに少ないコードで並列ツール実行を自動的に処理します。
メッセージ履歴で並列ツール呼び出しを適切にフォーマットする方法を示す完全な例を以下に示します:
import anthropic

client = anthropic.Anthropic()

# Define tools
tools = [
    {
        "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"
                }
            },
            "required": ["location"]
        }
    },
    {
        "name": "get_time",
        "description": "Get the current time in a given timezone",
        "input_schema": {
            "type": "object",
            "properties": {
                "timezone": {
                    "type": "string",
                    "description": "The timezone, e.g. America/New_York"
                }
            },
            "required": ["timezone"]
        }
    }
]

# Initial request
response = client.messages.create(
    model="claude-sonnet-4-5",
    max_tokens=1024,
    tools=tools,
    messages=[
        {
            "role": "user",
            "content": "What's the weather in SF and NYC, and what time is it there?"
        }
    ]
)

# Claude's response with parallel tool calls
print("Claude wants to use tools:", response.stop_reason == "tool_use")
print("Number of tool calls:", len([c for c in response.content if c.type == "tool_use"]))

# Build the conversation with tool results
messages = [
    {
        "role": "user",
        "content": "What's the weather in SF and NYC, and what time is it there?"
    },
    {
        "role": "assistant",
        "content": response.content  # Contains multiple tool_use blocks
    },
    {
        "role": "user",
        "content": [
            {
                "type": "tool_result",
                "tool_use_id": "toolu_01",  # Must match the ID from tool_use
                "content": "San Francisco: 68°F, partly cloudy"
            },
            {
                "type": "tool_result",
                "tool_use_id": "toolu_02",
                "content": "New York: 45°F, clear skies"
            },
            {
                "type": "tool_result",
                "tool_use_id": "toolu_03",
                "content": "San Francisco time: 2:30 PM PST"
            },
            {
                "type": "tool_result",
                "tool_use_id": "toolu_04",
                "content": "New York time: 5:30 PM EST"
            }
        ]
    }
]

# Get final response
final_response = client.messages.create(
    model="claude-sonnet-4-5",
    max_tokens=1024,
    tools=tools,
    messages=messages
)

print(final_response.content[0].text)
並列ツール呼び出しを含むアシスタントメッセージは次のようになります:
{
  "role": "assistant",
  "content": [
    {
      "type": "text",
      "text": "I'll check the weather and time for both San Francisco and New York City."
    },
    {
      "type": "tool_use",
      "id": "toolu_01",
      "name": "get_weather",
      "input": {"location": "San Francisco, CA"}
    },
    {
      "type": "tool_use",
      "id": "toolu_02",
      "name": "get_weather",
      "input": {"location": "New York, NY"}
    },
    {
      "type": "tool_use",
      "id": "toolu_03",
      "name": "get_time",
      "input": {"timezone": "America/Los_Angeles"}
    },
    {
      "type": "tool_use",
      "id": "toolu_04",
      "name": "get_time",
      "input": {"timezone": "America/New_York"}
    }
  ]
}
並列ツール呼び出しが正しく機能していることをテストおよび検証するための完全で実行可能なスクリプトを以下に示します:
#!/usr/bin/env python3
"""Test script to verify parallel tool calls with the Claude API"""

import os
from anthropic import Anthropic

# Initialize client
client = Anthropic(api_key=os.environ.get("ANTHROPIC_API_KEY"))

# Define tools
tools = [
    {
        "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"
                }
            },
            "required": ["location"]
        }
    },
    {
        "name": "get_time",
        "description": "Get the current time in a given timezone",
        "input_schema": {
            "type": "object",
            "properties": {
                "timezone": {
                    "type": "string",
                    "description": "The timezone, e.g. America/New_York"
                }
            },
            "required": ["timezone"]
        }
    }
]

# Test conversation with parallel tool calls
messages = [
    {
        "role": "user",
        "content": "What's the weather in SF and NYC, and what time is it there?"
    }
]

# Make initial request
print("Requesting parallel tool calls...")
response = client.messages.create(
    model="claude-sonnet-4-5",
    max_tokens=1024,
    messages=messages,
    tools=tools
)

# Check for parallel tool calls
tool_uses = [block for block in response.content if block.type == "tool_use"]
print(f"\n✓ Claude made {len(tool_uses)} tool calls")

if len(tool_uses) > 1:
    print("✓ Parallel tool calls detected!")
    for tool in tool_uses:
        print(f"  - {tool.name}: {tool.input}")
else:
    print("✗ No parallel tool calls detected")

# Simulate tool execution and format results correctly
tool_results = []
for tool_use in tool_uses:
    if tool_use.name == "get_weather":
        if "San Francisco" in str(tool_use.input):
            result = "San Francisco: 68°F, partly cloudy"
        else:
            result = "New York: 45°F, clear skies"
    else:  # get_time
        if "Los_Angeles" in str(tool_use.input):
            result = "2:30 PM PST"
        else:
            result = "5:30 PM EST"

    tool_results.append({
        "type": "tool_result",
        "tool_use_id": tool_use.id,
        "content": result
    })

# Continue conversation with tool results
messages.extend([
    {"role": "assistant", "content": response.content},
    {"role": "user", "content": tool_results}  # All results in one message!
])

# Get final response
print("\nGetting final response...")
final_response = client.messages.create(
    model="claude-sonnet-4-5",
    max_tokens=1024,
    messages=messages,
    tools=tools
)

print(f"\nClaude's response:\n{final_response.content[0].text}")

# Verify formatting
print("\n--- Verification ---")
print(f"✓ Tool results sent in single user message: {len(tool_results)} results")
print("✓ No text before tool results in content array")
print("✓ Conversation formatted correctly for future parallel tool use")
このスクリプトは以下を示しています:
  • 並列ツール呼び出しと結果を適切にフォーマットする方法
  • 並列呼び出しが行われていることを検証する方法
  • 将来の並列ツール使用を促進する正しいメッセージ構造
  • 回避すべき一般的な間違い(ツール結果の前のテキストなど)
このスクリプトを実行して実装をテストし、Claudeが並列ツール呼び出しを効果的に行っていることを確認してください。

並列ツール使用の最大化

Claude 4モデルはデフォルトで優れた並列ツール使用機能を備えていますが、ターゲットプロンプティングを使用してすべてのモデル全体で並列ツール実行の可能性を高めることができます:
Claude 4モデル(Opus 4.1、Opus 4、Sonnet 4)の場合、システムプロンプトに以下を追加してください:
For maximum efficiency, whenever you need to perform multiple independent operations, invoke all relevant tools simultaneously rather than sequentially.
さらに強力な並列ツール使用の場合(デフォルトが十分でない場合に推奨)、以下を使用してください:
<use_parallel_tool_calls>
For maximum efficiency, whenever you perform multiple independent operations, invoke all relevant tools simultaneously rather than sequentially. Prioritize calling tools in parallel whenever possible. For example, when reading 3 files, run 3 tool calls in parallel to read all 3 files into context at the same time. When running multiple read-only commands like `ls` or `list_dir`, always run all of the commands in parallel. Err on the side of maximizing parallel tool calls rather than running too many tools sequentially.
</use_parallel_tool_calls>
特定のユーザーメッセージ内で並列ツール使用を促すこともできます:
# Instead of:
"What's the weather in Paris? Also check London."

# Use:
"Check the weather in Paris and London simultaneously."

# Or be explicit:
"Please use parallel tool calls to get the weather for Paris, London, and Tokyo at the same time."
Claude Sonnet 3.7での並列ツール使用Claude Sonnet 3.7は、disable_parallel_tool_useを設定していない場合でも、応答で並列ツール呼び出しを行う可能性が低い場合があります。これを回避するには、トークン効率的なツール使用を有効にすることをお勧めします。これはClaudeが並列ツールを使用するように促すのに役立ちます。このベータ機能は、レイテンシも削減し、平均14%の出力トークンを節約します。トークン効率的なツール使用ベータにオプトインしない場合は、他のツールへの呼び出しを同時にラップできる「バッチツール」として機能するメタツールを導入することもできます。このツールが存在する場合、モデルはそれを使用して複数のツールを同時に並列で呼び出すことがわかっています。このワークアラウンドの使用方法については、クックブックのこの例を参照してください。

ツール使用とツール結果コンテンツブロックの処理

ツールランナーでより簡単に: このセクションで説明されている手動ツール処理は、ツールランナーによって自動的に管理されます。ツール実行をカスタム制御する必要がある場合は、このセクションを使用してください。
Claudeの応答は、クライアントツールまたはサーバーツールを使用するかどうかによって異なります。

クライアントツールからの結果の処理

応答はtool_usestop_reasonと、以下を含む1つ以上のtool_useコンテンツブロックを持ちます:
  • id:この特定のツール使用ブロックの一意の識別子。これは後でツール結果と照合するために使用されます。
  • name:使用されているツールの名前。
  • input:ツールのinput_schemaに準拠するツールに渡される入力を含むオブジェクト。
JSON
{
  "id": "msg_01Aq9w938a90dw8q",
  "model": "claude-sonnet-4-5",
  "stop_reason": "tool_use",
  "role": "assistant",
  "content": [
    {
      "type": "text",
      "text": "I'll check the current weather in San Francisco for you."
    },
    {
      "type": "tool_use",
      "id": "toolu_01A09q90qw90lq917835lq9",
      "name": "get_weather",
      "input": {"location": "San Francisco, CA", "unit": "celsius"}
    }
  ]
}
クライアントツールのツール使用応答を受け取ったら、以下を実行する必要があります:
  1. tool_useブロックからnameidinputを抽出します。
  2. ツール名に対応するコードベースの実際のツールを実行し、ツールinputを渡します。
  3. roleuserで、以下の情報を含むtool_resultタイプのcontentブロックを含む新しいメッセージを送信して会話を続けます:
    • tool_use_id:これが結果であるツール使用リクエストのid
    • content:ツールの結果。文字列(例:"content": "15 degrees")、ネストされたコンテンツブロックのリスト(例:"content": [{"type": "text", "text": "15 degrees"}])、またはドキュメントブロックのリスト(例:"content": ["type": "document", "source": {"type": "text", "media_type": "text/plain", "data": "15 degrees"}])。これらのコンテンツブロックはtextimage、またはdocumentタイプを使用できます。
    • is_error(オプション):ツール実行がエラーで発生した場合はtrueに設定します。
重要なフォーマット要件
  • ツール結果ブロックは、メッセージ履歴内の対応するツール使用ブロックの直後に続く必要があります。アシスタントのツール使用メッセージとユーザーのツール結果メッセージの間にメッセージを含めることはできません。
  • ツール結果を含むユーザーメッセージでは、tool_resultブロックはコンテンツ配列の最初に来る必要があります。テキストはすべてのツール結果の後に来る必要があります。
例えば、これは400エラーを引き起こします:
{"role": "user", "content": [
  {"type": "text", "text": "Here are the results:"},  // ❌ tool_resultの前のテキスト
  {"type": "tool_result", "tool_use_id": "toolu_01", ...}
]}
これは正しいです:
{"role": "user", "content": [
  {"type": "tool_result", "tool_use_id": "toolu_01", ...},
  {"type": "text", "text": "What should I do next?"}  // ✅ tool_resultの後のテキスト
]}
「tool_use ids were found without tool_result blocks immediately after」のようなエラーが表示される場合は、ツール結果が正しくフォーマットされていることを確認してください。
JSON
{
  "role": "user",
  "content": [
    {
      "type": "tool_result",
      "tool_use_id": "toolu_01A09q90qw90lq917835lq9",
      "content": "15 degrees"
    }
  ]
}
JSON
{
  "role": "user",
  "content": [
    {
      "type": "tool_result",
      "tool_use_id": "toolu_01A09q90qw90lq917835lq9",
      "content": [
        {"type": "text", "text": "15 degrees"},
        {
          "type": "image",
          "source": {
            "type": "base64",
            "media_type": "image/jpeg",
            "data": "/9j/4AAQSkZJRg...",
          }
        }
      ]
    }
  ]
}
JSON
{
  "role": "user",
  "content": [
    {
      "type": "tool_result",
      "tool_use_id": "toolu_01A09q90qw90lq917835lq9",
    }
  ]
}
JSON
{
  "role": "user",
  "content": [
    {
      "type": "tool_result",
      "tool_use_id": "toolu_01A09q90qw90lq917835lq9",
      "content": [
        {"type": "text", "text": "The weather is"},
        {
          "type": "document",
          "source": {
            "type": "text",
            "media_type": "text/plain",
            "data": "15 degrees"
          }
        }
      ]
    }
  ]
}
ツール結果を受け取った後、Claudeはその情報を使用して元のユーザープロンプトへの応答を生成し続けます。

サーバーツールからの結果の処理

Claudeはツールを内部で実行し、追加のユーザーインタラクションを必要とせずに結果を応答に直接組み込みます。
他のAPIとの違いツール使用を分離するか、toolまたはfunctionのような特別なロールを使用するAPIとは異なり、Claude APIはツールをuserおよびassistantメッセージ構造に直接統合します。メッセージにはtextimagetool_usetool_resultブロックの配列が含まれます。userメッセージにはクライアントコンテンツとtool_resultが含まれ、assistantメッセージにはAI生成コンテンツとtool_useが含まれます。

max_tokens停止理由の処理

Claudeのmax_tokens制限に達したため応答が切り取られた場合、切り取られた応答に不完全なツール使用ブロックが含まれている場合は、完全なツール使用を取得するために、より高いmax_tokens値でリクエストを再試行する必要があります。
# Check if response was truncated during tool use
if response.stop_reason == "max_tokens":
    # Check if the last content block is an incomplete tool_use
    last_block = response.content[-1]
    if last_block.type == "tool_use":
        # Send the request with higher max_tokens
        response = client.messages.create(
            model="claude-sonnet-4-5",
            max_tokens=4096,  # Increased limit
            messages=messages,
            tools=tools
        )

pause_turn停止理由の処理

Webサーチなどのサーバーツールを使用する場合、APIはpause_turn停止理由を返す可能性があり、APIが長時間実行されているターンを一時停止したことを示します。 pause_turn停止理由を処理する方法は以下の通りです:
import anthropic

client = anthropic.Anthropic()

# Initial request with web search
response = client.messages.create(
    model="claude-3-7-sonnet-latest",
    max_tokens=1024,
    messages=[
        {
            "role": "user",
            "content": "Search for comprehensive information about quantum computing breakthroughs in 2025"
        }
    ],
    tools=[{
        "type": "web_search_20250305",
        "name": "web_search",
        "max_uses": 10
    }]
)

# Check if the response has pause_turn stop reason
if response.stop_reason == "pause_turn":
    # Continue the conversation with the paused content
    messages = [
        {"role": "user", "content": "Search for comprehensive information about quantum computing breakthroughs in 2025"},
        {"role": "assistant", "content": response.content}
    ]

    # Send the continuation request
    continuation = client.messages.create(
        model="claude-3-7-sonnet-latest",
        max_tokens=1024,
        messages=messages,
        tools=[{
            "type": "web_search_20250305",
            "name": "web_search",
            "max_uses": 10
        }]
    )

    print(continuation)
else:
    print(response)
pause_turnを処理する場合:
  • 会話を続ける:一時停止された応答を後続のリクエストでそのまま渡して、Claudeがそのターンを続行できるようにします
  • 必要に応じて変更:会話を中断またはリダイレクトしたい場合は、オプションで続行する前にコンテンツを変更できます
  • ツール状態を保持:機能を維持するために、継続リクエストに同じツールを含めます

エラーのトラブルシューティング

組み込みエラーハンドリング: ツールランナーは、ほとんどの一般的なシナリオに対して自動エラーハンドリングを提供します。このセクションでは、高度なユースケースのための手動エラーハンドリングについて説明します。
Claudeでツールを使用する場合、いくつかの異なるタイプのエラーが発生する可能性があります:
ツール自体が実行中にエラーをスローする場合(例:天気データを取得する際のネットワークエラー)、contentと一緒に"is_error": trueでエラーメッセージを返すことができます:
JSON
{
  "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はこのエラーをユーザーへの応答に組み込みます。例えば、「申し訳ありませんが、天気サービスAPIが利用できないため、現在の天気を取得できませんでした。後でもう一度お試しください。」
Claudeがツールの使用を試みるのが無効な場合(例:必須パラメータが不足している)、通常はClaudeがツールを正しく使用するための情報が不足していることを意味します。開発中の最善の方法は、ツール定義のdescription値をより詳細にしてリクエストを再度試行することです。ただし、エラーを示すtool_resultで会話を続行することもでき、Claudeは不足している情報を入力してツールを再度使用しようとします:
JSON
{
  "role": "user",
  "content": [
    {
      "type": "tool_result",
      "tool_use_id": "toolu_01A09q90qw90lq917835lq9",
      "content": "Error: Missing required 'location' parameter",
      "is_error": true
    }
  ]
}
ツールリクエストが無効または不足しているパラメータがある場合、Claudeは修正を試みて2~3回再試行してからユーザーに謝罪します。
Claudeが<search_quality_reflection>タグで検索品質を反映するのを防ぐには、プロンプトに「Do not reflect on the quality of the returned search results in your response」を追加してください。
サーバーツールがエラーに遭遇した場合(例:Webサーチのネットワーク問題)、Claudeはこれらのエラーを透過的に処理し、ユーザーに代替応答または説明を提供しようとします。クライアントツールとは異なり、サーバーツールのis_error結果を処理する必要はありません。Webサーチの場合、可能なエラーコードは以下を含みます:
  • too_many_requests:レート制限を超過
  • invalid_input:無効な検索クエリパラメータ
  • max_uses_exceeded:最大Webサーチツール使用数を超過
  • query_too_long:クエリが最大長を超過
  • unavailable:内部エラーが発生
Claudeが予想される場合に並列ツール呼び出しを行っていない場合は、これらの一般的な問題を確認してください:1. 不正なツール結果フォーマット最も一般的な問題は、会話履歴でツール結果を不正にフォーマットすることです。これはClaudeに並列呼び出しを回避するように「教える」ものです。特に並列ツール使用の場合:
  • 間違い:各ツール結果に対して個別のユーザーメッセージを送信する
  • 正しい:すべてのツール結果は単一のユーザーメッセージに含まれる必要があります
// ❌ これは並列ツール使用を減らします
[
  {"role": "assistant", "content": [tool_use_1, tool_use_2]},
  {"role": "user", "content": [tool_result_1]},
  {"role": "user", "content": [tool_result_2]}  // 別のメッセージ
]

// ✅ これは並列ツール使用を維持します
[
  {"role": "assistant", "content": [tool_use_1, tool_use_2]},
  {"role": "user", "content": [tool_result_1, tool_result_2]}  // 単一のメッセージ
]
その他のフォーマット規則については、上記の一般的なフォーマット要件を参照してください。2. 弱いプロンプティングデフォルトプロンプティングは十分でない場合があります。より強力な言語を使用してください:
<use_parallel_tool_calls>
For maximum efficiency, whenever you perform multiple independent operations,
invoke all relevant tools simultaneously rather than sequentially.
Prioritize calling tools in parallel whenever possible.
</use_parallel_tool_calls>
3. 並列ツール使用の測定並列ツール呼び出しが機能していることを確認するには:
# Calculate average tools per tool-calling message
tool_call_messages = [msg for msg in messages if any(
    block.type == "tool_use" for block in msg.content
)]
total_tool_calls = sum(
    len([b for b in msg.content if b.type == "tool_use"])
    for msg in tool_call_messages
)
avg_tools_per_message = total_tool_calls / len(tool_call_messages)
print(f"Average tools per message: {avg_tools_per_message}")
# Should be > 1.0 if parallel calls are working
4. モデル固有の動作
  • Claude Opus 4.1、Opus 4、Sonnet 4:最小限のプロンプティングで並列ツール使用に優れています
  • Claude Sonnet 3.7:より強力なプロンプティングまたはトークン効率的なツール使用が必要な場合があります
  • Claude Haiku:明示的なプロンプティングなしで並列ツールを使用する可能性が低い