← All posts

Tutorial

Agent Kill Switch: A Budget and Loop Guard in Python

Build an agent kill switch in Python: caps on steps, spend and time, repeated call detection and a kill file, with real output from a runaway loop demo.

19 min read

Copy this article

Clipboard access is unavailable. Select the Markdown and copy it, then paste it into your chat.

Quick answer

An agent kill switch is a small check that runs on every step of the agent loop and stops the run when any limit trips: too many steps, too much spend, too much wall time, the same tool call repeated, or a kill file or environment flag that you set by hand. When a limit trips, the loop raises one named error, so the run ends as a clean failure that tells you which limit fired.

In our demo, a scripted looping agent ran 200 steps with no guard and cost $54.81 on a placeholder price table. With the guard it stopped after 4 steps (repeated call) or 18 steps (spend cap), depending on how the loop behaved. The guard itself is about 30 lines of standard library Python. One thing it can’t do is take back side effects that already happened, so the second half of this post is about that.

The agent here is a scripted stub, not a real language model, and the tools are fake. The numbers describe the stub, a placeholder price table and a hard cap that exists only so the demo finishes. Real model results will differ.

Original diagram of an agent loop with a guard before every tool call. Step 1 the model picks a tool call. Step 2 a guard checks five limits: steps over the max, spend over the cap, wall time over the limit, the same call repeated with the fourth identical call stopping the run, and a kill file or flag being set. Step 3 the tool runs only when every limit is clear and its result goes back into the transcript. Step 4 when a limit trips the guard raises one error that names the limit, such as repeated_call or max_spend, and the tool for that step never runs. In the demo stub run with no guard it ran 200 steps and cost $54.81, while with the guard it stopped at step 4 or step 18.

What a runaway loop looks like

Most agent loops look the same underneath. The model picks a tool, the code runs it, the result goes back into the transcript, and the model picks again. The loop ends when the model says it’s done. That last part is the problem, because “when the model says it’s done” is the only exit.

A runaway happens when the model never says it’s done. A search tool returns “no matching order”, the model decides to search again, gets the same answer, and carries on. Two things make it worse than it sounds. First, the transcript grows on every step, so each call costs more than the one before it. Second, if any tool has a side effect, such as sending an email or creating a ticket, every extra step repeats it.

You won’t see this in a short test run. It shows up at 2 a.m. when nobody’s watching, which is why the guard has to live in the loop and not in your attention. If you want the bigger picture on which tools deserve extra caution, the post on tool risk classes for agents sorts them into read, write and irreversible.

Download and run the demo

Download the kill switch demo and extract it into a new folder. You need Python 3.10 or newer. There are no packages to install, no model to download and no API keys, and nothing touches the network.

The zip holds five files:

  • guard.py is the guard, 31 lines.
  • agent_sim.py holds the fake tools, a scripted looping agent (the stub model) and a small run() loop.
  • demo.py runs every scenario in this post and prints the results.
  • test_guard.py has 7 unit tests.
  • README.md repeats these steps.

Run these two commands from inside the folder. Use py -3 instead of python3 on Windows.

python3 demo.py
python3 -m unittest -v

We ran both from a fresh unzip in an empty folder, and the output below is what they printed. The demo is deterministic, so a second run printed identical output.

The guard in about 30 lines

This is guard.py as we ran it. The one function you call is check(), once per step, before the tool runs.

"""Kill switch for an agent loop: steps, spend, wall time, repeats, kill flag."""
import json, os, time

# PLACEHOLDER prices in USD per 1M tokens. Replace with your provider's current table.
PRICES = {"stub-model": {"in": 3.00, "out": 15.00}}

class Stop(Exception):
    def __init__(self, limit, detail):
        super().__init__(f"{limit}: {detail}")
        self.limit, self.detail = limit, detail

class Guard:
    def __init__(self, max_steps=25, max_usd=0.50, max_seconds=30.0, max_repeats=3,
                 kill_file="KILL", env_flag="AGENT_KILL", clock=time.monotonic):
        self.max_steps, self.max_usd, self.max_seconds = max_steps, max_usd, max_seconds
        self.max_repeats, self.kill_file, self.env_flag, self.clock = max_repeats, kill_file, env_flag, clock
        self.start, self.steps, self.usd, self.seen = clock(), 0, 0.0, {}

    def check(self, model, usage, call):
        """Call once per step, BEFORE running the tool. Raises Stop when a limit trips."""
        p = PRICES[model]
        self.steps += 1
        self.usd += (usage["in"] * p["in"] + usage["out"] * p["out"]) / 1e6
        key = json.dumps(call, sort_keys=True)
        self.seen[key] = self.seen.get(key, 0) + 1
        if os.path.exists(self.kill_file) or os.environ.get(self.env_flag):
            raise Stop("kill_switch", "kill file or environment flag is set")
        if self.steps > self.max_steps: raise Stop("max_steps", f"step {self.steps} > {self.max_steps}")
        if self.usd > self.max_usd: raise Stop("max_spend", f"${self.usd:.4f} > ${self.max_usd:.2f}")
        if self.clock() - self.start > self.max_seconds: raise Stop("max_seconds", f"over {self.max_seconds}s")
        if self.seen[key] > self.max_repeats: raise Stop("repeated_call", f"{key} seen {self.seen[key]} times")

A few details matter more than they look.

check() runs before the tool call, so a tripped limit stops the step it trips on. That is why the tool call count in our output is one lower than the step count.

The prices in PRICES are placeholders for the stub, not any provider’s real rates. Put your own provider’s current prices in that table and stamp the date next to them. For the pricing side of that question, see how to compare AI tool prices in CAD with dates.

The repeat detector turns the call into a sorted JSON string and counts how often it has seen that exact string. The default allows 3 identical calls and stops on the fourth.

The kill check is a file that exists or an environment variable that’s set. Both are deliberately boring. A file works when the agent runs somewhere you can’t reach with a signal, such as a container or a scheduled job, because you can create the file from anywhere that shares the folder.

Why these five checks

No single limit catches every runaway, so the guard stacks five that fail in different ways.

Max steps

This is the blunt backstop. It needs no price table and no clock, so it still works when those are wrong. Pick a number a healthy run never reaches. If your normal tasks take 8 to 12 steps, 25 leaves room without allowing 200.

Max spend

Steps don’t capture cost, because later steps are bigger. The guard adds up input and output tokens times the price for each step. The check runs after the model call has already been made, so you always pay for the step that trips the cap. In our run the cap was $0.50 and the run stopped at $0.5113. Set the cap a little lower than the amount you can’t tolerate.

Max wall time

A slow tool or a model that retries quietly can burn an afternoon without many steps. The guard compares a clock against the start time. The clock is a parameter, which lets the tests use a fake one. One honest limit: the check only runs between steps, so a tool call that hangs forever needs its own timeout inside the tool.

Repeated identical calls

Spend and step caps catch a loop eventually. The repeat detector catches the obvious kind early. In the demo it ended an identical-call loop after 4 steps and $0.0375, long before the spend cap would have.

It has a blind spot, and our demo shows it. If the loop changes an argument on each pass, such as an attempt counter or a timestamp, the calls are never identical and the detector stays quiet. The spend cap caught those runs instead. If your tools take volatile arguments, strip them out before comparing.

Kill file or environment flag

The first four are automatic. This one is for you. When you see something wrong, you want a way to stop every run on a machine without finding the process. Creating a file named KILL (not run here, but it’s one command, touch KILL) trips it on the next step. Because the check is first in line, it fires even on a run that’s within every other limit.

The same runaway, with and without the guard

The first block of demo.py runs three kinds of looping stub, each with and without the guard. The unguarded runs only stop at 200 steps because the demo sets a hard cap of 200 so that it finishes. A real runaway has no such cap.

== One runaway, with and without the guard ==
no guard, identical calls          {"steps": 200, "tool_calls": 200, "usd": 54.8097, "emails_sent": 0, "stopped_by": "hard_cap (demo only)", "detail": ""}
guard, identical calls             {"steps": 4, "tool_calls": 3, "usd": 0.0375, "emails_sent": 0, "stopped_by": "repeated_call", "detail": "[\"search_orders\", {\"order_id\": \"A-1001\"}] seen 4 times"}
no guard, varying args             {"steps": 200, "tool_calls": 200, "usd": 54.8097, "emails_sent": 0, "stopped_by": "hard_cap (demo only)", "detail": ""}
guard, varying args                {"steps": 18, "tool_calls": 17, "usd": 0.5113, "emails_sent": 0, "stopped_by": "max_spend", "detail": "$0.5113 > $0.50"}
no guard, sends email each step    {"steps": 200, "tool_calls": 200, "usd": 54.8097, "emails_sent": 200, "stopped_by": "hard_cap (demo only)", "detail": ""}
guard, sends email each step       {"steps": 18, "tool_calls": 17, "usd": 0.5113, "emails_sent": 17, "stopped_by": "max_spend", "detail": "$0.5113 > $0.50"}

The spend is the same in all three unguarded runs because the stub’s token growth is the same. That is a property of the stub. A real agent’s spend depends on its transcript, its tool outputs and its model.

Each limit can also be tripped on its own. These runs lower one limit at a time, and the time limit uses a fake clock that moves 10 seconds per reading so we don’t have to wait.

== Each limit tripping on its own ==
max_steps=5 (repeat check off)     {"steps": 6, "tool_calls": 5, "usd": 0.0733, "emails_sent": 0, "stopped_by": "max_steps", "detail": "step 6 > 5"}
max_usd=0.05                       {"steps": 5, "tool_calls": 4, "usd": 0.0541, "emails_sent": 0, "stopped_by": "max_spend", "detail": "$0.0541 > $0.05"}
max_seconds=35 (fake clock)        {"steps": 4, "tool_calls": 3, "usd": 0.0375, "emails_sent": 0, "stopped_by": "max_seconds", "detail": "over 35s"}
kill file present                  {"steps": 1, "tool_calls": 0, "usd": 0.0055, "emails_sent": 0, "stopped_by": "kill_switch", "detail": "kill file or environment flag is set"}
env flag AGENT_KILL=1              {"steps": 1, "tool_calls": 0, "usd": 0.0055, "emails_sent": 0, "stopped_by": "kill_switch", "detail": "kill file or environment flag is set"}

Finally, the demo runs 50 seeded runs, cycling through the three stub behaviours, with and without the guard.

== 50 seeded runs (modes cycle same, vary, email) ==
guard off: tool_calls=10000 spend=$2740.45 emails_sent=3200
guard on : tool_calls=612 spend=$17.47 emails_sent=272
limits that tripped: {'repeated_call': 17, 'max_spend': 33}

Without the guard the 50 runs made 10,000 tool calls and spent $2,740.45 on the placeholder price table. With it they made 612 calls and spent $17.47. The repeat detector ended 17 runs and the spend cap ended 33. Remember that the 10,000 is just 50 runs times our demo’s 200 step cap, so the saving is mostly a statement about the cap we chose.

Which limit tripped and what was left behind

Two questions come up the moment a guard fires: which limit was it, and what’s the state of the world now?

The first is the easy one. Stop carries limit and detail, so the result record says repeated_call or max_spend, and the detail string shows the offending call or the dollar figures. Log both. A failure you can classify is one you can fix. If most of your stops are max_spend with varying arguments, your repeat detector needs to ignore a volatile argument. If they’re max_steps, your cap is too tight or your task is too big.

The second question is the one that matters. Look at the guarded email run: it stopped cleanly after 18 steps, and 17 emails had been sent. The guard did its job, and the customer in this fake world still got 17 identical messages. The loop ended; the state didn’t rewind.

What the demo leaves behind after a stop is this:

  • The transcript up to the stopping step, which is useful for working out why the loop started.
  • The fake outbox with 17 sent emails in the email scenario, and none in the others.
  • The cost already incurred, including the model call for the step that tripped the cap.
  • Nothing from the refused step. Because check() runs before the tool, the tool call that tripped the limit never ran.

That last point is worth copying: put the check before the side effect, never after.

What a kill switch can’t undo

A kill switch stops the future. It does not edit the past. Some practical consequences follow.

Side effects already made stay made. An email that’s sent, a ticket that’s filed and a payment that’s charged are outside the guard’s reach. The guard limits how many you get, and the 17 emails above is the number it allowed under a $0.50 cap. If 17 is too many, the fix is a tighter limit for that tool, such as a per-tool cap of 1 email per run, not a smarter global guard.

A retried run can repeat the damage. After a stop, someone will restart the job. If the first run already created the ticket, the second creates it again. This is the case where idempotency keys earn their place: a repeated logical action returns the stored result instead of repeating itself. The post on idempotency for agent tool calls builds that wrapper and measures it. The two fit together, since the guard limits how many calls happen and idempotency makes the repeats harmless.

Sort tools by whether they can be undone. A draft you can delete is a different thing from an email you can’t recall. Put the irreversible tools behind a human approval or a per-run quota, and keep the reversible ones cheap to run. The risk classes post walks through that split.

Record side effects as they happen. The easiest way to know what a stopped run left behind is to write a line to a ledger before each side effecting call: tool name, arguments and run id. After a stop, the ledger is your cleanup list. The demo’s World object plays this role in miniature, and in real code it should be a file or table that outlives the process.

A hung tool call isn’t interrupted. The guard only runs between steps. Give each tool its own timeout, and treat the guard’s wall time limit as a cap on the whole run.

How to test the guard

A guard you haven’t tested is a hope. The tests in test_guard.py are cheap, because every limit takes its inputs as parameters. We ran them and all 7 passed (Ran 7 tests ... OK).

Test each limit alone by setting it low and leaving the rest generous:

def test_max_spend(self):
    with self.assertRaises(Stop) as c:
        self.trip(Guard(max_usd=0.001))
    self.assertEqual(c.exception.limit, "max_spend")

That block is excerpted from the file we ran. A few habits make the set worth having.

  1. Assert the limit name, not just that something stopped. If a repeat test passes because the step cap fired first, the test is lying. Check c.exception.limit.
  2. Use a fake clock. Passing clock=lambda: next(ticks) lets the wall time test finish in microseconds.
  3. Test the kill file in both states. The test creates the file mid-run, confirms the first step passes and the next one stops.
  4. Test that a healthy run is untouched. A guard that kills good runs gets switched off by a frustrated developer, and then you have no guard. One test sends 5 varied calls and expects no error.
  5. Test the order of operations. The last test confirms the tool call is refused before it runs: a 4 step cap on the email agent leaves exactly 4 emails sent.

Once you’ve swapped in a real model, add a canary: a prompt you know loops and a cap you expect it to hit, run on a schedule. If that canary ever runs to completion, your guard is no longer in the loop. The post on prompt regression gates in CI shows how to wire a check like that into a pipeline.

To use a real model, replace LoopingAgent.next_step so it returns the token usage and the chosen tool call. The guard needs only those two things. Here’s the shape (not run here, and the client call is a placeholder for whichever API you use):

def next_step(self):
    reply = call_your_model(self.transcript)   # placeholder, not run here
    usage = {"in": reply.input_tokens, "out": reply.output_tokens}
    return usage, (reply.tool_name, reply.tool_args)

If you’re still building the loop itself, build an AI agent in Python covers that part.

Limits of this demo

  • The agent is a scripted stub that never finishes. Real models loop differently: some stall, some wander, some finish early. The numbers here are properties of the stub.
  • The price table is a placeholder for a made up model called stub-model. No dollar figure here is a real provider’s price, and nothing in this post is checked against a price page.
  • The 200 step hard cap exists only to end the unguarded demo. The unguarded totals, including $54.81 and $2,740.45, scale with that choice.
  • Wall time was tested only with a fake clock. We didn’t measure real elapsed time.
  • The kill file and environment flag are checked between steps. They cannot interrupt a tool call that’s already running.
  • The tools are fake and in memory. Real systems add partial failures, retries and concurrency that this demo doesn’t model, and the guard isn’t safe to share across threads as written.
  • The guard does not judge whether a run is making progress. It only counts.

FAQ

What is an agent kill switch?

It’s a check that runs on every step of an agent loop and ends the run when a limit trips. In this demo the limits are max steps, max spend, max wall time, repeated identical calls, and a kill file or environment flag. A tripped limit raises one error that names the limit.

How do you stop an AI agent from looping forever?

Don’t rely on the model to say it’s done. Count steps, add up the token cost and compare the elapsed time on every iteration, and stop when a cap is hit. In our demo a repeated call stopped a runaway after 4 steps, and a $0.50 spend cap stopped one after 18.

Why does the spend cap still overshoot a little?

The guard checks after the model call has been made, so it can only add the cost of that call and then stop. In our run the $0.50 cap stopped the run at $0.5113. Set the cap a little below the amount you can’t tolerate.

Does a kill switch undo what the agent already did?

No. It stops further steps, but sent emails, created tickets and charges stay. In the demo, the guarded email run stopped after 18 steps with 17 emails already sent. Idempotency keys and per-tool quotas are what limit that damage.

Why didn’t the repeated call detector catch every loop?

It only matches identical calls. When the stub changed an argument on each pass, the calls never matched, and the spend cap ended those runs instead. If a tool takes volatile arguments such as a timestamp, strip them before comparing.

How do you test an agent budget guard without a real model?

Set one limit low at a time and assert the limit name on the error, use a fake clock for the time limit, and create the kill file mid-run. Also check that a healthy run isn’t stopped. Our 7 tests ran in 0.002 seconds with no model and no network.

Where to go next

  • #ai-agents
  • #guardrails
  • #python
  • #cost-control