Skip to main content

AgentTrafficCop Python SDK

PyPI

Check an agent action before executing it. AgentTrafficCop evaluates submitted payloads for exact repetition, repeating cycles, step limits and applicable usage/spending policies. Your application must honor rejections; the service does not execute actions, intercept every model call or cancel in-flight work.

Version 1.2.0

This release adds opt-in local payload hashing with hash_only=True. It requires a backend supporting payload_mode="hash_only". Earlier SDK versions do not expose this option. Check PyPI for publication status; source version numbers alone do not publish packages. Never install from the private backend repository.

Hash-only payload checks

Inside an open Guard context (or GuardSync, without await):

result = await guard.check(
    session_id=run_id,
    sender="planner",
    recipient="worker",
    payload={"task": "review", "private_content": "stays local"},
    hash_only=True,
)

The SDK hashes nonempty JSON objects locally using sorted keys, compact JSON, unescaped Unicode and UTF-8 SHA-256. Non-finite numbers and unsupported JSON values are rejected. No raw payload is sent, metadata is rejected, and there is no fallback to raw transmission if a server rejects the format. Framework adapters do not automatically opt in. Keep legacy dry_run=False for enforcement.

Routing identifiers still leave your app. Hashes reveal equality and predictable inputs can be guessed; hashes are not anonymization or encryption. The server cannot validate original payload contents or verify the hash represents the executed action. Raw mode remains the default. Detectors, shadow mode, quotas, and report-driven budgets still apply. Volatile fields are not stripped.

Python 3.11+:

python -m pip install 'agenttrafficcop==1.2.0'

Run the command after 1.2.0 is available on PyPI. Prefer an isolated virtual environment. Base SDK compatibility is httpx>=0.27,<0.29, including 0.28.1; extras have their own dependencies. No compatibility with every notebook package is implied.

export ATC_API_KEY="your-api-key"

Verify your email, create an account and generate a key in the dashboard.

Async checks

import asyncio
import os
import uuid
from agenttrafficcop import Guard, AgentTrafficCopError

async def main():
    run_id = uuid.uuid4().hex
    async with Guard("https://api.agenttrafficcop.com", os.environ["ATC_API_KEY"]) as guard:
        try:
            result = await guard.check(
                session_id=run_id, sender="planner", recipient="worker",
                payload={"task": "review patch"},
            )
        except AgentTrafficCopError as exc:
            print("Not executed:", exc.error_code)
            return
        if result.approved:
            # Execute the actual action here.
            print("Approved at step", result.step)

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

Use one stable session ID per run. Changing timestamps/random IDs in each payload can defeat exact-repeat detection. Deterministic matching is not semantic detection.

Sync checks

import os
import uuid
from agenttrafficcop import GuardSync, AgentTrafficCopError

with GuardSync("https://api.agenttrafficcop.com", os.environ["ATC_API_KEY"]) as guard:
    try:
        result = guard.check(
            session_id=uuid.uuid4().hex, sender="planner", recipient="worker",
            payload={"task": "review patch"},
        )
    except AgentTrafficCopError as exc:
        print("Not executed:", exc.error_code)
    else:
        if result.approved:
            print("Execute action here")

Shadow mode

Requires SDK 1.1.0 and a backend that supports mode="shadow". Existing calls default to enforcement; the SDK omits the new field in default requests for compatibility with older backends.

result = await guard.check(
    session_id=run_id, sender="planner", recipient="worker",
    payload={"task": "review patch"}, mode="shadow",
)
if result.would_block:
    print(result.shadow_decision["error"])
if result.approved:
    # Continue while evaluating loop policies.
    pass

GuardSync.check accepts the same arguments without await. A loop/step detection returns an approved result with would_block=True and shadow_decision evidence. Eligible schema-change checks also participate. Only the first matching rule is reported. The dashboard timeline labels these as [Shadow] Would block.

Authentication, validation, rate limits, agent/message quotas, rolling spend blocks and exhausted run budgets still reject requests. Approved shadow requests consume quota. Shadow mode deliberately allows detected looping work to continue. Shadow/enforcement loop histories are separate; switching modes does not migrate history. Key/run spending policies remain shared regardless of mode.

Keep legacy dry_run=False (the default). Legacy dry-run suppresses additional errors and is not shadow mode. Don't let untrusted callers select a mode when blocking policies are mandatory. Existing framework adapters do not automatically select shadow mode; use direct guard calls or explicit adapter wiring.

Per-run budgets — Pro/Team

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

Requires a backend supporting run budgets. A trusted backend must separately report incremental costs to POST /v1/ingest/usage with the same ATC key and session ID, stable unique event IDs, and timestamped HMAC headers. The signing secret belongs only on the trusted reporter, never in browser code. Setting a budget does not connect billing or report costs automatically.

Reports use api_key, event_id, cost (decimal string), and session_id. X-ATC-Signature is the hex SHA-256 HMAC of timestamp + "." + exact_body, using the ingestion secret; X-ATC-Timestamp contains that timestamp. Do not report running totals or duplicate the same spending across reporting integrations.

When reported spending reaches a budget, subsequent guarded actions are rejected with RUN_BUDGET_EXCEEDED. Updates preserve accumulated spending; new runs need new session IDs. Budgets are API-key + session scoped.

These are report-driven controls, not provider hard caps. Missing/delayed reports, concurrency and in-flight calls can cause overshoot. Unguarded actions are outside ATC's control. CloudPulse key-level reports do not attribute spending to runs.

LangGraph

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

# With your existing graph, guard client and node function:
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 rejection exceptions propagating to stop execution. The wrapper supports sync and async node functions. No other framework is automatically intercepted by installing the SDK.

Legacy AutoGen 0.2.35

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

Only pyautogen==0.2.35 is supported, not AutoGen 0.4+/AgentChat or AG2.

import os
import uuid
from autogen import ConversableAgent
from agenttrafficcop import GuardSync, AgentTrafficCopError
from agenttrafficcop.autogen import GuardedConversableAgent

with GuardSync("https://api.agenttrafficcop.com", os.environ["ATC_API_KEY"]) as guard:
    worker = GuardedConversableAgent(
        "worker", atc_guard=guard, atc_session_id=uuid.uuid4().hex,
        llm_config=False, human_input_mode="NEVER", code_execution_config=False,
        default_auto_reply="Acknowledged.",
    )
    caller = ConversableAgent("caller", llm_config=False, human_input_mode="NEVER",
                             code_execution_config=False)
    try:
        print(worker.generate_reply(
            messages=[{"role": "user", "content": "Review this task"}], sender=caller,
        ))
    except AgentTrafficCopError as exc:
        print("Not executed:", exc.error_code)

The adapter checks before generate_reply and a_generate_reply reply handlers. The async path offloads the sync guard check to a thread. Keep GuardSync open for the agent's lifetime. Direct sends/tool calls outside guarded reply methods are not intercepted. One reply can contain multiple tools, not individual spending reservations. No automatic cost reporting or execution sandbox is supplied. Dry-run guards are rejected.

Operational notes

  • Normal route checks submit payloads for server-side hashing; timeline records omit raw payloads. Hash-only submission is not implemented yet.
  • Timelines contain bounded evidence, not complete traces or historical replay.
  • Without shared session storage, active loop history can be process-local and lost on restart; persistent timeline records do not restore it.
  • Catch AgentTrafficCopError for check failures; rejections aren't all HTTP 422.
  • Operator-only endpoints are not available to ordinary API keys.
  • SDK reset helpers require administrator permission on the hosted service.

Roadmap candidates

These are not available features or delivery commitments.

Candidate Goal
Hash-only payload mode Reduce raw payload exposure
Historical replay Compare settings against recorded event sequences
Local-first checks Evaluate selected deterministic rules locally
Controlled resume Human review and limited continuation
Spending reservations Coordinate participating parallel agents
Semantic detection experiments Evaluate rephrased repetition, initially warning-only

Website · Public SDK repository · Issues

The SDK is MIT licensed. See LICENSE.

Metadata

Release files for agenttrafficcop 1.2.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.2.0
File Size Uploaded Provenance Actions
agenttrafficcop-1.2.0.tar.gz 19.1 kB With provenance Details for agenttrafficcop-1.2.0.tar.gz

Built distribution (wheel)

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

Total release size: 34.5 kB

Release files / agenttrafficcop-1.2.0.tar.gz

Download URL agenttrafficcop-1.2.0.tar.gz
Size 19.1 kB
Tags Source
SHA-256 checksum
How to use checksums
7ec8b892d1bed5f42fa1f9494d8f111ec6f99bd7d2706ed3b6e6bd12f47e4e03
BLAKE2b-256 checksum
How to use checksums
defba742b56b9afea716bf3ec4cad53c014cbba4c28feb797b70f68104dcd435
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 21, 2026.

Transparency log

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

Download URL agenttrafficcop-1.2.0-py3-none-any.whl
Size 15.4 kB
Tags Python 3
SHA-256 checksum
How to use checksums
34b02cb46a439e7626817fd5e5e9f8b1ae57334e3bec5677ad4d6bd834e2991b
BLAKE2b-256 checksum
How to use checksums
e79170e418a90018ccec917e9cd99c19caa086072e878d97d9f73f95be8fde81
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 21, 2026.

Transparency log

Security for agenttrafficcop 1.2.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.2.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 21, 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