Skip to main content

Python SDK for GovernorAI - The execution boundary for autonomous AI

Project description

governor-sdk

Python SDK for GovernorAI — the execution boundary for autonomous AI.

PyPI version Python versions License: Apache 2.0

Autonomous AI agents can think anywhere — but with GovernorAI they can only act through a policy enforcement gateway. This SDK is how your Python agents talk to it: a @governed decorator, a universal govern() wrapper that auto-detects the framework, and native adapters for the major agent runtimes.


Install

pip install governor-sdk

Optional framework adapters:

pip install "governor-sdk[langchain]"     # LangChain + langchain-core
pip install "governor-sdk[langgraph]"     # LangGraph tool nodes
pip install "governor-sdk[llamaindex]"    # LlamaIndex query engines
pip install "governor-sdk[crewai]"        # CrewAI crews and tasks
pip install "governor-sdk[bedrock]"       # AWS Bedrock + boto3
pip install "governor-sdk[gcp]"           # GCP Vertex AI + google-cloud-aiplatform
pip install "governor-sdk[azure]"         # Azure AI Foundry + azure-ai-agents
pip install "governor-sdk[databricks]"    # Databricks + databricks-agents + mlflow
pip install "governor-sdk[all]"           # all of the above

Quickstart

import os
from governor import GovernorAIClient, GovernorAIDenied

client = GovernorAIClient(
    base_url=os.environ["GOVERNOR_URL"],
    api_key=os.environ["GOVERNOR_API_KEY"],
)

try:
    result = client.execute(
        tool="erp.process_payment",
        args={"amount": 50_000, "vendor": "ACME"},
        agent_id="finance-agent-v1",
    )
    print("Allowed:", result)
except GovernorAIDenied as e:
    print("Denied by policy:", e)

Or wrap any agent in one line:

from governor import govern

governed = govern(your_langchain_executor)
result = governed.invoke({"input": "process payment for ACME"})

govern() auto-detects LangChain, LangGraph, LlamaIndex, and CrewAI agents and applies the right adapter.


Features

  • Sync and async clientsGovernorAIClient and AsyncGovernorAIClient
  • One-line governancegovern(agent) for any supported framework
  • @governed decorator — wrap any function so it routes through a policy check before executing
  • Typed decisions — allow / deny / needs-approval surface as GovernorAIDenied and GovernorAIApprovalRequired exceptions
  • Fail-closed by default — if the gateway is unreachable, calls deny rather than silently proceeding
  • Framework adapters — LangChain, LangGraph, LlamaIndex, CrewAI, AWS Bedrock, Google Cloud ADK / Vertex AI, Azure AI Foundry, Databricks Mosaic AI, AutoGPT
  • Session and step tracking — every tool call carries agent_id and session_id so the gateway can enforce per-session step limits and cost caps
  • OpenTelemetry-friendlytrace_id propagation built in
  • Mypy-strict — type hints throughout

Configuration

The client auto-configures from environment variables when explicit values aren't passed:

Variable Description
GOVERNOR_URL Gateway URL (default: http://localhost:8080)
GOVERNOR_API_KEY API key for authentication
GOVERNOR_ORG_ID Organization ID (sent as X-Org-ID header)
# All three of these are equivalent if env vars are set:
client = GovernorAIClient()
client = GovernorAIClient(base_url=os.environ["GOVERNOR_URL"])
client = GovernorAIClient(base_url="...", api_key="...")

Patterns

1. Decorate any function

from governor import governed_fn

@governed_fn("crm.create_case", agent_id="support-agent")
def create_case(customer_id: str) -> dict:
    return {"case_id": "CASE-001", "customer_id": customer_id}

# Governance check happens before the function body runs.
# Raises GovernorAIDenied if the policy denies.
create_case(customer_id="123")

2. LangChain callback handler

from langchain.agents import AgentExecutor
from governor import GovernorAIClient
from governor.integrations.langchain import GovernorAICallbackHandler

client = GovernorAIClient()
callback = GovernorAICallbackHandler(client, agent_id="research-agent")
executor = AgentExecutor(agent=agent, tools=tools, callbacks=[callback])

3. LangGraph tool node

from governor.helpers import govern_langgraph

tool_node = govern_langgraph([search_web, write_file], agent_id="ops-agent")
graph.add_node("tools", tool_node)

4. CrewAI crew

from governor import GovernorAIClient
from governor.integrations.crewai import GovernorAICrew

crew = GovernorAICrew(
    crew=your_crew,
    governor_client=GovernorAIClient(),
    crew_id="research-crew-v2",
)

5. AWS Bedrock agent

import boto3
from governor import GovernorAIClient
from governor.integrations.bedrock import GovernorAIBedrockAgent

agent = GovernorAIBedrockAgent(
    bedrock_client=boto3.client("bedrock-agent-runtime"),
    governor_client=GovernorAIClient(),
    agent_id="bedrock-agent-v1",
)
response = agent.invoke_agent(
    agentId="...",
    agentAliasId="...",
    sessionId="session-123",
    inputText="Process a payment",
)

See examples/quickstart.py for the full set of integration patterns.


Decision model

Every call returns one of three outcomes:

Outcome Python surface
Allow Returns the gateway response dict containing the tool result
Deny Raises GovernorAIDenied with policy reason
Needs approval Raises GovernorAIApprovalRequired with approval URL — the agent can either block, poll, or hand off to a human
from governor import (
    GovernorAIClient,
    GovernorAIDenied,
    GovernorAIApprovalRequired,
    GovernorAIError,
)

try:
    result = client.execute(tool="...", args={...}, agent_id="...")
except GovernorAIDenied as e:
    log.warning("Denied: %s", e)
except GovernorAIApprovalRequired as e:
    notify_human(e.approval_url)
except GovernorAIError as e:
    # gateway unreachable, auth failed, etc — fail closed
    log.error("Gateway error: %s", e)

CLI

The SDK installs a small CLI for quick checks:

governorai --help
governorai check tool=erp.process_payment agent_id=finance-agent

Development

git clone https://github.com/SentinelLayer/GovernorAI
cd GovernorAI/sdk/python
pip install -e ".[all,dev]"
pytest
ruff check governor
mypy governor

End-to-end testing

The default pytest run only exercises unit tests. To verify the SDK against a real gateway, opt into the integration suite under tests/integration/.

Start a gateway locally:

docker-compose up -d gateway control-plane postgres redis

Create an API key (via the control-plane UI at http://localhost:3000 or by POSTing to /api/v1/auth/apikeys) and seed the smoke-test policy into the smoke namespace:

curl -X POST "$GOVERNOR_URL/api/v1/policies/opa" \
  -H "Authorization: Bearer $GOVERNOR_API_KEY" \
  -H "Content-Type: application/json" \
  --data-binary @- <<EOF
{"namespace": "smoke",
 "rego": $(jq -Rs . < tests/integration/policies/smoke_test.rego)}
EOF

Then run the suite:

export GOVERNOR_INTEGRATION=1
export GOVERNOR_URL=http://localhost:8080
export GOVERNOR_API_KEY=gov_xxx
pytest tests/integration/ -v

Or use the wrapper script, which validates the gateway is up and runs pytest for you:

./examples/smoke_test.sh

The integration suite exercises four invariants:

  • Allowsmoke.echo is permitted; response shape is well-formed.
  • Denysmoke.export_pii is denied; the SDK raises GovernorAIDenied with a non-empty reason.
  • Approval-requiredsmoke.process_payment requires approval; the SDK raises GovernorAIApprovalRequired.
  • Fail-closed — a closed gateway port raises GovernorAIError instead of silently allowing. This is the SDK's most important safety invariant.

Integration tests are auto-skipped when GOVERNOR_INTEGRATION is unset, so the default pytest invocation stays fast and CI-friendly.


Compatibility

  • Python 3.9, 3.10, 3.11, 3.12
  • Works with LangChain ≥1.2, LangGraph ≥1.1, LlamaIndex ≥0.14, CrewAI ≥0.11

Links


License

Apache License 2.0. See LICENSE.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

governor_sdk-0.4.1.tar.gz (138.9 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

governor_sdk-0.4.1-py3-none-any.whl (160.5 kB view details)

Uploaded Python 3

File details

Details for the file governor_sdk-0.4.1.tar.gz.

File metadata

  • Download URL: governor_sdk-0.4.1.tar.gz
  • Upload date:
  • Size: 138.9 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.14

File hashes

Hashes for governor_sdk-0.4.1.tar.gz
Algorithm Hash digest
SHA256 b896f86cdd508dc67623c94cc394889c6835940f21ae7a071e477c5a268e82ea
MD5 41486a00ffafbe0bebf6f0081901ae8f
BLAKE2b-256 23a9a1162bade484ed377e19ce8e2ac2b6dc7d46b1afa9396c9823bde2c73905

See more details on using hashes here.

File details

Details for the file governor_sdk-0.4.1-py3-none-any.whl.

File metadata

  • Download URL: governor_sdk-0.4.1-py3-none-any.whl
  • Upload date:
  • Size: 160.5 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.14

File hashes

Hashes for governor_sdk-0.4.1-py3-none-any.whl
Algorithm Hash digest
SHA256 4a764646f43aa16a035290e69acbc3a80c14e945326591e0a13db789b2efa8ab
MD5 39114c2a7b4e58ac063a4d4b156f61e5
BLAKE2b-256 9bbac3b8a9c807b457061906a89d62afad303344197bf92256bdfbfd1ee8a279

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page