Limiti di passaggi
Fa parte della sezione Strumenti e Agenti del percorso AI Engineering di Coddy. Lezione 9 di 22.
Un ciclo dell'agente termina quando il modello smette di richiedere strumenti, e nulla garantisce che lo farà. Uno strumento che continua a fallire con try again può far riprovare il modello all'infinito, e ogni passaggio costa una chiamata e i suoi token. Imposta un limite al ciclo:
steps = 1
while response.stop_reason == "tool_use":
if steps == MAX_STEPS:
break
# esegui i tool, aggiungi i turni, richiama il modello
steps += 1
if response.stop_reason == "tool_use":
print("Gave up: the task took too many steps")Il controllo si trova all'inizio del ciclo, quindi il programma non effettua mai la chiamata numero MAX_STEPS + 1. Dopo il ciclo, il motivo dell'arresto ti dice in che modo è terminato: se è ancora tool_use, significa che il limite lo ha fermato e non c'è alcuna risposta da mostrare. Dillo all'utente invece di non stampare nulla. Riprovare è spesso la scelta giusta: un servizio che va in timeout una volta potrebbe rispondere al tentativo successivo. Il limite consente al ciclo di riprovare e comunque terminare. Anche gli agenti in produzione limitano i token e il tempo allo stesso modo.
Sfida
MedioL'agente per i ristoranti nel codice iniziale va in esecuzione all'infinito quando un sistema di prenotazione continua a fallire, perché il modello riprova ogni volta. Aggiungi un limite di passaggi.
- All'inizio del ciclo, esegui
breakquandostepsè uguale aMAX_STEPS. - Dopo il ciclo, se lo stop reason è ancora
"tool_use", stampaStopped: no answer after 5 steps(usaMAX_STEPS). - Continua a stampare la risposta, quando ce n'è una, e i passaggi.
Ad esempio, per l'input Is there a table at Golden Dragon tonight? il programma stampa:
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: 5Provalo tu
import coddy_ai as anthropic # in produzione: 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}]
# Interrompi il ciclo quando ha chiamato il modello MAX_STEPS volte
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}")
Questa lezione include un breve quiz. Inizia la lezione per rispondere e tenere traccia dei tuoi progressi.
Tutte le lezioni di Strumenti e Agenti
1Basi sull'uso dei tool
Definire un toolLeggere una chiamata a un toolRestituire i risultati di un toolScegliere tra i toolRiepilogo: Weather Desk4Progetto: Agente di viaggio
Panoramica del progettoEsecuzione del loop dell'agente2Il loop dell'agente
Il loop dell'agenteChiamate parallele ai toolErrori dei toolLimiti di passaggiRiepilogo: Assistente acquistiEsercitati da solo: Compilatore Python online