Tool Use (ツール使用)
LLM 単体では計算・検索・DB アクセス・API 呼び出しが苦手です。 Tool Use はモデルに 「関数」を定義して渡し、必要なら呼び出してもらう 仕組み。 別名 Function Calling。
流れ
- ユーザーが質問する。
- モデルがツールを呼ぶ必要があるか判断 →
tool_useブロックを返す。 - アプリ側で実際に関数を実行し、結果を
tool_resultとして返す。 - モデルが最終回答を生成する。
User : 東京の天気は?
Claude : 🛠 get_weather(city="Tokyo") を呼びたい
App : ✅ 実行して結果を渡す → {"temp": 22, "rain": false}
Claude : 東京は気温22℃で雨は降っていません。
コード例
tools = [{
"name": "get_weather",
"description": "指定都市の天気を取得します",
"input_schema": {
"type": "object",
"properties": {
"city": {"type": "string", "description": "都市名 (例: Tokyo)"},
},
"required": ["city"],
},
}]
resp = client.messages.create(
model="claude-sonnet-4-6",
max_tokens=1024,
tools=tools,
messages=[{"role": "user", "content": "東京の天気は?"}],
)
if resp.stop_reason == "tool_use":
tu = next(b for b in resp.content if b.type == "tool_use")
result = real_get_weather(tu.input["city"])
# tool_result を含む新しいリクエスト
resp2 = client.messages.create(
model="claude-sonnet-4-6",
max_tokens=1024,
tools=tools,
messages=[
{"role": "user", "content": "東京の天気は?"},
{"role": "assistant", "content": resp.content},
{"role": "user", "content": [{
"type": "tool_result",
"tool_use_id": tu.id,
"content": str(result),
}]},
],
)
print(resp2.content[0].text)
設計のコツ
- description が命。ツールが何をするか明確に書く (Claude のツール選択判断はここに依存)。
- input_schema は JSON Schema。
requiredも明記する。 - 副作用のあるツール (送金等) は人間の確認を挟む設計に。
- 多すぎるツール は精度を落とす。10 個以上なら絞り込むか、上位ツールでルーティングする。
Parallel Tool Use
Claude は 複数のツールを同時に呼ぶ ことができます。 独立した関数なら並列実行で高速化できます。
[tool_use: get_weather(Tokyo)]
[tool_use: get_weather(Osaka)]
これらを並列に実行 → 両方の tool_result をまとめて返すと効率的。
tool_choice で制御
tools=[...],
tool_choice={"type": "tool", "name": "get_weather"}, # 強制
# tool_choice={"type": "any"} # ツールのいずれかを必ず使う
# tool_choice={"type": "auto"} # デフォルト (使うかどうか自動判断)
よく使う応用
- DB クエリ実行 (read-only から始める)
- 検索エンジン呼び出し (Web Search)
- 計算実行 (Python REPL)
- GitHub API, Slack 投稿 などの社内連携
試す: ツール定義を Claude に書かせる
最初の設計を Claude に手伝ってもらうと早いです。
▶ ツール JSON Schema 設計依頼
「会議室予約システム」用の Tool Use 定義 JSON Schema を、書き込み(reserve)・読み取り(list_rooms, get_availability) の 3 つで設計してください。各ツールに description と input_schema を含めて、JSON で返してください。