Stop Runaway AI Agents: Step Limits, Retries and Cost Budgets in Python
The problem: an agent loop does not know when to quit
A chatbot makes one model call per message. An agent makes as many as it decides it needs. Most of the time that is two or three. But nothing in the loop itself prevents twenty, or two hundred:
- A tool keeps failing and the model keeps retrying it with the same arguments.
- The model never feels confident enough to answer and keeps searching.
- The server is down and your code retries forever.
- A long task slowly fills the context window, and each call costs more than the last.
On a local model that wastes time. On a paid API it wastes money, and since the loop runs unattended, you find out when the bill arrives. Anthropic's "Building effective agents" names stopping conditions, such as a maximum number of iterations, as a standard way to keep agents in control.
This lesson adds five controls to the trip helper:
- a step limit
- a token budget
- a cost budget
- repeated call detection
- retries for errors that can succeed on a second try, and only those
The budgeted agent
This file uses trip_tools.py from lesson 4. Save it as budgeted_agent.py:
python# file: budgeted_agent.py import json import os import random import time from dataclasses import dataclass, field import openai from llm import client, MODEL from trip_tools import TOOLS, run_tool # Prices per million tokens. Local models cost 0. Set these to your provider's published prices. PRICE_IN = float(os.getenv("AGENT_PRICE_IN_PER_M", "0")) PRICE_OUT = float(os.getenv("AGENT_PRICE_OUT_PER_M", "0")) RETRYABLE = (openai.APIConnectionError, openai.APITimeoutError, openai.RateLimitError, openai.InternalServerError) @dataclass class Budget: max_steps: int = 6 max_tokens: int = 20_000 max_cost_usd: float = 0.05 steps: int = 0 tokens: int = 0 cost_usd: float = 0.0 seen_calls: dict = field(default_factory=dict) def charge(self, usage) -> None: self.steps += 1 self.tokens += usage.prompt_tokens + usage.completion_tokens self.cost_usd += (usage.prompt_tokens * PRICE_IN + usage.completion_tokens * PRICE_OUT) / 1_000_000 def exceeded(self) -> str | None: if self.steps >= self.max_steps: return "step limit" if self.tokens >= self.max_tokens: return "token budget" if self.cost_usd >= self.max_cost_usd: return "cost budget" return None def create_with_retry(attempts: int = 4, **kwargs): """Retry only errors that can succeed on a second try. Give up on the rest at once.""" for attempt in range(1, attempts + 1): try: return client.with_options(max_retries=0, timeout=120).chat.completions.create(**kwargs) except RETRYABLE as exc: if attempt == attempts: raise wait = min(2 ** attempt, 20) + random.random() # exponential backoff plus jitter print(f" {type(exc).__name__}, retry {attempt} in {wait:.1f}s") time.sleep(wait) def run_agent(user_text: str, budget: Budget) -> dict: messages = [{"role": "system", "content": "You are a trip helper. Use tools for facts. Be brief."}, {"role": "user", "content": user_text}] while True: reason = budget.exceeded() if reason: return {"status": "stopped", "reason": reason, "answer": None} response = create_with_retry(model=MODEL, messages=messages, tools=TOOLS, temperature=0) budget.charge(response.usage) choice = response.choices[0] messages.append(choice.message) if choice.finish_reason == "length": return {"status": "stopped", "reason": "reply cut off by max_tokens", "answer": choice.message.content} if not choice.message.tool_calls: return {"status": "done", "reason": "model finished", "answer": choice.message.content} for call in choice.message.tool_calls: key = (call.function.name, call.function.arguments) budget.seen_calls[key] = budget.seen_calls.get(key, 0) + 1 if budget.seen_calls[key] > 2: # the same call a third time means the agent is stuck return {"status": "stopped", "reason": f"repeated call {call.function.name}", "answer": None} messages.append({"role": "tool", "tool_call_id": call.id, "content": run_tool(call.function.name, call.function.arguments)}) if __name__ == "__main__": b = Budget() print(run_agent("Is it cold in Oslo? Answer with the low temperature.", b)) print(f"used {b.steps} steps, {b.tokens} tokens, ${b.cost_usd:.4f}") tight = Budget(max_tokens=300) print(run_agent("Compare the weather in Lisbon, Kyoto and Oslo.", tight)) print(f"used {tight.steps} steps, {tight.tokens} tokens")
The Budget object
Budget is a small dataclass that holds the limits and the running totals in one place. After every model call, charge(response.usage) adds:
- one step
prompt_tokens + completion_tokensfrom the response'susagefield- the cost, using prices per million tokens
Before every model call, exceeded() returns the name of the first limit that has been reached, or None. The loop checks it before calling the model, so the agent never starts a call it cannot afford.
Keeping the budget outside run_agent has a useful side effect: you can share one budget across several agent runs, for example all the workers in the multi-agent setup in lesson 12, and cap the whole job.
Token and cost budgets need real numbers
The token counts come from response.usage, which the server fills in. Ollama returns usage on its OpenAI compatible endpoint, which is why this works locally too. On a local model the cost is zero, so the code reads prices from environment variables that default to 0:
bashexport AGENT_PRICE_IN_PER_M=0.15 export AGENT_PRICE_OUT_PER_M=0.60
These are example values to show the format. Use the prices published on your provider's pricing page for the model you use, since prices differ between models and change over time. Input and output tokens are usually priced differently, which is why there are two variables.
Notice that the token budget counts the whole prompt on every call. Because the API is stateless (lesson 1), step 5 resends everything from steps 1 to 4. Token use grows faster than the number of steps, which is why a token budget catches problems a step limit misses.
What happened in the test run
Running python budgeted_agent.py with qwen2.5:1.5b on Ollama:
text{'status': 'done', 'reason': 'model finished', 'answer': 'The low temperature in Oslo is -1°C.'} used 2 steps, 876 tokens, $0.0000 {'status': 'stopped', 'reason': 'token budget', 'answer': None} used 1 steps, 447 tokens
The first question took two calls (one tool call, one answer) and 876 tokens in total. The second run used a deliberately tiny 300 token budget. The first call alone used 447 tokens, mostly the system prompt plus the three tool definitions. The budget check then stopped the run before a second call, and returned a clear status instead of an answer.
That second number is worth noticing: the tool definitions are sent on every call and count as input tokens, as OpenAI's function calling guide points out. A budget has to cover that fixed cost before the agent does anything useful.
Animation: The budget is checked before every call: 447 tokens after call 1 is over a 300 budget, so the run stops.
Return a status, not only an answer
run_agent returns a dictionary with status, reason and answer, never a bare string. The calling code can then decide what to do:
done: show the answer.stoppedwithtoken budgetorcost budget: tell the user the task was too large, or retry with a larger budget after approval.stoppedwithrepeated call: something is wrong with a tool or the prompt. Log it for a developer.stoppedwithreply cut off by max_tokens: the answer was truncated.
Returning "Stopped at the step limit." as if it were an answer, as the simple loops in earlier lessons did, makes these cases impossible to tell apart.
Detecting a stuck agent
seen_calls counts each exact (tool name, arguments string) pair. The same call a third time means the agent is going in circles: the result will not change, so calling again is pointless. The run stops with a reason that names the tool.
This catches the common failure where a tool returns an error and the model keeps sending the same bad arguments. Good error messages (lesson 4) make this rarer, and the detector puts a hard ceiling on it.
The check uses the raw arguments string, so {"city":"Oslo"} and {"city": "Oslo"} count as different. To be stricter, parse the JSON and compare the parsed values instead.
finish_reason: length
If a reply hits the output token limit, the API sets finish_reason to "length". The text is cut off mid sentence, and if the model was writing tool arguments, the JSON is incomplete. The code stops with a clear reason instead of trying to parse a broken reply. You can raise the limit with the max_tokens request parameter, or treat it as a sign the model is producing far more than you expected.
Retries: only for errors that can succeed
Not every error deserves a retry. Retrying a bad request gives the same bad result, just slower. The openai SDK raises different exception types, so the code can tell them apart:
| Exception | Meaning | Retry? |
|---|---|---|
APIConnectionError | could not reach the server | yes |
APITimeoutError | no reply in time | yes |
RateLimitError | too many requests (HTTP 429) | yes, after waiting |
InternalServerError | server error (HTTP 5xx) | yes |
AuthenticationError, BadRequestError | your key or request is wrong | no |
create_with_retry retries only the first group. The wait doubles each attempt (exponential backoff), with a cap, plus a random fraction of a second (jitter). Jitter prevents many clients from all retrying at the same moment after an outage.
The OpenAI Python SDK already retries some errors by itself, and its README documents a max_retries option for that. The code sets max_retries=0 with client.with_options so that only one retry layer is active, and it is the one you can see. Two stacked retry layers can multiply into far more attempts than either one intends.
flowchart TD S["create_with_retry, attempt 1"] --> C["Call the API, SDK max_retries=0"] C -->|success| OK["Return the response"] C -->|"AuthenticationError,<br/>BadRequestError"| NO["Raise at once: no retry"] C -->|"Connection, Timeout,<br/>RateLimit, 5xx"| L{"Last attempt?"} L -->|yes| RAISE["Raise the original exception"] L -->|no| W["Wait min(2^attempt, 20) s<br/>plus random jitter"] W --> N["attempt + 1"] N --> C
Diagram: Retry only errors that can succeed, wait about twice as long each time plus jitter, then give up.
Watch the retries happen
Save this as retry_demo.py. It points the client at a port where nothing is listening:
python# file: retry_demo.py import openai import budgeted_agent from budgeted_agent import create_with_retry # Point the client at a port where nothing is listening to watch the retries happen. budgeted_agent.client = openai.OpenAI(base_url="http://localhost:9/v1", api_key="none") try: create_with_retry(attempts=3, model="any", messages=[{"role": "user", "content": "hi"}]) except openai.APIConnectionError as exc: print("gave up after retries:", type(exc).__name__)
The tested output:
textAPIConnectionError, retry 1 in 2.4s APIConnectionError, retry 2 in 4.0s gave up after retries: APIConnectionError
Three attempts, two waits that roughly double, then the original exception is raised so the caller can handle it. The exact wait times vary because of the jitter.
Choosing limits
There is no universal number. Some practical ways to pick:
- Steps: run your eval cases (lesson 14) and look at how many steps successful runs take. Set the limit a little above the largest.
- Tokens: same approach, using the totals from the trace logs in lesson 15.
- Cost: start from what one task is worth to you. A trip question might be worth a fraction of a cent; a long research task more.
- Retries: three or four attempts with backoff covers short outages without making a user wait minutes.
Start strict and loosen with evidence. A limit that stops a few legitimate runs is easy to raise. A missing limit is discovered the expensive way.
Common mistakes
- Checking the budget after the call instead of before.
- Counting only completion tokens. The prompt is usually the larger share in agents.
- Retrying every exception, including bad requests and authentication errors.
- Retry layers stacked in the SDK, your code and a framework at once.
- Returning a stop message as if it were an answer, so callers cannot tell success from failure.
What to try next
- Set
max_steps=1and ask a question that needs a tool. Check that the status isstoppedwithstep limit. - Add a tool that always returns the same error and confirm the repeated call detector stops the run.
- Pass
max_tokens=20in thecreate_with_retrycall and trigger thelengthstop. - Share one
Budgetacross three questions in a row and watch the totals add up.
Next is the question of when to use more than one agent: an orchestrator that hands parts of a task to specialised workers, and the honest comparison with a single agent doing the same job.
