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_id: str, **data_sources):

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

Parameters:

  • step_id: Step identifier 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:
  step_id: "input-check"
  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-1.1.2.tar.gz (68.0 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-1.1.2-py3-none-any.whl (55.9 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: agent_control_sdk-1.1.2.tar.gz
  • Upload date:
  • Size: 68.0 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-1.1.2.tar.gz
Algorithm Hash digest
SHA256 097f24c94e0d93b5531a43c2b318117b91cb4e46928422c82d2eab7a69d8958a
MD5 89223737f772cd851dee4d8b77ad19ab
BLAKE2b-256 ab39ebcc8a43b519e0c0b52704541ec905b498da1be721fcd8fb018364343ef0

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for agent_control_sdk-1.1.2-py3-none-any.whl
Algorithm Hash digest
SHA256 36d8f2bc0250d7a099f7111b2b076ee8efd367bb8511c4a589851d8624d3701b
MD5 fbe6b5fe43942bd33d7b33d5dce17e69
BLAKE2b-256 996c57e4a2109506dd131dc8a64699007ecbc49adee71e3392cc0807dfc8dae1

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