Metadata-Version: 2.5
Name: agentgovern
Version: 2.8.5
Summary: Compliance-as-code middleware for agentic AI workflows.
Project-URL: Homepage, https://agentgovern.zirahn.com
Project-URL: Support, https://zirahn.com/contact
Author-email: Ahmed Khan <ahmed.khan@zirahn.com>
License: MIT
License-File: LICENSE
Keywords: agent-governance,agents,ai,compliance,eu-ai-act,governance,langchain,nist
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Topic :: System :: Monitoring
Requires-Python: >=3.10
Requires-Dist: httpx>=0.27.0
Requires-Dist: pydantic>=2.10.0
Provides-Extra: crewai
Requires-Dist: crewai>=0.80.0; extra == 'crewai'
Provides-Extra: dev
Requires-Dist: langchain>=1.0.0; extra == 'dev'
Requires-Dist: pytest-asyncio>=0.24.0; extra == 'dev'
Requires-Dist: pytest-cov>=6.0.0; extra == 'dev'
Requires-Dist: pytest>=8.3.0; extra == 'dev'
Requires-Dist: respx>=0.21.0; extra == 'dev'
Requires-Dist: ruff>=0.8.0; extra == 'dev'
Provides-Extra: langchain
Requires-Dist: langchain-core>=0.3.0; extra == 'langchain'
Provides-Extra: langgraph
Requires-Dist: langchain-core>=0.3.0; extra == 'langgraph'
Requires-Dist: langgraph<2.0.0,>=0.2.0; extra == 'langgraph'
Provides-Extra: openai
Requires-Dist: openai>=1.50.0; extra == 'openai'
Provides-Extra: sdk
Description-Content-Type: text/markdown

# AgentGovern Python SDK

**Compliance-as-code for agentic AI workflows.**

> **Beta** — API may change before 1.0. Report issues through [zirahn.com/contact](https://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.

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

## Quickstart — LangChain

```python
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:

```python
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:

```python
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)

```python
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](https://agentgovern.zirahn.com).

## 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` | not set | **Deprecated, removed in 3.0.** Passing it (any value) emits a `DeprecationWarning`. It has no effect: nothing in the SDK reads it, so either value behaves the same. Whether an exception reaches your code does not depend on it (see "What never stops your agent" under Enforcement modes) |

**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:

```bash
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`:

```bash
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:

  ```bash
  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

```bash
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:

```bash
AGENTGOVERN_HOOK_MODE=off claude
```

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

```powershell
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

## Links

- **Dashboard:** https://agentgovern.zirahn.com
- **Documentation:** this README
- **Support and issues:** https://zirahn.com/contact

## License

MIT — Copyright (c) 2026 Zirahn
