Menu
CoddyTech

Phê duyệt và báo cáo

Thuộc phần Công cụ và agent trong hành trình AI Engineering của Coddy. Bài học 19 trên 22.

challenge icon

Thử thách

Khó

Việc đặt vé sẽ tốn tiền của hành khách, vì vậy agent phải hỏi ý kiến trước. Sau đó báo cáo chi phí chạy. Giữ nguyên tất cả những gì bạn đã viết cho đến nay.

  1. Thêm một công cụ có tên book_flight với mô tả Book a seat on a flight to a destination và một thuộc tính chuỗi bắt buộc, destination, được mô tả là The destination city. Thêm công cụ đó vào TOOLS và vào danh sách công cụ mà bạn gửi.
  2. Khi một khối tool_use gọi book_flight, hãy đọc thêm một dòng đầu vào sau khi in dòng Tool: của nó. Nếu dòng đó là yes, in Approved và chạy công cụ. Nếu không, in Declined và gửi kết quả The traveller said no to this booking với "is_error": True mà không chạy công cụ.
  3. Cộng tổng input_tokens và output_tokens qua mọi cuộc gọi, bao gồm cả cuộc gọi đầu tiên.
  4. Ở cuối, in Steps: và số vòng lặp công cụ, sau đó in Tokens: <input> in, <output> out cùng với các giá trị tổng.

Ví dụ, với đầu vào Book a flight to Lisbon và yes, chương trình sẽ in ra:

Tool: book_flight {'destination': 'Lisbon'}
Approved
Agent: Here is what I found: Booked a seat to Lisbon for 120 dollars
Steps: 1
Tokens: 658 in, 35 out

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

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]
MAX_STEPS = 5

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

steps = 0
while response.stop_reason == "tool_use":
    if steps == MAX_STEPS:
        break
    steps += 1
    results = []
    for block in response.content:
        if block.type == "tool_use":
            print(f"Tool: {block.name} {block.input}")
            try:
                result = TOOLS[block.name](**block.input)
                results.append({"type": "tool_result", "tool_use_id": block.id, "content": result})
            except Exception as error:
                results.append({"type": "tool_result", "tool_use_id": block.id, "content": str(error), "is_error": True})
    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)

if response.stop_reason == "tool_use":
    print(f"Stopped after {MAX_STEPS} steps")
else:
    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