Menu
CoddyTech

Błędy i limity

Część sekcji Narzędzia i agenci ścieżki AI Engineering w Coddy. Lekcja 18 z 22.

challenge icon

Wyzwanie

Trudny

Prawdziwa podróż napotyka brakujące miasta i niedostępne usługi. Spraw, aby agent poradził sobie z obiema sytuacjami. Zachowaj wszystko, co zostało napisane do tej pory.

  1. Uruchom każde narzędzie wewnątrz try. Gdy zgłosi wyjątek, wyślij tool_result, którego zawartością jest komunikat błędu (str(error)) z "is_error": True, aby model mógł przeczytać, co poszło nie tak.
  2. Dodaj MAX_STEPS = 5 i zliczaj rundy wywołań narzędzi w steps. Przed uruchomieniem rundy zatrzymaj pętlę, gdy steps jest już równe MAX_STEPS.
  3. Po pętli, jeśli model nadal chce użyć narzędzia, wypisz Stopped after 5 steps (użyj MAX_STEPS); w przeciwnym razie wypisz wiersz Agent: tak jak wcześniej.

Usługa lotnicza dla Oslo odpowiada błędem informującym, aby spróbować ponownie, więc model wciąż ponawia próby. Na przykład dla danych wejściowych Find a flight to Oslo program wypisuje:

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

Dla Find a flight to Paris, miasta bez lotów, wypisuje:

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

Spróbuj swoich sił

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

# Napisz swój kod poniżej
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)

Wszystkie lekcje w sekcji Narzędzia i agenci

Poćwicz samodzielnie: Kompilator Python online