Halloween DealsAmazon USHalloween week deals: useful picks before month-endAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run ScanHalloween DealsAmazon USOctober picks are moving - compare before checkoutAmazon US: current deals, useful picks and tech finds.See Picks×
FREEDOM251

Freedom251 › Blog › agent loops

AI Agent Loop Controls: Budgets, Progress Checks, and Recovery

By Freedom251 Team · · 12 min read

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Some links on this page are affiliate links: if you buy through them we may earn a commission, at no extra cost to you.

Prevent runaway AI-agent costs with two independent safeguards: a hard run budget and a semantic completion test. Cap turns or iterations, total and per-call tokens, tool calls, and elapsed time; then require evidence that the task state changed or a valid final result was produced. Instrument every turn so repeated tool arguments, unchanged state, growing history, and abnormal duration trigger a pause instead of another call. If a loop is detected, save the trace and retry only with a changed plan, narrower tools, refreshed context, or human approval. No universal iteration threshold or token-savings percentage is established, so choose limits from your workload’s normal distribution and revise them using recorded traces.

What is an AI agent reasoning loop, and why does it waste tokens?

An agent loop is the repeated cycle in which a model selects an action, a tool or handoff runs, the result returns to the model, and the model chooses again. The cycle ends only when the agent emits a final answer or a stop condition fires. OpenAI’s Runner reference describes this pattern and reports a MaxTurnsExceeded failure when a configured turn budget is exceeded.

As an Amazon Associate I earn from qualifying purchases.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

A loop can be useful when each iteration adds evidence or completes a subtask. It becomes wasteful when the state does not change: the model retries the same search, submits equivalent tool arguments, reopens a finished task, or keeps “thinking” after the answer is already available. Every extra model invocation, tool call, returned payload, and growing message history can consume tokens. External actions may also incur API charges, alter records, send messages, or create duplicate work.

Do not assume that a long run is automatically a loop. A data migration or multi-step investigation may legitimately require many turns. The reliable question is whether the agent is making measurable progress toward a declared completion state.

#1 Best Overall
Elebase USB to USB C Adapter for iPhone 18 Pro Max,USBC Car Charger Adapter | 4Pack Type C Female to A Male Cable Converter for Apple Duo 17 16 15 14 Plus,iWatch Watch 12 11 10,iPad 9 8 Air,Airpods 5 4
  • Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
  • Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
  • Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
  • Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
  • 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.

What is the safest stop policy for an autonomous agent?

Use two separate gates. A hard budget guarantees termination even when the completion logic fails; a semantic completion test prevents premature stopping when the work is genuinely unfinished. Either gate must be able to end the run.

Gate What it checks Why it matters Typical failure it contains
Hard budget Maximum turns or iterations, total tokens, tool calls, and wall-clock time Provides a finite upper bound on resource use Stalled model, broken evaluator, unavailable tool, or malformed completion predicate
Semantic completion Final-state marker, resolved todo set, evaluator approval, schema-valid result, or explicit termination predicate Stops only when the requested outcome is actually demonstrated Agent that stops after a partial answer or before required side effects finish

Microsoft’s Agent Framework states the principle plainly: “Always bound autonomous loops. A completion condition can fail, a model can stall, and an evaluator can be probabilistic.” Its examples configure max_iterations rather than trusting a completion condition alone. AutoGen documents the same combination of max_turns and termination conditions, allowing whichever event occurs first to end the team run.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

How should I choose hard limits for turns, tokens, tools, and time?

Set limits at three scopes: each model call, the complete run, and the overall service request. Start from measurements of successful runs, then leave a finite margin for legitimate variation. There is no generally applicable iteration count or token-saving percentage published by the authoritative guidance, so copying a number from another workload is unsafe.

Per-call limits

  • Cap output tokens so one response cannot consume the whole run budget.
  • Limit the number of tool calls accepted in one model response or batch.
  • Reject oversized tool arguments and payloads before they enter the next prompt.

A per-call cap contains a single pathological response, but it does not stop a model from making many short calls. Pair it with run-level controls.

Per-run limits

  • Turns or iterations: count each model decision cycle, including cycles that return no useful tool result.
  • Total tokens: include input, output, tool-result text, and any framework-defined hidden or cached categories that are billable in your deployment.
  • Tool calls: count calls, not only model turns; one turn can fan out to several tools.
  • Elapsed time: use a wall-clock deadline so a hung tool or network dependency cannot hold the request forever.

Strands exposes explicit stop reasons for limit_turns, limit_total_tokens, and limit_output_tokens. Treat those as normal, inspectable outcomes rather than uncaught exceptions. OpenAI Runner surfaces a turn-budget failure as MaxTurnsExceeded; your caller should convert that into a bounded status and preserve the trace.

Service-level limits

Apply a concurrency or queue limit outside the agent itself. If many requests enter runaway loops simultaneously, individually reasonable budgets can still exhaust your account quota or worker pool. Return a clear “budget exhausted” or “deadline exceeded” status instead of silently retrying at the transport layer.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #2
Sale
Anker USB-C Hub, 5-in-1 USB Hub for Laptops, 4K HDMI Multiport Adapter | USB C Dongle with 90W Max Power Delivery, 3×5Gbps USB A Data Ports, for MacBook, Dell, and More (Charger Not Included)
  • 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
  • 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
  • Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
  • 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
  • What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.

How do I define a semantic completion condition?

Write completion as an observable fact, not an instruction such as “keep trying until you are confident.” A valid condition should be testable without asking the model to grade its own optimism.

Use an explicit final state

Represent the task with fields such as status, remaining_tasks, evidence, and result. Accept completion only when the status is terminal, the required task set is empty, and the result passes schema validation. If the agent must update an external system, verify the returned identifier or read the record back before marking the state complete.

Require a completion marker or evaluator decision

A reserved final marker can distinguish a finished response from an intermediate explanation. For higher-risk work, an evaluator can check required facts, citations, or test results. Because evaluators can be probabilistic, keep the hard budget active and log the evaluator’s decision and confidence or reason code.

Track subtasks instead of vague progress

Give every subtask a stable identifier and a terminal state such as done, blocked, or needs_human. A loop that keeps rewriting a narrative while one required subtask remains unresolved is not complete; a loop that has no remaining subtasks but continues calling tools is a control failure.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

What signals reveal that an agent is stuck?

Measure progress, not just activity. Camunda’s guidance emphasizes that “No single health indicator proves that an agent is stuck.” Combine state, usage, and duration signals before escalating, while still enforcing hard budgets unconditionally.

Signal How to measure it What it suggests Immediate action
Repeated tool request Normalize tool name and materially relevant arguments; compare with recent calls The agent is replaying an action Pause new tools and request a revised plan
Unchanged state Hash the task state or canonical result after each iteration Calls are not changing the work Escalate after a repeated action or failed progress test
Rising tool-call count Track calls per turn and cumulatively Work is expanding without completion Check for fan-out, duplicate arguments, or a missing stop condition
Abnormal duration Compare current thinking and tool time with normal successful-run distributions A tool, model, or handoff may be stalled Apply the deadline; cancel or isolate the slow dependency
History growth without evidence Track message and token growth alongside newly accepted evidence The context is getting larger without solving the task Summarize or refresh context, then retry with a changed plan
Budget proximity Compute remaining turns, tokens, calls, and milliseconds A valid completion may arrive too late Switch to a compact finalization path or terminate explicitly

TanStack loop strategies expose iteration count, total and last-turn tool-call counts, finish reason, and messages for custom stop logic. Use equivalent fields if your framework does not provide them. A state hash should be deterministic: exclude timestamps, request IDs, and other fields that change even when the substantive state does not.

Rank #3
Sale
Anker USB C Hub, 7in1 Multi-Port USB Adapter, 4K@60Hz USBC to HDMI Splitter | 85W Max PD, 2 USB 3.0 & 1 USBC Data Ports, SD/TF Card Reader, for Laptops/Mac and Other Type C Devices (Charger Not Included)
  • Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
  • Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
  • Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
  • Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
  • What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.

What should I log on every agent turn?

Record enough information to distinguish legitimate repetition from a no-progress loop and to reproduce the decision later. At minimum, capture:

  • Run ID, parent request ID, agent or workflow version, and iteration number.
  • Tool name, normalized arguments, tool result status, and a bounded representation of large payloads.
  • Model response finish reason, output token count, input token count, and cumulative usage.
  • Start and end timestamps, model latency, tool latency, and total elapsed time.
  • Canonical task-state hash, result hash, completed-subtask set, and newly accepted evidence.
  • Current stop-policy counters and the reason the run ended.

Protect secrets and personal data in traces. Redact credentials, authorization headers, and unnecessary user content while retaining the fields needed to diagnose duplication. Persist the final trace before returning a budget-exhausted response; otherwise the most useful evidence disappears when the controller cancels the run.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

How can I implement a progress-aware controller?

Place the controller outside the model prompt so a model cannot override its own limits. The following language-neutral flow shows the required order; adapt names to your SDK.

  1. Initialize budgets. Set maximum turns, total tokens, output tokens per call, tool calls, and a deadline. Store the initial canonical state hash.
  2. Ask for one bounded action. Supply only the tools and context needed for the current subtask. Reject a response that exceeds the per-call output or tool-call limit.
  3. Validate the action. Check tool names, argument schemas, authorization, and whether the action is permitted in the current state.
  4. Check approval requirements. Pause before destructive, expensive, irreversible, or externally visible actions. Do not execute merely because the model requested them.
  5. Execute and record. Run the tool, capture its result and usage, update the canonical state, and compute a new state or result hash.
  6. Evaluate progress. Accept the iteration only if it produced new evidence, changed the state, or completed a subtask. Compare normalized tool arguments with recent calls.
  7. Test semantic completion. Validate the final schema, required evidence, and empty remaining-task set. If valid, finalize immediately.
  8. Test hard limits. If any counter or deadline is exhausted, stop with an explicit budget or timeout status and persist the trace.
  9. Escalate no-progress runs. After a repeated action or failed progress test, stop issuing tools. Ask for a revised plan, reduce the tool set, refresh context, or request human input.

The order matters. Checking completion only after another tool call can spend one unnecessary iteration; checking budgets only after a tool executes can exceed a deadline or trigger an unwanted side effect.

When should a loop be paused for human approval?

Require approval when the next action can delete or alter data, spend money, contact a third party, publish content, change permissions, or create a difficult-to-reverse operational effect. Also pause when the agent has repeated an action, failed the progress test, or reached a max-turn boundary with unresolved work.

Present the human with the proposed action, normalized arguments, relevant evidence, current counters, and a concise explanation of the no-progress signal. AutoGen documents max-turn pauses and resumable state for human interaction. Resume from the saved state after approval or correction; do not restart the entire prompt and risk repeating completed side effects.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #4
Sale
UGREEN USB to USB C Adapter Combo 4-Pack, 10Gbps USB C Converter Space Gray | Data transfer & Fast charging for MacBook, iPhone 17/16/15, iPad, Samsung Galaxy, Apple Watch
  • Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
  • Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
  • Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
  • Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
  • Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft

How should a controller recover from a detected loop?

Stopping is only half of recovery. Preserve the diagnostic, then alter at least one causal factor before retrying.

Change the plan

Ask for a short plan that names the blocked subtask, evidence already collected, and the next distinct action. Include the repeated-tool summary so the model cannot mistake replay for progress.

Reduce the tool surface

Disable tools that are irrelevant to the blocked subtask and limit arguments to the fields required for the next test. A smaller action space makes duplicate detection and authorization easier.

Refresh or compress context

Replace a bloated history with a trusted state summary containing completed work, unresolved items, tool errors, and citations or evidence IDs. Do not discard facts merely to save tokens; preserve the information needed to avoid repeating a completed action.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use human feedback or terminate

If the agent cannot make progress after a changed plan, return a bounded diagnostic with the completed work and the exact blocker. Blindly replaying the same prompt usually recreates the same loop and spends more tokens without increasing the chance of success.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

How do agent frameworks differ in loop controls?

Framework APIs change, so verify the version you deploy. The documented capabilities below are useful comparison axes rather than interchangeable configuration names.

Best Value
Sale
Anker USB C Hub, 5-in-1 USBC to HDMI Splitter with 4K Display | 85W Max PD, 1 Powered USB-C 5Gbps & 2 Powered USB-A 3.0 5Gbps Data Ports, for MacBook Pro, MacBook Air, Dell and More (Black)
  • 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
  • Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
  • Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
  • HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
  • What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.
Framework or guidance Documented control Implementation lesson
OpenAI Runner reference Turn-budget failure reported as MaxTurnsExceeded Handle the limit as a first-class terminal status and retain the run trace.
Microsoft Agent Framework max_iterations examples alongside completion conditions Never rely on a probabilistic or failing completion evaluator alone.
AutoGen max_turns, termination conditions, pauses, and resumable state Combine finite turns with explicit termination and human recovery.
Strands limit_turns, limit_total_tokens, and limit_output_tokens stop reasons Expose which budget ended the run so callers can choose the right recovery.
TanStack loop strategies Iteration count, total and last-turn tool calls, finish reason, and messages Build custom duplicate and no-progress predicates from structured telemetry.
Camunda guidance State, usage, and duration should be combined; no single health indicator proves a stuck agent Use multi-signal alerts instead of a single counter threshold.

What common design mistakes cause token-wasting loops?

  • Only setting a semantic condition: a missing field, evaluator failure, or stalled model can prevent it from ever becoming true. Add hard limits.
  • Only setting a turn limit: the agent may stop with an incomplete or invalid result. Validate a terminal state and report what remains.
  • Counting turns but not fan-out: several tool calls in one response can multiply cost and side effects. Cap calls separately.
  • Comparing raw arguments: reordered JSON keys, default fields, or volatile IDs can hide duplicate actions. Normalize arguments and compare material fields.
  • Hashing volatile state: timestamps and request IDs make every iteration look different. Hash canonical business state instead.
  • Retrying transport errors blindly: a network retry can duplicate a non-idempotent action. Use idempotency keys or verify the external state first.
  • Letting the model control the counter: counters must be enforced by the runner, not by a prompt instruction.
  • Discarding traces at cancellation: without tool arguments, finish reasons, and state hashes, you cannot distinguish a bad plan from a bad tool.
  • Using a universal threshold: normal duration and turn counts vary by task. Establish baselines from successful runs and revisit them after workflow changes.

How do I improve the harness after a loop incident?

Treat each stopped run as input to engineering work, not as an isolated failure. Store the prompt version, tool inputs and outputs, stop reason, usage, and final state under a trace ID. Review representative failures and classify the cause: ambiguous tool description, missing state transition, weak validation, bad routing, unavailable dependency, or an evaluator that never accepts completion.

Convert recurring classes into regression evaluations. Test that duplicate actions are rejected, completed subtasks are not reopened, budgets produce the documented status, and destructive actions pause for approval. The OpenAI Agent Improvement Cookbook, dated May 12, 2026, describes an improvement loop combining traces, human and model feedback, evaluations, and reviewed harness changes; it presents a methodology, not a universal savings benchmark.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Recheck controls whenever you change models, prompts, tools, context windows, or framework versions. API defaults and experimental features can change, and a previously safe budget may become too high—or too low—after a workflow’s normal turn distribution shifts.

What should a production checklist contain?

  • A per-call output-token cap and tool-call batch cap.
  • Per-run limits for turns, total tokens, tool calls, and wall-clock time.
  • A machine-checkable terminal state and schema-valid final result.
  • Canonical state and result hashes for no-progress detection.
  • Normalized duplicate-tool detection with a defined escalation action.
  • Telemetry for iteration, tools, arguments, finish reason, tokens, duration, and stop reason.
  • Approval gates for destructive, costly, irreversible, or externally visible actions.
  • Persisted, redacted traces and resumable state for human recovery.
  • Explicit statuses for completed, blocked, budget-exhausted, timed-out, cancelled, and invalid-result runs.
  • Regression evaluations for every recurring loop pattern.

Frequently Asked Questions

Can a larger context window prevent an agent loop?

No. More context can preserve useful evidence, but it can also make each repeated turn more expensive and hide the fact that no state is changing. A context window is not a termination policy; pair context management with budgets and progress checks.

Should I automatically restart an agent after MaxTurnsExceeded?

Not with the same prompt and tools. Save the trace, summarize completed work and the blocker, then retry only after changing the plan, reducing the tool set, refreshing context, or obtaining human input.

How do I make tool calls safe to retry?

Design mutating tools to accept an idempotency key and return the existing result when that key was already applied. For tools you cannot make idempotent, read back external state before retrying so a transport failure does not create a duplicate action.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

What is a useful alert for a possible stuck agent?

Alert on a combination of repeated normalized tool arguments, an unchanged canonical state hash, rising tool-call counts, abnormal duration, or rapid budget consumption. A single signal is only a clue; combine state, usage, and duration as recommended in operational guidance.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

agent loopsAI agentsLLM operationsobservabilitytoken management

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Recommended PC Tool
Recommended PC Tool
Outdated Drivers Are Slowing You DownFree scan - exact matches
PC Slower Than It Used to Be?Free scan - under a minute

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.