Software to Control Runaway Agent Loops That Burn Tokens
Stop runaway agent loops with CLI turn caps, graph recursion limits, Python guards, or proxy budgets before token burn exhausts your API credits.
To control runaway agent loops that burn tokens, match your safeguards to your execution layer: enforce native turn bounds in Claude Code or the OpenAI Agents SDK, set recursion limits in LangGraph, wrap tool calls with AgentGuard, or gate provider traffic through LiteLLM.
An unattended agent stuck in an automated retry loop burns API credits in minutes. Scripts repeat failing tool calls dozens of times when unexpected errors occur. Halting runaway processes requires knowing where your architecture can enforce a hard boundary.
Open full-size image (opens in new tab)
Which software stops runaway agent loops?
The right software matches where your agent executes. Claude Code provides native turn limits at the CLI runtime. OpenAI Agents SDK and LangGraph enforce bounds inside application code. AgentGuard adds Python decorators around individual tools. LiteLLM reserves budgets at a shared proxy gateway before calls reach model providers.
| Tool | Control Layer | Primary Mechanism | Failure Signal |
|---|---|---|---|
| Claude Code | CLI runtime | --max-turns and --max-budget-usd | Process exit |
| OpenAI Agents SDK | Application runner | max_turns parameter | MaxTurnsExceeded |
| LangGraph | Graph orchestrator | recursion_limit setting | GRAPH_RECURSION_LIMIT |
| AgentGuard | Python application | LoopGuard and BudgetGuard | LoopDetected or BudgetExceeded |
| LiteLLM | Reverse proxy | Upstream cost reservation | HTTP 503 error |
How do framework turn and recursion limits work?
Framework limits stop runaway loops by halting execution when cycle counts pass set thresholds.
OpenAI Agents SDK raises MaxTurnsExceeded when agent LLM calls pass max_turns. Setting max_turns=None disables limits entirely.
LangGraph raises GRAPH_RECURSION_LIMIT when execution steps hit recursion_limit. When this error fires, inspect the graph for unintended cycles before raising the limit.
Claude Code supports turn limits in print mode. Documentation from the Claude Code CLI reference specifies that --max-turns restricts iterations while --max-budget-usd sets a spend ceiling. Documented subagent cap enforcement requires version 2.1.217 or later. The spend cap uses a client estimate, can overshoot, and excludes restored totals from earlier runs.
Run Claude Code in print mode with this command:
claude -p --max-turns 3 "query"
How does proxy reservation prevent token burn?
Proxy reservation prevents token burn by checking and holding spend capacity before dispatching calls to model providers.
LiteLLM calculates expected cost from token parameters, confirms available budget in Redis or a database, and blocks admission when accounts run out of funds. Token-priced requests calculate reservations using max_tokens or max_completion_tokens. Routes without token pricing check recorded spend. Batch submissions cannot reserve total job costs in advance.
When Redis budget state degrades, enable database verification:
general_settings: fail_closed_budget_enforcement: true
If neither Redis nor the database can verify the balance, the proxy returns HTTP 503. If you disable reservation, concurrent worker requests can overshoot your budget.
Where does AgentGuard fit into tool execution?
AgentGuard fits into Python tool execution by wrapping specific functions with code-level inspection.
Primary package evidence confirms that agentguard47 version 2.0.0 requires Python 3.11 or higher and imports as agentguard. BudgetGuard raises BudgetExceeded, and LoopGuard raises LoopDetected. The Claude Code hook in AgentGuard checks repeated or failing tool invocations rather than tracking token spend or subscription quotas. Installing the package without decorating code leaves uninstrumented functions unprotected.
An offline synthetic run of agentguard47==1.2.13 recorded 14 events across 3 review iterations, and retry attempt 4 stopped at limit 3. That run is historical simulated enforcement. It is not current-version acceptance, real token use, or money saved. For background on managing agent expenses, read about AI agent cost control with AgentGuard and review what an AI agent costs to build and run.
What are the limits of loop control tools?
No single tool offers an absolute token ceiling across every architecture. Turn and step bounds restrict iterations but do not limit token consumption per prompt. A single turn can consume thousands of tokens if input prompts or tool outputs are large.
AgentGuard package documentation states that blocked functions are not interrupted mid-flight, and responses can exceed remaining budget allowances. LiteLLM controls only requests routed through its proxy; direct provider calls bypass gateway budgets entirely. None of the source documents supply a common benchmark or universal token ceiling across these tools.
What should you do with this?
Audit your architecture to set loop boundaries at runtime, application, and gateway levels:
- Configure runner bounds: If you use OpenAI Agents SDK, set an explicit
max_turnsvalue. If you use LangGraph, definerecursion_limitin your invocation config. If you automate Claude Code, pass-p --max-turnson version 2.1.217 or higher. - Guard Python tool loops: Import
agentguardon Python 3.11 or newer. AttachLoopGuardto functions vulnerable to repetitive retries so they halt withLoopDetected. - Protect shared keys: Deploy LiteLLM in front of model APIs. Enable
fail_closed_budget_enforcementso unverified requests fail with HTTP 503 instead of burning unmonitored tokens.
Accompanying prompt
What the prompt does: Configure loop limits and cost guards for an agent deployment based on framework and budget requirements.
Copy/paste this prompt:
Copy-ready prompt
Paste the exact block into your coding agent.
No article chrome, no footnotes, no formatting drift.
This prompt and every other one we publish live in the free prompt library.
Copy the block above.
Inspect your tool loops and spend limits with AgentGuard: https://bmdpat.com/tools/agentguard
Get the Local AI Field Kit
Four copy-ready tools now, then one evidence-backed Local AI Lab Note on Friday when there is something worth sharing.
Try the free agent run check firstGet the requested artifact now, then at most one evidence-backed Local AI Lab Note on Friday when there is something worth sharing. One-click unsubscribe. No sponsored placements. Privacy.
Written by
Patrick Hughes
I build BMD and publish measured AI runs, failure reports, and reusable checks. Nashville, Tennessee.
More writing
- 5 min
OpenClaw: Who Is Using It? Demographics Survey 2026
See verified 2026 OpenClaw survey demographics, user limits, and real sample metrics to help you evaluate your local AI agent setup against real data.
- 4 min
Missing AI agent cost data is not zero
A spend ledger that counts missing billing data as $0 hides exactly the unattended agent spend you built it to catch.
- 6 min
How to Close the AI Agent Cost Gap at the Call Site
The cost gap between what an AI agent could cost and what it does cost is 40%. You close it at the call site, not in a dashboard. Here is how.
- 4 min
When JPMorgan's AI bill goes up, who controls it?
JPMorgan turned on AI for 250k people. The quiet line is that the usage racks up fees. Here is how to control the bill before it arrives.
- 4 min
Anthropic Draft S-1: BudgetGuard and Goal Verification
Following Anthropic's draft S-1 filing, use BudgetGuard to check recorded API usage and verify task completion outcomes without guaranteed savings.