Skip to main content

agent-stoploss

Stop AI agents from burning tokens on broken tools.

Based on the Agent Fuel study: 660 recorded agent runs under injected tool failures, with the controller, the run records and the analysis that this library's defaults come from.

An agent calls an API, the key has expired, and the agent tries again. And again, sixty times, each attempt resending the whole history of failures. A retry loop like this turns a task worth a few hundred tokens into a runaway bill, and a step limit or a monthly budget only notices once the money is gone.

agent-stoploss watches each agent run and ends it when the agent is spending without making progress:

  • the same tool call again and again;
  • the same answer from a tool again and again;
  • an error that retrying cannot fix (401, 403, 404, ...);
  • a tool that keeps failing.

It starts in shadow mode: it records what it would have done and changes nothing. agent-stoploss replay then shows, on your own recorded runs, what a configuration would have saved and which good runs it would have broken. Switch to enforce when the numbers look right.

pip install agent-stoploss

Python 3.10+. One dependency (PyYAML). Apache-2.0.

Why another spend guard?

Most guards count: steps, tokens, dollars. agent-stoploss also reads what the tools answer, so it can tell an agent that is stuck from one that is simply working through a long task.

It stops It leaves alone
a call answered with 401: retrying cannot help, so the run ends at the first one forty different domains looked up one by one
the same call made three times, even with case or spacing changed paging through results, page=1..N
the same result returned three times, timestamps and request ids ignored a tool that fails now and then, fewer than 4 of its last 5 calls
a tool that failed in 4 of its last 5 calls polling a job you marked as loop_detector: off

A run budget is there too, off by default: a fixed ceiling also cuts honest long tasks short, so replay suggests a value from your own runs instead.

Quick start

Claude Agent SDK

pip install "agent-stoploss[claude-agent-sdk]"
from claude_agent_sdk import ClaudeAgentOptions
from agent_stoploss import StopLoss, Stopped
from agent_stoploss.claude_agent import guarded_query

guard = StopLoss.from_file("stoploss.yaml")      # or StopLoss(mode="shadow")

try:
    async for message in guarded_query(guard, prompt="...", options=ClaudeAgentOptions(...),
                                       agent="weekly-report"):
        ...                                       # the same messages query() yields
except Stopped as stop:
    print(stop.reason, stop.summary)

guarded_query adds hooks before and after every tool call and reads token usage from the messages. In enforce mode a stop denies the pending tool call and ends the agent's turn, then Stopped is raised. A stop decided on a tool's answer, such as a 401, takes effect at the agent's next tool call: Claude Code lets the model reply once more first. Token counts are corrected from the SDK's final totals, so the journal matches what the SDK reports. With ClaudeSDKClient, use StopLossHooks directly; see agent_stoploss/claude_agent.py.

Your own agent loop

import anthropic
from agent_stoploss import StopLoss, Stopped

guard = StopLoss.from_file("stoploss.yaml")
client = guard.wrap(anthropic.Anthropic())        # tokens and cost recorded for you

@guard.tool                                        # calls, results and errors checked
def analytics(domain: str, period: str = "30d") -> dict: ...

with guard.run(agent="weekly-report") as run:
    try:
        while True:
            response = client.messages.create(model=..., max_tokens=..., tools=tools, messages=messages)
            if response.stop_reason == "end_turn":
                break
            ...                                    # run the tools, collect tool_result blocks
            results += [{"type": "text", "text": t} for t in run.notice_texts()]
            messages.append({"role": "user", "content": results})
        run.outcome("ok")
    except Stopped as stop:
        run.outcome("failed")
        report_partial_results(stop.reason)

wrap() works with the Anthropic and OpenAI clients, sync and async. Without them, record each model call yourself with run.record_usage(response.usage, model=...) and each tool call with run.before_tool(...) / run.after_tool(...).

Full examples: examples/agent_sdk.py, examples/anthropic_loop.py, and examples/offline_demo.py, which runs the whole workflow on a scripted agent with no API key.

Shadow, replay, enforce

  1. Shadow. Deploy with mode: shadow. Every run is recorded to ./stoploss_logs/stoploss-YYYY-MM-DD.jsonl; the agent never notices.

  2. Replay. Point the replay at the logs:

    $ agent-stoploss replay ./stoploss_logs --config stoploss.yaml
    Runs                           660   (660 labelled by the developer, the rest by heuristic)
    Recorded spend            12,888,348 tokens
    Would have stopped             251
      same call repeated         129
      error retrying cannot fix    73
      same result repeated        46
      tool keeps failing           3
    Would have saved          2,312,156 tokens
      of the excess in runs not ok: 99%
    
    Runs labelled ok that would have been stopped: 6
    ...
    

    The two lists that matter are the good runs it would have stopped and the failed runs it would have missed. Label your runs with run.outcome("ok") or run.outcome("failed"); without a label the replay guesses and says so.

  3. Tune. Exempt a tool, raise a threshold, replay again. Or use the dashboard.

  4. Enforce. Set mode: enforce. Before a loop or a failing tool ends the run, the agent gets a short notice it can act on; an error that retrying cannot fix ends the run at once. On a stop your code gets Stopped.

Dashboard

agent-stoploss dashboard ./stoploss_logs --config stoploss.yaml

A local page for tuning thresholds against your recorded runs: what would be stopped and why, what it would save, which good runs it would break, and each run step by step with the point where it would have ended. Every change is replayed at once. It exports stoploss.yaml with only what differs from the defaults.

It listens on 127.0.0.1 only, loads nothing from the internet, writes nothing to disk and never controls a running agent.

Configuration

Every key is optional. stoploss.example.yaml lists them all with their defaults:

mode: shadow
loop_detector:   {threshold: 3}
circuit_breaker: {window: 5, max_failures: 4, cooldown_seconds: 60}
error_classifier:
  terminal_statuses:  [400, 401, 403, 404, 405, 410, 422]
  transient_statuses: [408, 425, 429, 500, 502, 503, 504]
run_budget:      {max_tokens: null, max_cost_usd: null}
tools:
  job_status: {loop_detector: off}        # polls the same status on purpose

agent-stoploss check-config stoploss.yaml rejects unknown keys and bad values instead of quietly falling back to a default. Why the defaults are what they are: docs/design-notes.md.

What it records

One JSON line per event: run start and end, each step, model call (tokens, cost), tool call and result, verdict, notice. Arguments and results are kept as fingerprints and shapes, not text, unless you set log.raw_text: true. The journal stays on your disk; agent-stoploss sends nothing anywhere.

Built-in prices cover the Claude models (as of 2026-10-06). Other models need a prices: entry, or their cost is counted as $0 with a warning; strict_pricing: true stops such runs instead.

What it does not catch

  • An agent that changes its request every time and gets a different error each time. Each call looks new; only the circuit breaker and the budget see it.
  • Slow burns that make progress: a long task that is merely expensive is a budget question, not a loop.
  • Streaming responses inside a run: their tokens cannot be counted yet, so agent-stoploss raises StreamingNotSupported rather than count them as zero.
  • Behaviour after a warning is not in the replay. It assumes the run went on as recorded; in enforce mode an agent that heeds the notice may stop earlier.
  • Large models and real APIs have not been measured yet. The numbers below come from small models and a stub service.

Based on the Agent Fuel study

The mechanisms and defaults come from the Agent Fuel study (CSIT305, University of Wollongong in Dubai, 2026): 660 runs of two small models, Qwen 2.5 7B and Claude Haiku 5.5, against a stub analytics service in nine scenarios (six failures of the service, three healthy tasks), under thirteen system prompts, nine of them the default prompts of agent frameworks. Replayed with the default configuration, agent-stoploss stops 245 of the 444 failing runs and saves 99% of the tokens they spent beyond the minimum needed to see the failure. It would have stopped 6 of the 216 healthy runs, all with the local 7B model; 8 failing runs that spent above that minimum got through. The test suite reproduces these numbers from the study's records.

License

Apache-2.0. See LICENSE.

Metadata

Release files for agent-stoploss 1.0.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for agent-stoploss 1.0.0
File Size Uploaded Provenance Actions
agent_stoploss-1.0.0.tar.gz 76.5 kB Without provenance Details for agent_stoploss-1.0.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for agent-stoploss 1.0.0
File Interpreter ABI Platform Actions
agent_stoploss-1.0.0-py3-none-any.whl Python 3 none any Details for agent_stoploss-1.0.0-py3-none-any.whl

Total release size: 135.6 kB

Release files / agent_stoploss-1.0.0.tar.gz

Download URL agent_stoploss-1.0.0.tar.gz
Size 76.5 kB
Tags Source
SHA-256 checksum
How to use checksums
9b892a9c6d9a96c07560c0dc3dd0effe951d09e8e8a40519f598fe99a5cce90d
BLAKE2b-256 checksum
How to use checksums
3ae89251640500b707f969cc79f36b381a85f3c487d54ed5c1f289afe902e14d
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.12.16

Release files / agent_stoploss-1.0.0-py3-none-any.whl

Download URL agent_stoploss-1.0.0-py3-none-any.whl
Size 59.1 kB
Tags Python 3
SHA-256 checksum
How to use checksums
b995a8c6074812f469aca335d1f1ded303218942a57082a0091c13eae0e12233
BLAKE2b-256 checksum
How to use checksums
4871cbd9031cd5d3f112b7aa86770947223fbf34bd015ceb5f80e2cf04f6cbbe
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.12.16

Security for agent-stoploss 1.0.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

1.0.0 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page