Skip to main content

CortexHub Python SDK - Policy-as-Code for AI Agents

Project description

CortexHub Python SDK

Runtime Governance for AI Agents - Policy enforcement, PII/secrets detection, complete audit trails with OpenTelemetry.

Installation

# Core SDK
pip install cortexhub

# With framework support (choose one or more)
pip install cortexhub[langchain]      # LangChain/LangGraph
pip install cortexhub[crewai]         # CrewAI
pip install cortexhub[openai-agents]  # OpenAI Agents SDK
pip install cortexhub[llamaindex]     # LlamaIndex
pip install cortexhub[litellm]        # LiteLLM

# All frameworks (for development)
pip install cortexhub[all]

Quick Start

from cortexhub import init, Framework

# Initialize CortexHub FIRST, before importing your framework
cortex = init(
    agent_id="customer_support_agent",
    framework=Framework.LANGCHAIN,  # or CREWAI, OPENAI_AGENTS, etc.
)

# Now import and use your framework
from langchain_core.tools import tool

@tool
def process_refund(customer_id: str, amount: float) -> dict:
    """Process a customer refund."""
    return {"status": "processed", "amount": amount}

# All tool calls are now governed!

Supported Frameworks

Framework Enum Value Install
LangChain Framework.LANGCHAIN pip install cortexhub[langchain]
LangGraph Framework.LANGCHAIN pip install cortexhub[langchain]
CrewAI Framework.CREWAI pip install cortexhub[crewai]
OpenAI Agents Framework.OPENAI_AGENTS pip install cortexhub[openai-agents]
LlamaIndex Framework.LLAMAINDEX pip install cortexhub[llamaindex]
LiteLLM Framework.LITELLM pip install cortexhub[litellm]

Configuration

# Required: API key for telemetry
export CORTEXHUB_API_KEY=ch_live_...

# Optional: Backend URL (defaults to production)
export CORTEXHUB_API_URL=https://api.cortexhub.ai

# Optional: OpenAI key for LLM-based examples
export OPENAI_API_KEY=sk-...

Features

  • Policy Enforcement - Cedar-based policies, local evaluation
  • PII Detection - Presidio-powered, 50+ entity types, configurable
  • Secrets Detection - detect-secrets integration, 30+ secret types
  • Configurable Guardrails - Select specific PII/secret types to redact
  • Custom Patterns - Add company-specific regex patterns
  • OpenTelemetry - Industry-standard observability
  • Framework Adapters - Automatic interception for all major frameworks
  • Privacy Mode - Metadata-only by default, safe for production

Privacy Modes

# Production (default) - only metadata sent
cortex = init(agent_id="...", framework=..., privacy=True)
# Sends: tool names, arg schemas, PII types detected
# Never: raw values, prompts, responses

# Development - full data for testing policies  
cortex = init(agent_id="...", framework=..., privacy=False)
# Also sends: raw args, results, prompts (for policy testing)

Policy Enforcement

Policies are created in the CortexHub dashboard from detected risks. The SDK automatically fetches and enforces them:

from cortexhub.errors import PolicyViolationError, ApprovalRequiredError

# Policies are fetched automatically during init()
# If policies exist, enforcement mode is enabled

try:
    agent.run("Process a $10,000 refund")
except PolicyViolationError as e:
    print(f"Blocked by policy: {e.policy_name}")
    print(f"Reason: {e.reasoning}")
except ApprovalRequiredError as e:
    print(f"\n⏸️  APPROVAL REQUIRED")
    print(f"   Approval ID: {e.approval_id}")
    print(f"   Tool: {e.tool_name}")
    print(f"   Reason: {e.reason}")
    print(f"   Expires: {e.expires_at}")
    print(f"\n   Decision endpoint: {e.decision_endpoint}")
    print(f"   Configure a webhook to receive approval.decisioned event")

Guardrail Configuration

Guardrails detect PII and secrets in LLM prompts. Configure in the dashboard:

  1. Select types to redact: Choose specific PII types (email, phone, etc.)
  2. Add custom patterns: Regex for company-specific data (employee IDs, etc.)
  3. Choose action: Redact, block, or monitor only

The SDK applies your configuration automatically:

# With guardrail policy active:
# Input prompt: "Contact john@email.com about employee EMP-123456"
# After redaction: "Contact [REDACTED-EMAIL_ADDRESS] about employee [REDACTED-CUSTOM_EMPLOYEE_ID]"
# Only configured types are redacted

Examples

cd python/examples

# LangChain customer support
python langchain_example.py

# LangGraph fraud investigation  
python langgraph_example.py

# CrewAI financial operations
python crewai_example.py

# OpenAI Agents research assistant
python openai_agents_example.py

# LiteLLM multi-provider
python litellm_example.py

Important: Initialization Order

Always initialize CortexHub FIRST, before importing your framework:

# ✅ CORRECT
from cortexhub import init, Framework
cortex = init(agent_id="my_agent", framework=Framework.LANGCHAIN)

from langchain_core.tools import tool  # Import AFTER init

# ❌ WRONG
from langchain_core.tools import tool  # Framework imported first
from cortexhub import init, Framework
cortex = init(...)  # Too late!

This ensures:

  1. CortexHub sets up OpenTelemetry before frameworks that also use it
  2. Framework decorators/classes are properly wrapped

Architecture

Agent Decides → [CortexHub] → Agent Executes
                    │
              ┌─────┴─────┐
              │           │
         Policy      Guardrails
         Engine      (PII/Secrets)
              │           │
              └─────┬─────┘
                    │
              OpenTelemetry
               (to backend)

Development

cd python

# Install with all frameworks
uv sync --all-extras

# Run tests
uv run pytest

# Lint
uv run ruff check .

Links

License

MIT

Project details


Release history Release notifications | RSS feed

Download files

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

Source Distribution

cortexhub-0.1.0.tar.gz (57.5 kB view details)

Uploaded Source

Built Distribution

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

cortexhub-0.1.0-py3-none-any.whl (72.4 kB view details)

Uploaded Python 3

File details

Details for the file cortexhub-0.1.0.tar.gz.

File metadata

  • Download URL: cortexhub-0.1.0.tar.gz
  • Upload date:
  • Size: 57.5 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.9.6

File hashes

Hashes for cortexhub-0.1.0.tar.gz
Algorithm Hash digest
SHA256 d30ba16f4b683e0d578d8f66f049739dec34525c34bcfdbefa55968444c1cc12
MD5 462d90ed5f6e67612addcbf0fbcf0d8a
BLAKE2b-256 77c2d985e86cf9c2ed0713fbd106a1b058335365833b0581bf499b7631912279

See more details on using hashes here.

File details

Details for the file cortexhub-0.1.0-py3-none-any.whl.

File metadata

  • Download URL: cortexhub-0.1.0-py3-none-any.whl
  • Upload date:
  • Size: 72.4 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.9.6

File hashes

Hashes for cortexhub-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 5afe7371c7c885364b7c45ace198fbbd14bc7c3ba972f98cdddf41deaaca8394
MD5 b0fb5a42a0a3e6dd3746ff2a226a62de
BLAKE2b-256 cc91736b82c1cd711abc56240ccfd71bcee3eeaf7f24063addcc093d16c7df4c

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