Límites de pasos
Parte de la sección Herramientas y agentes del Journey de AI Engineering de Coddy. Lección 9 de 22.
Un bucle de agente termina cuando el modelo deja de solicitar herramientas, y nada garantiza que lo haga. Una herramienta que sigue fallando con try again puede hacer que el modelo reintente indefinidamente, y cada pasada cuesta una llamada y sus tokens. Ponle un límite al bucle:
steps = 1
while response.stop_reason == "tool_use":
if steps == MAX_STEPS:
break
# ejecuta las herramientas, añade los turnos, vuelve a llamar al modelo
steps += 1
if response.stop_reason == "tool_use":
print("Gave up: the task took too many steps")La comprobación está al inicio del bucle, por lo que el programa nunca realiza la llamada número MAX_STEPS + 1. Después del bucle, la razón de parada te indica de qué manera terminó: si sigue siendo tool_use, significa que el límite lo detuvo y no hay ninguna respuesta que mostrar. Infórmale de ello al usuario en lugar de no imprimir nada. Los reintentos suelen ser convenientes: un servicio que agota el tiempo de espera una vez puede responder en el siguiente intento. El límite permite que el bucle reintente y aun así termine. Los agentes en producción también limitan los tokens y el tiempo de la misma forma.
Desafío
IntermedioEl agente de restaurante en el código inicial se ejecuta infinitamente cuando un sistema de reservas sigue fallando, porque el modelo reintenta cada vez. Añade un límite de pasos.
- Al inicio del bucle, haz
breakcuandostepssea igual aMAX_STEPS. - Después del bucle, si la razón de parada sigue siendo
"tool_use", imprimeStopped: no answer after 5 steps(usaMAX_STEPS). - Sigue imprimiendo la respuesta, cuando la haya, y los pasos.
Por ejemplo, para la entrada Is there a table at Golden Dragon tonight? el programa imprime:
Tool: check_table {'restaurant': 'Golden Dragon'} -> error: The booking system is temporarily unavailable, try again
Tool: check_table {'restaurant': 'Golden Dragon'} -> error: The booking system is temporarily unavailable, try again
Tool: check_table {'restaurant': 'Golden Dragon'} -> error: The booking system is temporarily unavailable, try again
Tool: check_table {'restaurant': 'Golden Dragon'} -> error: The booking system is temporarily unavailable, try again
Stopped: no answer after 5 steps
Steps: 5Pruébalo tú mismo
import coddy_ai as anthropic # en producción: import anthropic
client = anthropic.Anthropic()
MAX_STEPS = 5
TABLES = {"Bella Vista": "a table for two at 8 pm", "Sunset Grill": "a table by the window at 9 pm"}
attempts = {}
def check_table(restaurant):
attempts[restaurant] = attempts.get(restaurant, 0) + 1
if restaurant == "Golden Dragon":
raise TimeoutError("The booking system is temporarily unavailable, try again")
if restaurant == "Sunset Grill" and attempts[restaurant] < 3:
raise TimeoutError("The booking system timed out, try again")
if restaurant in TABLES:
return f"{restaurant} has {TABLES[restaurant]}"
return f"{restaurant} has no free table tonight"
TOOLS = [
{
"name": "check_table",
"description": "Check if a restaurant has a free table tonight",
"input_schema": {
"type": "object",
"properties": {"restaurant": {"type": "string", "description": "The restaurant name"}},
"required": ["restaurant"],
},
}
]
def run_tool(block):
try:
output = check_table(**block.input)
except TimeoutError as error:
print(f"Tool: {block.name} {block.input} -> error: {error}")
return {"type": "tool_result", "tool_use_id": block.id, "content": str(error), "is_error": True}
print(f"Tool: {block.name} {block.input} -> {output}")
return {"type": "tool_result", "tool_use_id": block.id, "content": output}
request = input()
messages = [{"role": "user", "content": request}]
# Detén el bucle cuando haya llamado al modelo MAX_STEPS veces
response = client.messages.create(model="claude-opus-5-5", max_tokens=500, tools=TOOLS, messages=messages)
steps = 1
while response.stop_reason == "tool_use":
messages.append({"role": "assistant", "content": response.content})
results = [run_tool(block) for block in response.content if block.type == "tool_use"]
messages.append({"role": "user", "content": results})
response = client.messages.create(model="claude-opus-5-5", max_tokens=500, tools=TOOLS, messages=messages)
steps += 1
for block in response.content:
if block.type == "text":
print("Answer: " + block.text)
print(f"Steps: {steps}")
Esta lección incluye un breve cuestionario. Empieza la lección para responderlo y registrar tu progreso.
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