Menu
CoddyTech

並列ツール呼び出し

CoddyのAI Engineeringジャーニー「ツールとエージェント」セクションの一部。レッスン 7/22。

リクエストに複数の独立した質問が含まれている場合、モデルは1つのレスポンスですべてのツール呼び出しを要求します。各呼び出しは、独自の id を持った個別の tool_use ブロックとなります:

messages = [{"role": "user", "content": "Look up the opening hours for Luna Cafe and Mango House"}]
response = client.messages.create(model="claude-opus-5-5", max_tokens=500, tools=TOOLS, messages=messages)
calls = [block for block in response.content if block.type == "tool_use"]
for block in calls:
    print(block.name, block.input)

これにより、2行が出力されます: get_hours {'place': 'Luna Cafe'} と get_hours {'place': 'Mango House'}。

すべての呼び出しを実行し、すべての結果をまとめて送り返します。各呼び出しにつき1つのtool_resultを含むリストをコンテンツに持つ、1つのユーザーメッセージとして送信します。APIはこれをチェックします。ツール呼び出しの直後のメッセージに、いずれかのIDの結果が含まれていない場合、リクエストは400エラーで失敗するため、結果1つごとに1つのメッセージを送信するループは、2つの呼び出しが発生した時点ですぐに破綻します。結果をまとめて送信することで、一度に複数の呼び出しを依頼し続けてよいことをモデルに示すこともでき、毎回ラウンドトリップを削減できます。

challenge icon

チャレンジ

中級

スターターコードのウェザーエージェントは、2つの都市について質問されたときに動作しなくなります。各結果を個別のメッセージで送信してしまうためです。ループ内の部分を修正してください。

  1. レスポンスのtool_useブロックを収集し、Calls: と呼び出しの数を出力します。
  2. それぞれに対してget_weatherを実行し、すべてのtool_resultを1つのリストに入れます。
  3. そのリストを単一のユーザーメッセージとして追加します。

プログラムの残りの部分はそのままにしてください。例えば、入力What is the weather in Oslo and Lima?に対して、プログラムは以下のように出力します:

Calls: 2
Answer: Here is what I found:
- Oslo: 4 C and rainy
- Lima: 19 C and misty

自分で試してみよう

import coddy_ai as anthropic  # 本番環境: import anthropic

client = anthropic.Anthropic()

WEATHER = {
    "Paris": "18 C and sunny",
    "Tokyo": "22 C and cloudy",
    "Rome": "25 C and sunny",
    "Oslo": "4 C and rainy",
    "Cairo": "31 C and clear",
    "Lima": "19 C and misty",
}


def get_weather(city):
    return f"{city}: {WEATHER.get(city, 'no data')}"


TOOLS = [
    {
        "name": "get_weather",
        "description": "Get the current weather for a city",
        "input_schema": {
            "type": "object",
            "properties": {"city": {"type": "string", "description": "The city name"}},
            "required": ["city"],
        },
    }
]

request = input()
messages = [{"role": "user", "content": request}]

response = client.messages.create(model="claude-opus-5-5", max_tokens=500, tools=TOOLS, messages=messages)
while response.stop_reason == "tool_use":
    messages.append({"role": "assistant", "content": response.content})
    # この部分を修正: "Calls: " とこのレスポンス内のツール呼び出しの数を表示し、
    # すべての結果を1つのユーザーメッセージで送信します
    for block in response.content:
        if block.type == "tool_use":
            result = {"type": "tool_result", "tool_use_id": block.id, "content": get_weather(**block.input)}
            messages.append({"role": "user", "content": [result]})
    response = client.messages.create(model="claude-opus-5-5", max_tokens=500, tools=TOOLS, messages=messages)

for block in response.content:
    if block.type == "text":
        print("Answer: " + block.text)
quiz icon腕試し

このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。

ツールとエージェントのすべてのレッスン

自分で練習してみよう: Pythonオンラインコンパイラ