Menu
CoddyTech

错误与限制

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

challenge icon

挑战

困难

实际的旅行规划中可能会遇到未包含的城市或服务宕机的情况。请让智能体在这两种情况下都能正常应对。保留你之前编写的所有代码。

  1. 在 try 块中运行每个工具。当抛出异常时,发送一个 tool_result,其内容为错误的字符串信息(str(error)),并带有 "is_error": True,以便模型能够查看哪里出了问题。
  2. 添加 MAX_STEPS = 5 并用 steps 记录工具调用的轮数。在运行每一轮之前,当 steps 已经等于 MAX_STEPS 时停止循环。
  3. 循环结束后,如果模型仍然需要使用工具,打印 Stopped after 5 steps(使用 MAX_STEPS);否则像之前一样打印 Agent: 行。

针对 Oslo 的航班服务返回了一个提示重试的错误,因此模型会持续重试。例如,对于输入 Find a flight to Oslo,程序会输出:

Tool: search_flights {'destination': 'Oslo'}
Tool: search_flights {'destination': 'Oslo'}
Tool: search_flights {'destination': 'Oslo'}
Tool: search_flights {'destination': 'Oslo'}
Tool: search_flights {'destination': 'Oslo'}
Stopped after 5 steps

对于没有航班的城市,如输入 Find a flight to Paris,程序会输出:

Tool: search_flights {'destination': 'Paris'}
Agent: Sorry, I could not finish: No flights to Paris

亲手试试

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"],
    },
}

hotel_tool = {
    "name": "find_hotel",
    "description": "Find a hotel room in a city with its nightly rate",
    "input_schema": {
        "type": "object",
        "properties": {"city": {"type": "string", "description": "The city to stay in"}},
        "required": ["city"],
    },
}

TOOLS = {"search_flights": search_flights, "find_hotel": find_hotel}
tools = [flight_tool, hotel_tool]

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":
    results = []
    for block in response.content:
        if block.type == "tool_use":
            print(f"Tool: {block.name} {block.input}")
            result = TOOLS[block.name](**block.input)
            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=tools, messages=messages)

for block in response.content:
    if block.type == "text":
        print("Agent: " + block.text)

工具与 Agent中的所有课

自己练习: Python 在线编译器