Un loop agentico non è una libreria che si installa: è una condizione di uscita che scrivi tu. Il modello non esegue nulla per conto proprio — “The model never executes anything on its own. It emits a structured request, your code (or Anthropic’s servers) runs the operation, and the result flows back into the conversation.” Quante volte girare, quando fermarsi e chi verifica il risultato restano decisioni tue, ed è esattamente lì che i sistemi autonomi si rompono in produzione.

Il ciclo è guidato da stop_reason

Sulla Messages API la forma canonica del loop è “a while loop keyed on stop_reason”. I passi documentati sono cinque:

1. Send a request with your tools array and the user message.
2. Claude responds with stop_reason: "tool_use" and one or more tool_use blocks.
3. Execute each tool. Format the outputs as tool_result blocks.
4. Send a new request containing the original messages, the assistant's
   response, and a user message with the tool_result blocks.
5. Repeat from step 2 while stop_reason is "tool_use".

L’uscita però non è un caso solo: “The loop exits on any other stop reason (end_turn, max_tokens, stop_sequence, or refusal), which means Claude has either produced a final answer or stopped for another reason that your application should handle.” Trattarli tutti come «ha finito» è il primo bug di un agente autonomo. Con max_tokens la risposta è troncata, non conclusa. Con refusal la documentazione è esplicita: “Safety classifiers return this stop reason as a normal HTTP 200 response, not an error.” Un blocco try/except costruito sugli errori di rete non lo intercetta mai, e il tuo orchestratore archivia come completata una risposta che non esiste.

C’è poi un caso che sembra un guasto e non lo è. pause_turn viene “Returned when the server-side sampling loop reaches its iteration limit while executing server tools such as web search. The default limit is 10 iterations per request.” La mossa corretta è “continue the conversation by sending the response back as-is”: rispedire la richiesta originale ripaga le stesse ricerche e butta via il lavoro già fatto.

Tre fasi, e l’harness che le tiene insieme

A un livello sopra l’API, il ciclo ha una forma riconoscibile: “When you give Claude a task, it works through three phases: gather context, take action, and verify results.” Le fasi non sono stadi rigidi — si mescolano, e Claude “decides what each step requires based on what it learned from the previous step”.

Il pezzo che spesso manca nei disegni di architettura ha un nome: “Claude Code serves as the agentic harness around Claude: it provides the tools, context management, and execution environment that turn a language model into a capable coding agent.” Se stai progettando un agente in produzione, l’harness è il tuo prodotto; il modello è un componente.

Nell’Agent SDK l’unità di misura è il turno: “A turn is one round trip inside the loop: Claude produces output that includes tool calls, the SDK executes those tools, and the results feed back to Claude automatically.” Il ciclo prosegue “until Claude produces output with no tool calls”.

Il budget è la vera condizione di uscita

Senza tetti, “the loop runs until Claude finishes on its own, which is fine for well-scoped tasks but can run long on open-ended prompts”. Due manopole, con una differenza che conta a fine mese:

max_turns / maxTurns          tetto di round trip; conta solo i turni con tool
max_budget_usd / maxBudgetUsd tetto di spesa prima dello stop

Al limite “the SDK returns a ResultMessage with a corresponding error subtype (error_max_turns or error_max_budget_usd)”. E il campo con il testo finale c’è solo in caso di successo: controlla sempre il sottotipo prima di leggerlo, altrimenti il tuo codice a valle riceve un vuoto proprio quando l’agente ha fatto più lavoro. Il tetto di spesa, inoltre, “covers subagents: their spend counts toward the total”: è l’unico limite che tiene quando l’albero di deleghe cresce.

A questi si affianca effort (da low a max), che “trades latency and token cost for reasoning depth within each response”. Un agente che elenca file non merita high: paghi ragionamento su un lookup.

Loop che durano più di una sessione

Quando il compito supera la singola sessione, la struttura che regge è a due ruoli: “an initializer agent that sets up the environment on the first run, and a coding agent that is tasked with making incremental progress in every session, while leaving clear artifacts for the next session.” Gli artefatti sono banali e decisivi: uno script di init, un file di log del progresso, un commit iniziale.

Il fallimento tipico non è tecnico ma cognitivo: l’agente si dichiara finito troppo presto, oppure marca come completa una feature che non ha mai provato davvero. La contromisura raccomandata è verificare come farebbe una persona — “use browser automation tools and do all testing as a human user would”.

Ultima regola, che vale prima di tutte: “When building applications with LLMs, we recommend finding the simplest solution possible, and only increasing complexity when needed.” Un loop autonomo si giustifica quando serve davvero un sistema in cui “LLMs dynamically direct their own processes and tool usage”; se il percorso è noto, un workflow con percorsi di codice predefiniti costa meno e si debugga meglio.