A language model on its own maps text to text: it cannot look up an order or send a message. A tool-using agent closes that gap with ordinary code. The model proposes the next action, a runtime executes it, and the result goes back to the model for the next decision, until the model answers or the runtime stops it.
The loop is short. The engineering is in what surrounds it: tool descriptions, argument validation, stop conditions, failures, context growth, and what the runtime may do without asking a person. Token counts and other numbers are illustrations unless a source is given.
What makes a program an agent#
Three parts make a program an agent in the sense used here.
A model that chooses the next action: answer, or call a tool, and if so which tool with which arguments. The choice is made at run time, from the content of the conversation.
A runtime that executes it. The model only produces a structured request. Your code parses it, checks it, runs the tool and decides what to do with the outcome. The runtime holds the credentials, the limits and the logs.
A loop that feeds the result back. The result or the error becomes part of the next model input, which lets the model correct itself: an empty search leads to another search, an error to different arguments.
Agents and workflows#
A workflow runs the model and the tools along paths fixed in code: classify, retrieve, draft, check. An agent lets the model decide the sequence. Anthropic's engineering note on building agents (opens in a new tab) (December 2024) draws the same line: in workflows, models and tools are orchestrated through "predefined code paths", while agents "dynamically direct their own processes and tool usage".
The difference matters most in operations. In a workflow the code fixes or caps the number of model calls, so cost and latency have an upper bound you can compute, and it can be tested path by path. An agent has neither property: the number of iterations depends on the input and on what the tools return.
A workflow is the better choice when the steps are known in advance: extracting fields from an invoice, routing a ticket to one of five queues. An agent earns its cost when the path cannot be known up front, such as a support question that may need one lookup or six. Many production systems combine the two: a workflow that calls a bounded agent for one open-ended step.
The loop at a glance#
The agent loop over three model calls
The runtime sends the conversation to the model, executes each tool call the model asks for and feeds the result back, until a reply holds no tool call. That reply goes to the user.
Not started12 steps, listed below.
- 1The question arrives. The runtime puts it after the system prompt and attaches the tool definitions.
- 2Model call 1: the runtime sends the messages and the tool definitions to the model.
- 3The reply holds a tool call: a tool name, arguments and a call id. The runtime checks the arguments against the schema.
- 4The runtime executes the call. The model never runs anything itself.
- 5The tool result is appended to the messages, tagged with the call id it answers.
- 6Model call 2: the whole history, now with the tool result, goes back to the model.
- 7The model has read the result and asks for a second tool. The runtime validates the new call.
- 8The runtime executes the second call.
- 9Its result is appended as well. The history has grown by two messages per iteration.
- 10Model call 3, with both tool results in the context.
- 11This reply is text with no tool call. That is the normal stop condition. Real runs take one call or dozens.
- 12The runtime ends the loop and returns the final answer to the user.
Conceptual illustration of the order of execution. It is not measured telemetry, and the animation speed does not represent real latency.
The runtime sits in the middle and is the only part that talks to the user, the model and the tools. The model never calls a tool: it returns a reply, which either contains tool calls or does not.
One iteration in detail#
Provider APIs differ in field names, but the exchange has the same structure in the OpenAI function calling guide (opens in a new tab) and the Anthropic tool use documentation (opens in a new tab). I describe it neutrally and give the provider field names where they help.
The request: messages and tool definitions#
Each model call sends the conversation so far, as a list of messages with roles, and the definitions of the tools the model may call. A tool definition has a name, a description in natural language, which is the model's only documentation of the tool, and a schema of the arguments in JSON Schema (opens in a new tab).
{
"type": "function",
"name": "get_stock",
"description": "Return the number of units in stock for one product. Use the SKU exactly as the user or a previous tool result gave it, for example A-1042. Does not return prices.",
"parameters": {
"type": "object",
"properties": {
"sku": { "type": "string", "description": "Product SKU, for example A-1042" }
},
"required": ["sku"],
"additionalProperties": false
}
}OpenAI calls the schema field parameters, as in the example, Anthropic input_schema. Both use JSON Schema, whose current version is 2020-12: its validation vocabulary (opens in a new tab) defines keywords such as type, enum, minimum and required, and properties and additionalProperties come from the applicator vocabulary in JSON Schema Core (opens in a new tab). Providers accept a subset of the specification: OpenAI's strict mode (opens in a new tab) leaves out allOf and not, for example, and Anthropic's (opens in a new tab) leaves out minimum and maxLength. What the schema cannot express, the runtime checks itself.
The description deserves as much care as the schema. The model selects tools by reading descriptions: overlapping descriptions produce wrong selections, and a description that omits a constraint ("SKU, not product name") produces calls that fail validation. Anthropic's guide (opens in a new tab) calls detailed descriptions "by far the most important factor in tool performance". OpenAI's guide suggests, as a soft limit, fewer than 20 functions available at the start of a turn.
The model's reply: a tool call#
The model returns text or one or more tool calls. A tool call is structured data: a call id, the tool name and the arguments. In the OpenAI Responses API it is an output item of type function_call with call_id, name and arguments, a JSON string your code must parse. In the Anthropic Messages API it is a content block of type tool_use with id, name and input, already a JSON object, and the response has stop_reason set to tool_use.
The call id ties the exchange together: the result must reference it, and it is the only reliable way to pair results with calls.
Validation before execution#
The model generates arguments token by token and can produce JSON that does not parse, an unknown property, an integer where a string was required, or a value outside an enum. Both providers offer a strict mode that constrains generation to the schema. OpenAI documents strict: true on a function, which requires additionalProperties: false on every object and every property listed in required. Anthropic documents strict tool use (opens in a new tab), based on grammar-constrained sampling. Strict mode makes the arguments conform to the schema, not correct: a well-formed SKU can still be the wrong SKU.
So the runtime validates every call before it runs it, in this order:
- The tool name is one the runtime registered for this run. A name that is not on the list is an error, never a lookup in a wider registry.
- The arguments parse as JSON.
- The arguments validate against the schema.
- The arguments pass the checks the schema cannot express: the order belongs to this customer, the date is not in the past, the amount is under the limit.
A failure at any of these steps does not end the run. It becomes an error result for that call, and the model sees it on the next iteration.
Execution and the tool result#
The runtime runs the tool with a time-out and appends two things to the conversation: the model's reply with the tool call, unchanged, and a tool result that references the call id. In the OpenAI Responses API the result is an input item of type function_call_output with call_id and output. In the Anthropic API it is a tool_result content block with tool_use_id, content and an optional is_error flag, placed in the user message that directly follows the tool call, before any text.
Keep the result short and written for the model to read: the fields it needs, in a stable format, with units.
The next model call#
The model keeps no memory between calls: it processes the whole conversation on every call, also when the provider stores it, as with OpenAI's previous_response_id (opens in a new tab), which still bills all earlier input. It reads the result and decides again.
sequenceDiagram
participant U as User
participant R as Runtime
participant M as Model
participant T as Tool
U->>R: question
R->>M: system prompt, tool definitions, question
M-->>R: tool call get_stock, id c1
R->>R: parse and validate the arguments
R->>T: get_stock with sku A-1042
T-->>R: 7 units in stock
R->>M: tool definitions, full history, result for c1
M-->>R: text, no tool call
R-->>U: final answerStop conditions#
An agent loop needs several exits. The model decides the normal one. The runtime enforces the others, because a model that is stuck will not notice it is stuck.
| Condition | Who decides | What the runtime does |
|---|---|---|
| Final answer | Model: a reply without tool calls | Returns the text to the user |
| Step budget | Runtime: a maximum of model or tool calls | Stops with a partial result or a clear failure |
| Token or cost budget | Runtime: cumulative tokens, or their price | Stops before the next call would exceed it |
| Time-out | Runtime: a limit per run, and a shorter one per tool | Cancels pending work, reports what finished |
| Human needed | A tool or a runtime policy that needs approval or information | Pauses, stores the state, resumes on the answer |
| Refusal or error | Model or provider: a refusal, a truncated reply, an API error | Stops or retries by policy, never loops on it |
The budgets are not optional. A step budget is the simplest protection against a model that repeats the same call; set it from the distribution of steps in real runs. The stop should also be explicit in the result: "stopped after 12 steps without an answer" is a useful outcome for the caller, a truncated answer that looks complete is not.
A pause for a human is a stop condition from the loop's point of view. The run must be resumable: the messages, the pending call and its arguments are stored, and the person's answer goes into the conversation as the result of that call.
The token check needs one detail: the input of the next call is known before you send it, the output is not. Count the input, reserve the maximum output you allow, and stop if the sum would cross the budget.
Parallel tool calls#
A single reply can contain several tool calls, for example for the stock, the price and the delivery date of one product. OpenAI's parallel_tool_calls: false switches this off and "ensures exactly zero or one tool is called". Anthropic has parallel tool use on by default and switches it off with disable_parallel_tool_use: true inside the tool_choice object.
Parallel tool calls with one failure
One model reply holds three tool calls. The runtime runs them at the same time, one of them times out, and all three results, the error included, go back to the model in one turn.
Not started7 steps, listed below.
- 1One model reply holds three tool calls, each with its own call id: c1, c2 and c3.
- 2Fan-out: all three tools are read-only and marked safe to run concurrently, so the runtime starts them at once.
- 3c2, get_delivery, finishes first. Completion order is not call order.
- 4c1, get_stock, finishes.
- 5c3, get_price, hits its deadline. The runtime records an error result for c3 instead of failing the whole turn.
- 6Fan-in: the runtime has waited for every call. It pairs each result with its call id and keeps call order.
- 7All three results go back in one turn. The model decides what to do about the failed call.
Conceptual illustration of the order of execution. It is not measured telemetry, and the animation speed does not represent real latency.
The runtime then has four jobs.
Fan-out. "Parallel" in the API means only that the calls arrived together. Whether they run at the same time is up to the runtime, and it cannot tell from the reply alone which calls are safe to overlap. Anthropic's documentation (opens in a new tab) advises running independent, read-only operations in parallel and tools with side effects, shared state or ordering requirements sequentially. A per-tool flag such as "safe to run concurrently" turns that advice into a rule.
Fan-in. Wait for every call to finish or time out, then send all results back in one turn. Anthropic's documentation asks for one tool_result for each tool_use block, all together in the next user message. Sending only the first results leaves calls without a result and breaks the pairing both providers rely on.
Ordering. Completion order is not call order. The call id is enough for correctness, but I still put results in call order, so that the same inputs give the same transcript and logs and tests stay stable.
Partial failure. A failing call produces an error result for its call id; the other results go back as normal, and the model decides whether the failure matters. In the diagram the price lookup times out, and a good answer says that the price is not available.
Turn parallel calls off when the tools cannot safely overlap and you cannot mark them, or when the model batches calls that depend on each other. The cost is more iterations, each resending the whole context.
Errors and retries#
Invalid arguments#
The call failed validation: unknown tool, unparsable JSON, a schema violation or a business rule. The runtime executes nothing and returns an error result that says precisely what was wrong, in terms the model can act on: "'sku' must be a string, got an integer", or "no order 1042 for this customer". "Invalid request" gives the model nothing to correct.
Tool exceptions#
The call was valid and the tool failed: a time-out, a 500 from a downstream API, a database lock. Transient failures can be retried inside the runtime with a short backoff and a small limit, which saves an iteration and keeps noise out of the context. When the retries are exhausted, the failure goes to the model as an error result. Anthropic's API has an explicit is_error field for this; OpenAI's function_call_output has no such flag, so the error text goes in the output.
What the runtime must never do is swallow the error: return an empty result, or a default value, as if the call had succeeded. The model then reasons from a false observation, and the final answer is confidently wrong with nothing in the transcript to show why.
Retries with feedback#
With an error result the model can change its plan: other arguments, another tool, or an answer that explains what could not be done. But feedback can loop. Anthropic's documentation (opens in a new tab) warns that the model may call the tool again, "so limit how many retries your loop allows". Two guards help: stop after a few consecutive errors per tool, and detect a call that exactly repeats an earlier failed one.
Idempotency of tools that change state#
A tool that reads is safe to retry; a tool that writes is not. The runtime retries after a time-out without knowing whether the first attempt went through, and the model can call the same tool twice.
Make every state-changing tool idempotent. The runtime derives an idempotency key from the run id and the call id and passes it to the downstream service, which stores the key with the effect and returns the stored result when the key repeats. That covers retries of one call, not a second call from the model, which has a new call id. For that case the tool checks for a duplicate effect, such as a refund for the same order and amount in the same run, and refuses it with a clear error.
A runnable loop in Python#
The example below has the parts described so far: a tool registry with argument schemas, validation, parallel execution with results in call order, errors fed back as results, and a step budget. The model is a scripted stand-in that replays fixed replies, so the code runs without an API key or network access. It does not read the results it receives; a real model does, and that is why errors go back to it. The validator covers only the JSON Schema keywords the example uses. It runs on Python 3.12 with the standard library only, and prints the same on 3.9 and 3.15.
import json
from concurrent.futures import ThreadPoolExecutor
STOCK = {"A-1042": 7} # stand-in for an inventory service
def get_stock(sku):
return {"sku": sku, "in_stock": STOCK[sku]}
def get_price(sku):
raise TimeoutError("price service did not answer within 2 s")
# Tool registry: name -> (JSON Schema of the arguments, function).
TOOLS = {
"get_stock": ({"type": "object", "properties": {"sku": {"type": "string"}},
"required": ["sku"], "additionalProperties": False}, get_stock),
"get_price": ({"type": "object", "properties": {"sku": {"type": "string"}},
"required": ["sku"], "additionalProperties": False}, get_price),
}
def validate(args, schema):
"""A small subset of JSON Schema: required, no extra properties, string type."""
if not isinstance(args, dict):
return "arguments must be a JSON object"
for key in schema["required"]:
if key not in args:
return f"missing required property '{key}'"
for key, value in args.items():
if key not in schema["properties"]:
return f"unknown property '{key}'"
if schema["properties"][key]["type"] == "string" and not isinstance(value, str):
return f"'{key}' must be a string, got {type(value).__name__}"
return None
def scripted_model(messages):
"""Stand-in for the model: replays a fixed script, one reply per call."""
turn = sum(1 for m in messages if m["role"] == "assistant")
script = [
{"tool_calls": [{"id": "c1", "name": "get_stock", "arguments": '{"sku": 1042}'}]},
{"tool_calls": [{"id": "c2", "name": "get_stock", "arguments": '{"sku": "A-1042"}'},
{"id": "c3", "name": "get_price", "arguments": '{"sku": "A-1042"}'}]},
{"text": "A-1042: 7 in stock. The price service is not answering, so I cannot quote a price."},
]
return script[turn]
def execute(call):
if call["name"] not in TOOLS:
return f"unknown tool '{call['name']}'", True
schema, fn = TOOLS[call["name"]]
try:
args = json.loads(call["arguments"])
except json.JSONDecodeError as exc:
return f"arguments are not valid JSON: {exc}", True
if (problem := validate(args, schema)) is not None:
return f"invalid arguments: {problem}", True
try:
return json.dumps(fn(**args)), False
except Exception as exc: # the error goes back to the model, not up the stack
return f"{type(exc).__name__}: {exc}", True
def run(question, model, max_steps=5):
messages = [{"role": "user", "content": question}]
for step in range(1, max_steps + 1):
reply = model(messages)
messages.append({"role": "assistant", **reply})
if "text" in reply:
return reply["text"], step
calls = reply["tool_calls"]
with ThreadPoolExecutor() as pool: # fan-out; map() keeps the call order
results = list(pool.map(execute, calls))
for call, (content, is_error) in zip(calls, results):
print(f"step {step} {call['name']}{call['arguments']} -> "
f"{'ERROR ' if is_error else ''}{content}")
messages.append({"role": "tool", "call_id": call["id"],
"content": content, "is_error": is_error})
return "stopped: step budget exhausted", max_steps
answer, steps = run("How many A-1042 do we have, and at what price?", scripted_model)
print(f"final after {steps} model calls: {answer}")
def stubborn_model(messages):
"""A second stand-in that never stops calling the same tool."""
return {"tool_calls": [{"id": f"s{len(messages)}", "name": "get_stock",
"arguments": '{"sku": "A-1042"}'}]}
answer, steps = run("Same question", stubborn_model, max_steps=3)
print(f"final after {steps} model calls: {answer}")Output:
step 1 get_stock{"sku": 1042} -> ERROR invalid arguments: 'sku' must be a string, got int
step 2 get_stock{"sku": "A-1042"} -> {"sku": "A-1042", "in_stock": 7}
step 2 get_price{"sku": "A-1042"} -> ERROR TimeoutError: price service did not answer within 2 s
final after 3 model calls: A-1042: 7 in stock. The price service is not answering, so I cannot quote a price.
step 1 get_stock{"sku": "A-1042"} -> {"sku": "A-1042", "in_stock": 7}
step 2 get_stock{"sku": "A-1042"} -> {"sku": "A-1042", "in_stock": 7}
step 3 get_stock{"sku": "A-1042"} -> {"sku": "A-1042", "in_stock": 7}
final after 3 model calls: stopped: step budget exhaustedIn the first run, the integer SKU fails validation and the error goes back to the model. The second reply holds two concurrent calls: one succeeds, one raises, and both outcomes go back with their call ids. The third reply ends the loop. In the second run a stand-in calls the same tool forever, and the step budget stops it. get_price simulates a missed deadline by raising at once. A real runtime sets a deadline per call, and future.result(timeout=...) only stops the wait, not the thread.
Context growth, cost and latency#
Every iteration appends at least the model's reply with its tool calls and the tool results, and every model call processes the whole history again. The input grows with every step, and the total input of a run grows faster than the number of steps.
With a stable prefix of tokens (system prompt, tool definitions, question) and tokens added per iteration, model call sends
input tokens, and a run of model calls sends
in total. The second term is quadratic in . With the figure's numbers, and , four calls send 14,080 input tokens. Twelve calls would send . Input tokens are billed on every call, so tool results that are three times longer than needed cost three times as much on every later iteration of the run.
Length also affects quality. Liu et al. (2024) (opens in a new tab) found that models use information at the start and the end of a long context better than information in the middle. A long run pushes early tool results into the middle of the context.
Three techniques, in the order I would apply them:
Keep tool results short. Return the fields the model needs, not the raw response. Cap every result and say when it was cut ("first 20 of 312 rows"), so the model narrows its query instead of assuming it saw everything.
Truncate old results. After the model has used a large result, replace it in later calls with a short placeholder that keeps the call id, so that call and result stay paired.
Summarise. In a long run, replace a span of old iterations with a summary written by a model call. It loses detail and can be wrong, so keep the full transcript in the trace.
Both techniques change earlier history, which has a price. Both providers cache a repeated prompt prefix at a reduced rate: OpenAI (opens in a new tab) states up to 95 percent off, Anthropic (opens in a new tab) bills cache hits at a fraction of the input price. The cache matches from the start of the request, so shortening a tool result or summarising older turns (opens in a new tab) cuts reuse from that point on. Truncate in large steps, not on every call.
Latency adds up the same way. One iteration costs a model call, which grows with input length and output tokens, plus the slowest tool call of its batch. Parallel calls shorten an iteration; only fewer iterations shorten the run.
Reasoning and acting: patterns from the literature#
A few papers help explain what the model is asked to do inside the loop.
ReAct: interleaving thought and action#
Yao et al. (2022) (opens in a new tab) proposed ReAct, in which the model produces interleaved thoughts, actions and observations. A thought is free text the environment ignores: a plan, a summary, a decision about what to look up next. An action is a command such as search[entity], lookup[string] or finish[answer] in their question-answering setup over a Wikipedia API, and the observation is what comes back. The main results come from prompting with a few example trajectories; the paper adds first fine-tuning experiments.
On ALFWorld and WebShop, two interactive decision-making benchmarks, ReAct outperformed imitation and reinforcement learning baselines by 34 and 10 percentage points of absolute success rate, with one or two in-context examples. It also reports failure modes that agents still show today: the model repeats the same thoughts and actions in a loop, and an uninformative search result derails the reasoning that follows.
ReAct changes the content of each reply: the model writes its reasoning before the action, and that reasoning stays in the context. Current tool-calling APIs keep the structure, with a structured tool call in place of a text command and a tool result message as the observation.
Toolformer: learning when to call a tool#
Schick et al. (2023) (opens in a new tab) took a different route. Toolformer is a language model trained, in a self-supervised way, to insert API calls into its own text: candidate calls were sampled and executed, and only the calls whose results made the following tokens easier to predict were kept. The tools were a calculator, a question-answering system, a Wikipedia search engine, a translation system and a calendar. Toolformer cannot chain tools, feeding the output of one call into another, or use them interactively.
Toolformer is not an agent loop, but it shows that a model can learn when a tool call helps and what arguments to give it.
Reflection: learning from failed attempts#
Shinn et al. (2023) (opens in a new tab) put a second loop around the first. In Reflexion an actor runs a task, an evaluator scores the outcome, and a self-reflection model writes a short verbal lesson from the failure, which is stored in an episodic memory and placed in the context of the next attempt. The weights do not change. On the Python version of the HumanEval coding benchmark the authors report 91 percent pass@1, against 80 percent for GPT-4 as reported at the time.
Reflection adds an outer loop over attempts, each with its own inner loop and budget, and it needs an evaluator: unit tests, a reward from the environment, or a model acting as judge. The method is only as good as that signal, and the paper shows it. In the coding tasks the model writes its own unit tests. On the MBPP Python benchmark, 16.3 percent of the solutions that passed all of those tests were still wrong, against 1.4 percent on HumanEval, and there Reflexion scored below the GPT-4 baseline: 77.1 against 80.1 percent. Self-Refine (opens in a new tab) is a lighter variant without an external evaluator: the same model critiques and revises its own output.
Safety: what the runtime allows#
Every safety property of an agent is a property of the runtime, because anyone who can influence the context can influence the model's output.
Allow-listed tools. Each run gets an explicit list of tools, and the runtime executes only those. The list is per task: an agent that answers stock questions has no refund tool.
Least privilege. A tool runs with the permissions of the user the agent acts for, or narrower, and never with a broad service account that can read every customer. Credentials stay in the runtime and the tools, never in the prompt or in a tool result.
Approval before side effects. Reads can run automatically. Actions that change state outside the system, such as a payment, an email or a deletion, wait for a person, who sees the exact call and its arguments. The approval belongs in the runtime, not in the system prompt: an instruction to "always ask first" is a request to the model, not a control.
Untrusted tool output. The model reads a tool result in the same context as its instructions, so a web page, an email or a document returned by a tool can carry text written to steer it. Greshake et al. (2023) (opens in a new tab) call this indirect prompt injection and demonstrated it against real LLM-integrated applications. Treat every tool result as untrusted, keep the tools that read external content apart from the tools that act, and make sure approval and least privilege hold even when the model has been misled. Prompt injection is a subject of its own.
Observability#
When an agent answers wrongly, you need to know what the model saw at the step that went wrong, and what it decided. A trace shows that; a log of the final answer does not.
OpenTelemetry names these operations in its semantic conventions for generative AI, which recently moved into their own repository, semantic-conventions-genai (opens in a new tab), first released as v0.1.0 on 21 November 2026; the GenAI pages on opentelemetry.io (opens in a new tab) now point there. All gen_ai.* names in them have the status Development, so they can still change: pin the version you implement. The shape they describe:
- One span for the agent run, with the operation name
invoke_agent. The conventions reserve it for runs where "an LLM drives the control flow through tool calls" and useinvoke_workflowwhen the application defines the control flow: the same line as the one between agents and workflows above. - One span per model call, named after the operation and the model, for example
chatfollowed by the model name, with attributes such asgen_ai.request.model,gen_ai.usage.input_tokens,gen_ai.usage.output_tokensandgen_ai.response.finish_reasons. - One span per tool call, named
execute_toolfollowed by the tool name, withgen_ai.tool.name,gen_ai.tool.call.id, anderror.typewhen it failed.
The call id on the tool span connects a tool execution to the model reply that requested it. On top of the conventions I log the run id, the step number on every span, the stop reason, the cumulative tokens and cost per step, the validation errors, and the approvals with the person who gave them.
Message and tool content is the most useful data for debugging and the most sensitive, which is why the conventions make it opt-in: gen_ai.input.messages, gen_ai.output.messages, gen_ai.tool.call.arguments and gen_ai.tool.call.result are not captured by default. Store it with access control and a retention period, and redact what does not need to be there.
Failure modes#
| Symptom | Likely cause | Fix |
|---|---|---|
| The run repeats the same tool call until the budget stops it | The result does not answer what the model asked, or the error gives it nothing to change | Specific results and errors; detect repeated identical calls; stop after a few consecutive errors |
| Arguments that do not exist, such as an invented order number | The model filled a required argument it did not have | Validate business rules, not only the schema; say where a value comes from; let the model ask the user |
| A confident answer that contradicts the data | A tool error was swallowed and returned as an empty or default result | Return errors as error results, never a silent default |
| Cost per run far above the estimate | Large tool results resent on every iteration; no token budget | Cap result size; truncate used results; enforce a token budget per run |
| A duplicate payment, email or record | A retry or a repeated call of a tool that is not idempotent | Idempotency keys per call; duplicate checks in the tool; approval for side effects |
| The API rejects the next request after a parallel batch | A call id without a result, or results split over several turns | One result per call id, all in the next turn |
| The agent follows instructions found in a web page or email | Untrusted tool output read as instructions | Least privilege, approval in the runtime, reading tools apart from acting tools |

