Repaso: Asistente de compras
Parte de la sección Herramientas y agentes del Journey de AI Engineering de Coddy. Lección 10 de 22.
Desafío
DifícilConstruye 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.
- Escribe
run_tool(block): ejecutaFUNCTIONS[block.name](**block.input)y devuelve sutool_result. CapturaValueErroryTimeoutErrory devuelve un resultado de error con el mensaje y"is_error": True. ImprimeTool: <name> <input> -> <output>para un resultado, oTool: <name> <input> -> error: <message>para un error. - 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. - Detén el bucle cuando haya llamado al modelo
MAX_STEPSveces, y después imprimeStopped: no answer after 4 steps. - Imprime
Answer:y el texto final cuando haya uno, despuésSteps: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: 2Prué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
1Uso básico de herramientas
Definir una herramientaLeer una llamada a una herramientaDevolver resultados de la herramientaElegir entre herramientasRepaso: Weather Desk4Proyecto: Agente de viajes
Descripción general del proyectoEl bucle del agente se ejecuta2El bucle del agente
El bucle del agenteLlamadas a herramientas en paraleloErrores de herramientasLímites de pasosRepaso: Asistente de comprasPractica por tu cuenta: Compilador de Python online