Menu
CoddyTech

Freigabe und Bericht

Teil des Abschnitts Tools und Agenten der AI Engineering-Journey von Coddy. Lektion 19 von 22.

challenge icon

Aufgabe

Schwer

Eine Buchung gibt das Geld des Reisenden aus, daher muss der Agent zuerst nachfragen. Berichte dann, was der Durchlauf gekostet hat. Behalte alles bei, was du bisher geschrieben hast.

  1. Füge ein Werkzeug namens book_flight mit der Beschreibung Book a seat on a flight to a destination und einer erforderlichen String-Eigenschaft, destination, beschrieben als The destination city, hinzu. Füge es zu TOOLS und zu den Werkzeugen hinzu, die du sendest.
  2. Wenn ein tool_use-Block den Namen book_flight hat, lies eine weitere Eingabezeile nach dem Ausgeben der Tool:-Zeile. Wenn sie yes ist, gib Approved aus und führe das Werkzeug aus. Gib andernfalls Declined aus und sende das Ergebnis The traveller said no to this booking mit "is_error": True, ohne das Werkzeug auszuführen.
  3. Summiere input_tokens und output_tokens über jeden Aufruf hinweg auf, einschließlich des ersten.
  4. Gib am Ende Steps: und die Anzahl der Werkzeug-Runden aus, danach Tokens: <input> in, <output> out mit den Gesamtsummen.

Für die Eingabe Book a flight to Lisbon und yes gibt das Programm zum Beispiel Folgendes aus:

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

Probier es selbst

import coddy_ai as anthropic  # In Produktion: 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()

# Schreibe deinen Code unten
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)

Alle Lektionen in Tools und Agenten

Übe selbstständig: Online-Python-Compiler