Menu
CoddyTech

智能体循环运行

本课属于 Coddy AI Engineering 学习旅程的“工具与 Agent”单元。第 17 课,共 22 课。

challenge icon

挑战

中等

让 Agent 也搜索酒店,并持续运行,直到模型不再要求使用工具。保留你目前为止编写的所有代码。

  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 名称对应的函数并传入该块的输入,在一条用户消息中发回所有结果,并再次调用模型。
  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

模型在一次响应中请求了这两个工具,因此这两个结果会在一条用户消息中发回。

亲手试试

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)

工具与 Agent中的所有课

自己练习: Python 在线编译器