Skip to main content

AgentTrafficCop Python SDK

PyPI version Python versions

Check the next agent action before it runs.

AgentTrafficCop provides deterministic checks for repeated actions, repeating cycles, and approved-step limits. Choose local in-process checks or a hosted API with shadow decisions, incident timelines, threshold comparison, and reported-cost controls. Your application must honor every rejected or failed check.

Legacy checks do not execute actions, automatically intercept every model call, understand semantic repetition with deterministic checks, or cancel in-flight work. The new runtime execution helpers invoke only the callable explicitly passed to them. The separate experimental SemanticMonitor uses your encoder for warnings only.

Install

Python 3.11+:

python -m pip install --upgrade 'agenttrafficcop==1.6.0'
python -c "from importlib.metadata import version; print(version('agenttrafficcop'))"

Base dependency: httpx>=0.27.0,<0.29.0. Use a virtual environment; optional framework extras have their own requirements.

New in 1.6.0

  • GuardRuntime: one explicit sync/async facade, opt-in semantic blocking, root transport-metadata normalization and connection-only degraded fail-open.
  • Registration-time hooks for a pinned LangGraph/CrewAI/current AutoGen set and an explicit MCP call_tool proxy; no global instrumentation or streaming support.
  • Configured-price non-streaming OpenAI/Anthropic token-usage adapters and trusted signed reporting; check/reserve/execute/final-settlement helpers.
  • Client-reported semantic evidence in compatible hosted timelines/replay; observations are not verified hosted approvals or re-evaluated semantic replay.
  • Required-shared-state deployment gate and a durable Redis configuration; Redis must still be provisioned/configured by the operator.

See RUNTIME_FEATURES.md for examples, supported versions, privacy, failure/cancellation limits and infrastructure requirements. Existing client defaults and detector thresholds remain unchanged. The new root metadata preset is opt-in, not the previously reverted recursive field stripper.

Included from 1.5.0

  • Explicit outage policy: fail-closed hosted enforcement with optional safe connection-establishment retries and redacted events. No automatic local fallback.
  • Experimental semantic warnings: opt-in SemanticMonitor with your own encoder, bounded embedding history, and no approvals or blocking authority.
  • Human review: compatible hosted dashboards let account owners authorize one exact retry, without resetting history or bypassing quotas/spend controls.

See FEATURES.md for usage, privacy and failure-path limits.

Included from 1.4.0

  • Optional payload normalization: explicitly ignore selected object fields when computing action identity. Original action data is not mutated.
  • Threshold comparison: compare repeat/cycle/step policies offline or against bounded hosted incident history, without executing actions or changing policy.
  • Shared run spending reservations: reserve estimated cost before participating calls and settle through trusted signed actual-cost reporting. Pro/Team hosted creation; not a provider-side hard spending cap.

LocalGuard shipped in 1.3.0; hosted hash-only helpers shipped in 1.2.0. Defaults remain unchanged in 1.5.0. New hosted helpers require a compatible backend.

Local or hosted?

Capability LocalGuard Guard / GuardSync
API key / network required No Yes
Exact repeats, cycles, step limits Yes Yes
Optional field exclusions Yes With hash_only=True
Shadow mode No Yes
Dashboard records and retained-run replay No Yes
Schema-change heuristic No Pro/Team
Reported run budgets / reservations No Pro/Team
State sharing One guard instance Depends on backend configuration
Automatic action interception No No

Local quick start

from agenttrafficcop import LocalGuard

guard = LocalGuard(max_repeats=3, max_steps=50)
for _ in range(3):
    result = guard.check(
        session_id="example-run",
        payload={"tool": "search", "arguments": {"query": "refund policy"}},
    )
    if not result.approved:
        print("Not executed:", result.reason)
        break
    print("Approved step", result.step)
    # Execute your protected action here.

The first two checks approve; the third returns REPEATED_PAYLOAD_LOOP. Reuse one guard instance and stable session ID throughout a run.

Local defaults:

guard = LocalGuard(
    max_repeats=3, max_steps=50,
    max_cycle_length=2, max_cycle_repeats=3,
    max_sessions=1000, session_ttl=3600,
    ignore_paths=(),
)

LocalResult contains approved, session_id, step, payload_hash, and reason. Policy rejection reasons are REPEATED_PAYLOAD_LOOP, CYCLIC_PAYLOAD_LOOP, STEP_LIMIT_EXCEEDED, or LOCAL_CAPACITY_EXCEEDED. Invalid inputs raise ValueError; do not execute after a failed check.

Checks and updates are thread-safe within one instance. History is in memory, expires after inactivity, and is lost on restart or guard.reset(session_id). Separate processes/instances do not share history. At capacity, new unexpired sessions are rejected rather than evicting active protection. Rejected checks refresh existing activity time but do not advance approved history.

Local mode makes no network requests, uploads no decisions, and has no hosted fallback, spending controls, or shadow mode. Approval counts checks, not verified executions. A different action can be approved after a repeat rejection if no other policy blocks it.

Optional payload normalization

Changing timestamps or request IDs can hide exact repeats. Exclude only fields you explicitly know are irrelevant:

from agenttrafficcop import LocalGuard, normalize_payload

guard = LocalGuard(ignore_paths=["/timestamp", "/request/id"])
action = {"tool": "search", "arguments": {"query": "refund"}, "timestamp": 123}
result = guard.check(session_id="run-1", payload=action)
if result.approved:
    pass  # Execute the ORIGINAL action here.

normalized_copy = normalize_payload(action, ignore_paths=["/timestamp"])

Paths are JSON pointers through objects only, not arrays or wildcards. ~1 escapes /; ~0 escapes ~. Missing keys are ignored; root deletion is unsupported. Up to 64 paths, 512 characters and 32 components per path are accepted. Invalid paths/non-finite JSON inputs raise ValueError.

No fields are removed automatically. Keep exclusions stable throughout a run; old hashes are not rewritten. Excluding meaningful arguments can make different actions look identical. This is not semantic detection.

Hosted quick start

Verify your email, create an account and generate an API key in the dashboard. Store it server-side:

export ATC_API_KEY="your-api-key"
import asyncio
import os
import uuid
from agenttrafficcop import AgentTrafficCopError, Guard

async def main():
    run_id = uuid.uuid4().hex
    async with Guard(
        url="https://api.agenttrafficcop.com",
        api_key=os.environ["ATC_API_KEY"],
        dry_run=False,
    ) as guard:
        try:
            result = await guard.check(
                session_id=run_id, sender="planner", recipient="worker",
                payload={"tool": "search", "arguments": {"query": "refund"}},
            )
        except AgentTrafficCopError as exc:
            print("Not executed:", exc.error_code)
            return
        if result.approved:
            print("Approved at step", result.step)
            # Execute your protected action here.

if __name__ == "__main__":
    asyncio.run(main())

Use a stable ID throughout a run and a new ID for each independent run. Call at all relevant execution boundaries. Client creation alone does not protect code.

GuardSync provides the same check without await:

import os
from agenttrafficcop import AgentTrafficCopError, GuardSync

with GuardSync("https://api.agenttrafficcop.com", os.environ["ATC_API_KEY"], dry_run=False) as guard:
    try:
        result = guard.check(
            session_id="my-stable-run-id", sender="planner", recipient="worker",
            payload={"tool": "search", "arguments": {"query": "refund"}},
        )
    except AgentTrafficCopError as exc:
        print("Not executed:", exc.error_code)
    else:
        if result.approved:
            pass  # Execute your protected action here.

Hosted hash-only checks

Within an open Guard context:

result = await guard.check(
    session_id=run_id, sender="planner", recipient="worker",
    payload={"tool": "search", "query": "refund", "timestamp": 123},
    hash_only=True,
    ignore_paths=["/timestamp"],  # Optional; introduced in 1.4.0.
)

GuardSync uses the same arguments without await. Hosted field exclusions require hash_only=True; otherwise they raise ValueError before a request. The helper hashes a nonempty JSON object using sorted keys, compact separators, unescaped Unicode, UTF-8 and SHA-256. Non-finite numbers are rejected. This is not RFC 8785 canonicalization. A normalized empty object is rejected.

Raw transmission is the hosted default. Hash-only omits the raw payload, rejects metadata, and never falls back to sending raw contents. Hashes and routing identifiers still leave the application. Hashes reveal equality; predictable inputs can be guessed. They are not encryption or guaranteed anonymization. The backend cannot prove that the submitted hash matches the eventual action.

REST callers use payload_mode="hash_only" and a 64-character lowercase hex payload_hash, omitting both payload and metadata entirely, including nulls. Raw and hash-only checks share history when their hashes, key, session and mode match. Required routing fields and ordinary policies still apply.

Shadow mode

Within an open hosted client:

result = await guard.check(
    session_id=run_id, sender="planner", recipient="worker",
    payload={"tool": "search"}, mode="shadow",
)
if result.would_block:
    print(result.shadow_decision["error"])
if result.approved:
    pass  # Application may execute in shadow mode.

Supported repeat/cycle/step and eligible schema detections become warnings. Authentication, validation, rate limits, message/agent quotas, spending blocks, exhausted budgets and coordination failures can still reject. Approved shadow checks consume quota. Shadow and enforcement histories are separate. Switching modes does not transfer history. Run spending retains its key/run scope.

Keep dry_run=False: legacy dry-run is not shadow mode. Do not let untrusted callers change policy modes or reset history when enforcement is mandatory.

Historical replay and threshold comparison

Offline, supply ordered SHA-256 hashes of observed attempted actions:

from agenttrafficcop import compare_thresholds

comparison = compare_thresholds(
    payload_hashes,
    policies=[{"max_repeats": 3, "max_steps": 25},
              {"max_repeats": 4, "max_steps": 40}],
)

Up to 10,000 hashes and four policies are accepted. Supported settings are max_repeats, max_steps, max_cycle_length and max_cycle_repeats. Offline omitted settings follow LocalGuard defaults (50 steps). Each simulation starts with empty history and stops at its first block. No actions run or alerts fire.

For retained hosted history, inside an open client:

comparison = await guard.replay_run(
    session_id=run_id,
    policies=[{"max_repeats": 3, "max_steps": 25},
              {"max_repeats": 4, "max_steps": 40}],
    mode="shadow",
)

GuardSync omits await. Hosted omitted settings use 3 repeats, 25 steps, cycle length 2 and 3 cycle repetitions. In the dashboard, use Inspect run → Compare detector thresholds. Its reference is explicit—not the run's verified original policy. Nothing changes live detector settings.

Results always set full_history_verified=false: timelines are bounded to 200 recorded checks per run, up to 10,000 per key within plan retention. Missing hashes stop replay; discontinuous steps are flagged. Enforcement and shadow are selected separately. Resets, expiry, historical policy changes, missing actions and complete execution traces are not reconstructed. A different threshold cannot invent actions the original workflow never attempted.

Comparison covers repeat/cycle/step rules—not schemas, semantic similarity, quotas, spending or every custom hosted policy. Hashes cannot be re-normalized without original payloads. Timeline records omit raw payloads and metadata; raw-mode checks still transmit payloads for validation and hashing.

Reported spending and run budgets — Pro/Team

budget = await guard.set_run_budget(session_id=run_id, budget_usd="2.00")
# GuardSync: budget = guard.set_run_budget(...)

Setting a budget does not connect provider billing. An authorized backend must report incremental costs through timestamp/HMAC-signed POST /v1/ingest/usage requests. Use matching key/session attribution and stable unique event IDs; never report cumulative run totals or duplicate spending across integrations.

Run budgets are API key + session scoped. Rolling thresholds cover a key's reported costs over 60 seconds. Updating budgets preserves spending; a new run needs a new session ID. Delayed reports, unguarded actions and in-flight work can overshoot. These are not provider-side hard caps.

Shared spending reservations — Pro/Team

Reserve estimated cost before participating calls start, after setting a run budget. Admission atomically checks reported spending plus outstanding holds:

hold = await guard.reserve_spend(
    session_id=run_id,
    reservation_id="operation-123",  # Stable, unique per logical operation.
    estimated_cost_usd="0.20",
)
if hold["duplicate"] or hold["status"] != "held":
    raise RuntimeError("Recover through your execution ledger; do not execute twice")
# Execute this operation once, only after all other required checks pass.

Sync clients omit await. Estimates are positive, at most $1 billion, with up to 6 decimal places. Missing budgets return 409; insufficient available budget returns 402. Same ID/estimate returns the existing reservation with duplicate=true; changed estimates conflict. A duplicate is not permission to execute again. Keep an execution ledger/provider idempotency key for recovery.

A trusted reporter submits one final incremental actual cost per reservation:

{
  "api_key": "YOUR_ATC_KEY",
  "session_id": "run-1",
  "reservation_id": "operation-123",
  "event_id": "final-cost-123",
  "cost": "0.17"
}

Send this body to /v1/ingest/usage with X-ATC-Timestamp and X-ATC-Signature. The signature is hexadecimal SHA-256 HMAC of timestamp + "." + exact_body, using the server-side ingestion secret. An ordinary API key does not grant access to that signing secret. Arrange an authorized integration for the hosted service; never expose it in browser code.

Settlement records actual cost and clears its hold in one transaction. Retry the same event with unchanged cost/attribution. Do not also report that operation through another integration. Partial/streamed settlements of a single hold are not supported; aggregate the final cost at the trusted reporter. CloudPulse key-level reports do not settle individual run reservations.

There is no automatic expiry or bearer-token cancellation: a timed-out worker may still be executing. A trusted reporter can settle at zero only after knowing that no cost was incurred. Unknown outcomes remain held and require recovery. There is a 10,000 unresolved-hold cap per run; active holds are not evicted.

The ledger is persistent and shared only by workers using the same database. Separate SQLite files do not coordinate even when detector history uses Redis. Reservations are key/run scoped, not account-wide or rolling-window allowances. Unreserved calls are not prevented. Actual costs above estimates are still recorded and can exceed the budget. check() does not reserve automatically.

Budget reads include reserved_spend_usd and available_to_reserve_usd. GET /v1/runs/{session_id}/reservations supports after and limit pagination.

Framework integrations

LangGraph

python -m pip install 'agenttrafficcop[langgraph]==1.6.0'
from agenttrafficcop.langgraph import guarded_node

# Existing graph, open hosted guard, and reviewer_fn:
graph.add_node("reviewer", guarded_node(
    reviewer_fn, guard=guard, sender="coder", recipient="reviewer",
    session_id=lambda state: state["run_id"],
    payload=lambda state: {"draft": state["draft"]},
    raise_on_trip=True,
))

Only wrapped nodes are protected. Keep exceptions propagating so failed checks stop execution. Adapters do not automatically enable normalization, hash-only, shadow mode or spending reservations. Use direct checks for unexposed options.

Legacy AutoGen

python -m pip install 'agenttrafficcop[autogen]==1.6.0'

This legacy adapter supports only pyautogen==0.2.35, not AgentChat or AG2. For current AgentChat 0.7.5 use the separate guard_autogen_tools hook documented in RUNTIME_FEATURES.md. The legacy adapter does not support other similarly named packages. GuardedConversableAgent checks supported generate_reply / a_generate_reply pipelines, including registered handlers. Direct sends, direct tool calls and work outside those methods are not intercepted. One reply can execute multiple tools; costs are not automatically reported or reserved. It is not an execution sandbox. Dry-run guards are rejected. LocalGuard is not a drop-in replacement for hosted adapters.

Failure handling and reliability

  • Catch AgentTrafficCopError around hosted check() calls—not just loop errors.
  • Budget, replay and reservation helpers expose HTTPX HTTP/transport exceptions.
  • Local policy failures are results; invalid local input raises ValueError.
  • Stop on every failed check, including timeouts and HTTP 503 coordination errors.
  • A failed response does not prove that no history or quota update occurred.
  • Policy-rejected checks do not consume approved-message quota. Ambiguous crash/storage failures can retain conservative charges without client approval.
  • Memory-backed hosted detector history remains single-process and is lost on restart/expiry/reset. Redis coordination needs compatible participating workers. Persistent incident records do not restore active detector history.
  • Webhook notifications are best effort, not a guaranteed-delivery incident queue.

Use a trusted execution boundary, stable session identity and a stable payload policy. Different wording with different hashes is not detected semantically. The SDK is Alpha software, not a compliance certification or a zero-error guarantee.

License

The Python SDK is licensed under the MIT License. This does not license the hosted service or private backend.

Metadata

Release files for agenttrafficcop 1.6.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 agenttrafficcop 1.6.0
File Size Uploaded Provenance Actions
agenttrafficcop-1.6.0.tar.gz 51.3 kB With provenance Details for agenttrafficcop-1.6.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for agenttrafficcop 1.6.0
File Interpreter ABI Platform Actions
agenttrafficcop-1.6.0-py3-none-any.whl Python 3 none any Details for agenttrafficcop-1.6.0-py3-none-any.whl

Total release size: 89.9 kB

Release files / agenttrafficcop-1.6.0.tar.gz

Download URL agenttrafficcop-1.6.0.tar.gz
Size 51.3 kB
Tags Source
SHA-256 checksum
How to use checksums
d8280b3448008d47bb235c471ac98b1a44bf8d869c3e2de3dc73bf52700d3715
BLAKE2b-256 checksum
How to use checksums
c6fda47aba94c759ca9ce481ceeeb6275328d03104c05e8ef2fa6320831fa1fc
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

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 Nov 25, 2026.

Transparency log

Release files / agenttrafficcop-1.6.0-py3-none-any.whl

Download URL agenttrafficcop-1.6.0-py3-none-any.whl
Size 38.6 kB
Tags Python 3
SHA-256 checksum
How to use checksums
ca495e389ba302c25acc6ae18aec6fe431c9c043452e035a1245f8d01f731ea7
BLAKE2b-256 checksum
How to use checksums
4bf2a0c0fa24c3399f708597166ba602e4c8ee390c9877f9356f3706ed2e4868
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

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 Nov 25, 2026.

Transparency log

Security for agenttrafficcop 1.6.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.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for agenttrafficcop-1.6.0.tar.gz

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 Nov 25, 2026.

Transparency log

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.

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