ゲスト
📢 PR Claude Opus 4.7 公開! 新機能・破壊的変更・移行手順を 5 分で確認 →

Claude マスターレッスン / Level 5 — API / レッスン 5-3

Level 5 — API

Tool Use(関数呼び出し)

所要時間: 10分  |  更新: 2026-04-24

Tool Use(関数呼び出し)

要約 — このレッスンの要点

  • Tool Use とは、Claude がユーザー定義の外部関数を呼び出せる仕組み。Claude が判断し、実行はアプリ側が行うという役割分担が基本。
  • ツールは JSON Schema で定義する。name / description / input_schema の 3 項目が必須。
  • Claude が tool_use を返したら、アプリ側で関数を実行して結果を tool_result として送り返す。この往復を agentic loop と呼ぶ。
  • Anthropic 提供のサーバーサイドツール(web_search 等)は Anthropic 側で実行されるため、agentic loop の実装が不要。
  • コード例は出典を一次情報とする。

Tool Use の仕組み

Claude はテキスト生成に特化した言語モデルです。しかし Tool Use を使うと、 Claude がリアルタイムのデータ取得・計算・外部サービスへの操作を「依頼」できます。 実際の処理はアプリ側が担い、Claude は「何をいつ呼ぶか」を判断する役割を担います 出典

ツール定義(JSON Schema)

ツールは tools パラメータに配列で渡します。 各ツールの input_schema は JSON Schema 形式で記述します 出典

# ツール定義の例(Python)
tools = [
    {
        "name": "get_weather",
        "description": "指定した都市の現在の天気を取得します。",
        "input_schema": {
            "type": "object",
            "properties": {
                "location": {
                    "type": "string",
                    "description": "都市名。例: Tokyo, Japan"
                },
                "unit": {
                    "type": "string",
                    "enum": ["celsius", "fahrenheit"],
                    "description": "温度単位"
                }
            },
            "required": ["location"]
        }
    }
]

Python — 最小コード例

以下は公式ドキュメントのコード例に準拠した構成です 出典

import anthropic

client = anthropic.Anthropic()

response = client.messages.create(
    model="claude-opus-4-7",
    max_tokens=1024,
    tools=tools,  # 上記で定義したツール
    messages=[{"role": "user", "content": "東京の天気を教えてください"}]
)

# stop_reason が "tool_use" のとき Claude がツール呼び出しを要求している
print(response.stop_reason)   # => "tool_use"
print(response.content)       # => tool_use ブロックを含む配列

agentic loop の流れ

Tool Use を使う場合の基本的なやりとりは以下の順序です。

  1. アプリがツール定義を添えて Claude にリクエスト送信
  2. Claude が stop_reason: "tool_use"tool_use ブロックを返す
  3. アプリが tool_usenameinput を読み取り、対応する関数を実行
  4. 実行結果を tool_result としてメッセージ配列に追加して再度 API に送信
  5. Claude が最終的な回答テキストを生成して返す

詳細な実装手順は出典を参照してください。

tool_choice でツール使用を制御する

tool_choice パラメータで Claude のツール選択を制御できます。

  • "auto"(デフォルト) — Claude がツールを使うかどうかを判断する
  • "any" — 提供されたツールのいずれかを必ず使う
  • "tool" + "name" — 指定したツールを必ず使う
  • "none" — ツールを使わない

ツール設計のポイント

description は Claude がツールをいつ使うかを判断する最大の根拠です。 「何をするか」「いつ使うべきか」「何を返すか」を 3〜4 文以上で丁寧に書くと、 精度が大幅に向上します 出典

さらに深く読む