Vòng lặp agent hoạt động
Thuộc phần Công cụ và agent trong hành trình AI Engineering của Coddy. Bài học 17 trên 22.
Thử thách
Trung bìnhCho phép agent tìm kiếm cả khách sạn nữa, và tiếp tục cho đến khi mô hình ngừng yêu cầu công cụ. Giữ nguyên mọi thứ bạn đã viết cho đến nay.
- Thêm một công cụ tên là
find_hotelvới mô tảFind a hotel room in a city with its nightly ratevà một thuộc tính chuỗi (string) bắt buộc,city, được mô tả làThe city to stay in. - Thêm
TOOLS = {"search_flights": search_flights, "find_hotel": find_hotel}và gửi cả hai công cụ trong mỗi lần gọi. - Thay thế lần gọi bổ sung duy nhất bằng một vòng lặp (loop): trong khi
response.stop_reasonlà"tool_use", in ra dòngTool:cho mỗi khối (block)tool_use, chạy hàm màTOOLSđặt tên với đầu vào của khối, gửi tất cả kết quả trở lại trong một tin nhắn user, và gọi lại mô hình. - Sau vòng lặp, in ra
Agent:và nội dung của khối text.
Ví dụ, với đầu vào Find a flight to Rome and a hotel in Lisbon chương trình sẽ in ra:
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 nightMô hình đã yêu cầu cả hai công cụ trong một phản hồi, vì vậy cả hai kết quả được gửi lại trong một tin nhắn user.
Tự 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"],
},
}
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)
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