By Flavio
Tagged: AI
How tight JSON tool schemas cut turns and tokens in half, and the five deterministic stopping conditions every production agent loop needs.
Suppose an AI agent burns twenty turns calling the wrong function, retries a dead endpoint until it times out, or claims success when the database never changed. Most teams react by swapping in a bigger, more expensive model.
A stronger model might hide those bugs for a week. Then a new edge case shows up, and the failure comes right back because the real problem is in the harness around the model.
I ran a controlled benchmark on gpt-4.1-mini to measure how much reliability comes from the code outside the model weights. The task was straightforward: find a paid order in the EU region and mark it refunded for a customer request.
With a sloppy three-tool schema and vague error codes, gpt-4.1-mini burned 7 turns, made 6 tool calls, hit 6 errors, and spent 1,783 tokens. It gave up without ever refunding order ord_101.
With a tight strict schema on the same model, the run finished in 3 turns, 2 tool calls, 0 errors, and 788 tokens. That cut tokens by 56% and turns by 57%, and ord_101 ended up cleanly refunded.
Then I forced an upstream 503 outage so the model got stuck retrying the refund call. A deterministic duplicate-call loop breaker halted the run safely on Turn 3 at 819 tokens instead of letting it spin through ten turns.
Two things separated the failed run from the clean one: the JSON schemas describing the tools, and the stopping conditions written into the loop around the model.
Why reliability bugs live in the harness #
An agent loop is a plain while loop wrapped around a stateless text API. The model never runs your code, never connects to your database, and never remembers anything you leave out of the messages array.
Your harness owns the conversation state, the tool definitions, the validation layer, the side effects, and every exit path.
When you pull up traces from a flaky production agent, the same four root causes repeat themselves:
- Open-ended arguments. A parameter typed as
stringwith the description “filter query” forces the model to guess. Depending on the turn, it’ll invent SQL, Lucene syntax, key-value pairs, or raw JSON. - Opaque tool errors. When a tool returns a bare string like
ERR_INVALID_FILTERor400 Bad Request, the model has no stack trace and no access to your backend source code. Without a message explaining what failed and what valid input looks like, it falls back to blind trial and error. - Unchecked text exits. A model can emit a polite apology saying it couldn’t retrieve the orders, and the API still returns a clean
stoporend_turnfinish reason. If your code only checks whether the loop exited without throwing an exception, silent failures look identical to completed jobs. - Runaway retries. When an upstream payment gateway returns HTTP 503, a helpful model often retries the same call hoping the outage cleared. Without a deterministic guard in your code, a generous turn cap keeps feeding the growing transcript back into the API until your timeout or spend budget gives out.
You don’t need better model pre-training to fix any of these bugs. Treat tool calling as a strict programmatic boundary instead of a loose chat convention, and we can eliminate them in the harness.
Anatomy of a tool call on the wire #
Before we tighten schemas or write stopping guards, let’s trace what travels over HTTP during a single turn. Many harness bugs start when we picture tool calling as an in-process function call instead of a multi-request JSON exchange with strict protocol rules.
On every turn, your harness sends the conversation history (messages), the list of available tool schemas ( tools), and decoding controls like max_tokens and tool_choice. The model never sees your JavaScript or Python handlers.
Everything the model knows about a tool comes from the JSON object inside tools and any examples you put in the system prompt.
When the model needs external data or a side effect, it stops generating normal user-facing text and emits one or more structured tool call objects. In OpenAI’s Chat Completions API, those show up under message.tool_calls, where each entry carries an opaque id, a function.name, and function.arguments serialized as a JSON string.
In Anthropic’s Messages API, the same mechanism appears as tool_use blocks inside content, carrying id, name, and an already-parsed input object. Here is how one turn moves through your harness.
Parsing and pairing every call ID
That wire contract gives our loop a few operational rules to enforce on every iteration.
Start with JSON parsing. In OpenAI’s API, function.arguments arrives as a raw string, and a response cut off by max_tokens can leave half an object in that string even with strict decoding enabled.
Check finish_reason before parsing, wrap JSON.parse in a try/catch, and turn syntax failures into structured tool errors instead of letting an uncaught exception kill the worker.
Here is the wire shape of an assistant turn requesting list_orders, paired with the tool result message your harness appends before the next API call.
[
{
"role": "assistant",
"content": null,
"tool_calls": [
{
"id": "call_9f2a8c11",
"type": "function",
"function": {
"name": "list_orders",
"arguments": "{\"status\":\"paid\",\"region\":\"EU\"}"
}
}
]
},
{
"role": "tool",
"tool_call_id": "call_9f2a8c11",
"content": "{\"orders\":[{\"id\":\"ord_101\",\"customer\":\"marta@nordic.test\",\"status\":\"paid\",\"cents\":4900,\"region\":\"EU\"}]}"
}
]
Provider wire formats differ slightly on how you send that result back. OpenAI expects one role: "tool" message per tool_call_id, while Anthropic expects tool_result blocks packed inside a role: "user" message referencing each tool_use_id.
Either way, the pairing rule is strict: every emitted call ID needs a matching result before the next assistant turn begins.
Even if a tool times out, fails validation, throws an exception, or gets denied by a permission check, you still emit a tool result carrying that ID with an error payload. Skip even one ID, and the next request triggers an HTTP 400 error that breaks the conversation in half.
Steering turns and validating at runtime
You can also steer tool usage on specific turns with tool_choice:
autolets the model choose between calling a tool and replying with text.'required'forces at least one tool call on that turn, which helps on Turn 1 of a lookup workflow so the model can’t answer from memory.'none'guarantees prose on a final synthesis turn instead of letting the model sneak in one last tool call after your budget runs low.
Runtime validation sits right after JSON parsing. Never trust decoded arguments blindly, even in strict mode.
Constrained decoding enforces JSON syntax, required keys, and enum membership, yet it knows nothing about your live database state. It can’t verify whether ord_101 belongs to the authenticated account, whether a refund amount exceeds the original charge, or whether the order is already refunded.
Treat every tool invocation with the same defensive validation you’d put on an untrusted public HTTP endpoint.
How tool schemas affect token costs
Finally, pay attention to what your tools array does to token economics across turns. Because the API is stateless, Turn 1 sends the system prompt, the tools array, and the user prompt.
Turn 2 resends all of that plus Turn 1’s call and result. By Turn 10, you’ve sent the entire prefix ten times.
Say a bloated 25-tool CRUD schema adds 3,200 tokens to every request. Over 10 uncached turns, those schemas alone consume 32,000 input tokens before you even count tool outputs.
A focused 3-tool schema around 450 tokens costs 4,500 input tokens over those same 10 turns. Keeping the tools array byte-for-byte identical across turns also keeps provider prompt caches warm.
Inserting or reordering a tool mid-session busts the cached prefix and charges full input rates for everything that follows.
Designing tool schemas models rarely misuse #
A tool schema does double duty. First, the model reads the names, parameter keys, and descriptions to decide which action to take and what arguments to supply.
Second, constrained decoding engines compile the JSON Schema rules into token masks that restrict what the model can physically emit. When we tighten both halves, most multi-turn failures vanish before the loop ever hits a retry.
Coarse task-oriented tools beat CRUD sprawl
When we first connect an agent to an existing backend, the fastest shortcut is wrapping every REST endpoint or database table as its own tool. Before long the agent has thirty granular tools: get_customer, list_order_ids, fetch_order_row, list_payment_intents, create_refund_row, update_order_status, insert_audit_entry, and send_receipt_email.
That layout falls apart fast in real runs.
Tool-selection accuracy drops as the list grows, especially when names overlap. When a model sees update_order, patch_order_status, and modify_record in the same tools array, it spends turns guessing which one handles refunds cleanly.
Granular CRUD tools also push distributed transaction logic onto the LLM. If refunding an order takes four separate tool calls in sequence and the third call fails, the model has to improvise rollback steps in natural language.
Deterministic server code runs those four steps inside one database transaction and never forgets the audit row.
Coarse workflow tools keep invariants inside your backend boundary. In my MCP server design guide, I scoped a domain-registrar integration to four complete actions (search ideas, check one exact domain, create a short-lived quote, and purchase one quoted domain after approval) rather than exposing raw registrar API endpoints.
Plain function calling works best under the same rule. Use verb-first names that match a concrete unit of work (list_orders instead of query_db, mark_order_refunded instead of modify_record), and aim for 3 to 8 tools per agent.
When a single agent needs twenty tools, you usually have two distinct workflows crammed into one prompt.
Strict JSON Schema eliminates structural guesswork
Modern tool-calling endpoints support strict structured decoding (strict: true in OpenAI’s function definitions, with equivalent constrained-decoding modes across major providers). When you turn it on, the server compiles your JSON Schema into a finite-state grammar that masks out any token producing an illegal key, wrong type, or out-of-range enum value before sampling.
That wipes out a whole layer of brittle bugs. You won’t get missing required properties, typos in field names, a string "4900" when your handler expects an integer 4900, or surprise extra keys invented by the model.
Strict mode also brings a few JSON Schema constraints that trip people up until they know the rules:
- Every object needs
"additionalProperties": false. That includes nested objects inside arrays or sub-objects. Omitting it on even one nested object makes the API reject the whole request before inference begins. - Every property belongs in
required. You can’t leave optional parameters out ofrequiredin strict mode. Express optional fields as nullable unions liketype: ['string', 'null'](oranyOfpairing the real type with{ type: 'null' }), and tell the model in the description to passnullwhen it wants no filter. - Advanced keywords often fail on the wire. Depending on the provider, strict-mode grammar compilers reject or ignore complex
patternregexes,minLength,maxLength,minimum,maximum,format, andoneOfwith overlapping branches. Keep the wire schema to objects, arrays, primitives,enum,anyOf,additionalProperties: false, andrequired, then enforce regex formats or numeric ranges in your runtime validator right afterJSON.parse.
Whenever a field has a closed set of values, replace free-text strings with a narrow enum. If order status can only be paid, pending, or refunded, put those three strings in enum.
Without an enum, Turn 1 sends "paid", Turn 2 tries "PAID", and Turn 3 tries "completed".
Write parameter descriptions that answer what the model would otherwise guess. Spell out where an ID comes from, what unit a number uses (cents, not dollars), whether the tool mutates state, and one concrete example value.
Let’s compare the loose schema from my benchmark against the tight strict schema for the same order-refund job. Here is the sloppy version first.
export const sloppyTools = [
{
type: 'function',
function: {
name: 'query_db',
description: 'Query database records using a filter string.',
parameters: {
type: 'object',
properties: {
q: {
type: 'string',
description: 'Filter query string'
},
filter_mode: {
type: 'string',
description: 'Optional filter mode'
},
include_all: {
type: 'boolean',
description: 'Whether to include all rows'
}
}
}
}
},
{
type: 'function',
function: {
name: 'modify_record',
description: 'Modify a database record.',
parameters: {
type: 'object',
properties: {
table: { type: 'string' },
id: { type: 'string' },
payload: { type: 'string', description: 'JSON patch string' }
}
}
}
}
]
Count the hidden assumptions packed into those forty lines. What query grammar does q expect: status=paid, state:paid AND region:EU, or SQL?
What strings are valid for filter_mode, and what happens if include_all is true while q isn’t empty? Inside modify_record, the model even has to guess the table name and serialize a JSON patch inside another JSON string.
Now compare that with the tight strict schema wired to the same backend.
export const tightTools = [
{
type: 'function',
function: {
name: 'list_orders',
strict: true,
description: 'List customer orders filtered by exact status and region. Read-only.',
parameters: {
type: 'object',
additionalProperties: false,
required: ['status', 'region'],
properties: {
status: {
type: ['string', 'null'],
enum: ['paid', 'pending', 'refunded', null],
description: 'Exact order status to match, or null for any status.'
},
region: {
type: ['string', 'null'],
enum: ['EU', 'US', 'APAC', null],
description: 'Exact billing region code, or null for all regions.'
}
}
}
}
},
{
type: 'function',
function: {
name: 'mark_order_refunded',
strict: true,
description: 'Mark one paid order as refunded. Mutates order state; call only after confirming the order ID with list_orders.',
parameters: {
type: 'object',
additionalProperties: false,
required: ['order_id', 'reason'],
properties: {
order_id: {
type: 'string',
description: 'Exact order ID returned by list_orders, for example ord_101.'
},
reason: {
type: 'string',
enum: ['customer_request', 'duplicate_charge', 'fraud_prevention'],
description: 'Refund category recorded on the order.'
}
}
}
}
}
]
Every ambiguity is gone. The model can’t invent a query syntax, pass "Europe" instead of "EU", forget reason, or hallucinate an extra filter key.
Even a small, fast model like gpt-4.1-mini produces valid calls on the very first turn.
Eliminate boolean-flag soup
Boolean parameters look harmless in hand-written TypeScript functions, yet they quietly sabotage tool calling. Three booleans on a single tool (include_archived, include_all, exact_match) create eight possible combinations, and several of them contradict each other.
You can see that confusion in Turn 4 of my sloppy benchmark trace, where after three failed queries gpt-4.1-mini sent { "q": "state:paid", "filter_mode": "and", "include_all": true }.
It flipped include_all to true hoping to relax the query, with no way to know whether include_all overrode q or expanded the search fields.
Replace overlapping booleans with a single mutually exclusive enum: instead of pairing include_archived: boolean with only_active: boolean, expose visibility: 'active_only' | 'include_archived' | 'archived_only'.
For write tools, drop dry_run: boolean and split preview and commit into two distinct tools (preview_refund and mark_order_refunded). Separating read-only previews from mutating writes also makes permission policies, audit logs, and approval gates much easier to enforce in your harness.
This table compares loose schema habits against the tight strict patterns and their effect on the loop.
| Design dimension | Loose schema habit | Tight strict schema pattern | Effect on the agent loop |
|---|---|---|---|
| Tool naming | Generic ( query_db ,modify_record ) |
Verb-first workflow ( list_orders ,mark_order_refunded ) |
Eliminates tool-selection guesswork |
| Filtering inputs | Free-text query DSL string ( q ) |
Typed fields with enum and nullable types |
Cuts malformed filter retries to zero |
| Optional arguments | Omitted from required , loose types |
Listed in required with['type', 'null'] andstrict: true |
Enforced at token-sampling time |
| Extra keys | Unconstrained objects | additionalProperties: false on every object |
Prevents invented parameters |
| Modes and flags | Multiple booleans ( include_all ,dry_run ) |
Single mutually exclusive enum or separate tools |
Removes contradictory flag states |
| Error responses | Opaque codes ( ERR_INVALID_FILTER ) |
Structured JSON with code ,field ,hint ,retryable |
Guides immediate recovery or clean stop |
Write actionable error messages that teach recovery
Even with strict JSON Schemas, runtime errors are unavoidable. An order_id might not exist, an order might already be refunded, a user might lack permission, or an upstream gateway might return HTTP 503.
What you serialize inside the role: "tool" error response directly shapes the model’s next turn. Returning bare strings like "ERR_INVALID_FILTER" or "ERR_BAD_MODIFY" gives the model zero gradient.
It knows the call failed, has no idea why, and starts randomly permuting fields across the next five turns.
Design tool errors as structured recovery hints for an automated caller. Give every error payload a machine-readable code, a plain explanation, the offending field (when relevant), concrete allowed_values or a hint explaining the next step, and a retryable boolean.
Here is a small helper we can use to separate recoverable input mistakes from non-retryable state conflicts and upstream outages.
export function toolError({ code, message, field = null, allowedValues = null, hint, retryable }) {
return JSON.stringify({
ok: false,
error: {
code,
message,
field,
allowed_values: allowedValues,
hint,
retryable
}
})
}
const alreadyRefunded = toolError({
code: 'INVALID_STATUS_TRANSITION',
message: 'Order ord_101 is already refunded.',
field: 'order_id',
hint: 'Do not call mark_order_refunded again. Report the existing refunded status to the user.',
retryable: false
})
const gatewayDown = toolError({
code: 'UPSTREAM_503',
message: 'Payment gateway is unreachable (HTTP 503).',
hint: 'Stop retrying and tell the user the refund could not be processed because the payment gateway is down.',
retryable: false
})
Look closely at gatewayDown. Returning {"error":"UPSTREAM_503: payment gateway unreachable"} gives no signal on whether retrying might help.
In my forced 503 lab run, gpt-4.1-mini immediately repeated the same refund call on Turn 2 and Turn 3 until our loop breaker stopped it. Adding retryable: false and an explicit stop hint cuts down pointless retries, while the loop breaker underneath still protects you if a model ignores the hint.
Here is how those two paths diverge from the same refund goal.
Cap oversized tool outputs before they hit the transcript
Unbounded tool output is another quiet killer of agent loops. A list_orders handler looks clean against a 5-row local test fixture.
Then in production, a large customer has 14,000 orders. The model passes status: null and region: null, and your handler serializes 6 megabytes of JSON straight into role: "tool".
One of two bad things happens next. Either the API rejects the next turn with a context-length HTTP 400 error, or the payload barely fits and dumps 80,000 tokens of noise into the conversation.
That noise degrades attention on the original instructions and multiplies the cost of every turn that follows.
Enforce two separate ceilings on every read tool: a tight default page size inside the query (such as limit = 20) and a hard character cap at the harness boundary before appending any string to messages. When we trim an output, wrap the preview inside valid JSON metadata showing the original length and how to narrow the query.
export function formatToolResult(payload, { maxChars = 8000 } = {}) {
const raw = typeof payload === 'string' ? payload : JSON.stringify(payload)
if (raw.length <= maxChars) {
return raw
}
return JSON.stringify({
truncated: true,
original_chars: raw.length,
shown_chars: maxChars,
hint: 'Output exceeded max size. Re-run with tighter filters or a smaller limit.',
preview: raw.slice(0, maxChars)
})
}
Wrapping truncation in a valid JSON envelope beats blindly slicing the raw string with .slice(0, 8000). Half-cut JSON looks like a broken response and frequently tricks the model into calling the same tool again to fetch the missing closing braces.
Parallel tool calls, idempotency keys, and partial failures #
Modern tool-calling models rarely stop at one tool per turn when a task spans several items. Ask an agent to inspect orders across EU and US or refund two separate orders, and it’ll often return an assistant message containing two or three entries inside message.tool_calls.
Handling parallel batches cleanly takes care in three places: concurrency, side effects, and partial failure reporting.
Avoid Promise.all for tool batches
The most common bug in JavaScript agent harnesses is writing await Promise.all(toolCalls.map(runTool)). Suppose call 1 succeeds, call 2 throws a network error, and call 3 is still running.
Promise.all rejects on call 2, discards call 1’s output, skips creating role: "tool" messages for the whole batch, and leaves the transcript broken for the next API turn.
Separate read-only tools from mutating tools in your dispatcher. Run read-only calls concurrently with Promise.allSettled (bounded by a small concurrency cap if batches can grow large), and run mutating calls serially one after another.
Every tool_call_id gets its own role: "tool" message in the order emitted by the model, whether the individual call succeeded or threw.
Derive idempotency keys in the harness, not the model
In a regular web app, double writes happen when someone clicks a submit button twice. In an agent loop, double writes happen automatically.
A network timeout can drop an HTTP response after the server already committed, a retry wrapper can replay a model turn, or a partial batch failure can make the model re-emit an already-completed call alongside a failed sibling.
Every state-changing tool (refunds, outgoing emails, invoice creation, DNS updates, deploys) needs an idempotency key. Never ask the model to generate a random UUID parameter for idempotency, because on a retry turn it’ll happily invent a fresh UUID and trigger the side effect a second time.
Derive the idempotency key deterministically inside your harness or backend from (runId, toolName, canonicalArgs) or from the domain target itself, such as refund:${orderId}. When the backend receives the same key a second time within its retention window, it returns the stored result of the first execution instead of charging or refunding twice.
Preserve per-call outcomes on partial failures
When two calls in a batch succeed and one fails with a 503, return the real success payload for the two working IDs and the structured error payload for the failed ID.
The model immediately sees which work already completed and only decides how to handle the single failure, instead of starting over from scratch.
Here is a complete dispatcher that canonicalizes JSON arguments, validates inputs at runtime, and builds deterministic SHA-256 idempotency keys for mutating tools. It runs reads via Promise.allSettled, runs writes serially, and guarantees a 1-to-1 tool_call_id mapping.
import { createHash } from 'node:crypto'
export function canonicalStringify(value) {
if (value === null || typeof value !== 'object') {
return JSON.stringify(value)
}
if (Array.isArray(value)) {
return `[${value.map(canonicalStringify).join(',')}]`
}
const keys = Object.keys(value).sort()
const entries = keys.map((k) => `${JSON.stringify(k)}:${canonicalStringify(value[k])}`)
return `{${entries.join(',')}}`
}
export function buildIdempotencyKey(runId, toolName, args) {
const hash = createHash('sha256')
.update(`${runId}:${toolName}:${canonicalStringify(args)}`)
.digest('hex')
.slice(0, 24)
return `${toolName}_${hash}`
}
export async function dispatchToolCalls(toolCalls, registry, ctx) {
const results = new Map()
const readCalls = []
const writeCalls = []
for (const call of toolCalls) {
const def = registry[call.function.name]
if (!def) {
results.set(
call.id,
JSON.stringify({
ok: false,
error: {
code: 'UNKNOWN_TOOL',
message: `Tool ${call.function.name} does not exist.`,
allowed_values: Object.keys(registry),
retryable: true
}
})
)
continue
}
if (def.mutating) {
writeCalls.push({ call, def })
} else {
readCalls.push({ call, def })
}
}
const runOne = async ({ call, def }) => {
let args
try {
args = JSON.parse(call.function.arguments || '{}')
} catch (err) {
return JSON.stringify({
ok: false,
error: {
code: 'MALFORMED_JSON',
message: `Could not parse arguments JSON: ${err.message}`,
retryable: true
}
})
}
const validationError = def.validate(args)
if (validationError) {
return validationError
}
const idempotencyKey = def.mutating
? buildIdempotencyKey(ctx.runId, call.function.name, args)
: null
try {
const output = await def.execute(args, {
signal: ctx.signal,
idempotencyKey
})
return formatToolResult(output)
} catch (err) {
return JSON.stringify({
ok: false,
error: {
code: err.code || 'TOOL_EXECUTION_ERROR',
message: err.message,
hint: err.hint || 'Check the arguments or stop if this is an upstream outage.',
retryable: Boolean(err.retryable)
}
})
}
}
const readSettled = await Promise.allSettled(readCalls.map(runOne))
readCalls.forEach(({ call }, index) => {
const outcome = readSettled[index]
results.set(
call.id,
outcome.status === 'fulfilled'
? outcome.value
: JSON.stringify({
ok: false,
error: {
code: 'UNEXPECTED_FAILURE',
message: String(outcome.reason),
retryable: false
}
})
)
})
for (const item of writeCalls) {
const content = await runOne(item)
results.set(item.call.id, content)
}
return toolCalls.map((call) => ({
role: 'tool',
tool_call_id: call.id,
content: results.get(call.id)
}))
}
Even if a model invents a nonexistent tool name, passes malformed JSON, or hits a downstream exception on one call out of three, dispatchToolCalls keeps the transcript contract intact and never executes two mutating calls concurrently.
The five stopping conditions every production agent loop needs #
Tight schemas keep the model on track during normal turns, yet control flow is what protects you when something goes sideways. A loop that only stops when the model decides to stop hands an open budget to a probabilistic system.
As I wrote in Give your coding agent a state machine, the surrounding program has to own every transition and every terminal exit. Asking a model in a system prompt to “stop after three retries” is advice, while coding five deterministic stopping conditions into the loop runner turns it into an enforceable boundary.
Let’s look at the five guards I wire into every production loop.
1. Native finish_reason and stop_reason handling
Every LLM response reports why generation ended (finish_reason in OpenAI, stop_reason in Anthropic). Many quick prototype loops only check if (message.tool_calls?.length) and treat every other response as a finished answer.
That shortcut swallows real failure modes. Handle each finish reason explicitly:
tool_calls(ortool_use): the model requested tools. Run duplicate-call checks, validate, execute, and proceed to the next turn.stop(orend_turn): the model finished speaking. Pass the run through your verification gate before declaring success.length(ormax_tokens): generation hit the output token limit mid-sentence or mid-argument. Iftool_callsappear alongsidelength, their JSON is almost certainly cut off, so never execute them. Halt withoutput_truncatedor retry once with a shorter-output instruction.content_filter: provider safety filters stopped the generation. Halt immediately and surface a clear status.refusal(structuredmessage.refusalfield): the model declined the request. Stop the loop instead of arguing with it for ten more turns.
2. Hard execution budgets (turns, wall-clock time, and spend)
Every production loop needs three independent ceilings checked before and during every turn:
- Max turn cap (
maxTurns): bounds total round trips. A focused workflow like checking orders and issuing a refund finishes in 2 to 4 turns when working properly, so capping it at 8 turns stops broken runs early without hurting legitimate recovery. - Wall-clock deadline (
AbortSignal.timeout(maxDurationMs)): bounds real elapsed time. Pass thatAbortSignalinto both the model APIfetchcall and every downstream tool I/O call (HTTP requests, database clients, child processes). A turn limit alone won’t save a serverless worker or HTTP route when one stalled upstream socket hangs for four minutes. - Token and dollar budget: tracks real spend from the authoritative
usage.prompt_tokensandusage.completion_tokensfields returned on every API response. Sum those counts after each turn, compute cumulative dollars against your model’s input/output rate card, and refuse to start another turn once either cap is reached instead of relying ontext.length / 4heuristics.
3. Duplicate-call and consecutive-error loop breakers
Turn caps limit maximum damage, yet waiting until Turn 10 when a run is clearly stuck on Turn 3 wastes 70% of your tokens and user patience. Two runtime breakers catch loops the moment they form.
The duplicate-call breaker builds a canonical signature for each requested tool call by sorting object keys recursively and hashing ${toolName}:${canonicalArgs} with SHA-1 (or SHA-256). When the same signature shows up maxDuplicateCalls times (typically 2 or 3), the harness halts before invoking the tool again.
Key sorting matters because {"region":"EU","status":"paid"} and {"status":"paid","region":"EU"} are identical calls even though their raw JSON strings differ.
One practical nuance is a legitimate polling tool like check_export_status({ job_id: "exp_44" }), where calling the tool three times with identical arguments is expected while a background job finishes. Support an optional maxRepeats override per tool definition, such as maxRepeats: 6 with a short delay for read-only polling tools and 2 or 3 for everything else.
That avoids false positives on polling while keeping mutating calls tightly guarded.
The consecutive-error breaker tracks turns where tool calls keep returning errors even when the arguments change each time. In my sloppy schema benchmark, gpt-4.1-mini mutated the q parameter on every turn from Turn 1 through Turn 6, so a duplicate-call hash never tripped.
A consecutive-error limit of 3 would’ve caught that blind guessing on Turn 3 and cut the wasted token burn in half.
4. Verification-gated exit
Receiving finish_reason: "stop" only means the model chose to emit text instead of a tool call. As my sloppy benchmark proved, a model can return end_turn while politely telling the user it failed to query the database and leaving ord_101 unrefunded.
Whenever a task has a checkable outcome, verify it in code before accepting stop.
One pattern is an external state verifier in the harness. For an order-refund agent, the verifier inspects the real order record (or checks whether the model reported an expected non-retryable blocker), and for a coding agent, it runs the test command and checks the process exit code.
If verification fails and a bounded repair attempt remains (maxVerificationRetries = 1), append one concise feedback message stating what failed and give the model one chance to fix it. Cap verification retries so a failing verifier can never create an infinite repair loop.
A second pattern is an explicit submit tool (such as submit_resolution) backed by a strict schema requiring structured evidence ( order_id, outcome, summary). The harness only marks the run completed when the model invokes that submit tool and its arguments reconcile with the tool outputs observed during the run.
5. Graceful partial-result handoff
When a guard stops a run early, don’t throw a raw exception that wipes out everything the agent already accomplished.
By Turn 3, a loop might have gathered useful diagnostic context or completed one of two valid actions. Return a consistent, typed envelope on every exit path containing status ('completed' or 'halted'), the stopReason, finalText, completedActions, lastError, turns, totalTokens, and the structured trace.
That gives your application code everything it needs to show an honest message to the user (“Payment gateway returned 503, so order ord_101 was not refunded”) or hand the state off to a human operator.
Here is how the five stopping conditions compare across triggers, false-positive risks, and recovery paths.
| Stopping condition | Exact trigger in harness | What it catches | False-positive risk | Recovery action |
|---|---|---|---|---|
| Native finish reason | finish_reason islength ,content_filter , orrefusal |
Truncated tool JSON, policy halts, model refusals | Very low | Halt immediately and return typed stop reason |
| Hard execution budgets | turn >= maxTurns ,signal.aborted , ortokens >= maxTokens |
Runaway long sessions, hung sockets, spend spikes | Low when sized per workflow | Abort in-flight I/O and return partial envelope |
| Duplicate-call breaker | Same SHA-1 (tool, canonicalArgs) seen>= maxRepeats times |
Blind retries against 503 outages or dead locks | Low (raise limit on polling tools) | Block pre-execution and halt with duplicate_call_loop_breaker |
| Consecutive-error breaker | >= 3 consecutive tool turns with errors across any args |
Schema guessing and blind filter permutations | Medium on open-ended search tools | Halt with consecutive_tool_errors and surface last error |
| Verification gate | end_turn reached while post-condition check fails |
Silent failures where model apologizes or hallucinates success | Low when check tests real state | Allow 1 bounded repair turn, then halt as verification_failed |
Next is the full control flow showing how these five guards wrap each turn of the loop.
A complete runnable agent loop harness in Node.js
Putting all five guards into one reusable Node.js ESM module takes roughly 140 lines with zero external dependencies. Here is the complete loop runner wired to OpenAI’s Chat Completions API (gpt-4.1-mini).
It enforces AbortSignal.timeout, authoritative token and dollar budgets, per-tool SHA-1 duplicate detection, a consecutive-error breaker, post-condition verification, and a unified handoff envelope.
import { createHash, randomUUID } from 'node:crypto'
export async function runAgentLoop({
apiKey,
model = 'gpt-4.1-mini',
systemPrompt,
userPrompt,
tools,
registry,
verify = async () => ({ ok: true }),
maxTurns = 8,
maxTokens = 12000,
maxCostUsd = 0.05,
ratesPerMillion = { input: 0.4, output: 1.6 },
maxDurationMs = 30000,
maxDuplicateCalls = 3,
maxConsecutiveErrors = 3,
maxVerificationRetries = 1
}) {
const runId = randomUUID()
const signal = AbortSignal.timeout(maxDurationMs)
const messages = [
{ role: 'system', content: systemPrompt },
{ role: 'user', content: userPrompt }
]
const callCounts = new Map()
const trace = []
const completedActions = []
let totalTokens = 0
let estimatedCostUsd = 0
let consecutiveErrors = 0
let verificationRetries = 0
let lastError = null
const halt = (stopReason, finalText = null) => ({
runId,
status: 'halted',
stopReason,
finalText,
completedActions,
lastError,
turns: trace.length,
totalTokens,
estimatedCostUsd: Number(estimatedCostUsd.toFixed(6)),
trace
})
for (let turn = 1; turn <= maxTurns; turn += 1) {
if (signal.aborted) {
return halt('wall_clock_timeout')
}
if (totalTokens >= maxTokens) {
return halt('token_budget_exceeded')
}
if (estimatedCostUsd >= maxCostUsd) {
return halt('cost_budget_exceeded')
}
let response
try {
response = await fetch('https://api.openai.com/v1/chat/completions', {
method: 'POST',
signal,
headers: {
'content-type': 'application/json',
authorization: `Bearer ${apiKey}`
},
body: JSON.stringify({
model,
messages,
tools,
temperature: 0
})
})
} catch (err) {
lastError = err.message
return halt(signal.aborted ? 'wall_clock_timeout' : 'provider_network_error')
}
if (!response.ok) {
lastError = `HTTP ${response.status}`
return halt('provider_http_error')
}
const data = await response.json()
const promptTokens = data.usage?.prompt_tokens ?? 0
const completionTokens = data.usage?.completion_tokens ?? 0
totalTokens += data.usage?.total_tokens ?? promptTokens + completionTokens
estimatedCostUsd +=
(promptTokens / 1_000_000) * ratesPerMillion.input +
(completionTokens / 1_000_000) * ratesPerMillion.output
const choice = data.choices?.[0]
const message = choice?.message
const finishReason = choice?.finish_reason
if (!message) {
return halt('empty_model_response')
}
if (message.refusal) {
trace.push({ turn, event: 'refusal', text: message.refusal })
return halt('model_refusal', message.refusal)
}
if (finishReason === 'length') {
trace.push({ turn, event: 'length_truncated' })
return halt('output_truncated', message.content)
}
if (finishReason === 'content_filter') {
trace.push({ turn, event: 'content_filter' })
return halt('content_filter')
}
messages.push(message)
if (finishReason === 'tool_calls' && message.tool_calls?.length) {
for (const call of message.tool_calls) {
let canonicalArgs = call.function.arguments || '{}'
try {
canonicalArgs = canonicalStringify(JSON.parse(canonicalArgs))
} catch {
// Keep raw text so repeated broken JSON still trips the breaker
}
const signature = createHash('sha1')
.update(`${call.function.name}:${canonicalArgs}`)
.digest('hex')
const repeats = (callCounts.get(signature) ?? 0) + 1
callCounts.set(signature, repeats)
const toolLimit = registry[call.function.name]?.maxRepeats ?? maxDuplicateCalls
if (repeats >= toolLimit) {
trace.push({
turn,
event: 'loop_breaker_tripped',
tool: call.function.name,
args: canonicalArgs,
repeats
})
return halt('duplicate_call_loop_breaker')
}
}
const toolMessages = await dispatchToolCalls(message.tool_calls, registry, {
runId,
signal
})
let turnHadError = false
for (let i = 0; i < toolMessages.length; i += 1) {
const call = message.tool_calls[i]
const toolMsg = toolMessages[i]
messages.push(toolMsg)
const parsed = safeParseJson(toolMsg.content)
const failed = parsed?.ok === false || Boolean(parsed?.error)
if (failed) {
turnHadError = true
lastError = toolMsg.content
} else if (registry[call.function.name]?.mutating) {
completedActions.push({
turn,
tool: call.function.name,
args: safeParseJson(call.function.arguments)
})
}
trace.push({
turn,
tool: call.function.name,
args: safeParseJson(call.function.arguments),
outPreview: toolMsg.content.slice(0, 120)
})
}
consecutiveErrors = turnHadError ? consecutiveErrors + 1 : 0
if (consecutiveErrors >= maxConsecutiveErrors) {
return halt('consecutive_tool_errors')
}
continue
}
if (finishReason === 'stop') {
const check = await verify({ completedActions, finalText: message.content })
if (check.ok) {
trace.push({ turn, event: 'final_answer', text: message.content })
return {
runId,
status: 'completed',
stopReason: 'end_turn',
finalText: message.content,
completedActions,
lastError,
turns: turn,
totalTokens,
estimatedCostUsd: Number(estimatedCostUsd.toFixed(6)),
trace
}
}
if (verificationRetries < maxVerificationRetries) {
verificationRetries += 1
trace.push({ turn, event: 'verification_failed', reason: check.reason })
messages.push({
role: 'user',
content: `Verification check failed: ${check.reason}. Resolve this or explain clearly why it cannot be completed.`
})
continue
}
trace.push({ turn, event: 'verification_exhausted', reason: check.reason })
return halt('verification_failed', message.content)
}
return halt(`unexpected_finish_reason_${finishReason}`)
}
return halt('max_turns_reached')
}
function safeParseJson(text) {
try {
return JSON.parse(text)
} catch {
return null
}
}
Every exit path returns the same envelope shape. Whether the loop completes normally, trips the SHA-1 duplicate-call breaker, hits a budget ceiling, times out, or fails post-condition verification, your caller only inspects status, stopReason, and completedActions to know what happened.
Inside the live gpt-4.1-mini benchmark #
To see these patterns behave against a real model instead of synthetic mocks, I ran three live scenarios on OpenAI’s gpt-4.1-mini. Every run used the same in-memory order store and the same goal: locate the paid order in the EU region (ord_101, belonging to marta@nordic.test, 4,900 cents) and mark it refunded for a customer request.
Here is the terminal output from running those three scenarios back to back with node run.mjs.
The table below shows every measured metric from the live benchmark.
Scenario ( gpt-4.1-mini ) |
Turns | Tool calls | Tool errors | Total tokens | Goal achieved ( ord_101 refunded) |
Stop condition |
|---|---|---|---|---|---|---|
| Sloppy 3-tool schema | 7 | 6 | 6 | 1,783 | No ( false ) |
end_turn |
| Tight strict schema | 3 | 2 | 0 | 788 | Yes ( true ) |
end_turn |
| Forced 503 retry loop | 3 | 3 | 2 | 819 | Halted safely ( false ) |
duplicate_call_loop_breaker |
Moving from the sloppy schema to the tight strict schema cut turns from 7 to 3 (down 57%) and total tokens from 1,783 to 788 (down 56%). It also reduced tool errors from 6 to 0 and turned a silent failure into a verified refund.
Here is the benchmark comparison table from the live run.
Reading the turn-by-turn traces shows clearly why the numbers moved so dramatically.
Trace 1: How the sloppy schema flailed across 7 turns
In the sloppy scenario, gpt-4.1-mini had three loose tools: query_db (taking free-text q, filter_mode, and include_all), plus generic inspection and modification tools that returned opaque error strings like ERR_INVALID_FILTER and ERR_BAD_MODIFY.
Watch every turn the model attempted as query_db kept rejecting its filter syntax without explaining what valid input looked like:
- Turn 1:
query_dbwith{"q": "state:paid AND region:EU"}->ERR_INVALID_FILTER - Turn 2:
query_dbwith{"q": "state:paid region:EU"}->ERR_INVALID_FILTER - Turn 3:
query_dbwith{"q": "state:paid AND region:EU", "filter_mode": "and"}->ERR_INVALID_FILTER - Turn 4:
query_dbwith{"q": "state:paid", "filter_mode": "and", "include_all": true}->ERR_INVALID_FILTER - Turn 5:
query_dbwith{"q": "state:paid"}->ERR_INVALID_FILTER - Turn 6:
query_dbwith{}->ERR_INVALID_FILTER - Turn 7: final text reply:
"I am unable to retrieve orders with the current query format. Could you please confirm the exact filter criteria or provide more details on ..."
Look at how rationally the model tried to debug the opaque tool. It dropped AND, added filter_mode: "and", narrowed to a single term with include_all: true, stripped all flags, and tried an empty object {} hoping to list every row.
Because every failure came back as the bare token ERR_INVALID_FILTER, the model never learned the real query format.
Notice Turn 7’s stopReason too: end_turn. Any naive harness checking only for a non-error text response would log this run as finished, even though ord_101 stayed untouched in paid status.
A post-condition verification gate catches that silent miss immediately.
Trace 2: The tight strict schema finishing in 3 turns
Next, the same gpt-4.1-mini model ran with list_orders and mark_order_refunded, backed by strict JSON Schema ( strict: true, additionalProperties: false, narrow enums for status, region, and reason). Here is the entire 3-turn trace:
- Turn 1:
list_orderswith{"status": "paid", "region": "EU"}->{"orders":[{"id":"ord_101","customer":"marta@nordic.test","status":"paid","cents":4900,"region":"EU",...}]} - Turn 2:
mark_order_refundedwith{"order_id": "ord_101", "reason": "customer_request"}->{"ok":true,"order":{"id":"ord_101","customer":"marta@nordic.test","status":"refunded","cents":4900,...}} - Turn 3: final answer:
"There was one paid order in the EU region (order ID ord_101). It has been refunded due to a customer request."
There were zero syntax guesses, zero tool errors, and 995 fewer tokens spent than in the failed sloppy run. Every argument matched the backend contract on the first try, and ord_101 ended in refunded status.
Trace 3: Halting a forced 503 retry loop on Turn 3
Strict schemas prevent self-inflicted argument mistakes, yet real production dependencies still go down. In the third test, I gave gpt-4.1-mini the same tight schema, pointed it straight at ord_101, and configured mark_order_refunded to simulate an unreachable payment gateway ({"error":"UPSTREAM_503: payment gateway unreachable"}).
Here is what happened across the 3 turns:
- Turn 1:
mark_order_refundedwith{"order_id": "ord_101", "reason": "customer_request"}->{"error":"UPSTREAM_503: payment gateway unreachable"} - Turn 2:
mark_order_refundedwith{"order_id": "ord_101", "reason": "customer_request"}->{"error":"UPSTREAM_503: payment gateway unreachable"} - Turn 3: model emitted
mark_order_refundedwith{"order_id": "ord_101", "reason": "customer_request"}a third time -> the SHA-1 duplicate-call loop breaker sawrepeats === 3and blocked execution before calling the tool a third time. It loggedloop_breaker_trippedand halted cleanly withstopReason: "duplicate_call_loop_breaker"at 819 tokens.
Without that SHA-1 breaker, the model would’ve kept hammering the degraded payment gateway and resending the growing transcript all the way to Turn 10. With the breaker in place, the run stopped on Turn 3 at almost the same token count as the happy path (819 vs 788), returning a clean halted status instead of burning money on retries.
How I build agent loops for production #
Before I write an agent loop for a new feature, I ask whether the job needs a loop at all.
If every input always runs the same two or three steps in a fixed sequence, a plain deterministic script with one structured LLM call in the middle beats an agent loop on latency, cost, and testability. An agent loop only earns its extra moving parts when the next operation genuinely depends on what the previous tool returned, such as triaging messy account state, inspecting a codebase, or choosing among several recovery paths.
When a workflow really needs a loop, I design the tool surface before writing any system prompt. If I can’t describe a tool’s job in one short sentence without using the word “or”, I split it into two tools.
Every tool gets strict: true, additionalProperties: false, explicit enums wherever the domain is finite, and nullable types for optional filters.
I also test every tool handler with deliberately wrong inputs and read the error JSON as if I were a model seeing the API for the first time. Whenever an error doesn’t explain what broke, whether retrying makes sense, and what valid input looks like, I rewrite it before shipping.
On the control-flow side, I wire the five stopping conditions into one shared loop runner and forbid feature code from writing ad-hoc while (true) loops. Individual workflows only tune the bounds (maxTurns, maxTokens, maxCostUsd, maxDurationMs, maxDuplicateCalls, and an optional verify check).
Once a loop is live, I log the full structured envelope (runId, turn count, tool signatures, token usage, and stopReason) for every execution and read ten halted traces a week. Almost every time a trace trips duplicate_call_loop_breaker or consecutive_tool_errors, the fix turns out to be a small edit to one tool description, one enum, or one error hint.
Before putting any agent loop in front of real users or real money, I check off these ten items:
- 3 to 8 verb-first workflow tools per agent instead of auto-generated CRUD wrappers.
strict: trueandadditionalProperties: falseon every object schema, with closed string domains turned intoenumarrays.- Overlapping boolean flags replaced by mutually exclusive enums, and read-only previews split from mutating writes.
- Hard length caps on tool outputs inside the harness, with truncated previews wrapped in valid JSON metadata.
- Every
tool_call_idpaired with arole: "tool"result even on parse, validation, or execution failures, running reads withPromise.allSettledand writes serially. - Deterministic idempotency keys derived in the harness for every mutating tool call.
- Explicit switching on every
finish_reason(tool_calls,stop,length,content_filter,refusal). - Hard caps on turn count, wall-clock duration (
AbortSignal.timeout), and authoritative API token and dollar spend. - Both a canonicalized SHA-1 duplicate-call breaker (with per-tool overrides for polling) and a consecutive-error breaker on every tool dispatch.
- A real post-condition check or strict submit tool required before marking a run completed, plus a typed partial-result envelope whenever any guard halts the loop.
When those checks live in your harness code, even a small, inexpensive model like gpt-4.1-mini handles multi-step tool workflows predictably and fails safely when downstream systems go down.
Pair these loop guards with structured outputs and few-shot examples for validating final payloads, and token pricing and budgeting for wiring authoritative dollar caps around multi-turn agent runs.
Want me to talk about your product? You can sponsor this site.