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.3.tar.gz (139.3 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.3-py3-none-any.whl (160.9 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: governor_sdk-0.4.3.tar.gz
  • Upload date:
  • Size: 139.3 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.3.tar.gz
Algorithm Hash digest
SHA256 53405e599e387d57c8a0b75699c1713ea7093dcdb0173c747f2f0c0ee74bd967
MD5 05e22cd23192d021fb1f5cacf6103598
BLAKE2b-256 b435dbf1e87ede377f361fc95ae4432775afc3187c28a48a7a62f867363be46b

See more details on using hashes here.

File details

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

File metadata

  • Download URL: governor_sdk-0.4.3-py3-none-any.whl
  • Upload date:
  • Size: 160.9 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.3-py3-none-any.whl
Algorithm Hash digest
SHA256 e33b82f0879a565c0cc3595308f3b25282a17d5ff5c3bf753aa91f0a1af29683
MD5 457437da1d32a3258d73d7837e6cae81
BLAKE2b-256 c5175fceb65b48fc9cc4b769ee1877fdf2ff7339ef56b7f198f67ac8fe6de65a

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