Menu
CoddyTech

Fehler und Limits

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

challenge icon

Aufgabe

Schwer

Bei einer echten Reise trifft man auf fehlende Städte und Dienste, die nicht erreichbar sind. Sorge dafür, dass der Agent beides übersteht. Behalte alles bei, was du bisher geschrieben hast.

  1. Führe jedes Tool innerhalb von try aus. Wenn dabei eine Exception ausgelöst wird, sende ein tool_result, dessen Inhalt die Fehlermeldung (str(error)) mit "is_error": True ist, damit das Modell lesen kann, was schiefgelaufen ist.
  2. Füge MAX_STEPS = 5 hinzu und zähle die Runden der Tool-Aufrufe in steps. Beende die Schleife vor dem Ausführen einer Runde, wenn steps bereits gleich MAX_STEPS ist.
  3. Wenn das Modell nach der Schleife immer noch ein Tool verwenden möchte, gib Stopped after 5 steps aus (verwende MAX_STEPS); andernfalls gib die Zeile Agent: wie zuvor aus.

Der Flugdienst für Oslo antwortet mit einem Fehler, der besagt, dass es erneut versucht werden soll, sodass das Modell es weiterhin versucht. Für die Eingabe Find a flight to Oslo gibt das Programm beispielsweise Folgendes aus:

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

Für Find a flight to Paris, eine Stadt ohne Flüge, gibt es Folgendes aus:

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

Probier es selbst

import coddy_ai as anthropic  # In der 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]

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)

Alle Lektionen in Tools und Agenten

Übe selbstständig: Online-Python-Compiler