A bounded agent loop with budgets, deadlines and cancellation
Implement an agent loop with allowed tools, call and token budgets, a deadline and cancellation that always ends in an answer or escalation.
By Invicly Tech, , in Generative AI, Agentic AI and RAG. About 11 minutes to read.
In short
An agent loop must always stop, and it must stop with a useful result. Give each run an allowlist of tools, caps on tool calls and tokens, a wall-clock deadline and support for cancellation. Whatever happens, the run ends in either an answer or an escalation with a reason, never in silence or an endless loop.
Think of it like this: It is like giving a courier a route list, a fuel card with a limit and a return time: they come back with the parcel or with a note saying why not.
Explained simply
An agent works in a loop: think, maybe use a tool, think again. Without limits, a loop like that can run for a very long time, call the same tool again and again, or spend a lot of money on one question.
So you set limits before the run starts. Which tools may it use? How many tool calls? How many tokens? How many seconds? Your code checks these limits on every turn, not only at the end.
Sometimes the run must stop early for another reason. The user closes the page or presses stop. That is called cancellation, and the agent should stop calling tools straight away.
Whatever happens, the user should get something useful. Either the agent answers with sources, or it escalates with a clear reason such as ran out of time. A loop that just stops with nothing is a bug.
Press Play on a diagram to walk through it one step at a time.
- 1Check budgets
Calls, tokens and time left?
- 2Ask the model
Final answer or next tool
- 3Check allowlist
Tool permitted for this run?
- 4Run tool
With its own timeout
- 5Record result
Update counters and history
- Back to step 1
- Answered
- Model gives final answer
- Citations validated
- Escalated: limits
- Call budget spent
- Token budget spent
- Deadline reached
- Escalated: problems
- Tool not allowed
- Repeated identical call
- Invalid output after retry
- Tool timeout
- Cancelled
- Recorded in trace
- CancelledError re-raised
In depth
Allowlists and budgets
Create the limits per run, from configuration and the caller's role, before the first model call. The allowlist names the tools this run may use. A staff user's run might allow search_knowledge and get_ticket_status; an anonymous run only search_knowledge. Only send allowed tools to the model, and also check the name again before running anything.
The call budget caps tool calls, for example four. The token budget caps total input and output tokens, using the usage numbers the model API returns, or an estimate for the stub. Check both before each model call and each tool call. Also stop repeated calls with identical arguments; they are a common sign the loop is stuck.
Record which limit ended the run. These reason codes later show whether budgets are too tight or the agent is struggling.
- Allowlist per run, from role and config
- Re-check tool name before running
- Call budget, e.g. 4 tool calls
- Token budget from reported usage
- Stop identical repeated calls
Deadlines with asyncio
A deadline is wall-clock time for the whole run, for example 8 seconds. In Python 3.11 and later, async with asyncio.timeout(seconds) cancels the work inside it when time runs out and raises TimeoutError when the block exits. Catch that outside the loop and return an escalation with reason deadline.
Give each tool its own, shorter timeout too, with asyncio.timeout or asyncio.wait_for. A slow ticket lookup then fails in 2 seconds and the loop can still answer from search results or escalate, instead of losing the whole run.
Leave room for the final step. If the deadline is 8 seconds and the final answer call takes about 2, stop starting new tool calls once less than 2 seconds remain. asyncio.timeout objects expose when() and reschedule(), and the event loop's time() tells you how much is left.
- Agent loop to Model: Next step?1Next step?
- Model to Agent loop: Call get_ticket_status2Call get_ticket_status
- Agent loop to Ticket tool: Run with 2 s timeout3Run with 2 s timeout
- Ticket tool to Agent loop: TimeoutError after 2 s4TimeoutError after 2 s
- Agent loop to Model: Tool result: ticket_unavailable5Tool result: ticket_unavailable
- Model to Agent loop: Final: escalate, reason tool_timeout6Final: escalate, reason tool_timeout
Cancellation done properly
When a client disconnects or a user presses stop, the server cancels the task running the agent. In asyncio this raises CancelledError at the current await point inside the loop. That is your signal to stop: make no more tool or model calls.
The Python documentation advises that code catching CancelledError should clean up and then re-raise it, so the caller and the event loop know the task was cancelled. A good pattern is a try block around the loop with an except CancelledError clause that records the run as cancelled in the trace, with steps and tokens so far, and then raises again. Use finally for resources that must always close.
Do not swallow the cancellation and keep working. The user has gone, so any further calls only cost money.
Always end in an answer or escalation
Define one result type with a status of answered or escalated, the text, source IDs and a reason code. Then list every way the loop can end and map each to a result: final answer from the model; tool not allowed; call budget spent; token budget spent; deadline; repeated call; invalid model output after one retry; and cancellation, which is recorded and re-raised.
An escalation should carry what was found so far: source IDs, ticket status, the question. A person picking it up can continue instead of starting again.
Test each exit with a scripted stub model. One script loops forever; the test asserts the run stops at the call budget. Another sleeps; the test asserts the deadline result. These tests are cheap, fast and catch most loop bugs.
- One typed result for every exit
- Reason codes for each limit
- Escalations carry evidence found so far
- One stub script per exit path
Learn it in 5 short steps
About 50m each. Track them with a timer in your plan.
- 1Allowlist tools per run~50m
- 2Cap tool calls and tokens~50m
- 3Enforce a deadline~50m
- 4Handle cancellation~50m
- 5Return an answer or escalation~50m
Key points
- Check every limit before each model call and each tool call, not only at the end.
- The allowlist is per run and enforced by code; an unknown tool name ends the step, it is not executed.
- Use asyncio.timeout (Python 3.11 and later) for the overall deadline and a shorter timeout per tool.
- On cancellation, stop calling tools, record the state and let CancelledError propagate.
- Every exit path returns a typed result: answered, or escalated with a reason code.
Key terms
Tap a card to flip it. 0/5 known
Examples
import asyncio
async def run_agent(question, ctx, model, tools, lim):
calls = 0
try:
async with asyncio.timeout(lim.deadline_s):
while True:
step = await model.next_step(question, ctx.history)
if step.kind == 'final':
return Result('answered', step.text, step.source_ids)
if step.tool not in lim.allowed or calls >= lim.max_calls:
return Result('escalated', reason='tool_limit')
calls += 1
ctx.history.append(await tools[step.tool](step.args, ctx.identity))
except TimeoutError:
return Result('escalated', reason='deadline')A token budget check and per-tool timeouts are added in the extra exercises.
A stub that never stops
Prerequisites: the run_agent loop and a scripted stub model. Step 1: script the stub to request search_knowledge forever with different queries. Step 2: run with max_calls = 4. Expected evidence: exactly four tool calls in the trace and a result with status escalated and reason tool_limit. Step 3: repeat with identical queries and a repeat check enabled; expect reason repeated_call after the second call. No network or paid model is involved.
class LoopingStub:
def __init__(self):
self.n = 0
async def next_step(self, question, history):
self.n += 1
return Step(kind='tool', tool='search_knowledge', args={'query': f'q{self.n}'})
async def test_call_budget_stops_loop(ctx, tools):
lim = Limits(allowed={'search_knowledge'}, max_calls=4, deadline_s=5)
r = await run_agent('Refund time?', ctx, LoopingStub(), tools, lim)
assert (r.status, r.reason) == ('escalated', 'tool_limit')
assert len(ctx.history) == 4Cancellation when the client leaves
Step 1: start a run with a stub whose tool sleeps for 10 seconds. Step 2: after 0.5 seconds, cancel the task, as a web server does when the client disconnects. Expected evidence: the awaiting code receives CancelledError, the trace shows status cancelled with one started tool call, and no further model calls happen. Rollback: none; nothing was written because the tools are read-only.
import asyncio, pytest
async def test_cancel_stops_work(ctx, slow_tools, stub, trace):
lim = Limits(allowed={'get_ticket_status'}, max_calls=4, deadline_s=30)
task = asyncio.create_task(run_agent('T-1042?', ctx, stub, slow_tools, lim))
await asyncio.sleep(0.5)
task.cancel()
with pytest.raises(asyncio.CancelledError):
await task
assert trace.last_status(ctx.request_id) == 'cancelled'
assert stub.calls == 1Quick reference
- Set allowlist, call budget, token budget and deadline before the first model call
- Check limits before every model call and every tool call
- async with asyncio.timeout(s) (Python 3.11+) raises TimeoutError at block exit
- Give each tool its own shorter timeout; reserve time for the final answer
- On CancelledError: stop, record, re-raise; never keep working
- Every exit returns answered or escalated with a reason code
- Test each exit path with a scripted stub model
Common mistakes
- Only limiting the number of loop turns, so one slow tool call can still hang the request.
- Catching CancelledError and carrying on, which keeps work running after the client has gone.
- Returning None or an empty string when a budget runs out instead of an escalation with a reason.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Write a Limits dataclass with allowed tools, max_calls, max_tokens and deadline_s, with sensible defaults for a staff run.
- Exercise 2medium
Wrap a tool call in a 2 second timeout that returns a structured tool error instead of raising.
- Exercise 3hard
Extend run_agent with a token budget, a repeated-call check and cancellation recording, keeping every exit typed.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- What is a good default call budget?
- Start small, around three to five tool calls for a support question, then adjust using fixture runs. If many runs hit the limit, look at why before raising it.
- Does asyncio.timeout work on Python 3.10?
- No, it was added in Python 3.11. On older versions use asyncio.wait_for, or better, upgrade.
- Should a cancelled run return an escalation to the user?
- Usually there is no user left to receive it. Record the cancellation in the trace and re-raise; if the product needs a record, store it from the trace.