Menu
CoddyTech

Errores y límites

Parte de la sección Herramientas y agentes del Journey de AI Engineering de Coddy. Lección 18 de 22.

challenge icon

Desafío

Difícil

Un viaje real se topa con ciudades que faltan y servicios caídos. Haz que el agente sobreviva a ambos. Mantén todo lo que has escrito hasta ahora.

  1. Ejecuta cada herramienta dentro de try. Cuando lance una excepción, envía un tool_result cuyo contenido sea el mensaje de error (str(error)) con "is_error": True, para que el modelo pueda leer qué salió mal.
  2. Añade MAX_STEPS = 5 y cuenta las rondas de llamadas a herramientas en steps. Antes de ejecutar una ronda, detén el bucle cuando steps ya sea igual a MAX_STEPS.
  3. Después del bucle, si el modelo todavía quiere una herramienta, imprime Stopped after 5 steps (usa MAX_STEPS); de lo contrario, imprime la línea con Agent: como antes.

El servicio de vuelos para Oslo responde con un error que dice que lo intente de nuevo, por lo que el modelo sigue reintentándolo. Por ejemplo, para la entrada Find a flight to Oslo el programa imprime:

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

Para Find a flight to Paris, una ciudad sin vuelos, imprime:

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

Pruébalo tú mismo

import coddy_ai as anthropic  # en producción: 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()

# Escribe tu código a continuación
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)

Todas las lecciones de Herramientas y agentes

Practica por tu cuenta: Compilador de Python online