Skip to content
[bmdpat]
All writing
5 min read

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.

ShareLinkedIn

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.

Agent Spend Control Flow: Inspect recorded totals, Record after each call, Catch missing pricing.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.

ToolControl LayerPrimary MechanismFailure Signal
Claude CodeCLI runtime--max-turns and --max-budget-usdProcess exit
OpenAI Agents SDKApplication runnermax_turns parameterMaxTurnsExceeded
LangGraphGraph orchestratorrecursion_limit settingGRAPH_RECURSION_LIMIT
AgentGuardPython applicationLoopGuard and BudgetGuardLoopDetected or BudgetExceeded
LiteLLMReverse proxyUpstream cost reservationHTTP 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:

  1. Configure runner bounds: If you use OpenAI Agents SDK, set an explicit max_turns value. If you use LangGraph, define recursion_limit in your invocation config. If you automate Claude Code, pass -p --max-turns on version 2.1.217 or higher.
  2. Guard Python tool loops: Import agentguard on Python 3.11 or newer. Attach LoopGuard to functions vulnerable to repetitive retries so they halt with LoopDetected.
  3. Protect shared keys: Deploy LiteLLM in front of model APIs. Enable fail_closed_budget_enforcement so 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.

Role: AI Infrastructure Engineer Context: You are configuring safeguards to prevent an automated agent loop from running indefinitely and exhausting API tokens. Inputs: - Framework: __ - Agent runner command: __ - Max turns allowed: __ - Dollar budget limit: __ - Proxy endpoint: __ Task: 1. Review the framework specified in Inputs. 2. Determine whether to enforce limits using native flags, framework recursion limits, Python guards, or proxy settings based on Inputs. 3. If Claude Code is used, configure the print-mode max-turns and max-budget-usd parameters for Agent runner command. 4. If OpenAI Agents SDK or LangGraph is used, configure max_turns or recursion_limit matching Max turns allowed. 5. If LiteLLM is used, configure request cost reservation and fail-closed budget enforcement for Proxy endpoint. 6. If Python function loops require tool guards, specify BudgetGuard and LoopGuard configuration. Output: - Specific CLI command or code snippet applying the selected limits - Failure mode explanation for the configured guard when a limit is reached Constraints: - Use only verified parameters documented for the selected runtime. - Do not assume in-flight requests stop instantly upon budget exhaustion. - State all limits where native controls cannot enforce total invoice ceilings.
29 lines1304 chars
Ready

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 first

Get 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