ツール結果の返却
CoddyのAI Engineeringジャーニー「ツールとエージェント」セクションの一部。レッスン 3/22。
ツールを実行した後も、モデルが回答するにはその結果を確認する必要があります。会話に2つのターンを追加して再度呼び出します。モデルのcontent全体(ツール呼び出しを含む)を持つassistantターン、そしてtool_resultブロックを含むuserターンです。ブロックのtool_use_idは呼び出しのidであり、そのcontentは関数が返した結果です。
messages.append({"role": "assistant", "content": response.content})
messages.append({
"role": "user",
"content": [{"type": "tool_result", "tool_use_id": call.id, "content": "Lima: 14:05"}],
})
final = client.messages.create(model="claude-opus-5-5", max_tokens=300, tools=tools, messages=messages)同じ tools を再度送信します。モデルが別の呼び出しを必要とする可能性があるためです。APIはペアリングをチェックします。次のメッセージに tool_result がない tool_use や、どの呼び出しの id にも一致しない結果は、BadRequestError で拒否されます。スタンドインはその結果をもとに Here is what I found: ... と回答しますが、実際のモデルはその周りに独自の文章を作成します。
チャレンジ
中級ラウンドトリップを完了させます:ツールを実行し、その結果を返信して、モデルの回答を出力します。スターターコードは質問を送信し、ツール呼び出しを call に保持しています。
- 呼び出しの input から
dayを使用してget_opening_hoursを呼び出し、Result:とその戻り値を出力します。 response.contentを保持する assistant ターンを追加し、次にコンテンツがその結果であるcall.idのtool_resultブロックを1つ持つ user ターンを追加します。- 同じ model、
max_tokens、tools、messages を使用して、再度モデルを呼び出します。 Answer:と text ブロックのテキストを出力します。
例えば、入力が When are you open on Saturday? の場合、プログラムは次のように出力します:
Result: Saturday: 10 am to 4 pm
Answer: Here is what I found: Saturday: 10 am to 4 pm自分で試してみよう
import coddy_ai as anthropic # 本番環境: import anthropic
client = anthropic.Anthropic()
HOURS = {"monday": "9 am to 6 pm", "friday": "9 am to 8 pm", "saturday": "10 am to 4 pm", "sunday": "closed"}
def get_opening_hours(day):
return f"{day}: {HOURS.get(day.lower(), '9 am to 6 pm')}"
hours_tool = {
"name": "get_opening_hours",
"description": "Get the shop's opening hours for a day of the week",
"input_schema": {
"type": "object",
"properties": {"day": {"type": "string", "description": "A day of the week"}},
"required": ["day"],
},
}
question = input()
messages = [{"role": "user", "content": question}]
response = client.messages.create(model="claude-opus-5-5", max_tokens=300, tools=[hours_tool], messages=messages)
call = next(block for block in response.content if block.type == "tool_use")
# 1. ツールを実行し、"Result: " とその返り値を表示する。
# 2. assistantのターンを追加し、次にtool_resultを含むuserのターンを追加する。
# 3. 同じツールを使用して再度問い合わせを行い、"Answer: " と返答のテキストを表示する。
このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。
ツールとエージェントのすべてのレッスン
自分で練習してみよう: Pythonオンラインコンパイラ