{"slug": "tool-schemas-and-stopping-conditions-for-reliable-agent-loops", "title": "Tool schemas and stopping conditions for reliable agent loops", "summary": "A controlled benchmark on gpt-4.1-mini found that tightening JSON tool schemas cut a refund task from 7 turns, 6 tool calls, 6 errors and 1,783 tokens to 3 turns, 2 tool calls, 0 errors and 788 tokens — a 56% token reduction and 57% fewer turns — with order ord_101 successfully refunded instead of abandoned. The author also forced an upstream 503 outage and showed a deterministic duplicate-call loop breaker halting the run safely on Turn 3 at 819 tokens rather than spinning through ten turns. The results argue that agent reliability failures stem from the harness — open-ended arguments, opaque tool errors, unchecked text exits and runaway retries — rather than from model weights.", "body_md": "# Tool schemas and stopping conditions for reliable agent loops\n\nBy [Flavio](https://flaviocopes.com/about/)\n\nTagged: [AI](https://flaviocopes.com/tags/ai/)\n\nHow tight JSON tool schemas cut turns and tokens in half, and the five deterministic stopping conditions every production agent loop needs.\n\nSuppose 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.\n\nA 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.\n\nI 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.\n\nWith 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`.\n\nWith 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.\n\nThen 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.\n\nTwo 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.\n\n## Why reliability bugs live in the harness\n\nAn [agent loop](https://flaviocopes.com/ai-glossary/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.\n\nYour harness owns the conversation state, the tool definitions, the validation layer, the side effects, and every exit path.\n\nWhen you pull up traces from a flaky production agent, the same four root causes repeat themselves:\n\n- **Open-ended arguments.** A parameter typed as`string` with 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.\n- **Opaque tool errors.** When a tool returns a bare string like`ERR_INVALID_FILTER` or`400 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.\n- **Unchecked text exits.** A model can emit a polite apology saying it couldn’t retrieve the orders, and the API still returns a clean`stop` or`end_turn` finish reason. If your code only checks whether the loop exited without throwing an exception, silent failures look identical to completed jobs.\n- **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.\n\nYou don’t need better model pre-training to fix any of these bugs. Treat [tool calling](https://flaviocopes.com/ai-glossary/tool-calling/) as a strict programmatic boundary instead of a loose chat convention, and we can eliminate them in the harness.\n\n## Anatomy of a tool call on the wire\n\nBefore 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.\n\nOn 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.\n\nEverything the model knows about a tool comes from the JSON object inside `tools` and any examples you put in the system prompt.\n\nWhen 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.\n\nIn 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.\n\n### Parsing and pairing every call ID\n\nThat wire contract gives our loop a few operational rules to enforce on every iteration.\n\nStart 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.\n\nCheck `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.\n\nHere 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.\n\n```\n[\n  {\n    \"role\": \"assistant\",\n    \"content\": null,\n    \"tool_calls\": [\n      {\n        \"id\": \"call_9f2a8c11\",\n        \"type\": \"function\",\n        \"function\": {\n          \"name\": \"list_orders\",\n          \"arguments\": \"{\\\"status\\\":\\\"paid\\\",\\\"region\\\":\\\"EU\\\"}\"\n        }\n      }\n    ]\n  },\n  {\n    \"role\": \"tool\",\n    \"tool_call_id\": \"call_9f2a8c11\",\n    \"content\": \"{\\\"orders\\\":[{\\\"id\\\":\\\"ord_101\\\",\\\"customer\\\":\\\"marta@nordic.test\\\",\\\"status\\\":\\\"paid\\\",\\\"cents\\\":4900,\\\"region\\\":\\\"EU\\\"}]}\"\n  }\n]\n```\n\nProvider 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`.\n\nEither way, the pairing rule is strict: every emitted call ID needs a matching result before the next assistant turn begins.\n\nEven 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.\n\n### Steering turns and validating at runtime\n\nYou can also steer tool usage on specific turns with `tool_choice`:\n\n- `auto` lets the model choose between calling a tool and replying with text.\n- `'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.\n- `'none'` guarantees prose on a final synthesis turn instead of letting the model sneak in one last tool call after your budget runs low.\n\nRuntime validation sits right after JSON parsing. Never trust decoded arguments blindly, even in strict mode.\n\nConstrained 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.\n\nTreat every tool invocation with the same defensive validation you’d put on an untrusted public HTTP endpoint.\n\n### How tool schemas affect token costs\n\nFinally, 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.\n\nTurn 2 resends all of that plus Turn 1’s call and result. By Turn 10, you’ve sent the entire prefix ten times.\n\nSay 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.\n\nA 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.\n\nInserting or reordering a tool mid-session busts the cached prefix and charges full input rates for everything that follows.\n\n## Designing tool schemas models rarely misuse\n\nA 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.\n\nSecond, 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.\n\n### Coarse task-oriented tools beat CRUD sprawl\n\nWhen 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`.\n\nThat layout falls apart fast in real runs.\n\nTool-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.\n\nGranular 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.\n\nDeterministic server code runs those four steps inside one database transaction and never forgets the audit row.\n\nCoarse workflow tools keep invariants inside your backend boundary. In my [MCP server design guide](https://flaviocopes.com/product-mcp/), 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.\n\nPlain 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.\n\nWhen a single agent needs twenty tools, you usually have two distinct workflows crammed into one prompt.\n\n### Strict JSON Schema eliminates structural guesswork\n\nModern 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.\n\nThat 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.\n\nStrict mode also brings a few JSON Schema constraints that trip people up until they know the rules:\n\n- **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.\n- **Every property belongs in `required`.** You can’t leave optional parameters out of` required` in strict mode. Express optional fields as nullable unions like`type: ['string', 'null']` (or`anyOf` pairing the real type with`{ type: 'null' }` ), and tell the model in the description to pass`null` when it wants no filter.\n- **Advanced keywords often fail on the wire.** Depending on the provider, strict-mode grammar compilers reject or ignore complex`pattern` regexes,`minLength` ,`maxLength` ,`minimum` ,`maximum` ,`format` , and`oneOf` with overlapping branches. Keep the wire schema to objects, arrays, primitives,`enum` ,`anyOf` ,`additionalProperties: false` , and`required` , then enforce regex formats or numeric ranges in your runtime validator right after`JSON.parse` .\n\nWhenever 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`.\n\nWithout an enum, Turn 1 sends `\"paid\"`, Turn 2 tries `\"PAID\"`, and Turn 3 tries `\"completed\"`.\n\nWrite 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.\n\nLet’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.\n\n``` js\nexport const sloppyTools = [\n  {\n    type: 'function',\n    function: {\n      name: 'query_db',\n      description: 'Query database records using a filter string.',\n      parameters: {\n        type: 'object',\n        properties: {\n          q: {\n            type: 'string',\n            description: 'Filter query string'\n          },\n          filter_mode: {\n            type: 'string',\n            description: 'Optional filter mode'\n          },\n          include_all: {\n            type: 'boolean',\n            description: 'Whether to include all rows'\n          }\n        }\n      }\n    }\n  },\n  {\n    type: 'function',\n    function: {\n      name: 'modify_record',\n      description: 'Modify a database record.',\n      parameters: {\n        type: 'object',\n        properties: {\n          table: { type: 'string' },\n          id: { type: 'string' },\n          payload: { type: 'string', description: 'JSON patch string' }\n        }\n      }\n    }\n  }\n]\n```\n\nCount the hidden assumptions packed into those forty lines. What query grammar does `q` expect: `status=paid`, `state:paid AND region:EU`, or SQL?\n\nWhat 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.\n\nNow compare that with the tight strict schema wired to the same backend.\n\n``` js\nexport const tightTools = [\n  {\n    type: 'function',\n    function: {\n      name: 'list_orders',\n      strict: true,\n      description: 'List customer orders filtered by exact status and region. Read-only.',\n      parameters: {\n        type: 'object',\n        additionalProperties: false,\n        required: ['status', 'region'],\n        properties: {\n          status: {\n            type: ['string', 'null'],\n            enum: ['paid', 'pending', 'refunded', null],\n            description: 'Exact order status to match, or null for any status.'\n          },\n          region: {\n            type: ['string', 'null'],\n            enum: ['EU', 'US', 'APAC', null],\n            description: 'Exact billing region code, or null for all regions.'\n          }\n        }\n      }\n    }\n  },\n  {\n    type: 'function',\n    function: {\n      name: 'mark_order_refunded',\n      strict: true,\n      description: 'Mark one paid order as refunded. Mutates order state; call only after confirming the order ID with list_orders.',\n      parameters: {\n        type: 'object',\n        additionalProperties: false,\n        required: ['order_id', 'reason'],\n        properties: {\n          order_id: {\n            type: 'string',\n            description: 'Exact order ID returned by list_orders, for example ord_101.'\n          },\n          reason: {\n            type: 'string',\n            enum: ['customer_request', 'duplicate_charge', 'fraud_prevention'],\n            description: 'Refund category recorded on the order.'\n          }\n        }\n      }\n    }\n  }\n]\n```\n\nEvery ambiguity is gone. The model can’t invent a query syntax, pass `\"Europe\"` instead of `\"EU\"`, forget `reason`, or hallucinate an extra filter key.\n\nEven a small, fast model like `gpt-4.1-mini` produces valid calls on the very first turn.\n\n### Eliminate boolean-flag soup\n\nBoolean 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.\n\nYou 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 }`.\n\nIt 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.\n\nReplace 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'`.\n\nFor 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.\n\nThis table compares loose schema habits against the tight strict patterns and their effect on the loop.\n\n| Design dimension | Loose schema habit | Tight strict schema pattern | Effect on the agent loop | \n|---|---|---|---|\n| Tool naming | Generic ( `query_db` ,`modify_record` ) | Verb-first workflow ( `list_orders` ,`mark_order_refunded` ) | Eliminates tool-selection guesswork | \n| Filtering inputs | Free-text query DSL string ( `q` ) | Typed fields with `enum` and nullable types | Cuts malformed filter retries to zero | \n| Optional arguments | Omitted from `required` , loose types | Listed in `required` with`['type', 'null']` and`strict: true` | Enforced at token-sampling time | \n| Extra keys | Unconstrained objects | `additionalProperties: false` on every object | Prevents invented parameters | \n| Modes and flags | Multiple booleans ( `include_all` ,`dry_run` ) | Single mutually exclusive `enum` or separate tools | Removes contradictory flag states | \n| Error responses | Opaque codes ( `ERR_INVALID_FILTER` ) | Structured JSON with `code` ,`field` ,`hint` ,`retryable` | Guides immediate recovery or clean stop | \n\n### Write actionable error messages that teach recovery\n\nEven 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.\n\nWhat 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.\n\nIt knows the call failed, has no idea *why*, and starts randomly permuting fields across the next five turns.\n\nDesign 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.\n\nHere is a small helper we can use to separate recoverable input mistakes from non-retryable state conflicts and upstream outages.\n\n```\nexport function toolError({ code, message, field = null, allowedValues = null, hint, retryable }) {\n  return JSON.stringify({\n    ok: false,\n    error: {\n      code,\n      message,\n      field,\n      allowed_values: allowedValues,\n      hint,\n      retryable\n    }\n  })\n}\n\nconst alreadyRefunded = toolError({\n  code: 'INVALID_STATUS_TRANSITION',\n  message: 'Order ord_101 is already refunded.',\n  field: 'order_id',\n  hint: 'Do not call mark_order_refunded again. Report the existing refunded status to the user.',\n  retryable: false\n})\n\nconst gatewayDown = toolError({\n  code: 'UPSTREAM_503',\n  message: 'Payment gateway is unreachable (HTTP 503).',\n  hint: 'Stop retrying and tell the user the refund could not be processed because the payment gateway is down.',\n  retryable: false\n})\n```\n\nLook closely at `gatewayDown`. Returning `{\"error\":\"UPSTREAM_503: payment gateway unreachable\"}` gives no signal on whether retrying might help.\n\nIn 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.\n\nHere is how those two paths diverge from the same refund goal.\n\n### Cap oversized tool outputs before they hit the transcript\n\nUnbounded tool output is another quiet killer of agent loops. A `list_orders` handler looks clean against a 5-row local test fixture.\n\nThen 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\"`.\n\nOne 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.\n\nThat noise degrades attention on the original instructions and multiplies the cost of every turn that follows.\n\nEnforce 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.\n\n``` js\nexport function formatToolResult(payload, { maxChars = 8000 } = {}) {\n  const raw = typeof payload === 'string' ? payload : JSON.stringify(payload)\n  if (raw.length <= maxChars) {\n    return raw\n  }\n\n  return JSON.stringify({\n    truncated: true,\n    original_chars: raw.length,\n    shown_chars: maxChars,\n    hint: 'Output exceeded max size. Re-run with tighter filters or a smaller limit.',\n    preview: raw.slice(0, maxChars)\n  })\n}\n```\n\nWrapping 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.\n\n## Parallel tool calls, idempotency keys, and partial failures\n\nModern 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`.\n\nHandling parallel batches cleanly takes care in three places: concurrency, side effects, and partial failure reporting.\n\n### Avoid `Promise.all` for tool batches\n\nThe 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.\n\n`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.\n\nSeparate 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.\n\nEvery `tool_call_id` gets its own `role: \"tool\"` message in the order emitted by the model, whether the individual call succeeded or threw.\n\n### Derive idempotency keys in the harness, not the model\n\nIn a regular web app, double writes happen when someone clicks a submit button twice. In an agent loop, double writes happen automatically.\n\nA 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.\n\nEvery 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.\n\nDerive 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.\n\n### Preserve per-call outcomes on partial failures\n\nWhen 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.\n\nThe model immediately sees which work already completed and only decides how to handle the single failure, instead of starting over from scratch.\n\nHere 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.\n\n``` js\nimport { createHash } from 'node:crypto'\n\nexport function canonicalStringify(value) {\n  if (value === null || typeof value !== 'object') {\n    return JSON.stringify(value)\n  }\n  if (Array.isArray(value)) {\n    return `[${value.map(canonicalStringify).join(',')}]`\n  }\n  const keys = Object.keys(value).sort()\n  const entries = keys.map((k) => `${JSON.stringify(k)}:${canonicalStringify(value[k])}`)\n  return `{${entries.join(',')}}`\n}\n\nexport function buildIdempotencyKey(runId, toolName, args) {\n  const hash = createHash('sha256')\n    .update(`${runId}:${toolName}:${canonicalStringify(args)}`)\n    .digest('hex')\n    .slice(0, 24)\n  return `${toolName}_${hash}`\n}\n\nexport async function dispatchToolCalls(toolCalls, registry, ctx) {\n  const results = new Map()\n  const readCalls = []\n  const writeCalls = []\n\n  for (const call of toolCalls) {\n    const def = registry[call.function.name]\n    if (!def) {\n      results.set(\n        call.id,\n        JSON.stringify({\n          ok: false,\n          error: {\n            code: 'UNKNOWN_TOOL',\n            message: `Tool ${call.function.name} does not exist.`,\n            allowed_values: Object.keys(registry),\n            retryable: true\n          }\n        })\n      )\n      continue\n    }\n    if (def.mutating) {\n      writeCalls.push({ call, def })\n    } else {\n      readCalls.push({ call, def })\n    }\n  }\n\n  const runOne = async ({ call, def }) => {\n    let args\n    try {\n      args = JSON.parse(call.function.arguments || '{}')\n    } catch (err) {\n      return JSON.stringify({\n        ok: false,\n        error: {\n          code: 'MALFORMED_JSON',\n          message: `Could not parse arguments JSON: ${err.message}`,\n          retryable: true\n        }\n      })\n    }\n\n    const validationError = def.validate(args)\n    if (validationError) {\n      return validationError\n    }\n\n    const idempotencyKey = def.mutating\n      ? buildIdempotencyKey(ctx.runId, call.function.name, args)\n      : null\n\n    try {\n      const output = await def.execute(args, {\n        signal: ctx.signal,\n        idempotencyKey\n      })\n      return formatToolResult(output)\n    } catch (err) {\n      return JSON.stringify({\n        ok: false,\n        error: {\n          code: err.code || 'TOOL_EXECUTION_ERROR',\n          message: err.message,\n          hint: err.hint || 'Check the arguments or stop if this is an upstream outage.',\n          retryable: Boolean(err.retryable)\n        }\n      })\n    }\n  }\n\n  const readSettled = await Promise.allSettled(readCalls.map(runOne))\n  readCalls.forEach(({ call }, index) => {\n    const outcome = readSettled[index]\n    results.set(\n      call.id,\n      outcome.status === 'fulfilled'\n        ? outcome.value\n        : JSON.stringify({\n            ok: false,\n            error: {\n              code: 'UNEXPECTED_FAILURE',\n              message: String(outcome.reason),\n              retryable: false\n            }\n          })\n    )\n  })\n\n  for (const item of writeCalls) {\n    const content = await runOne(item)\n    results.set(item.call.id, content)\n  }\n\n  return toolCalls.map((call) => ({\n    role: 'tool',\n    tool_call_id: call.id,\n    content: results.get(call.id)\n  }))\n}\n```\n\nEven 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.\n\n## The five stopping conditions every production agent loop needs\n\nTight 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.\n\nAs I wrote in [Give your coding agent a state machine](https://flaviocopes.com/agent-state-machines/), 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.\n\nLet’s look at the five guards I wire into every production loop.\n\n### 1. Native `finish_reason` and `stop_reason` handling\n\nEvery 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.\n\nThat shortcut swallows real failure modes. Handle each finish reason explicitly:\n\n- `tool_calls` (or`tool_use` ): the model requested tools. Run duplicate-call checks, validate, execute, and proceed to the next turn.\n- `stop` (or`end_turn` ): the model finished speaking. Pass the run through your verification gate before declaring success.\n- `length` (or`max_tokens` ): generation hit the output token limit mid-sentence or mid-argument. If`tool_calls` appear alongside`length` , their JSON is almost certainly cut off, so never execute them. Halt with`output_truncated` or retry once with a shorter-output instruction.\n- `content_filter` : provider safety filters stopped the generation. Halt immediately and surface a clear status.\n- `refusal` (structured`message.refusal` field): the model declined the request. Stop the loop instead of arguing with it for ten more turns.\n\n### 2. Hard execution budgets (turns, wall-clock time, and spend)\n\nEvery production loop needs three independent ceilings checked before and during every turn:\n\n- **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.\n- **Wall-clock deadline (`AbortSignal.timeout(maxDurationMs)`):** bounds real elapsed time. Pass that` AbortSignal` into both the model API`fetch` call 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.\n- **Token and dollar budget:** tracks real spend from the authoritative`usage.prompt_tokens` and`usage.completion_tokens` fields 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 on`text.length / 4` heuristics.\n\n### 3. Duplicate-call and consecutive-error loop breakers\n\nTurn 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.\n\nThe **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.\n\nKey sorting matters because `{\"region\":\"EU\",\"status\":\"paid\"}` and `{\"status\":\"paid\",\"region\":\"EU\"}` are identical calls even though their raw JSON strings differ.\n\nOne 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.\n\nThat avoids false positives on polling while keeping mutating calls tightly guarded.\n\nThe **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.\n\nA consecutive-error limit of 3 would’ve caught that blind guessing on Turn 3 and cut the wasted token burn in half.\n\n### 4. Verification-gated exit\n\nReceiving `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.\n\nWhenever a task has a checkable outcome, verify it in code before accepting `stop`.\n\nOne 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.\n\nIf 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.\n\nA 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.\n\n### 5. Graceful partial-result handoff\n\nWhen a guard stops a run early, don’t throw a raw exception that wipes out everything the agent already accomplished.\n\nBy 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`.\n\nThat 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.\n\nHere is how the five stopping conditions compare across triggers, false-positive risks, and recovery paths.\n\n| Stopping condition | Exact trigger in harness | What it catches | False-positive risk | Recovery action | \n|---|---|---|---|---|\n| Native finish reason | `finish_reason` is`length` ,`content_filter` , or`refusal` | Truncated tool JSON, policy halts, model refusals | Very low | Halt immediately and return typed stop reason | \n| Hard execution budgets | `turn >= maxTurns` ,`signal.aborted` , or`tokens >= maxTokens` | Runaway long sessions, hung sockets, spend spikes | Low when sized per workflow | Abort in-flight I/O and return partial envelope | \n| 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` | \n| 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 | \n| 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` | \n\nNext is the full control flow showing how these five guards wrap each turn of the loop.\n\n### A complete runnable agent loop harness in Node.js\n\nPutting 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`).\n\nIt 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.\n\n``` js\nimport { createHash, randomUUID } from 'node:crypto'\n\nexport async function runAgentLoop({\n  apiKey,\n  model = 'gpt-4.1-mini',\n  systemPrompt,\n  userPrompt,\n  tools,\n  registry,\n  verify = async () => ({ ok: true }),\n  maxTurns = 8,\n  maxTokens = 12000,\n  maxCostUsd = 0.05,\n  ratesPerMillion = { input: 0.4, output: 1.6 },\n  maxDurationMs = 30000,\n  maxDuplicateCalls = 3,\n  maxConsecutiveErrors = 3,\n  maxVerificationRetries = 1\n}) {\n  const runId = randomUUID()\n  const signal = AbortSignal.timeout(maxDurationMs)\n  const messages = [\n    { role: 'system', content: systemPrompt },\n    { role: 'user', content: userPrompt }\n  ]\n\n  const callCounts = new Map()\n  const trace = []\n  const completedActions = []\n  let totalTokens = 0\n  let estimatedCostUsd = 0\n  let consecutiveErrors = 0\n  let verificationRetries = 0\n  let lastError = null\n\n  const halt = (stopReason, finalText = null) => ({\n    runId,\n    status: 'halted',\n    stopReason,\n    finalText,\n    completedActions,\n    lastError,\n    turns: trace.length,\n    totalTokens,\n    estimatedCostUsd: Number(estimatedCostUsd.toFixed(6)),\n    trace\n  })\n\n  for (let turn = 1; turn <= maxTurns; turn += 1) {\n    if (signal.aborted) {\n      return halt('wall_clock_timeout')\n    }\n    if (totalTokens >= maxTokens) {\n      return halt('token_budget_exceeded')\n    }\n    if (estimatedCostUsd >= maxCostUsd) {\n      return halt('cost_budget_exceeded')\n    }\n\n    let response\n    try {\n      response = await fetch('https://api.openai.com/v1/chat/completions', {\n        method: 'POST',\n        signal,\n        headers: {\n          'content-type': 'application/json',\n          authorization: `Bearer ${apiKey}`\n        },\n        body: JSON.stringify({\n          model,\n          messages,\n          tools,\n          temperature: 0\n        })\n      })\n    } catch (err) {\n      lastError = err.message\n      return halt(signal.aborted ? 'wall_clock_timeout' : 'provider_network_error')\n    }\n\n    if (!response.ok) {\n      lastError = `HTTP ${response.status}`\n      return halt('provider_http_error')\n    }\n\n    const data = await response.json()\n    const promptTokens = data.usage?.prompt_tokens ?? 0\n    const completionTokens = data.usage?.completion_tokens ?? 0\n    totalTokens += data.usage?.total_tokens ?? promptTokens + completionTokens\n    estimatedCostUsd +=\n      (promptTokens / 1_000_000) * ratesPerMillion.input +\n      (completionTokens / 1_000_000) * ratesPerMillion.output\n\n    const choice = data.choices?.[0]\n    const message = choice?.message\n    const finishReason = choice?.finish_reason\n\n    if (!message) {\n      return halt('empty_model_response')\n    }\n\n    if (message.refusal) {\n      trace.push({ turn, event: 'refusal', text: message.refusal })\n      return halt('model_refusal', message.refusal)\n    }\n\n    if (finishReason === 'length') {\n      trace.push({ turn, event: 'length_truncated' })\n      return halt('output_truncated', message.content)\n    }\n\n    if (finishReason === 'content_filter') {\n      trace.push({ turn, event: 'content_filter' })\n      return halt('content_filter')\n    }\n\n    messages.push(message)\n\n    if (finishReason === 'tool_calls' && message.tool_calls?.length) {\n      for (const call of message.tool_calls) {\n        let canonicalArgs = call.function.arguments || '{}'\n        try {\n          canonicalArgs = canonicalStringify(JSON.parse(canonicalArgs))\n        } catch {\n          // Keep raw text so repeated broken JSON still trips the breaker\n        }\n\n        const signature = createHash('sha1')\n          .update(`${call.function.name}:${canonicalArgs}`)\n          .digest('hex')\n\n        const repeats = (callCounts.get(signature) ?? 0) + 1\n        callCounts.set(signature, repeats)\n\n        const toolLimit = registry[call.function.name]?.maxRepeats ?? maxDuplicateCalls\n        if (repeats >= toolLimit) {\n          trace.push({\n            turn,\n            event: 'loop_breaker_tripped',\n            tool: call.function.name,\n            args: canonicalArgs,\n            repeats\n          })\n          return halt('duplicate_call_loop_breaker')\n        }\n      }\n\n      const toolMessages = await dispatchToolCalls(message.tool_calls, registry, {\n        runId,\n        signal\n      })\n\n      let turnHadError = false\n      for (let i = 0; i < toolMessages.length; i += 1) {\n        const call = message.tool_calls[i]\n        const toolMsg = toolMessages[i]\n        messages.push(toolMsg)\n\n        const parsed = safeParseJson(toolMsg.content)\n        const failed = parsed?.ok === false || Boolean(parsed?.error)\n        if (failed) {\n          turnHadError = true\n          lastError = toolMsg.content\n        } else if (registry[call.function.name]?.mutating) {\n          completedActions.push({\n            turn,\n            tool: call.function.name,\n            args: safeParseJson(call.function.arguments)\n          })\n        }\n\n        trace.push({\n          turn,\n          tool: call.function.name,\n          args: safeParseJson(call.function.arguments),\n          outPreview: toolMsg.content.slice(0, 120)\n        })\n      }\n\n      consecutiveErrors = turnHadError ? consecutiveErrors + 1 : 0\n      if (consecutiveErrors >= maxConsecutiveErrors) {\n        return halt('consecutive_tool_errors')\n      }\n\n      continue\n    }\n\n    if (finishReason === 'stop') {\n      const check = await verify({ completedActions, finalText: message.content })\n      if (check.ok) {\n        trace.push({ turn, event: 'final_answer', text: message.content })\n        return {\n          runId,\n          status: 'completed',\n          stopReason: 'end_turn',\n          finalText: message.content,\n          completedActions,\n          lastError,\n          turns: turn,\n          totalTokens,\n          estimatedCostUsd: Number(estimatedCostUsd.toFixed(6)),\n          trace\n        }\n      }\n\n      if (verificationRetries < maxVerificationRetries) {\n        verificationRetries += 1\n        trace.push({ turn, event: 'verification_failed', reason: check.reason })\n        messages.push({\n          role: 'user',\n          content: `Verification check failed: ${check.reason}. Resolve this or explain clearly why it cannot be completed.`\n        })\n        continue\n      }\n\n      trace.push({ turn, event: 'verification_exhausted', reason: check.reason })\n      return halt('verification_failed', message.content)\n    }\n\n    return halt(`unexpected_finish_reason_${finishReason}`)\n  }\n\n  return halt('max_turns_reached')\n}\n\nfunction safeParseJson(text) {\n  try {\n    return JSON.parse(text)\n  } catch {\n    return null\n  }\n}\n```\n\nEvery 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.\n\n## Inside the live `gpt-4.1-mini` benchmark\n\nTo 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.\n\nHere is the terminal output from running those three scenarios back to back with `node run.mjs`.\n\nThe table below shows every measured metric from the live benchmark.\n\n| Scenario ( `gpt-4.1-mini` ) | Turns | Tool calls | Tool errors | Total tokens | Goal achieved ( `ord_101` refunded) | Stop condition | \n|---|---|---|---|---|---|---|\n| Sloppy 3-tool schema | 7 | 6 | 6 | 1,783 | No ( `false` ) | `end_turn` | \n| Tight strict schema | 3 | 2 | 0 | 788 | Yes ( `true` ) | `end_turn` | \n| Forced 503 retry loop | 3 | 3 | 2 | 819 | Halted safely ( `false` ) | `duplicate_call_loop_breaker` | \n\nMoving 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.\n\nHere is the benchmark comparison table from the live run.\n\nReading the turn-by-turn traces shows clearly why the numbers moved so dramatically.\n\n### Trace 1: How the sloppy schema flailed across 7 turns\n\nIn 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`.\n\nWatch every turn the model attempted as `query_db` kept rejecting its filter syntax without explaining what valid input looked like:\n\n- Turn 1: `query_db` with`{\"q\": \"state:paid AND region:EU\"}` ->`ERR_INVALID_FILTER`\n- Turn 2: `query_db` with`{\"q\": \"state:paid region:EU\"}` ->`ERR_INVALID_FILTER`\n- Turn 3: `query_db` with`{\"q\": \"state:paid AND region:EU\", \"filter_mode\": \"and\"}` ->`ERR_INVALID_FILTER`\n- Turn 4: `query_db` with`{\"q\": \"state:paid\", \"filter_mode\": \"and\", \"include_all\": true}` ->`ERR_INVALID_FILTER`\n- Turn 5: `query_db` with`{\"q\": \"state:paid\"}` ->`ERR_INVALID_FILTER`\n- Turn 6: `query_db` with`{}` ->`ERR_INVALID_FILTER`\n- 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 ...\"`\n\nLook 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.\n\nBecause every failure came back as the bare token `ERR_INVALID_FILTER`, the model never learned the real query format.\n\nNotice 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.\n\nA post-condition verification gate catches that silent miss immediately.\n\n### Trace 2: The tight strict schema finishing in 3 turns\n\nNext, 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:\n\n- Turn 1: `list_orders` with`{\"status\": \"paid\", \"region\": \"EU\"}` ->`{\"orders\":[{\"id\":\"ord_101\",\"customer\":\"marta@nordic.test\",\"status\":\"paid\",\"cents\":4900,\"region\":\"EU\",...}]}`\n- Turn 2: `mark_order_refunded` with`{\"order_id\": \"ord_101\", \"reason\": \"customer_request\"}` ->`{\"ok\":true,\"order\":{\"id\":\"ord_101\",\"customer\":\"marta@nordic.test\",\"status\":\"refunded\",\"cents\":4900,...}}`\n- 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.\"`\n\nThere 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.\n\n### Trace 3: Halting a forced 503 retry loop on Turn 3\n\nStrict 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\"}`).\n\nHere is what happened across the 3 turns:\n\n- Turn 1: `mark_order_refunded` with`{\"order_id\": \"ord_101\", \"reason\": \"customer_request\"}` ->`{\"error\":\"UPSTREAM_503: payment gateway unreachable\"}`\n- Turn 2: `mark_order_refunded` with`{\"order_id\": \"ord_101\", \"reason\": \"customer_request\"}` ->`{\"error\":\"UPSTREAM_503: payment gateway unreachable\"}`\n- Turn 3: model emitted `mark_order_refunded` with`{\"order_id\": \"ord_101\", \"reason\": \"customer_request\"}` a third time -> the SHA-1 duplicate-call loop breaker saw`repeats === 3` and blocked execution before calling the tool a third time. It logged`loop_breaker_tripped` and halted cleanly with`stopReason: \"duplicate_call_loop_breaker\"` at 819 tokens.\n\nWithout 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.\n\n## How I build agent loops for production\n\nBefore I write an agent loop for a new feature, I ask whether the job needs a loop at all.\n\nIf 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.\n\nWhen 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.\n\nEvery tool gets `strict: true`, `additionalProperties: false`, explicit enums wherever the domain is finite, and nullable types for optional filters.\n\nI 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.\n\nOn 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).\n\nOnce 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.\n\nBefore putting any agent loop in front of real users or real money, I check off these ten items:\n\n- 3 to 8 verb-first workflow tools per agent instead of auto-generated CRUD wrappers.\n- `strict: true` and`additionalProperties: false` on every object schema, with closed string domains turned into`enum` arrays.\n- Overlapping boolean flags replaced by mutually exclusive enums, and read-only previews split from mutating writes.\n- Hard length caps on tool outputs inside the harness, with truncated previews wrapped in valid JSON metadata.\n- Every `tool_call_id` paired with a`role: \"tool\"` result even on parse, validation, or execution failures, running reads with`Promise.allSettled` and writes serially.\n- Deterministic idempotency keys derived in the harness for every mutating tool call.\n- Explicit switching on every `finish_reason` (`tool_calls` ,`stop` ,`length` ,`content_filter` ,`refusal` ).\n- Hard caps on turn count, wall-clock duration (`AbortSignal.timeout` ), and authoritative API token and dollar spend.\n- Both a canonicalized SHA-1 duplicate-call breaker (with per-tool overrides for polling) and a consecutive-error breaker on every tool dispatch.\n- 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.\n\nWhen 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.\n\nPair these loop guards with [structured outputs and few-shot examples](https://flaviocopes.com/structured-outputs-few-shot/) for validating final payloads, and [token pricing and budgeting](https://flaviocopes.com/llm-token-pricing-budgeting/) for wiring authoritative dollar caps around multi-turn agent runs.\n\nWant me to talk about your product? You can [sponsor this site](https://flaviocopes.com/sponsor/).", "url": "https://wpnews.pro/news/tool-schemas-and-stopping-conditions-for-reliable-agent-loops", "canonical_source": "https://flaviocopes.com/tool-schemas-stopping-conditions/", "published_at": "2026-12-04 08:00:00+00:00", "updated_at": "2026-12-04 08:15:13.838081+00:00", "lang": "en", "topics": ["ai-agents", "ai-tools", "large-language-models", "developer-tools"], "entities": ["gpt-4.1-mini", "Flavio", "ord_101"], "also_reported_by": [], "takeaway": "On gpt-4.1-mini, replacing a sloppy three-tool schema and vague error codes with a strict schema cut a refund task from 7 turns, 6 tool calls, 6 errors and 1,783 tokens to 3 turns, 2 tool calls, 0 errors and 788 tokens.", "recommendation": {"advice": "Define strict JSON schemas with enumerated arguments and descriptive tool errors, and add deterministic guards such as a duplicate-call loop breaker so retries halt instead of burning turns and tokens.", "playbook": "agent-architecture", "playbook_url": "https://wpnews.pro/playbooks/agent-architecture"}, "alternates": {"html": "https://wpnews.pro/news/tool-schemas-and-stopping-conditions-for-reliable-agent-loops", "markdown": "https://wpnews.pro/news/tool-schemas-and-stopping-conditions-for-reliable-agent-loops.md", "text": "https://wpnews.pro/news/tool-schemas-and-stopping-conditions-for-reliable-agent-loops.txt", "jsonld": "https://wpnews.pro/news/tool-schemas-and-stopping-conditions-for-reliable-agent-loops.jsonld"}}