How do I stop an agent loop before it spends more than its execution budget?
By Thrive AI Editorial · Created 2026-10-07 · Updated 2026-10-08
Thrive AI Editorial · AI-assisted worked example, not a member conversation.
A LangGraph agent keeps returning to its tool node. It eventually raises GraphRecursionError, and increasing recursion_limit only lets it perform more work.
I want a deterministic cap on tool calls, including a zero-call budget, and an explicit budget_exhausted result rather than an exception that looks like successful completion. Where should the guard and graph exit live?
This AI-assisted editorial reproduction runs an actual cyclic StateGraph. It counts local tool invocations, not token charges or monetary cost.
0 score
Sign in to vote or contribute. Scores count actual member votes, not editorial endorsements.
1 published answer
A selected solution is chosen by the question author or moderator, not an independent certification. Check assumptions before using any code in production.
Thrive AI Editorial
AI-assisted editorial answer · not member testimony
2026-10-07
Executed framework reproduction
Use an application stop condition before a tool call. The graph recursion limit is an emergency ceiling, not your business budget.
Failure → corrected execution path
Failure
01Unconditional self-loop
↓
02Budget never checked
↓
03GraphRecursionError after 5 calls
Correction
01Check remaining call budget
↓
02Execute only admitted work
↓
03Route budget_exhausted to END
Execution record · LangGraph 1.2.14 · Python 3.13.2
Assertions and captured output cover the shown local example only. This record appears only while the published question and answer bodies exactly match the tested editorial version.
Jump to a section 8 section links
Short answer
Put the application budget check before the effect, record the terminal reason in state, and route that terminal state to END. Retain recursion_limit as a separate backstop for broken routing.
Do not raise the recursion limit until you understand why the graph is still running. A legitimate longer computation may need a larger ceiling; an unconditional cycle needs a stop condition.
Two limits, two different jobs
Limit
Counts or bounds
What happens at the boundary
Application call budget
Work this workflow is allowed to admit
Returns budget_exhausted before another tool call
LangGraph recursion_limit
Graph execution steps/super-steps
Raises GraphRecursionError if no stop condition is reached
These are not interchangeable. Parallel nodes can execute in one super-step. One node can call several tools or retry a provider internally. A graph-step ceiling is therefore not a reliable count of billable calls.
The deliberate failure
The unbounded variant has one node and an unconditional edge back to itself. Its state contains budget=3, but no code enforces it. With recursion_limit=5, the pinned framework executes five local calls and then raises GraphRecursionError. Merely storing a budget in state does nothing.
The bounded variant checks used >= budget before appending a call. It then routes budget_exhausted to END. The zero-budget case is important: it proves that the first call is not admitted accidentally.
Run the reproduction
Save the Python block as graph_budget.py. It makes no model calls and requires no API key. Use an isolated environment; these commands are for macOS/Linux shells.
The recorded run used Python 3.13.2 on macOS. The two direct dependencies above are pinned; our full transitive dependency lock is maintained in scripts/community-examples/requirements.lock. Other runtime combinations are not claimed as tested.
The runner executed this exact source with assertions enabled. The following is captured standard output, not an invented transcript. Error descriptions are deliberately normalized by the example; they are not full exception tracebacks.
With a budget of three, the node admits three calls. A fourth node execution performs the guard, returns budget_exhausted and routes to END. It does not call the tool.
The example gives this small graph a recursion limit of ten so its application policy can finish first. Do not copy ten as a universal production setting; count the actual planning, tool and cleanup steps in your topology.
Scenario
Actual calls
Completion
Unbounded, nominal budget=3
5
GraphRecursionError
Bounded, budget=0
0
budget_exhausted
Bounded, budget=3
3
budget_exhausted
Extend the boundary deliberately
Validate budgets as non-negative integers at the service boundary. The reproduction supplies fixed valid inputs.
Count provider retries and tool calls at the layer that actually issues them, not only at a planner node.
For parallel workers, reserve shared capacity atomically before starting work. This single-worker state counter is not a concurrency-safe ledger.
Enforce elapsed-time and provider limits separately. A call-count cap does not stop a single indefinitely blocking call.
If the task completes early, add a distinct completed route. Do not return a fabricated success message when the budget ran out.
For monetary budgets, replace a call count with a justified upper-bound reservation and reconcile actual charges. Without a defensible upper bound and provider enforcement, this example cannot promise a strict currency cap.
Troubleshoot before changing the ceiling
Inspect the transition that returned to the same node, the state change that should have enabled termination, and the guard that actually admitted the last call. Log node/transition names and counters, not private prompts or tool payloads.
Source checked 2026-10-08: LangGraph GRAPH_RECURSION_LIMIT and graph execution model. Original AI-assisted reproduction; observed counts refer to this one-node graph and pinned runtime, not arbitrary agent topologies.
0 score
Sign in to vote or contribute. Scores count actual member votes, not editorial endorsements.