Skip to main content

AgentGovern Python SDK

Compliance-as-code for agentic AI workflows.

Beta — API may change before 1.0. Report issues through zirahn.com/contact.

AgentGovern intercepts AI agent actions, evaluates them against configurable compliance policies (the EU AI Act today; NIST AI RMF and ISO 42001 are on the roadmap — see the table below), and generates audit-ready evidence in near real-time. Tracking runs in a background thread and fails open. An enforce-mode block raises in your code (see Enforcement modes below for exactly what it stops). This SDK auto-instruments LangChain and LangGraph; any other framework (CrewAI, OpenAI Agents and the rest) can report actions with track_action().

Install

Needs Python 3.10 or later. The macOS system Python is 3.9, which is too old: install a newer one first, from python.org or with Homebrew (brew install python@3.12). On 3.9 this command fails with "No matching distribution found" rather than installing an old release.

python3 -m pip install "agentgovern[langchain]>=2.8.0"

Quickstart — LangChain

import agentgovern
from langchain.agents import create_agent
from langchain_openai import ChatOpenAI

# 1. Initialize once at startup
agentgovern.init(
    api_key="ag_prod_...",           # from https://agentgovern.zirahn.com/settings/api-keys
    base_url="https://agentgovern.zirahn.com",
    environment="production",        # your API key's environment: "production" | "staging" | "development"
)

# 2. Register your agent
agentgovern.register_agent(
    external_id="credit-scoring-v2",
    name="Credit Scoring Agent v2",
    framework="langchain",
)

# 3. Get the callback handler — binds to credit-scoring-v2 automatically
handler = agentgovern.instrument_langchain()

# 4. Build the agent and pass the handler via config — no other changes needed
agent = create_agent(model=ChatOpenAI(model="gpt-4o"), tools=tools)

result = agent.invoke(
    {"messages": [{"role": "user", "content": "Evaluate loan application for customer #12345"}]},
    config={"callbacks": [handler]},
)

instrument_langchain() binds to the most recently registered agent. Every tool call, LLM invocation, and agent step is captured, evaluated against your compliance policies, and visible in the dashboard.

Enforcement modes

AgentGovern supports five enforcement modes per policy:

Mode Behavior
warn Records the violation; the agent continues
log Records the violation silently; the agent continues
alert Same as warn today: records the violation; the agent continues
disabled Still evaluated, and failures are recorded; the agent continues
enforce Records the violation, and raises in your code where the check runs before the action (below)

What enforce stops, through the LangChain and LangGraph integrations

When an enforce-mode policy blocks, the exception reaches the code that called invoke(), ainvoke(), stream() or astream():

  • Gate 1 (input) raises PolicyViolation before the model call runs. This is the control that stops an agent before it acts. By default (auto_evaluate_input=True) it runs before every model call the handler sees, chat models and completion-style LLMs alike, and checks the last 4,000 characters of the call's input against your policies' input rules: the newest message, and as much history before it as fits. Anything earlier is not checked in that call, and a single message longer than 4,000 characters is checked only on its last 4,000. (Changed in SDK 2.8.0, NAGT-555. Earlier releases checked chat models only, and only the first 4,000 characters, so a long conversation's newest message went unchecked.)
  • Gate 2 (output) raises OutputBlocked (block) or OutputEscalated (escalate) when the run finishes, if you pass gate_2_enforcement_mode="enforce" to instrument_langchain() or instrument_langgraph(). It is off by default. Gate 2 stops invoke() from returning a blocked answer. It does not undo anything that already happened: tool calls have already run, a LangGraph checkpointer has already saved the final state, and a stream() caller has already received the streamed output. On LangChain, a run whose LLM streamed tokens skips the synchronous Gate 2 entirely.
  • Redact replaces the answer on LangChain; LangGraph does not apply it.
  • An output over the policy engine's 256 KB limit is cut to fit, and the part that fits is evaluated; the result's partial (or the exception's) says so. A block, escalate or redact found in that part raises OutputBlocked / OutputEscalated (a redact can't be applied to the whole answer). When no policy applies to the action, it is allowed, as it would be whole. Anything else is treated as unchecked: with gate_2_failure_mode="fail_closed" it raises OutputBlocked, as the engine's refusal did before; otherwise it is allowed. (SDK 2.8.0, NAGT-545. Before, such an output was never evaluated at all.) On LangGraph, see the last item below.

What enforce does not stop:

  • A tool call. The SDK does not check a tool call before it runs. A policy on tool calls is evaluated on the recorded action after the tool has run, so in enforce mode it records the failure but cannot prevent the call. (Guard's Claude Code hook, below, does check each tool call before it runs.)
  • An agent AgentGovern can't find. Gate 1 allows the call, and records no evaluation, when the agent isn't registered yet or is registered under a different environment from the one init() names. register_agent() sends the registration in the background, so a new agent's first model calls can pass this way.
  • An input that also fails a warn, log, alert or disabled policy, until AgentGovern's policy engine is updated (NAGT-555). Gate 1 acts on the first input rule the input fails, and that rule's policy decides. So when an input fails rules in two policies, one set to enforce and one set to warn or disabled, it can be allowed instead of blocked. The engine is updated separately from this SDK; after that update the strictest failing rule decides, whatever SDK version you run.
  • The rest of a long LangGraph output. The LangGraph integration cuts the graph's output to its first 65,536 characters before Gate 2 and evaluates that part as if it were the whole output: it is not marked partial, and Gate 2 does not check the rest.

What never stops your agent: warn, log, alert and allow verdicts, and any error inside the SDK itself. If Gate 1 can't complete its check (AgentGovern can't be reached, doesn't answer within 5 seconds, returns a server error, or refuses the request with a 4xx, such as a wrong API key or a rate limit), the model call goes ahead, unless you pass fail_open=False, which makes Gate 1 raise GateUnavailable before the model is called. With fail_open=False, a wrong, revoked or expired API key stops every model call. (Changed in SDK 2.8.1: before, a 4xx let the call go ahead even with fail_open=False.) With fail_open=False, a 200 answer that is not a Gate 1 answer (no action_taken, or one Gate 1 never sends) also raises GateUnavailable. (Changed in SDK 2.8.2.) If Gate 2 can't complete its check, the output is returned, unless you pass both gate_2_enforcement_mode="enforce" and gate_2_failure_mode="fail_closed", which makes Gate 2 raise OutputBlocked.

Pass AgentGovern's handler last. When an enforce block raises, LangChain can stop delivering that event to the handlers after ours in the callbacks list (on synchronous runs it always does). A tracing or logging handler placed after AgentGovern's might not see the event that was blocked. Put AgentGovern's handler at the end of the list: config={"callbacks": [your_tracer, agentgovern_handler]}.

How: an instrumentor sets LangChain's raise_error when an enforce gate is configured (Gate 2 enforce, or Gate 1 auto-evaluation on), and lets out of its callbacks only the three verdict exceptions above and, when you pass fail_open=False, GateUnavailable.

(Changed in SDK 2.6.0, NAGT-380. Earlier releases recorded enforce-mode violations but did not stop the agent: LangChain caught the exception.)

You can also check input yourself before invoking an agent. evaluate_input() raises PolicyViolation when a policy set to enforce blocks the input, and otherwise returns the result:

from agentgovern import PolicyViolation

try:
    agentgovern.evaluate_input(agent_external_id="my-agent", prompt=user_prompt)
except PolicyViolation:
    raise HTTPException(status_code=403, detail="Prompt blocked by compliance policy")
agent.invoke({"input": user_prompt})

It sends the whole prompt, not 4,000 characters. Unlike the integrations, it raises ClientError when AgentGovern refuses the request (a 4xx). If AgentGovern can't be reached, doesn't answer within 5 seconds, returns a server error, or answers 200 with an empty or malformed body, it returns an allowed result, unless you pass fail_closed=True, which makes it raise GateUnavailable. The policy engine accepts a prompt of up to 100,000 characters; a longer one is refused with a 422, so evaluate_input raises ClientError.

Multiple agents in one process

If you run more than one agent in the same process, pass the agent ID explicitly to avoid ambiguity:

agentgovern.register_agent("fraud-detector", name="Fraud Detector")
agentgovern.register_agent("kyc-agent", name="KYC Agent")

handler_fraud = agentgovern.instrument_langchain("fraud-detector")
handler_kyc   = agentgovern.instrument_langchain("kyc-agent")

fraud_agent = create_agent(model=..., tools=...)
kyc_agent   = create_agent(model=..., tools=...)

fraud_agent.invoke(inputs, config={"callbacks": [handler_fraud]})
kyc_agent.invoke(inputs, config={"callbacks": [handler_kyc]})

Manual instrumentation (all frameworks)

from agentgovern.types import ActionType, ActionStatus

agentgovern.track_action(
    agent_external_id="my-agent-id",
    action_type=ActionType.TOOL_CALL,
    action_name="fetch_credit_bureau_data",
    status=ActionStatus.COMPLETED,
    duration_ms=312,
    input_payload={"bureau": "experian", "customer_id": "..."},
    output_payload={"fico_score": 720},
)

Supported frameworks

Framework Auto-instrumentation Status
LangChain instrument_langchain() — wraps tool and LLM callbacks Stable
LangGraph instrument_langgraph() — attaches to a StateGraph through callbacks= Stable
CrewAI Manual via track_action() Beta
OpenAI Agents API Manual via track_action() Beta

Auto-instrumentation for CrewAI and OpenAI Agents is on the roadmap.

Compliance frameworks

Framework Status
EU AI Act (High-Risk Systems) Available
NIST AI RMF Coming soon
ISO 42001 Coming soon

Enable policy packs from the AgentGovern dashboard.

Configuration

Parameter Default Description
api_key required SDK ingest key from the dashboard
base_url https://agentgovern.zirahn.com API endpoint
environment "production" "production" | "staging" | "development". Use your API key's environment. Actions are recorded under the key's environment whatever this says, and so are the Gate 1 and Gate 2 lookups of your agent; an agent that is not registered there yet goes unchecked
policy_engine_url https://engine.zirahn.com Policy engine endpoint for Gate 1 (evaluate_input) and Gate 2 checks. Override with this argument or the AGENTGOVERN_POLICY_ENGINE_URL env var
fail_silently True If True, SDK errors never raise into your agent

Policy engine address (2.4.0). The default engine address is now the stable name https://engine.zirahn.com. Versions 2.3.0 and earlier call https://agentgovern.onrender.com directly. That address keeps working, so nothing breaks if you stay on an older version, but only the stable name can follow the engine if it moves. Upgrade with python3 -m pip install --upgrade "agentgovern>=2.8.0". If you set policy_engine_url or AGENTGOVERN_POLICY_ENGINE_URL yourself, it still takes precedence.

Claude Code Hook

The SDK ships a built-in CLI for installing the AgentGovern hook into Claude Code. The hook checks every tool call against your tenant's policies before the tool runs. A policy in enforce mode blocks the call and Claude Code shows the reason; warn lets it run and shows a warning; log only records it. A new organization starts with no policy in enforce mode. A tool AgentGovern doesn't yet have a specific classification for is still captured and evaluated, tagged action_type=unmapped_tool rather than silently skipped.

Install

The simplest way is the dashboard: on Settings → Developers, Add Developer gives an install snippet for bash and PowerShell that finds Python 3.10 or later, installs this package into its own virtual environment, and runs agentgovern setup. setup checks your developer id and API key with AgentGovern, saves your two settings for new terminals, and installs the hook. agentgovern remove undoes all of it. To do it by hand:

agentgovern hook install

This deploys the hook script to ~/.agentgovern/hook.py, merges the correct entry into ~/.claude/settings.json (with an atomic backup), and prints instructions for any missing env vars.

Upgrading an existing install

Upgrading the package does not update a hook that is already installed. hook install copies the hook script to ~/.agentgovern/hook.py and writes its entries into ~/.claude/settings.json, and a plain agentgovern hook install against an existing install reports it as already installed and changes nothing. Upgrade, read what is installed now, then reinstall with --force:

python3 -m pip install --upgrade "agentgovern>=2.8.0"   # or the extra you installed with, e.g. "agentgovern[langchain]>=2.8.0"
agentgovern hook status                        # note each line's cmd= value and the "Install mode" line
agentgovern hook install --force               # keeps the python command, capture mode and PostToolUse matcher
agentgovern hook status                        # reports no [DRIFT] lines once the hook is current

--force keeps what the existing install has, unless you override it with a flag. It prints one Keeping ... line per setting it kept, so you can see what was preserved. agentgovern hook install --force --dry-run shows the same values and writes nothing.

Setting What --force does To change it
Python command (cmd= in hook status) Keeps the interpreter the existing entries name. If it can't be read with confidence (more than a plain interpreter path, or the entries disagree), it detects the interpreter running the installer and says so in one line. --python-command <path>
Capture mode (Install mode in hook status) Keeps the recorded mode, enriched or minimal. An install with no marker is read from its registered events: all four is enriched, PreToolUse alone is minimal, anything else gets enriched. --capture-mode=enriched or --capture-mode=minimal
PostToolUse matcher Keeps the existing one. Exception: a matcher that is exactly a tool list this package once shipped as its default (the fixed lists of earlier versions, which leave out PowerShell and other tools) is upgraded to *, with a line naming the old value. --matcher <pattern>
PreToolUse matcher Always *. Not overridable. none

With no existing install, or without --force, nothing changes: --force against nothing writes the defaults, and a plain hook install against an existing install still reports it and changes nothing. The timeout and the hook script are always the current ones. Before SDK 2.8.2, --force reset all three kept settings to the defaults, so a reinstall needed --python-command, --capture-mode=minimal and --matcher repeated; it no longer does.

Your environment variables are not touched. Restart any running Claude Code session afterwards.

If a command isn't found:

  • pip: command not found: use python3 -m pip, as above.

  • agentgovern: command not found (the command was installed somewhere that isn't on your PATH), or pip refuses with externally-managed-environment: install the CLI into its own virtual environment and call it by its full path:

    python3 -m venv ~/.agentgovern-venv
    ~/.agentgovern-venv/bin/python -m pip install --upgrade "agentgovern>=2.8.0"
    ~/.agentgovern-venv/bin/agentgovern hook status
    ~/.agentgovern-venv/bin/agentgovern hook install --force   # keeps what is installed; flags override
    

    The venv holds only the CLI. The hook itself runs with the interpreter recorded in ~/.claude/settings.json (the cmd= value in hook status). That interpreter needs no packages, because the hook script uses only the standard library, and --force keeps it even when you run the CLI from a venv, unless you pass --python-command.

If your hook was installed by 2.2.1 or earlier, this step matters for coverage, not just freshness. Those versions wrote a PreToolUse matcher naming a fixed list of tools (ten, in 2.2.1), so a call through any other tool (PowerShell, for example) never reached the hook. Starting with 2.3.0 the matcher is *, every tool — but only once hook install --force has rewritten the entry.

Required env vars

export AGENTGOVERN_API_KEY="ag_prod_..."           # Settings → API Keys
export AGENTGOVERN_ACTOR_USER_ID="<your-actor-id>"  # Settings → Developers: your install snippet, or "Your actor ID" (see the hook README)

Subcommands

Command Description
agentgovern hook install Install the hook (flags: --dry-run, --force, --capture-mode, --matcher (the PostToolUse matcher only), --python-command, --mode, --api-key, --actor-user-id, --api-url)
agentgovern hook uninstall Remove the hook entry from settings.json (script file preserved)
agentgovern hook status Show installation state, script path, deployed hook version, and env var status
agentgovern --version Print the package version and the hook version this package bundles
agentgovern setup Check the key and developer id, save both settings for new terminals, and install the hook (flags: --actor-user-id, --check, --profile)
agentgovern remove Remove the hook entry, Guard's profile lines or user variables, and Guard's files under ~/.agentgovern
agentgovern hook test Fire a synthetic event to verify end-to-end connectivity

Bypass

To skip governance for a session without removing the hook:

AGENTGOVERN_HOOK_MODE=off claude

In PowerShell (the variable is removed again when claude exits):

try { $env:AGENTGOVERN_HOOK_MODE='off'; claude } finally { Remove-Item Env:AGENTGOVERN_HOOK_MODE }

agentgovern hook install --help lists the install options, and agentgovern hook status shows what is installed. The environment variables are in Required env vars and Bypass above.

Design guarantees

  • track_action() does not wait on the network — all I/O happens in a background thread.
  • Buffer cap: 10,000 actions; oldest dropped when full
  • Retry: 3 attempts with exponential backoff (1 s → 30 s max)
  • If AgentGovern is unreachable, your agent continues unaffected

License

MIT — Copyright (c) 2026 Zirahn

Metadata

Release files for agentgovern 2.8.3

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

Source distribution (sdist)

Source distribution for agentgovern 2.8.3
File Size Uploaded Provenance Actions
agentgovern-2.8.3.tar.gz 292.9 kB With provenance Details for agentgovern-2.8.3.tar.gz

Built distribution (wheel)

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

Total release size: 421.8 kB

Release files / agentgovern-2.8.3.tar.gz

Download URL agentgovern-2.8.3.tar.gz
Size 292.9 kB
Tags Source
SHA-256 checksum
How to use checksums
a4db19f568e4a16f4038022bf7d1e076ae4b62661abe86ebaa756e8245bc46b6
BLAKE2b-256 checksum
How to use checksums
905e2d1bc470d790db8cd94f28cb1bcc6b9ca78fcd31c2d56fe8fe1370508e94
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 7, 2026.

Transparency log

Release files / agentgovern-2.8.3-py3-none-any.whl

Download URL agentgovern-2.8.3-py3-none-any.whl
Size 128.9 kB
Tags Python 3
SHA-256 checksum
How to use checksums
aab2bdd0fd0480ff0ad554f4c84de085ecb8de04bf4c56277f262cd959642f75
BLAKE2b-256 checksum
How to use checksums
3e06f10d365909f5ce987cffdae94bcc5129233440b114c2cfb7ee0c56b53e7d
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 7, 2026.

Transparency log

Security for agentgovern 2.8.3

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 agentgovern-2.8.3.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 7, 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.

Release history Release notifications | RSS feed

This release

2.8.3 This release

2 release files Full 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