Skip to main content

Python SDK for AI Agent Security Platform

Project description

AgentGuard Python SDK

The first open-source AI agent security SDK with client-side guardrails ๐Ÿ›ก๏ธ

PyPI version Python versions License: MIT

โœจ What's New in v0.2.2

Cost Tracking & Guarded AI Clients - Complete feature parity with TypeScript SDK!

  • ๐Ÿ’ฐ Cost Tracking - Track AI costs across OpenAI, Anthropic, Azure OpenAI
  • ๐Ÿ“Š Budget Management - Set budgets with alerts and automatic enforcement
  • ๐Ÿ›ก๏ธ Guarded Clients - Drop-in replacements with integrated security
  • ๐Ÿ”’ GuardedOpenAI - Secure OpenAI client with guardrails + cost tracking
  • ๐Ÿ”’ GuardedAnthropic - Secure Anthropic client with guardrails + cost tracking
  • ๐Ÿ”’ GuardedAzureOpenAI - Secure Azure OpenAI with deployment mapping
  • โšก 20+ Models - Accurate pricing for GPT-4, Claude 3, and more

โœจ What's New in v0.2.0

Client-Side Guardrails - Run security checks directly in your application without server calls!

  • ๐Ÿ” PII Detection - Detect and protect emails, phones, SSNs, credit cards
  • ๐Ÿ›ก๏ธ Content Moderation - Block harmful content (hate speech, violence, harassment)
  • ๐Ÿšซ Prompt Injection Prevention - Prevent jailbreak and instruction attacks
  • โšก Offline - No server dependency, works anywhere
  • ๐Ÿš€ Fast - Runs in milliseconds

๐Ÿš€ Quick Start

Installation

pip install agentguard-sdk

Guarded AI Clients (New in v0.2.2!)

Drop-in replacements for AI clients with integrated security and cost tracking:

import asyncio
from agentguard import (
    GuardedOpenAI,
    GuardrailEngine,
    PIIDetectionGuardrail,
    CostTracker,
    BudgetManager,
    InMemoryCostStorage,
)

async def main():
    # Set up guardrails
    engine = GuardrailEngine()
    engine.register_guardrail(PIIDetectionGuardrail())
    
    # Set up cost tracking
    storage = InMemoryCostStorage()
    tracker = CostTracker()
    budget_manager = BudgetManager(storage)
    
    # Create daily budget
    budget_manager.create_budget({
        "name": "Daily Budget",
        "limit": 10.0,
        "period": "daily",
        "alert_thresholds": [50, 75, 90],
    })
    
    # Create guarded client
    client = GuardedOpenAI(
        api_key="your-openai-key",
        agent_id="my-agent",
        guardrail_engine=engine,
        cost_tracker=tracker,
        budget_manager=budget_manager,
        cost_storage=storage,
    )
    
    # Make secure, cost-tracked request
    response = await client.chat.completions.create(
        model="gpt-4",
        messages=[{"role": "user", "content": "Hello!"}],
    )
    
    print(f"Response: {response.choices[0].message.content}")
    print(f"Cost: ${response.security.cost_record.actual_cost:.4f}")
    print(f"Guardrails passed: {response.security.guardrail_result.passed}")

asyncio.run(main())

Cost Tracking (New in v0.2.2!)

from agentguard import CostTracker, BudgetManager, InMemoryCostStorage

# Initialize
storage = InMemoryCostStorage()
tracker = CostTracker()
budget_manager = BudgetManager(storage)

# Estimate cost before request
estimate = tracker.estimate_cost(
    model="gpt-4",
    usage={"input_tokens": 1000, "output_tokens": 500},
    provider="openai"
)
print(f"Estimated cost: ${estimate.estimated_cost:.4f}")

# Calculate actual cost after request
cost = tracker.calculate_actual_cost(
    request_id="req-123",
    agent_id="agent-456",
    model="gpt-4",
    usage={"input_tokens": 1050, "output_tokens": 480},
    provider="openai"
)

# Store and query costs
await storage.store(cost)
agent_costs = await storage.get_by_agent_id("agent-456")

Client-Side Guardrails (New!)

from agentguard import GuardrailEngine, PIIDetectionGuardrail, PromptInjectionGuardrail

# Create guardrail engine
engine = GuardrailEngine()

# Register guardrails
engine.register_guardrail(PIIDetectionGuardrail())
engine.register_guardrail(PromptInjectionGuardrail())

# Evaluate user input
result = await engine.execute("Contact me at john@example.com")

if not result.passed:
    print(f'Security check failed: {result.message}')
    print(f'Risk score: {result.risk_score}')

Server-Side Security

from agentguard import AgentGuard

# Initialize the SDK
guard = AgentGuard(
    api_key="your-api-key",
    ssa_url="https://ssa.agentguard.io"
)

# Secure tool execution
result = await guard.execute_tool(
    tool_name="web-search",
    parameters={"query": "AI agent security"},
    context={"session_id": "user-session-123"}
)

๐Ÿ›ก๏ธ Client-Side Guardrails

PIIDetectionGuardrail

Detect and protect personally identifiable information:

from agentguard import PIIDetectionGuardrail

guard = PIIDetectionGuardrail(
    action='redact',  # or 'block', 'mask', 'allow'
    custom_patterns=[
        {'name': 'custom-id', 'pattern': r'ID-\d{6}', 'category': 'identifier'}
    ]
)

result = await guard.evaluate("My email is john@example.com")
# result.passed = False
# result.violations = [{'type': 'email', 'value': 'john@example.com', ...}]

Detects:

  • Email addresses
  • Phone numbers (US, international)
  • Social Security Numbers
  • Credit card numbers
  • Custom patterns

ContentModerationGuardrail

Block harmful content:

from agentguard import ContentModerationGuardrail

guard = ContentModerationGuardrail(
    categories=['hate', 'violence', 'harassment', 'self-harm'],
    threshold=0.7,
    use_openai=True,  # Optional: Use OpenAI Moderation API
    openai_api_key='your-key'
)

result = await guard.evaluate("I hate everyone")
# result.passed = False
# result.risk_score = 85

PromptInjectionGuardrail

Prevent jailbreak attempts:

from agentguard import PromptInjectionGuardrail

guard = PromptInjectionGuardrail(
    sensitivity='high',  # 'low', 'medium', 'high'
    custom_patterns=[
        r'custom attack pattern'
    ]
)

result = await guard.evaluate("Ignore previous instructions and...")
# result.passed = False
# result.risk_score = 90

Detects:

  • Instruction injection
  • Role-playing attacks
  • System prompt leakage
  • DAN jailbreaks
  • Developer mode attempts

GuardrailEngine

Execute multiple guardrails:

from agentguard import (
    GuardrailEngine,
    PIIDetectionGuardrail,
    ContentModerationGuardrail,
    PromptInjectionGuardrail
)

engine = GuardrailEngine(
    mode='parallel',  # or 'sequential'
    timeout=5000,  # ms
    continue_on_error=True
)

# Register guardrails
engine.register_guardrail(PIIDetectionGuardrail())
engine.register_guardrail(ContentModerationGuardrail())
engine.register_guardrail(PromptInjectionGuardrail())

# Execute all guardrails
result = await engine.execute(user_input)

print(f'Passed: {result.passed}')
print(f'Risk Score: {result.risk_score}')
print(f'Results: {result.results}')

๐Ÿ”’ Guarded AI Clients

Drop-in replacements for AI provider clients with integrated security and cost tracking.

GuardedOpenAI

from agentguard import GuardedOpenAI, GuardrailEngine, CostTracker

client = GuardedOpenAI(
    api_key="your-openai-key",
    agent_id="my-agent",
    guardrail_engine=engine,  # Optional
    cost_tracker=tracker,      # Optional
    budget_manager=budget_mgr, # Optional
)

response = await client.chat.completions.create(
    model="gpt-4",
    messages=[{"role": "user", "content": "Hello!"}],
)

# Access security metadata
print(response.security.guardrail_result.passed)
print(response.security.cost_record.actual_cost)
print(response.security.budget_check.allowed)

GuardedAnthropic

from agentguard import GuardedAnthropic

client = GuardedAnthropic(
    api_key="your-anthropic-key",
    agent_id="my-agent",
    guardrail_engine=engine,
    cost_tracker=tracker,
)

response = await client.messages.create(
    model="claude-3-sonnet-20240229",
    max_tokens=1000,
    messages=[{"role": "user", "content": "Hello!"}],
)

GuardedAzureOpenAI

from agentguard import GuardedAzureOpenAI

client = GuardedAzureOpenAI(
    api_key="your-azure-key",
    endpoint="https://your-resource.openai.azure.com",
    api_version="2024-02-15-preview",
    agent_id="my-agent",
    guardrail_engine=engine,
    cost_tracker=tracker,
)

# Automatically maps deployment names to models for pricing
response = await client.chat.completions.create(
    deployment="gpt-4-deployment",
    messages=[{"role": "user", "content": "Hello!"}],
)

๐Ÿ’ฐ Cost Tracking & Budget Management

Cost Tracking

Track AI costs across multiple providers and models:

from agentguard import CostTracker, InMemoryCostStorage

storage = InMemoryCostStorage()
tracker = CostTracker()

# Estimate cost before making request
estimate = tracker.estimate_cost(
    model="gpt-4",
    usage={"input_tokens": 1000, "output_tokens": 500},
    provider="openai"
)

# Calculate actual cost after request
cost = tracker.calculate_actual_cost(
    request_id="req-123",
    agent_id="agent-456",
    model="gpt-4",
    usage={"input_tokens": 1050, "output_tokens": 480},
    provider="openai"
)

# Store and query
await storage.store(cost)
costs = await storage.get_by_agent_id("agent-456")
summary = await storage.get_summary()

Supported Models:

  • OpenAI: GPT-4, GPT-4 Turbo, GPT-3.5 Turbo, GPT-4o, o1, o1-mini
  • Anthropic: Claude 3 Opus, Sonnet, Haiku
  • Azure OpenAI: All OpenAI models with deployment mapping
  • Custom models with custom pricing

Budget Management

Create and enforce budgets with alerts:

from agentguard import BudgetManager

budget_manager = BudgetManager(storage)

# Create budget
budget = budget_manager.create_budget({
    "name": "Daily GPT-4 Budget",
    "limit": 10.0,
    "period": "daily",  # hourly, daily, weekly, monthly, total
    "alert_thresholds": [50, 75, 90, 100],
    "action": "block",  # or "alert"
    "enabled": True,
})

# Check budget before request
check = await budget_manager.check_budget("agent-id", estimated_cost)
if not check.allowed:
    print(f"Budget exceeded: {check.blocked_by.name}")

# Record actual cost
await budget_manager.record_cost(cost_record)

# Get budget status
status = await budget_manager.get_budget_status(budget.id)
print(f"Spent: ${status.current_spending:.2f} / ${status.limit:.2f}")
print(f"Usage: {status.percentage_used:.1f}%")

Budget Features:

  • Multiple budget periods (hourly, daily, weekly, monthly, total)
  • Alert thresholds with severity levels
  • Automatic blocking when budget exceeded
  • Agent-scoped budgets for multi-agent systems
  • Budget status tracking and reporting

๐Ÿ“‹ Features

Guarded AI Clients (v0.2.2)

  • ๐Ÿ”’ GuardedOpenAI - Secure OpenAI client
  • ๐Ÿ”’ GuardedAnthropic - Secure Anthropic client
  • ๐Ÿ”’ GuardedAzureOpenAI - Secure Azure OpenAI client
  • ๐Ÿ›ก๏ธ Integrated Guardrails - Automatic input/output protection
  • ๐Ÿ’ฐ Cost Tracking - Automatic cost calculation and recording
  • ๐Ÿ“Š Budget Enforcement - Pre-request budget checking
  • ๐Ÿ“ˆ Security Metadata - Full visibility into security decisions

Cost Tracking & Budgets (v0.2.2)

  • ๐Ÿ’ฐ Multi-Provider Support - OpenAI, Anthropic, Azure OpenAI
  • ๐Ÿ“Š Accurate Pricing - Real-time cost calculation for 20+ models
  • ๐ŸŽฏ Budget Management - Create and enforce spending limits
  • ๐Ÿšจ Alert System - Configurable thresholds with severity levels
  • ๐Ÿ‘ฅ Agent-Scoped Budgets - Separate budgets per agent
  • ๐Ÿ“ˆ Cost Queries - Query by agent, date range, request ID
  • ๐Ÿ”ง Custom Pricing - Override pricing for custom models
  • ๐Ÿ—บ๏ธ Deployment Mapping - Azure deployment to model mapping

Client-Side (Offline)

  • ๐Ÿ” PII Detection - Protect sensitive data
  • ๐Ÿ›ก๏ธ Content Moderation - Block harmful content
  • ๐Ÿšซ Prompt Injection Prevention - Prevent attacks
  • โšก Fast - Millisecond latency
  • ๐Ÿ”’ Private - No data leaves your server

Server-Side (Platform)

  • ๐Ÿ” Runtime Security Enforcement - Mediate all agent tool/API calls
  • ๐Ÿ“œ Policy-Based Access Control - Define and enforce security policies
  • ๐Ÿ” Comprehensive Audit Trails - Track every agent action
  • โšก High Performance - <100ms latency for security decisions
  • ๐Ÿ”„ Request Transformation - Automatically transform risky requests
  • ๐Ÿ“Š Real-time Monitoring - Track agent behavior and security events
  • ๐ŸŽฏ Type Hints - Full type annotations for better IDE support
  • ๐Ÿ”„ Async Support - Built-in async/await support

๐ŸŽฏ Use Cases

  • Customer Support Bots - Protect customer PII
  • Healthcare AI - HIPAA compliance
  • Financial Services - Prevent data leakage
  • E-commerce - Secure payment information
  • Enterprise AI - Policy enforcement
  • Education Platforms - Content safety

๐Ÿ“š Documentation

๐Ÿค Contributing

We welcome contributions! Please see our Contributing Guide.

๐Ÿ“„ License

MIT License - see LICENSE

๐Ÿ”— Links

๐ŸŒŸ Star Us!

If you find AgentGuard useful, please give us a star on GitHub! โญ


Made with โค๏ธ by the AgentGuard team

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

agentguard_sdk-0.2.2.tar.gz (78.8 kB view details)

Uploaded Source

Built Distribution

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

agentguard_sdk-0.2.2-py3-none-any.whl (42.2 kB view details)

Uploaded Python 3

File details

Details for the file agentguard_sdk-0.2.2.tar.gz.

File metadata

  • Download URL: agentguard_sdk-0.2.2.tar.gz
  • Upload date:
  • Size: 78.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.14.2

File hashes

Hashes for agentguard_sdk-0.2.2.tar.gz
Algorithm Hash digest
SHA256 98eea30393bb87f8ac748ca12ac7332f7d45ad3e28540b12958012466b76b0fb
MD5 3d5c620731c1da06e62765dfc28b00ce
BLAKE2b-256 26f9ad087c2be64263ef40add04bcad7e30f698a819f0c94af5501c818342521

See more details on using hashes here.

File details

Details for the file agentguard_sdk-0.2.2-py3-none-any.whl.

File metadata

  • Download URL: agentguard_sdk-0.2.2-py3-none-any.whl
  • Upload date:
  • Size: 42.2 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.14.2

File hashes

Hashes for agentguard_sdk-0.2.2-py3-none-any.whl
Algorithm Hash digest
SHA256 42933aebc1fa90016446b4547c86c77eb9520dc928cc9f9713bbd1d48619e2e2
MD5 de871212ca9c8f7895f19f0b7d35dc7c
BLAKE2b-256 eb0c760e5ed271691f0e972154bf23f040557c902c6758f138556f1af0c0aa42

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