Skip to main content

Python SDK for Agent Control - protect your AI agents with controls

Project description

Agent Protect - Python SDK

Unified Python SDK for Agent Protect - providing agent protection, monitoring, and rule enforcement in one clean package.

Installation

pip install agent-control

Quick Start

Simple Initialization

import agent_protect

# Initialize at the base of your agent
agent_protect.init(
    agent_name="My Customer Service Bot",
    agent_id="csbot-prod-v1"
)

# Use the protect decorator
from agent_protect import protect

@protect('input-validation', input='message')
async def handle_message(message: str):
    return f"Processed: {message}"

With Full Metadata

import agent_protect

agent_protect.init(
    agent_name="Customer Service Bot",
    agent_id="csbot-prod-v1",
    agent_description="Handles customer inquiries and support",
    agent_version="2.1.0",
    server_url="https://protect.example.com",
    # Add any custom metadata
    team="customer-success",
    environment="production"
)

Features

1. Simple Initialization

One line to set up your agent with full protection:

agent_protect.init(agent_name="...", agent_id="...")

This automatically:

  • Creates an Agent instance with your metadata
  • Discovers and loads rules.yaml
  • Registers with the Agent Protect server
  • Enables the @protect decorator

2. Decorator-Based Protection

Protect any function with YAML-defined rules:

@protect('input-check', input='user_text')
async def process(user_text: str):
    return user_text

3. HTTP Client

Use the client directly for custom workflows:

async with agent_protect.AgentProtectClient() as client:
    # Check content safety
    result = await client.check_protection(
        content="User input here",
        context={"user_id": "123"}
    )
    
    if result.is_safe:
        print("Safe to process!")
    
    # Check server health
    health = await client.health_check()
    print(f"Server status: {health['status']}")

4. Agent Metadata

Access your agent information:

agent = agent_protect.get_agent()
print(f"Agent: {agent.agent_name}")
print(f"ID: {agent.agent_id}")
print(f"Version: {agent.agent_version}")

Complete Example

import asyncio
import agent_protect
from agent_protect import protect

# Initialize
agent_protect.init(
    agent_name="Customer Support Bot",
    agent_id="support-bot-v1",
    agent_version="1.0.0"
)

# Protect input
@protect('input-validation', input='message', context='ctx')
async def handle_message(message: str, ctx: dict):
    # Input is automatically checked against rules.yaml
    return f"Processed: {message}"

# Protect output
@protect('output-filter', output='response')
async def generate_response(query: str) -> str:
    # Output is automatically filtered (e.g., PII redaction)
    return f"Response with SSN: 123-45-6789"

# Use the functions
async def main():
    try:
        # Safe input
        result1 = await handle_message(
            "Hello, I need help",
            {"user_id": "123"}
        )
        print(result1)
        
        # Output with PII (will be redacted)
        result2 = await generate_response("Get user info")
        print(result2)  # SSN will be [REDACTED]
        
    except Exception as e:
        print(f"Blocked: {e}")

asyncio.run(main())

API Reference

Initialization

agent_protect.init()

def init(
    agent_name: str,
    agent_id: str,
    agent_description: Optional[str] = None,
    agent_version: Optional[str] = None,
    server_url: Optional[str] = None,
    rules_file: Optional[str] = None,
    **kwargs
) -> Agent:

Initialize Agent Protect with your agent's information.

Parameters:

  • agent_name: Human-readable name
  • agent_id: Unique identifier (user-defined)
  • agent_description: Optional description
  • agent_version: Optional version string
  • server_url: Optional server URL (defaults to AGENT_PROTECT_URL env var)
  • rules_file: Optional rules file path (auto-discovered if not provided)
  • **kwargs: Additional metadata

Returns: Agent instance

Decorator

@protect()

def protect(step_name: str, **data_sources):

Decorator to protect a function with rules from rules.yaml.

Parameters:

  • step_name: Step name matching rules.yaml
  • **data_sources: Mapping of data types to parameter names

Example:

@protect('input-check', input='text', context='ctx')
async def my_func(text: str, ctx: dict):
    return text

Client

AgentProtectClient

class AgentProtectClient:
    def __init__(
        self,
        base_url: str = "http://localhost:8000",
        timeout: float = 30.0
    ):

Async HTTP client for Agent Protect server.

Methods:

  • health_check() - Check server health
  • check_protection(content, context=None) - Check content safety
  • register_agent(agent) - Register an agent

Example:

async with AgentProtectClient(base_url="http://server") as client:
    result = await client.check_protection("content")

Models

If agent-control-models is installed, these classes are available:

  • Agent - Agent metadata
  • ProtectionRequest - Protection request model
  • ProtectionResult - Protection result with helper methods
  • HealthResponse - Health check response

Configuration

Environment Variables

  • AGENT_PROTECT_URL - Server URL (default: http://localhost:8000)
  • AGENT_ID - Agent identifier (optional)

Rules File

Create a rules.yaml in your project:

input-validation:
  description: "Validate user inputs"
  rules:
    - match:
        string: ["forbidden", "blocked"]
      action: deny
      data: input
  default_action: allow

See the Rules Guide for complete documentation.

Package Name

This package is named agent-control (with hyphen in PyPI) but imported as agent_protect (with underscore in Python):

# Install (uses hyphen)
pip install agent-control

# Import (uses underscore)
import agent_protect

Or use the simpler decorator approach:

import agent_protect

agent_protect.init(agent_name="...", agent_id="...")

from agent_protect import protect

@protect('input-check', input='message')
async def handle(message: str):
    return message

Development

# Install in development mode
cd sdks/python
uv sync

# Run tests
uv run pytest

# Lint
uv run ruff check .

Examples

See the examples directory for complete examples:

  • example_with_agent_protect.py - Using agent_protect.init()
  • simple_example.py - Minimal example
  • agent_with_rules.py - LangGraph integration

Documentation

License

Apache License 2.0 - see LICENSE file for details.

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

agent_control_sdk-2.0.0.tar.gz (86.9 kB view details)

Uploaded Source

Built Distribution

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

agent_control_sdk-2.0.0-py3-none-any.whl (72.1 kB view details)

Uploaded Python 3

File details

Details for the file agent_control_sdk-2.0.0.tar.gz.

File metadata

  • Download URL: agent_control_sdk-2.0.0.tar.gz
  • Upload date:
  • Size: 86.9 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for agent_control_sdk-2.0.0.tar.gz
Algorithm Hash digest
SHA256 c88bb6856ffb1123d391e8fc5e023f7e80874affad3bf24baa82e006ac83dd35
MD5 22cad91dee41c496ee1c16770f82109b
BLAKE2b-256 a5bdeedfca69abbb27d363208022a6e4df9c53707e9034ed085df14b8906b5ba

See more details on using hashes here.

File details

Details for the file agent_control_sdk-2.0.0-py3-none-any.whl.

File metadata

File hashes

Hashes for agent_control_sdk-2.0.0-py3-none-any.whl
Algorithm Hash digest
SHA256 c78da15fef72fb35d804ac2c5297a8317a17543499e6067617206a4c436c1cfe
MD5 bc96abd3bd3b36ba53e2bb78d439cf6e
BLAKE2b-256 df19a2abf1ab4f5e47027174f9edfa278aba4d8c9940693edd4a9051dff29378

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