ツールの定義
CoddyのAI Engineeringジャーニー「ツールとエージェント」セクションの一部。レッスン 1/22。
モデルはテキストを出力することしかできません。モデルに情報を調べさせたりアクションを実行させたりするには、ツールを提供します。ツールとは、モデルが実行を要求する可能性のあるプログラム内の関数です。各ツールは名前、説明、および引数のJSONスキーマであるinput_schemaで定義し、そのリストをtoolsとして渡します。
time_tool = {
"name": "get_time",
"description": "Get the current local time in a city",
"input_schema": {
"type": "object",
"properties": {"city": {"type": "string"}},
"required": ["city"],
},
}
response = client.messages.create(model="claude-opus-5-5", max_tokens=300,
tools=[time_tool], messages=[{"role": "user", "content": "What time is it in Lima?"}])
print(response.stop_reason)
print(response.content[0].name, response.content[0].input)これは tool_use、次に get_time {'city': 'Lima'} を出力します。
モデルは何も実行していません。選択したツールと引数を指定した tool_use ブロックと、停止理由 "tool_use" で応答しました。質問にツールが不要な場合はテキストで回答し、"end_turn" で停止するため、ツール呼び出しを読み取る前に確認してください。
チャレンジ
簡単モデルに天気ツールを提供し、要求された内容を出力してください。
- 名前が
get_weather、説明がGet the current weather for a city、必須の文字列プロパティcityを1つ持つツールを定義します。 tools=[...]、model="claude-opus-5-5"、およびmax_tokens=300を指定して質問を送信します。Stop:と停止理由を出力します。- typeが
"tool_use"であるすべてのブロックについて、Tool:、ツールの名前、スペース、およびその入力を出力します。
例えば、入力が What is the weather in Oslo? の場合、プログラムは以下のように出力します:
Stop: tool_use
Tool: get_weather {'city': 'Oslo'}天気を必要としない質問の場合、停止行のみを出力します。
自分で試してみよう
import coddy_ai as anthropic # 本番環境では: import anthropic
client = anthropic.Anthropic()
question = input()
# 1. 名前が "get_weather"、説明が "Get the current weather for a city" のツールを定義します
# かつ、必須の文字列プロパティ "city" を1つ持たせます。
# 2. tools=[...]、model="claude-opus-5-5"、max_tokens=300 を指定して質問を送信します。
# 3. "Stop: " と停止理由を出力し、すべての tool_use ブロックに対して "Tool: <name> <input>" を出力します。
このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。
ツールとエージェントのすべてのレッスン
自分で練習してみよう: Pythonオンラインコンパイラ