Lỗi và giới hạn
Thuộc phần Công cụ và agent trong hành trình AI Engineering của Coddy. Bài học 18 trên 22.
Thử thách
KhóMột chuyến đi thực tế có thể gặp phải các thành phố không có thông tin hoặc các dịch vụ bị ngừng hoạt động. Hãy làm cho agent xử lý được cả hai trường hợp này. Giữ nguyên tất cả những gì bạn đã viết cho đến nay.
- Chạy từng tool bên trong
try. Khi nó tạo ra ngoại lệ (exception), gửi mộttool_resultcó nội dung là thông điệp của lỗi (str(error)) cùng với"is_error": True, để mô hình có thể đọc được điều gì đã gặp sự cố. - Thêm
MAX_STEPS = 5và đếm số lượt gọi tool trongsteps. Trước khi chạy một lượt, dừng vòng lặp (loop) khistepsđã bằngMAX_STEPS. - Sau vòng lặp, nếu mô hình vẫn muốn dùng tool, in ra
Stopped after 5 steps(sử dụngMAX_STEPS); nếu không, in ra dòngAgent:như trước.
Dịch vụ chuyến bay cho Oslo trả về lỗi yêu cầu thử lại, vì vậy mô hình sẽ liên tục thử lại. Ví dụ: với đầu vào Find a flight to Oslo, chương trình sẽ in ra:
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 stepsVới Find a flight to Paris, một thành phố không có chuyến bay nào, chương trình sẽ in ra:
Tool: search_flights {'destination': 'Paris'}
Agent: Sorry, I could not finish: No flights to ParisTự làm thử
import coddy_ai as anthropic # trong môi trường thực tế: 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()
# Viết code ở bên dưới
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)
Tất cả bài học trong Công cụ và agent
Tự luyện tập: Trình biên dịch Python online