Skip to main content

AISentinel Python SDK for AI governance and security

Project description

AISentinel Python SDK

PyPI version Python versions License CI

The official Python SDK for AISentinel - zero-latency governance for AI agents.

Features

  • Preflight Checks: Validate agent actions before execution
  • Offline Support: Continue operating when network connectivity is lost
  • Local Caching: Cache decisions and rulepacks for improved performance
  • Multi-tenant: Support for multiple organizations and environments
  • Thread-safe: Designed for concurrent agent deployments
  • Embedded Database: SQLite-based storage for audit logs and metrics

Installation

pip install aisentinel-sdk

Quick Start

from aisentinel import Governor

# Initialize the governor
governor = Governor(
    base_url="https://api.aisentinel.ai",
    token="your-api-token"
)

# Check if an action is allowed
candidate = {
    "tool": "web_search",
    "args": {"query": "python tutorials"}
}

state = {"user_id": "user123", "session_id": "sess456"}

decision = governor.preflight(candidate, state)

if decision["allowed"]:
    # Execute your tool
    result = perform_web_search(candidate["args"]["query"])
    print(f"Search results: {result}")
else:
    print(f"Blocked: {decision['reasons']}")

Advanced Usage

Offline Mode

The SDK automatically handles network interruptions and queues operations for later execution:

# The governor automatically detects connectivity and handles offline scenarios
governor = Governor(token="your-token")

# If offline, decisions are cached or deferred
decision = governor.preflight(candidate, state)

Multi-tenant Support

# Configure multiple tenants
governor = Governor(token="default-token")

# Use tenant-specific tokens
decision = governor.preflight(candidate, state, tenant_id="tenant-123")

Rulepack Management

# Fetch and cache rulepacks
rulepack = governor.fetch_rulepack("security-rules", version="1.2.0")
print(f"Rulepack version: {rulepack['version']}")

Guarded Execution

# Automatically execute allowed actions, return alternatives for blocked ones
def search_web(query):
    return {"results": ["result1", "result2"]}

result = governor.guarded_execute(
    search_web,
    {"tool": "web_search", "args": {"query": "python"}},
    {"user_id": "user123"}
)

if "error" in result:
    print(f"Action blocked: {result['error']}")
else:
    print(f"Results: {result}")

Configuration

Configure the SDK via environment variables, config files, or programmatically:

# Environment variables
export AISENTINEL_BASE_URL="https://api.aisentinel.ai"
export AISENTINEL_TOKEN="your-token"
export AISENTINEL_CACHE_TTL_SECONDS="600"
# Programmatic configuration
from aisentinel import Governor, SDKConfig

config = SDKConfig.load(
    overrides={
        "base_url": "https://api.aisentinel.ai",
        "token": "your-token",
        "offline_mode_enabled": True
    }
)

governor = Governor(config=config)

Config File

Create a aisentinel.json file:

{
  "base_url": "https://api.aisentinel.ai",
  "token": "your-token",
  "cache_ttl_seconds": 300,
  "offline_mode_enabled": true,
  "tenants": {
    "tenant-1": {
      "token": "tenant-specific-token"
    }
  }
}

Integration Examples

LangChain Integration

from langchain.tools import Tool
from aisentinel import Governor

governor = Governor(token="your-token")

def guarded_web_search(query: str) -> str:
    candidate = {"tool": "web_search", "args": {"query": query}}
    state = {"user_id": "agent123"}

    decision = governor.preflight(candidate, state)
    if not decision["allowed"]:
        return f"Search blocked: {decision['reasons'][0]}"

    # Perform actual search
    return perform_search(query)

search_tool = Tool(
    name="WebSearch",
    description="Search the web for information",
    func=guarded_web_search
)

CrewAI Integration

from crewai import Agent, Task
from aisentinel import Governor

governor = Governor(token="your-token")

class GovernedAgent(Agent):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.governor = governor

    def execute_task(self, task: Task):
        # Check if task execution is allowed
        candidate = {
            "tool": "agent_execution",
            "args": {"task": task.description}
        }
        state = {"agent_id": self.id}

        decision = self.governor.preflight(candidate, state)
        if not decision["allowed"]:
            raise ValueError(f"Task execution blocked: {decision['reasons']}")

        return super().execute_task(task)

API Reference

Governor

The main SDK class for AISentinel governance.

Methods

  • preflight(candidate, state, tenant_id=None) - Check if an action is allowed
  • guarded_execute(func, candidate, state, tenant_id=None) - Execute function if allowed
  • fetch_rulepack(rulepack_id, version=None) - Fetch rulepack with caching
  • get_cache_metrics() - Get cache performance metrics

SDKConfig

Configuration management for the SDK.

Methods

  • SDKConfig.load(file_path=None, env_prefix="AISENTINEL_", overrides=None) - Load configuration

Development

# Clone the repository
git clone https://github.com/aisentinel/aisentinel-python-sdk.git
cd aisentinel-python-sdk

# Install development dependencies
pip install -e ".[dev]"

# Run tests
pytest

# Run linting
black aisentinel/
isort aisentinel/
mypy aisentinel/

Contributing

We welcome contributions! Please see our Contributing Guide for details.

License

This project is licensed under the MIT License - see the LICENSE file for details.

Support

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

aisentinel_sdk-0.1.0.tar.gz (16.3 kB view details)

Uploaded Source

Built Distribution

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

aisentinel_sdk-0.1.0-py3-none-any.whl (14.5 kB view details)

Uploaded Python 3

File details

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

File metadata

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

File hashes

Hashes for aisentinel_sdk-0.1.0.tar.gz
Algorithm Hash digest
SHA256 b8e3567342b0e7fd21c03055b4bf616adcf19ba1e571665724f23328c3360c97
MD5 b775845757639c7e3555238582d6eee1
BLAKE2b-256 4d8de43a8ce177de5d92f9207e76f1f5f3088d9d20037fb397f53ccc8c1ac73e

See more details on using hashes here.

File details

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

File metadata

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

File hashes

Hashes for aisentinel_sdk-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 2493a3eb856cd7b50928bf96022de0a7bcdd1e3b10f4ea503f6a1bcf8abc5c9b
MD5 7f6fef4990ddd23906d61c559d6d824b
BLAKE2b-256 08c9c032da9ea12501001c023156eb6ddbd51a1dccb600e2870ad8e5b3d6452f

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