Menu
CoddyTech

エージェントループの実行

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

challenge icon

チャレンジ

中級

エージェントがホテルも検索できるようにし、モデルがツールの要求を停止するまで処理を継続させます。これまでに作成したコードはそのまま残してください。

  1. 名前が find_hotel で、説明が Find a hotel room in a city with its nightly rate、必須の文字列プロパティ city(説明: The city to stay in)を持つツールを追加します。
  2. TOOLS = {"search_flights": search_flights, "find_hotel": find_hotel} を追加し、毎回の呼び出しで両方のツールを送信します。
  3. 単一の追加の呼び出しをループに置き換えます。response.stop_reason が "tool_use" である間、各 tool_use ブロックに対して Tool: の行を出力し、TOOLS が指定する関数をブロックの入力とともに実行し、すべての結果を1つのユーザーメッセージとして送り返し、再度モデルを呼び出します。
  4. ループの後に、Agent: とテキストブロックのテキストを出力します。

例えば、入力 Find a flight to Rome and a hotel in Lisbon に対して、プログラムは以下を出力します:

Tool: search_flights {'destination': 'Rome'}
Tool: find_hotel {'city': 'Lisbon'}
Agent: Here is what I found:
- Flight to Rome: 95 dollars
- Hotel in Lisbon: 80 dollars a night

モデルは1つのレスポンスで両方のツールを要求したため、両方の結果が1つのユーザーメッセージで送り返されます。

自分で試してみよう

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

client = anthropic.Anthropic()

FLIGHTS = {"Lisbon": 120, "Rome": 95, "Tokyo": 640, "Oslo": None}
HOTELS = {"Lisbon": 80, "Rome": 110, "Tokyo": 150, "Oslo": 130}


def search_flights(destination):
    if destination not in FLIGHTS:
        raise ValueError(f"No flights to {destination}")
    if FLIGHTS[destination] is None:
        raise ConnectionError("The flight service is temporarily unavailable, try again")
    return f"Flight to {destination}: {FLIGHTS[destination]} dollars"


def find_hotel(city):
    if city not in HOTELS:
        raise ValueError(f"No hotels in {city}")
    return f"Hotel in {city}: {HOTELS[city]} dollars a night"


def book_flight(destination):
    return f"Booked a seat to {destination} for {FLIGHTS[destination]} dollars"


request = input()

# 以下にコードを記述してください
flight_tool = {
    "name": "search_flights",
    "description": "Search flights to a destination and give the ticket price",
    "input_schema": {
        "type": "object",
        "properties": {"destination": {"type": "string", "description": "The destination city"}},
        "required": ["destination"],
    },
}

messages = [{"role": "user", "content": request}]
response = client.messages.create(model="claude-opus-5-5", max_tokens=500, tools=[flight_tool], messages=messages)

results = []
for block in response.content:
    if block.type == "tool_use":
        print(f"Tool: {block.name} {block.input}")
        result = search_flights(block.input["destination"])
        results.append({"type": "tool_result", "tool_use_id": block.id, "content": result})
messages.append({"role": "assistant", "content": response.content})
messages.append({"role": "user", "content": results})

response = client.messages.create(model="claude-opus-5-5", max_tokens=500, tools=[flight_tool], messages=messages)
for block in response.content:
    if block.type == "text":
        print("Agent: " + block.text)

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

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