Menu
CoddyTech

Repaso: Asistente de compras

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

challenge icon

Desafío

Difícil

Construye el bucle de agente del asistente de la tienda. El código inicial define dos herramientas, las funciones detrás de ellas en FUNCTIONS, MAX_STEPS y el primer mensaje. Ambas funciones lanzan ValueError para un producto desconocido, y check_stock lanza TimeoutError cuando el sistema de almacén no está disponible.

  1. Escribe run_tool(block): ejecuta FUNCTIONS[block.name](**block.input) y devuelve su tool_result. Captura ValueError y TimeoutError y devuelve un resultado de error con el mensaje y "is_error": True. Imprime Tool: <name> <input> -> <output> para un resultado, o Tool: <name> <input> -> error: <message> para un error.
  2. Llama al modelo (model="claude-opus-5-5", max_tokens=500, tools=TOOLS) y haz un bucle mientras solicite herramientas: añade el turno del asistente, envía todos los resultados en un solo mensaje de usuario y vuelve a llamar.
  3. Detén el bucle cuando haya llamado al modelo MAX_STEPS veces, y después imprime Stopped: no answer after 4 steps.
  4. Imprime Answer: y el texto final cuando haya uno, después Steps: y el número de llamadas.

Por ejemplo, para la entrada Check stock for the desk lamp and the price of the desk lamp el programa imprime:

Tool: check_stock {'product': 'desk lamp'} -> desk lamp: 12 in stock
Tool: get_price {'item': 'desk lamp'} -> desk lamp: 40 dollars
Answer: Here is what I found:
- desk lamp: 12 in stock
- desk lamp: 40 dollars
Steps: 2

Pruébalo tú mismo

import coddy_ai as anthropic  # en producción: import anthropic

client = anthropic.Anthropic()

MAX_STEPS = 4
STOCK = {"desk lamp": 12, "bookshelf": 5, "office chair": 0}
PRICES = {"desk lamp": 40, "bookshelf": 85, "office chair": 65, "garden bench": 150}


def check_stock(product):
    if product == "garden bench":
        raise TimeoutError("The warehouse system is temporarily unavailable, try again")
    if product not in STOCK:
        raise ValueError(f"Unknown product: {product}")
    return f"{product}: {STOCK[product]} in stock"


def get_price(item):
    if item not in PRICES:
        raise ValueError(f"No price for {item}")
    return f"{item}: {PRICES[item]} dollars"


TOOLS = [
    {
        "name": "check_stock",
        "description": "Check how many units of a product are in stock",
        "input_schema": {
            "type": "object",
            "properties": {"product": {"type": "string", "description": "The product name"}},
            "required": ["product"],
        },
    },
    {
        "name": "get_price",
        "description": "Look up the price of an item in dollars",
        "input_schema": {
            "type": "object",
            "properties": {"item": {"type": "string", "description": "The item to price"}},
            "required": ["item"],
        },
    },
]
FUNCTIONS = {"check_stock": check_stock, "get_price": get_price}

request = input()
messages = [{"role": "user", "content": request}]

# Escribe tu código a continuación

Todas las lecciones de Herramientas y agentes

Practica por tu cuenta: Compilador de Python online