An agent is a loop: the real choice is who runs it
A chatbot receives a question and answers. An agent receives a task and decides the steps on its own: it calls a tool, looks at the result, decides whether it needs another one, and only at the end answers. Anthropic's documentation defines it like this: an application that completes a task by planning its own steps and calling tools that read files, run commands or modify code. Almost everything else (memory, security, cost) follows from a single decision: who runs this loop, your code, a library or a provider's infrastructure. This article compares the options on that criterion, using the official pages, and then builds the loop from scratch with real tools to review code: you write it and run it, so you understand what the other solutions take out of your hands. Names, features and beta status of the products are those read on 2026-11-12 and they change: check again before deciding.
The model is not called in any listing: a ModelloFinto (fake model) returns prepared answers in the documented shape, because the loop, the tools and the guardrails are code you can try without a key. The listings are Python 3.14.4 with the standard library only. For the fundamentals of tool design see Tool design for agents; for loops that never end, Debugging agent loops.
Four places where the loop can live
The table summarises, for each option, what its documentation declares. The first three are Anthropic products, named here as the object of a comparison; the fourth is a local runtime. I do not report prices or measures of latency or quality: they vary, and those that circulated for these products could not be traced back to a source.
| Option | Who runs the loop | What the documentation declares |
|---|---|---|
| Messages with tool use (client SDK) | Your code | The model answers with stop_reason: "tool_use"; you run the tool and reply with a tool_result. Designed for custom loops and fine control. |
| Agent SDK | A library in your process | The same tools, loop and context management as Claude Code, programmable in Python and TypeScript, in a process you manage yourself. |
| Managed Agents | The provider's infrastructure | A preconfigured harness running on managed infrastructure, for long, asynchronous tasks. At the time of consultation it is in beta and requires a specific beta header. |
| Local runtime (Ollama) | Your code, with a model on your hardware | The chat endpoint accepts a tools list and the model can return tool_calls. Quality and speed depend on the model and the hardware you choose. |
Read it as a ladder of delegation. At the top the loop is yours: more code, but also more control over how many steps, which tool, what to record. At the bottom you would delegate it: less work, but you accept the provider's choices and, in the case of the managed service, the data passing through its infrastructure. No row is the best in absolute terms; the decision depends on how much you want to control and which data you can let out. The rest of the article stays entirely on the first row, because understanding the manual loop is what lets you evaluate the others.
The tools: a code reviewer that really reads
The example is the review of a change to a Python file. Three tools are needed, and none is fake: get_diff returns the change, run_linter analyses the added code with the ast module (unused imports, except without a type), analyze_complexity estimates cyclomatic complexity by counting decision points. The test change contains three deliberate defects: two imports never used and a generic except.
import ast
import json
import re
DIFF = '''--- a/pagamenti.py
+++ b/pagamenti.py
@@ -1,2 +1,17 @@
+import os
+import json
+
+def sconto(totale, cliente, codice):
+ try:
+ if cliente == "vip":
+ if totale > 100 and codice:
+ return totale * 0.8
+ elif totale > 50:
+ return totale * 0.9
+ for c in codice or "":
+ if c == "!":
+ return totale
+ except:
+ return totale
+ return totale
'''
def get_diff(_args) -> str:
return DIFF
def codice_aggiunto(diff: str) -> str:
righe = [r[1:] for r in diff.splitlines() if r.startswith("+") and not r.startswith("+++")]
return "\n".join(righe)
def run_linter(args) -> str:
albero = ast.parse(codice_aggiunto(DIFF))
problemi = []
importati = {a.asname or a.name.split(".")[0] for n in ast.walk(albero)
if isinstance(n, (ast.Import, ast.ImportFrom)) for a in n.names}
usati = {n.id for n in ast.walk(albero) if isinstance(n, ast.Name)}
for nome in sorted(importati - usati):
problemi.append(f"unused import: {nome}")
for n in ast.walk(albero):
if isinstance(n, ast.ExceptHandler) and n.type is None:
problemi.append(f"line {n.lineno}: bare except")
return json.dumps(problemi, ensure_ascii=False)
def analyze_complexity(args) -> str:
albero = ast.parse(codice_aggiunto(DIFF))
risultati = {}
for f in [n for n in ast.walk(albero) if isinstance(n, ast.FunctionDef)]:
punti = sum(isinstance(n, (ast.If, ast.For, ast.While, ast.ExceptHandler, ast.IfExp)) for n in ast.walk(f))
punti += sum(len(n.values) - 1 for n in ast.walk(f) if isinstance(n, ast.BoolOp))
risultati[f.name] = 1 + punti # approximate cyclomatic complexity
return json.dumps(risultati)
STRUMENTI = {"get_diff": get_diff, "run_linter": run_linter, "analyze_complexity": analyze_complexity}
for nome, fn in STRUMENTI.items():
if nome != "get_diff":
print(nome, "->", fn({}))
# Output:
# run_linter -> ["unused import: json", "unused import: os", "line 14: bare except"]
# analyze_complexity -> {"sconto": 9}
The linter reports the two unused imports (os and json) and the except without a type at line 14 of the added code. The codice_aggiunto function takes only the lines that start with + in the diff and not the headers, because parsing the diff lines themselves would not be valid Python. The complexity of sconto comes out as 9: 1 as a base plus one decision for each if/elif, for and except, plus one for each additional boolean operator. It is an approximation of a well-known heuristic, not a certified measure: it serves to decide whether to reread carefully, not to set a limit.
The loop: what everyone does, written in thirty lines
The loop has a fixed shape, described in the page on handling tool calls: read the answer; if the stop reason is tool_use, run every tool requested and reply with a user message containing a tool_result block with the same tool_use_id; otherwise the model has finished. The maximum number of steps is a parameter, not an option: without it, a model that never concludes never stops the program.
class ModelloFinto:
"""Stands in for the model: emits blocks in the documented shape (tool_use / text)."""
def __init__(self, copione):
self.copione, self.i = copione, 0
def risposta(self, messaggi):
r = self.copione[min(self.i, len(self.copione) - 1)]
self.i += 1
return r
def tool_use(id_, nome, **input_):
return {"stop_reason": "tool_use", "content": [{"type": "tool_use", "id": id_, "name": nome, "input": input_}]}
def fine(testo):
return {"stop_reason": "end_turn", "content": [{"type": "text", "text": testo}]}
def esegui_agente(modello, strumenti, compito, max_passi=6):
messaggi = [{"role": "user", "content": compito}]
for passo in range(1, max_passi + 1):
r = modello.risposta(messaggi)
messaggi.append({"role": "assistant", "content": r["content"]})
if r["stop_reason"] != "tool_use":
print(f"step {passo}: end -> {r['content'][0]['text']}")
return messaggi
risultati = []
for blocco in (b for b in r["content"] if b["type"] == "tool_use"):
esito = strumenti[blocco["name"]](blocco["input"])
print(f"step {passo}: {blocco['name']} -> {esito[:60]}")
risultati.append({"type": "tool_result", "tool_use_id": blocco["id"], "content": esito})
messaggi.append({"role": "user", "content": risultati})
print(f"stopped: exceeded {max_passi} steps")
return messaggi
copione = [
tool_use("t1", "get_diff"),
tool_use("t2", "run_linter"),
tool_use("t3", "analyze_complexity"),
fine("3 findings (two unused imports, one bare except) and complexity 9 in sconto(): to simplify."),
]
storia = esegui_agente(ModelloFinto(copione), STRUMENTI, "Review this PR")
print("messages exchanged:", len(storia))
# Output:
# step 1: get_diff -> --- a/pagamenti.py
# +++ b/pagamenti.py
# @@ -1,2 +1,17 @@
# +impo
# step 2: run_linter -> ["unused import: json", "unused import: os", "line 14: bare
# step 3: analyze_complexity -> {"sconto": 9}
# step 4: end -> 3 findings (two unused imports, one bare except) and complexity 9 in sconto(): to simplify.
# messages exchanged: 8
The script makes the fake model call the three tools in sequence, then makes it conclude. The output shows the four steps: get_diff, run_linter, analyze_complexity and the final answer, consistent with what the tools returned (three findings and complexity 9). The eight messages exchanged are the history that a real model would receive at every step: this is why the context grows with every call, and for a long agent it becomes a cost and a limit. Note that tool_use_id links each result to its request: if you get the identifier wrong, the model does not know which call the answer belongs to. One change from the typical patterns: the linter's result is a JSON string, so the model reads it as text without interpreting Python objects.
The guardrails nobody writes until they are needed
An agent with tools wants to be limited. The minimum protection has four parts: a maximum number of steps, a list of allowed tools, a budget of calls, and a way to report an error to the model without bringing the program down. The documentation provides an is_error field in the tool_result block to signal a tool's failure, and the listing uses it. In a real agent you would add argument checking and an audit log.
import time
def con_guardrail(strumenti, consentiti, budget_chiamate, log):
"""Wraps the tools: allow-list, call budget, errors as tool_result with is_error."""
chiamate = {"n": 0}
def avvolgi(nome):
def eseguito(args):
chiamate["n"] += 1
if nome not in consentiti:
log.append((nome, "denied: not in the allow-list"))
raise PermissionError(f"tool '{nome}' not allowed")
if chiamate["n"] > budget_chiamate:
log.append((nome, "denied: budget exhausted"))
raise RuntimeError("call budget exhausted")
log.append((nome, "ok"))
return strumenti[nome](args)
return eseguito
return {nome: avvolgi(nome) for nome in strumenti}
def esegui_sicuro(modello, strumenti, compito, max_passi=5):
messaggi = [{"role": "user", "content": compito}]
for passo in range(1, max_passi + 1):
r = modello.risposta(messaggi)
if r["stop_reason"] != "tool_use":
return f"finished at step {passo}"
blocco = r["content"][0]
try:
esito, errore = strumenti[blocco["name"]](blocco["input"]), False
except Exception as e:
esito, errore = f"{type(e).__name__}: {e}", True
messaggi.append({"role": "user", "content": [{"type": "tool_result", "tool_use_id": blocco["id"],
"content": esito[:40], "is_error": errore}]})
return f"STOPPED: {max_passi} steps without finishing"
log = []
protetti = con_guardrail(STRUMENTI, consentiti={"get_diff", "run_linter"}, budget_chiamate=3, log=log)
# a model that never finishes and also asks for a tool that is not allowed
ostinato = ModelloFinto([tool_use("a", "get_diff"), tool_use("b", "analyze_complexity"), tool_use("c", "run_linter"),
tool_use("d", "run_linter")])
print(esegui_sicuro(ostinato, protetti, "Review", max_passi=5))
for voce in log:
print(" ", voce)
# Output:
# STOPPED: 5 steps without finishing
# ('get_diff', 'ok')
# ('analyze_complexity', 'denied: not in the allow-list')
# ('run_linter', 'ok')
# ('run_linter', 'denied: budget exhausted')
# ('run_linter', 'denied: budget exhausted')
To try the guardrails I used a stubborn fake model, which never concludes and also asks for a tool that is not allowed. The output tells what happened: get_diff and run_linter go through; analyze_complexity is denied because it is not in the allow-list; the fourth and fifth attempts are denied because the budget is exhausted; in the end the program prints "STOPPED: 5 steps without finishing" instead of running forever. The log (log) keeps the outcome of each call, and it is the material for an audit. You will notice that the budget also counts denied calls: it is a choice (an agent that insists on forbidden tools consumes its budget anyway). The values of the budget and of the number of steps must be chosen according to the cost of each step and how long a normal task is; the numbers in the example are illustrative.
When it makes sense to delegate the loop
Writing the loop by hand is instructive and gives control, but it has a maintenance cost: handling edge cases, memory, parallelism. A library such as the Agent SDK moves that work into someone else's code, provided you accept its way of working. A managed service also removes execution and infrastructure, and makes sense for long tasks you do not want to keep alive on your own server, at the price of letting your data through and depending on a service that is still in beta. For sensitive data or for the constraint of not leaving your network, a local model is the only option that guarantees it by construction: but it requires the hardware, and the quality in tool use must be measured on your model, not presumed. If you choose a provider for the models, prices and limits live on its official page and change: Anthropic's pricing page is the source, consulted on 2026-11-12, and I do not copy it here because it would become false.
Frequently asked questions
What is the difference between an agent and a chatbot with tools?
The boundary is initiative: a chatbot with tools uses a tool when asked to; an agent decides on its own how many steps to take and which tools to call to reach a goal. The loop shown here is the minimum that makes it one.
How much does it cost to run an agent?
It depends on the model, on the number of steps and on how much context travels at each step, which grows. There is no figure valid in general: record the real tokens of your tasks and multiply them by the provider's current prices.
Which parts were not run?
No call to a model, to an SDK or to a managed service: the model in the listings is a script. The real behaviour of those products is described only according to the documentation, consulted on 2026-11-12.
What you can do now
You can tell where an agent's loop can live and what is delegated in each case, write tools that do real work and the loop that calls them according to the documented protocol, put around the loop the limits that make it safe (steps, allow-list, budget, reported errors), and read critically a comparison between products that does not cite the sources of its numbers. The next step is to replace the fake model with a real one, in one of the environments in the table, and compare the results on your own task.
Sources
- Anthropic: Agent SDK overview - the definition of an agent and the comparison between Agent SDK, client SDK and Managed Agents on who runs the agent, consulted on 2026-11-12
- Anthropic: Managed Agents overview - the managed harness, the target for long tasks and the beta status with a dedicated header, consulted on 2026-11-12
- Anthropic: Handle tool calls - the
tool_useandtool_resultblocks, thetool_use_idfield andis_error, consulted on 2026-11-12 - Ollama: API reference - the
toolsparameter and thetool_callsin the chat response, consulted on 2026-11-12 - Anthropic: Pricing - pricing page, cited as a source to consult and not reproduced, consulted on 2026-11-12
The listings were run in a single Python 3.14.4 process. No call to a model was made; no price, latency or quality score is reported.

Commenti
Caricamento commenti...
Sign in to comment