Agent Decisions: Confidence, Stopping, Loops and Budgets
The decisions between the steps, which determine whether an agent is safe, affordable and finished.
At every step an agent decides whether to act, ask, retry, stop or hand over. Set confidence thresholds from the cost of being wrong, use checks instead of self-reported certainty where possible, define what done means, and enforce limits on steps, tokens, money and time in code. When the agent stops, it should say why and what remains.
What you will learn: how agents choose tools and rank actions, how to set confidence thresholds, when to ask a question, how to stop and escalate, how to detect loops and how to reason within a budget.
Prerequisites: The Agent Loop: Observe, Reason, Plan, Act, Reflect and Agent Tools, Function Calling and Tool Registries.
Five possible moves
Choosing the tool or action
A model selects tools from their names, descriptions and parameters. You can make the choice easier and safer:
- Offer only the tools relevant to this task and permitted to this user.
- Give each tool a distinct purpose, and say when not to use it.
- Prefer read-only actions while information is incomplete.
- When several actions could work, rank them by expected benefit, cost, risk and whether they can be undone.
- Let code veto choices that break a rule, and return the reason so the agent can adjust.
A simple ranking rule serves many cases: gather cheap, safe information first; take reversible steps before irreversible ones; and leave consequential actions until the evidence is in and approval is given. See Tool Permissions, Approvals and Abuse Risks.
Check limits before choosing
The order of questions matters. First, is the run still within its limits? Second, is the task already complete? Third, is anything essential missing that only a person can supply? Only then should the agent pick the next action. Putting the limit and completion checks first stops an agent from doing extra work after success, one of the quieter sources of cost and of unwanted changes.
Say what done means
"The model said it finished" is not a completion test. Define a condition that something other than the model can verify: the tests pass, the record exists with the right values, every item has a status, the reply cites a source for each claim. If no check is possible, require the agent to list what it did and what it could not confirm.
One request, five decisions
Follow an invented request: "Please move my appointment to next week."
| What the agent finds | Right move | Why |
|---|---|---|
| It does not yet know which appointment | Act: look up the bookings | A safe read can answer the question |
| The calendar service times out | Retry once or twice with a delay | Reading again changes nothing |
| One booking; three free times next week | Ask which time suits | Only the person knows, and the choice matters |
| The chosen time is booked successfully | Finish after reading the record back | The new booking is verified, the old one released |
| A late-change fee applies that the agent may not waive, and the person disputes it | Hand off with a summary | The decision is outside its authority |
Notice that the agent did not ask which appointment before looking. Questions should cover what tools cannot discover. Notice also that finishing involved a read-back: the booking call returning without error is not the same as the calendar showing the right result.
How confident is confident enough?
The right threshold depends on consequences. Acting is worthwhile when the expected benefit exceeds the expected harm. If success is worth B and a mistake costs H, act only when the chance of being right exceeds H / (H + B). The second half of the problem is that a stated confidence may not match reality, so compare it with history:
"""When is an agent confident enough to act? Let costs set the threshold."""
def threshold(benefit, harm):
"""Act when p * benefit > (1 - p) * harm."""
return harm / (harm + benefit)
# (stated confidence band, cases, how many were actually right). Invented.
HISTORY = [(0.55, 40, 21), (0.65, 60, 37), (0.75, 90, 61),
(0.85, 120, 93), (0.95, 200, 178)]
if __name__ == "__main__":
print("confidence says actually right")
for stated, cases, right in HISTORY:
print(f"{stated:>12.0%} {right / cases:>13.0%} ({cases} cases)")
print()
for name, benefit, harm in (("add a tag", 1.0, 0.5),
("send a reply", 2.0, 8.0),
("issue a refund", 2.0, 60.0)):
need = threshold(benefit, harm)
usable = [s for s, n, r in HISTORY if r / n >= need]
rule = (f"act from the {min(usable):.0%} band" if usable
else "always ask a person")
print(f"{name:<15} needs {need:.0%} real accuracy -> {rule}")
Output:
confidence says actually right
55% 52% (40 cases)
65% 62% (60 cases)
75% 68% (90 cases)
85% 78% (120 cases)
95% 89% (200 cases)
add a tag needs 33% real accuracy -> act from the 55% band
send a reply needs 80% real accuracy -> act from the 95% band
issue a refund needs 97% real accuracy -> always ask a person
In this invented history the stated figures run higher than the real success rates. A low-harm action such as tagging can proceed freely. Replies need the top band. Refunds cannot reach the required accuracy, so a person approves them. The costs are placeholders; agreeing them is a business decision.
Better signals than "I am 90% sure"
Research has found that language models can carry useful information about what they know in some settings, but self-reported confidence in free text is not dependable across tasks and models. Combine independent signals:
| Signal | Idea | Caution |
|---|---|---|
| Validation result | Output passes schema and business checks | Valid does not mean correct |
| Agreement across attempts | Independent samples reach the same answer | They can agree on the same mistake |
| Evidence strength | Sources found, recent and consistent | Search scores are not probabilities |
| Familiarity | Similar to cases that succeeded before | Needs a maintained history |
| Missing inputs | Required fields are absent or ambiguous | Easy to check and very useful |
| Risk flags | Large amount, new recipient, unusual pattern | Should override high confidence |
Calibrate whichever score you use: group past cases by score and look at how often each group was right. Repeat this after changing the model or prompt.
Asking clarifying questions
Asking too little causes wrong actions; asking too much makes the agent tiresome. Ask when all of these hold: the possible meanings lead to materially different results, the answer cannot be found with an available tool, and guessing wrong would cost more than the interruption.
- Ask one focused question, offering the likely options.
- Say what you already established, so the person need not repeat it.
- Gather related questions into one message.
- State the default you will use, where a harmless default exists.
- Do not treat silence as approval for a consequential action.
If the account has one open order, the agent shows it and asks for confirmation. With three, it lists them and asks which. If cancellation is no longer possible, it says so and offers a return instead of asking anything.
Retry, change, or hand off
| Situation | Response |
|---|---|
| Timeout or rate limit | Retry with increasing delay, a few times; check whether the action already happened |
| Invalid arguments | Correct using the error message; limit attempts |
| Not found | Check the identifier or ask; do not invent one |
| Permission denied | Stop that route; report or request approval |
| Unexpected result | Verify with a second source, then replan |
| Instructions inside a tool result | Treat as data; flag it; do not obey |
| User upset or request sensitive | Hand off according to policy |
Retrying an action that changes something is safe only if repeating it has no extra effect. See Reliable Tool Execution and Error Recovery.
Preventing loops
Agents can repeat a failing call, alternate between two actions or keep searching for something that does not exist. Detect it in code:
"""Stop loops and overspending, and say why the run ended."""
import json
from collections import Counter
class Guard:
def __init__(self, max_steps=8, max_tokens=20_000, max_repeats=2,
max_stale=3):
self.max_steps, self.max_tokens = max_steps, max_tokens
self.max_repeats, self.max_stale = max_repeats, max_stale
self.steps = self.tokens = self.stale = 0
self.calls, self.seen_results = Counter(), set()
def check(self, tool, args, result, tokens):
"""Return None to continue, or the reason to stop."""
self.steps += 1
self.tokens += tokens
call = (tool, json.dumps(args, sort_keys=True))
self.calls[call] += 1
self.stale = self.stale + 1 if result in self.seen_results else 0
self.seen_results.add(result)
if self.calls[call] > self.max_repeats:
return f"same call made {self.calls[call]} times"
if self.stale >= self.max_stale:
return f"no new information for {self.stale} steps"
if self.steps >= self.max_steps:
return "step limit"
if self.tokens >= self.max_tokens:
return "token budget"
return None
RUNS = {
"repeats itself": [("search", {"q": "vpn"}, "r1", 900)] * 5,
"goes nowhere": [("search", {"q": f"vpn {n}"}, "nothing", 900)
for n in range(8)],
"too expensive": [("read", {"page": n}, f"page {n}", 7_000)
for n in range(8)],
}
if __name__ == "__main__":
for name, steps in RUNS.items():
guard = Guard()
for step in steps:
reason = guard.check(*step)
if reason:
print(f"{name:<15} stopped at step {guard.steps}: {reason}")
break
Output:
repeats itself stopped at step 3: same call made 3 times
goes nowhere stopped at step 4: no new information for 3 steps
too expensive stopped at step 3: token budget
The guard catches an identical repeated call, a run of results that add nothing new, a step limit and a token limit. Real systems add time and money limits, and detect alternating patterns. Do not simply cut the run: pass the reason to the caller, and consider giving the agent one final step to summarize its progress.
Budget-aware reasoning
| Budget | Enforce by |
|---|---|
| Steps and tool calls | Counter in the agent loop |
| Tokens, including reasoning | Usage reported with each response |
| Money | Price table applied to usage and tool fees, with an account-level cap |
| Wall-clock time | Deadline passed to every call |
| Side effects | Maximum number of messages, writes or spend per run |
| Delegation depth | Child agents draw from the parent's budget |
Telling the agent how much budget remains can help it prioritize, but the limit must be enforced outside the model. Reserve part of the budget for finishing: the final check, the summary and any clean-up. Where your model offers a reasoning-effort setting, use less for routine steps and more for difficult decisions. See Agent Cost Model and Token Economics.
An unattended agent with no spending cap can run up a large bill quickly. Set provider-side limits as well as application limits, and alert before they are reached.
A useful hand-off
Escalation is a successful outcome when it is the right one. The person receiving it should not have to start again. Include:
- The request in the user's own words and the goal as understood.
- What was checked, with links or identifiers.
- What was changed, if anything.
- Why the agent stopped, in plain terms.
- The recommended next action and any deadline.
Tell the user what happens next and roughly when. See Human-in-the-Loop and Approval Gates.
Leaving things in a safe state
A run can stop halfway through a change: the new booking is made but the old one is not released. Plan for this before it happens. Prefer a single operation that does both. Where that is impossible, record each completed change, give every change an undo action where one exists, and have the agent or a recovery job finish or reverse the set. The final report must say plainly which parts happened. Never report success for the whole when only a part completed. Durable Execution, Checkpoints and Approvals shows how to resume such work reliably.
Write the decision policy down
Put the rules in one place that product owners can read: which actions run automatically, which need confirmation, which need a second person, which questions the agent may ask, when it must hand off and what the limits are. Implement the enforceable parts in code and describe the rest in the instructions. When someone asks why the agent did something, you can then point to a rule instead of guessing at the model's reasoning.
Measure the decisions
| Measure | Too high suggests | Too low suggests |
|---|---|---|
| Questions per task | Over-caution or weak tools | Guessing |
| Escalation rate | Thresholds too strict | Agent exceeding its ability |
| Wrong autonomous actions | Thresholds too loose | Good, if work is still completed |
| Runs ended by a limit | Loops or limits too tight | Limits may be too generous to protect you |
| Unnecessary steps | Unclear completion rule | Check that verification still happens |
Review samples of both automatic actions and hand-offs. Loosen thresholds gradually, one action type at a time, as evidence accumulates. Autonomy Levels and Human Oversight describes those stages.
Record every run as ending in one of a few values, such as completed, needs-input, needs-approval, limit-reached, blocked or failed. Dashboards, retries and user messages then follow from the value instead of from reading free text.
Decision checklist
- Completion is verified by something other than the model's claim.
- Each action type has a threshold based on the cost of error.
- Confidence signals are compared with real outcomes.
- The agent can ask, and asks in one focused message.
- Retries are limited and safe to repeat.
- Loops and all budgets are enforced in code.
- Every stop reports a reason and the remaining work.
Frequently asked questions
What step limit should I use?
Look at how many steps successful runs need, then add a margin. Investigate runs that hit the limit rather than raising it automatically.
Can I trust a confidence score from the model?
Only after comparing it with real outcomes on your tasks, and not for actions whose mistakes are serious.
What should happen when the budget runs out?
Stop safely, avoid leaving changes half done, report progress and remaining work, and let a person or policy decide whether to continue.
References and further reading
- Kadavath et al., Language Models (Mostly) Know What They Know
- Anthropic: Building effective agents
- OWASP Top 10 for LLM applications
Next steps
Reasoning Traces and Planning Benchmarks
Record decisions and measure planning.
Action Guardrails and Policy Engines
Enforce rules before actions run.
Fix Loops, Memory, Handoff, RAG and SQL Errors
Debug agents that go round in circles.