AgentGuard
Stop runaway agents with runtime checks in Python.
AgentGuard checks budgets, repeated tool calls, retries, and elapsed time in instrumented Python code. Guards raise exceptions so your application can stop the next operation. The base SDK has no runtime dependencies and needs no account.
Names: this repository is agent47, the PyPI package is agentguard47,
and the Python import is agentguard. Requires Python 3.9 or newer.
Getting started
Install in a virtual environment, then run the offline checks:
python -m pip install agentguard47
agentguard doctor
agentguard demo
doctor checks the installation and local trace writing. demo exercises
budget, loop, and retry stops without provider keys or network access. Follow
the trace path printed by the command to inspect its output.
agentguard demo --feedback prints a local redacted report; nothing is sent.
Stop before a third call
Save this as budget_demo.py and run python budget_demo.py. It makes no
network requests.
from agentguard import BudgetExceeded, BudgetGuard
budget = BudgetGuard(max_calls=2)
completed = 0
for _ in range(3):
try:
budget.check() # Check before the operation.
# Put your provider or tool call here.
completed += 1
budget.consume(calls=1) # Record the completed operation.
except BudgetExceeded:
print(f"Stopped before call {completed + 1}")
assert completed == 2
Expected output: Stopped before call 3.
Connect a provider
Install the provider's client separately. For OpenAI:
python -m pip install openai
from agentguard import BudgetGuard, JsonlFileSink, Tracer, patch_openai
budget = BudgetGuard(max_cost_usd=5.00)
tracer = Tracer(
service="my-agent",
sink=JsonlFileSink(".agentguard/traces.jsonl"),
)
patch_openai(tracer, budget_guard=budget)
# Make your OpenAI chat.completions.create calls after this setup.
The patch checks recorded usage before dispatch and records response usage
afterward, including streamed calls once the final usage arrives. A response
can exceed the remaining cost or token allowance. Concurrent requests do not
reserve capacity. OpenAI streams request include_usage unless the caller
already set it. See the getting started guide
for setup, traces, and framework starters.
How enforcement works
flowchart TD
accTitle: AgentGuard operation checks
accDescr: Check a limit before an operation, then record usage.
A[Instrumented operation] --> B{Guard check}
B -->|Limit reached| C[Raise exception]
B -->|Allowed| D[Run operation]
D --> E[Record usage and trace]
E --> A
Text equivalent: check before an operation, run it if allowed, then record usage. A guard exception returns control to your application's error handler.
| Guard | Checks | Raises |
|---|---|---|
BudgetGuard |
Recorded calls, tokens, or estimated cost | BudgetExceeded |
LoopGuard |
Repeated tool calls | LoopDetected |
FuzzyLoopGuard |
Tool frequency and alternating patterns | LoopDetected |
RetryGuard |
Retries per tool | RetryLimitExceeded |
TimeoutGuard |
Elapsed time when checked | TimeoutExceeded |
RateLimitGuard |
Calls within a sliding minute | BudgetExceeded |
X402SpendGuard |
Payment amounts before the payment callback | BudgetExceeded |
For task budgets, use BudgetGuard.goal(...). For signatures and defaults,
read the guard source and
public exports.
Limits and security
- Guards cover operations you instrument. Installing the package does not intercept every action in Cursor, Claude Code, or another agent.
- A guard is not a sandbox or permission system. A permitted operation can still be destructive.
- Timeout checks do not interrupt an already blocked function or cancel an agent running on a provider's server.
- Cost estimates are not invoices. Supply reported cost or use strict cost resolution when an estimate is insufficient.
- Recorded-budget preflight refuses the next instrumented call when stored usage is already at a cap. It does not reserve concurrent in-flight requests, predict the next response, or cap a provider subscription. See the enforcement boundary.
- The base SDK uses the standard library. Optional framework extras install third-party dependencies and need their own security review.
- Trace content can contain application data. Review it before sharing or configuring a remote sink.
See security reporting, the dated dependency audit, and release notes. Audit results describe their recorded date, not a permanent clean bill of health.
Local traces and optional hosted ingest
The SDK is the free local proof path. Start local. Add hosted ingest only when you need retained history, alerts, team visibility, spend trends, hosted decision history, or dashboard-managed remote kill signals.
Local guards remain authoritative. HttpSink mirrors trace and decision events;
it does not execute remote kill signals by itself. See the
dashboard contract before configuring it.
Local use has no hosted event quota, retention period, or API-key allocation.
Network egress requires an integration you configure, such as HttpSink or
an OpenTelemetry exporter.
Nothing in the local SDK phones home. The AgentGuard website describes the optional hosted service.
Documentation
| You want to | Start here |
|---|---|
| See which paths actually stop a call | Enforcement boundary |
| Install and trace a first run | Getting started |
| Find guides and source references | Documentation index |
| Try a runnable example | Examples |
| Connect LangChain, LangGraph, or CrewAI | Integration guides |
| Inspect hosted data through MCP | Read-only TypeScript MCP server |
| Use local budget tools through MCP | Python budget MCP server |
| Navigate with an AI assistant | AI documentation index |
| Contribute a fix | Contributing |
| Check what changed | Changelog |
Help and maintenance
Maintained by Patrick Hughes. Report a bug with the package version, a minimal reproduction, and the expected result. Report vulnerabilities through SECURITY.md.
The source metadata defines the branch version. The PyPI badge links to the published version. Documentation examples and local links are tested in CI. The PyPI README is generated from this README and the changelog.
Latest Release Notes (1.4.0)
Stream reservation (AG-05)
- Store-backed OpenAI and Anthropic streams reserve one call before send. Final usage commits once. A dropped connection, a provider timeout, or a stream that stops early keeps the hold, including after a partial usage chunk. Missing usage under a token or dollar cap stays unresolved instead of an authoritative zero. A calls-only cap settles one call.
- Unknown model cost is an overestimate. Dated model ids use the owned alias
map. Cache and reasoning tokens follow the owned price table. Pass
prices=toresolve_billable_costto override that table. No new public export. - In-memory streams, async non-stream calls, and Anthropic non-stream calls stay on recorded-budget preflight. Not an invoice cap.
One local reservation path (AG-04)
- Sync, non-streaming OpenAI Chat Completions now reserve before send when
BudgetGuardhas aStateStore. One shared key and one remaining call produce one dispatch. Commit records provider usage. Cancel frees the hold only if the request never left. Timeout, crash, and unknown outcomes keep the hold. BudgetGuard.reservation_totals()reports settled, reserved, and unresolved amounts.check()andconsume()are unchanged. This slice left streaming, async, and Anthropic on recorded-budget preflight. Store-backed streams are the AG-05 note above.- This is not an invoice cap. Token and dollar holds need
max_tokenson the request. The dollar bound is the owned high-water estimate.
Local reservation contract (AG-03)
- Designed reserve / commit / cancel / unresolved semantics for a future
local
StateStorepath: docs/guides/reservation-contract.md. - Executable private model:
sdk/agentguard/_reservation_contract.py. Unknown provider outcomes cannot silently free funds. No public type.BudgetGuard.check()still does not reserve. AG-04 wires one OpenAI path.
Activation evidence (AG-02)
- Landing-page navigation never counts as install or activation.
agentguard demo --feedbackprints a local redacted report (version,adapter,result,reproduction). Users inspect,--omit, or decline. The demo still makes no network call.- Weekly classifier:
python scripts/activation_weekly_report.py docs/guides/activation-baseline-2026-09-18.json. - bmdpat
install_intentfollow-up: docs/guides/bmdpat-measurement-contract.md.
Honest enforcement boundary (AG-01)
- Published the tested surface map in docs/enforcement-boundary.md: advisory, recorded-budget preflight, recorded-event preflight, reservation-backed, or unsupported.
- Replaced absolute bill-prevention copy with recorded-budget bounds. Direct SDK bypass, in-flight spend, missing usage, concurrent overshoot, and provider subscription quotas stay documented as remaining exposure.
- Offline reproductions:
examples/enforcement_boundary/exhausted_budget_blocks_dispatch.pyandexamples/enforcement_boundary/two_worker_overshoot.py.
Full changelog: CHANGELOG.md
Release files for agentguard47 1.4.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | |
|---|---|---|---|
| agentguard47-1.4.0.tar.gz | 251.9 kB | Details |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Reset |
|---|---|---|---|---|
| agentguard47-1.4.0-py3-none-any.whl | Python 3 | none | any | Details |
Total release size: 384.8 kB
Release files / agentguard47-1.4.0.tar.gz
| Download URL | agentguard47-1.4.0.tar.gz |
|---|---|
| Size | 251.9 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
a80873bd1f4c06e7c1c3a58d91106e5cb80e62fa814985fddd7ba3c054102781
|
|
BLAKE2b-256 checksum How to use checksums |
524ed1b90e84a2c95a9ff6d8f0a4898ed228d96fa3da0c2b1591e271fc595c14
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.14
|
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.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Sep 24, 2026.
Transparency logRelease files / agentguard47-1.4.0-py3-none-any.whl
| Download URL | agentguard47-1.4.0-py3-none-any.whl |
|---|---|
| Size | 132.9 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
ca8efaacff03cc373a30610c7fa7d9797a87fe140f56ece344e782df8b0435fa
|
|
BLAKE2b-256 checksum How to use checksums |
cfe37bbd7bb3a573a79887e7f9d4bb16cdadb873cbdb3824d4ecb3474fe87958
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.14
|
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.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Sep 24, 2026.
Transparency log