# Doopal AI Governance Python SDK
The Doopal Python SDK provides a simple and powerful way to integrate AI governance, redaction, and policy enforcement into your Python applications. Route your LLM API calls through Doopal to ensure compliance, security, and cost control.
## Installation
```bash
pip install doopal
```
## Quick Start
### Async Usage (Recommended)
```python
import asyncio
from doopal_client import DoopalClient
async def main():
async with DoopalClient(api_key="your-api-key") as client:
response = await client.chat_completion(
provider="openai",
model="gpt-3.5-turbo",
messages=[
{"role": "user", "content": "Hello, how are you?"}
]
)
print(response.response)
asyncio.run(main())
```
### Synchronous Usage
```python
from doopal_client import DoopalSyncClient
client = DoopalSyncClient(api_key="your-api-key")
response = client.chat_completion(
provider="openai",
model="gpt-3.5-turbo",
messages=[
{"role": "user", "content": "Hello, how are you?"}
]
)
print(response.response)
client.close()
```
## Features
### Core AI Gateway
- **Multi-Provider Support**: Works with OpenAI, Anthropic, Azure OpenAI, Cohere, and more
- **Governance & Compliance**: Automatic policy enforcement and compliance checking
- **Content Redaction**: Sensitive data detection and redaction
- **Cost Control**: Budget management and usage tracking
- **Streaming Support**: Real-time streaming responses
- **Error Handling**: Comprehensive error handling with specific exception types
- **Async/Sync**: Both asynchronous and synchronous interfaces
### Enterprise Features (v1.1.0+)
- **Organization Management**: Multi-tenant organization administration
- **Role-Based Access Control (RBAC)**: User roles and permissions management
- **Single Sign-On (SSO)**: SAML/OIDC enterprise authentication
- **Advanced Analytics**: Compliance, threat detection, performance, and cost analytics
- **Audit Logging**: Comprehensive audit trails and compliance reporting
- **Security Monitoring**: Real-time threat detection and alerting
- **Policy Management**: Advanced policy creation, testing, and management
- **Provider Management**: AI provider configuration and monitoring
- **Comprehensive Health Checks**: Kubernetes-ready health, readiness, and liveness probes
- **Data Validation**: Structured data and PII validation capabilities
## Configuration
### Environment Variables
```bash
export DOOPAL_API_KEY="your-api-key"
export DOOPAL_BASE_URL="https://api.doopal.com" # Optional
export DOOPAL_ORG_ID="your-org-id" # Optional for multi-tenant setups
```
### Client Configuration
```python
client = DoopalClient(
api_key="your-api-key",
base_url="https://api.doopal.com", # Default
timeout=30, # Request timeout in seconds
max_retries=3, # Maximum retry attempts
organization_id="your-org-id" # Optional
)
```
## API Reference
### Chat Completions
```python
response = await client.chat_completion(
provider="openai",
model="gpt-3.5-turbo",
messages=[
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "What is the capital of France?"}
],
temperature=0.7,
max_tokens=100,
stream=False
)
```
### Streaming Chat Completions
```python
async for chunk in await client.chat_completion(
provider="openai",
model="gpt-3.5-turbo",
messages=[{"role": "user", "content": "Tell me a story"}],
stream=True
):
print(chunk, end="")
```
### Text Completions
```python
response = await client.completion(
provider="openai",
model="gpt-3.5-turbo-instruct",
prompt="The capital of France is",
max_tokens=50
)
```
### Embeddings
```python
response = await client.embeddings(
provider="openai",
model="text-embedding-ada-002",
input_text="Hello world"
)
```
### Usage Statistics
```python
stats = await client.get_usage_stats()
print(f"Total requests: {stats['total_requests']}")
print(f"Total cost: ${stats['total_cost']}")
```
### Health Check
```python
# Basic health check
health = await client.health_check()
print(f"Status: {health['status']}")
# Detailed health status (includes database, redis, etc.)
detailed_health = await client.get_detailed_health()
print(f"Database: {detailed_health['database']['status']}")
print(f"Redis: {detailed_health['redis']['status']}")
# Kubernetes readiness probe
readiness = await client.get_readiness_status()
print(f"Ready: {readiness['status']}")
# Kubernetes liveness probe
liveness = await client.get_liveness_status()
print(f"Live: {liveness['status']}")
```
### Enterprise Organization Management
```python
# Get organization information
org = await client.get_organization()
print(f"Organization: {org['name']}")
# Update organization settings
updated_org = await client.update_organization({
'name': 'Acme Corp',
'settings': {
'enableAdvancedAnalytics': True,
'complianceFrameworks': ['gdpr', 'hipaa']
}
})
# Get user roles and permissions
roles = await client.get_user_roles()
print(f"User role: {roles['role']}")
print(f"Permissions: {roles['permissions']}")
# Get organization members
members = await client.get_organization_members()
print(f"{len(members)} members in organization")
# Invite new user
invitation = await client.invite_user({
'email': 'user@company.com',
'role': 'manager'
})
# Configure SSO
sso_config = await client.configure_sso({
'provider': 'okta',
'domain': 'company.okta.com',
'clientId': 'your-client-id',
'clientSecret': 'your-client-secret'
})
```
### Advanced Analytics
```python
# Compliance analytics
compliance_data = await client.get_compliance_analytics({
'framework': 'gdpr',
'startDate': '2024-01-01',
'endDate': '2024-12-31'
})
# Threat detection analytics
threats = await client.get_threat_analytics({
'severity': 'high',
'timeframe': '24h'
})
# Performance analytics
performance = await client.get_performance_analytics({
'metric': 'response_time',
'aggregation': 'avg'
})
# Cost analytics
costs = await client.get_cost_analytics({
'provider': 'openai',
'groupBy': 'model'
})
```
### Compliance Reporting
```python
# Get compliance status
status = await client.get_compliance_status('gdpr')
print(f"GDPR compliance: {status['score']}%")
# Generate compliance report
report = await client.generate_compliance_report({
'framework': 'hipaa',
'format': 'pdf',
'period': 'quarterly'
})
# Get compliance violations
violations = await client.get_compliance_violations({
'severity': 'high',
'status': 'open'
})
```
### Policy Management
```python
# Get all policies
policies = await client.get_policies()
# Create new policy
new_policy = await client.create_policy({
'name': 'Content Safety Policy',
'description': 'Prevent harmful content generation',
'policyType': 'rego',
'policyContent': 'package content.safety\n\ndefault allow = false...',
'enabled': True,
'priority': 1
})
# Update policy
updated_policy = await client.update_policy('policy-id', {
'enabled': False,
'priority': 2
})
# Delete policy
deleted = await client.delete_policy('policy-id')
# Test policy
test_result = await client.test_policy({
'policyId': 'policy-id',
'testInput': {
'content': 'Test content',
'user': {'role': 'user'}
}
})
```
### Provider Management
```python
# Get available providers
providers = await client.get_providers()
# Add new provider
new_provider = await client.add_provider({
'name': 'OpenAI Production',
'providerType': 'openai',
'apiKey': 'sk-...',
'modelConfigs': {
'gpt-4': {
'maxTokens': 4000,
'temperature': 0.7,
'costPerToken': 0.00003
}
},
'rateLimits': {
'requestsPerMinute': 3500,
'tokensPerMinute': 90000
}
})
# Update provider
updated_provider = await client.update_provider('provider-id', {
'rateLimits': {
'requestsPerMinute': 5000
}
})
```
### Security & Monitoring
```python
# Get security threats
threats = await client.get_security_threats({
'severity': 'high',
'timeframe': '1h'
})
# Get observability metrics
metrics = await client.get_observability_metrics({
'metric': 'request_rate',
'timeframe': '5m'
})
# Get system alerts
alerts = await client.get_alerts({
'status': 'active',
'severity': 'critical'
})
```
### Integrations
```python
# Get available integrations
integrations = await client.get_integrations()
# Configure integration
configured_integration = await client.configure_integration({
'type': 'slack',
'config': {
'webhookUrl': 'https://hooks.slack.com/...',
'channel': '#ai-governance'
}
})
```
### Data Validation
```python
# Validate structured data
validation = await client.validate_structured_data({
'schema': {
'type': 'object',
'properties': {
'name': {'type': 'string'},
'age': {'type': 'number'}
}
},
'data': {'name': 'John', 'age': 30}
})
# Validate PII detection
pii_validation = await client.validate_pii({
'content': 'My email is john@example.com'
})
print(f"PII detected: {pii_validation['piiDetected']}")
```
### Audit Logging
```python
# Get audit logs
audit_logs = await client.get_audit_logs({
'action': 'policy_violation',
'startDate': '2024-01-01',
'endDate': '2024-01-31',
'userId': 'user123'
})
print(f"Found {len(audit_logs)} audit entries")
```
## Error Handling
The SDK provides specific exception types for different error scenarios:
```python
from doopal_client import DoopalError, PolicyViolationError, RedactionError
try:
response = await client.chat_completion(
provider="openai",
model="gpt-3.5-turbo",
messages=[{"role": "user", "content": "Sensitive content here"}]
)
except PolicyViolationError as e:
print(f"Policy violation: {e}")
except RedactionError as e:
print(f"Content blocked: {e}")
except DoopalError as e:
print(f"API error: {e}")
```
## Advanced Usage
### Custom Metadata
```python
response = await client.chat_completion(
provider="openai",
model="gpt-3.5-turbo",
messages=[{"role": "user", "content": "Hello"}],
metadata={
"user_id": "user123",
"session_id": "session456",
"department": "engineering"
}
)
```
### Multiple Providers
```python
# OpenAI
openai_response = await client.chat_completion(
provider="openai",
model="gpt-3.5-turbo",
messages=[{"role": "user", "content": "Hello"}]
)
# Anthropic
anthropic_response = await client.chat_completion(
provider="anthropic",
model="claude-3-sonnet-20240229",
messages=[{"role": "user", "content": "Hello"}]
)
# Azure OpenAI
azure_response = await client.chat_completion(
provider="azure_openai",
model="gpt-35-turbo",
messages=[{"role": "user", "content": "Hello"}]
)
```
## Response Format
All responses include governance and redaction information:
```python
{
"response": "The generated text response",
"provider": "openai",
"model": "gpt-3.5-turbo",
"usage": {
"prompt_tokens": 10,
"completion_tokens": 20,
"total_tokens": 30
},
"metadata": {
"request_id": "req_123",
"processing_time": 1.5,
"policies_applied": ["content_filter", "rate_limit"],
"cost": 0.0001
},
"redacted_content": [
"email@example.com was redacted",
"SSN 123-45-6789 was blocked"
]
}
```
## Enterprise Integration Examples
### Multi-Tenant Setup
```python
# Initialize client with organization context
client = DoopalClient(
api_key='your-api-key',
base_url='https://api.your-domain.com',
organization_id='org-123' # Important for multi-tenant deployments
)
# All subsequent calls will be scoped to this organization
org_data = await client.get_organization()
compliance = await client.get_compliance_status('gdpr')
```
### Production Monitoring
```python
import asyncio
from datetime import datetime
# Health monitoring for production deployments
health_checks = {
'basic': await client.health_check(),
'detailed': await client.get_detailed_health(),
'ready': await client.get_readiness_status(),
'live': await client.get_liveness_status()
}
print('Production health status:', health_checks)
# Real-time threat monitoring
async def monitor_threats():
while True:
threats = await client.get_security_threats({'timeframe': '5m'})
if threats:
print(f"{len(threats)} security threats detected!")
await asyncio.sleep(30) # Check every 30 seconds
# Run monitoring in background
asyncio.create_task(monitor_threats())
```
### Compliance Automation
```python
# Automated compliance reporting
compliance_report = await client.generate_compliance_report({
'framework': 'sox',
'format': 'json',
'period': 'monthly',
'includeViolations': True,
'includeRemediation': True
})
# Send to compliance team
print(f"Generated SOX report: {compliance_report['reportId']}")
```
### Enterprise Policy Management
```python
# Bulk policy management for enterprise deployments
policies_config = [
{
'name': 'GDPR Data Protection',
'description': 'Ensure GDPR compliance for EU data',
'policyType': 'rego',
'policyContent': open('policies/gdpr.rego').read(),
'enabled': True,
'priority': 1
},
{
'name': 'HIPAA Healthcare Data',
'description': 'Protect healthcare information',
'policyType': 'rego',
'policyContent': open('policies/hipaa.rego').read(),
'enabled': True,
'priority': 2
}
]
# Deploy policies
for policy_config in policies_config:
policy = await client.create_policy(policy_config)
print(f"Created policy: {policy['id']}")
# Test policy
test_result = await client.test_policy({
'policyId': policy['id'],
'testInput': {'content': 'Test healthcare data: Patient ID 12345'}
})
print(f"Policy test result: {test_result['allowed']}")
```
## Development
### Running Tests
```bash
pip install -e ".[dev]"
pytest
```
### Code Formatting
```bash
black .
isort .
```
### Type Checking
```bash
mypy .
```
## Changelog
### v1.1.0 (Latest)
- ✨ Added enterprise organization management
- ✨ Implemented RBAC and user management
- ✨ Added advanced compliance analytics
- ✨ Comprehensive health checks for Kubernetes
- ✨ Security threat detection and monitoring
- ✨ Policy management and testing capabilities
- ✨ Provider management and configuration
- ✨ Audit logging and compliance reporting
- ✨ Integration management
- ✨ Structured data and PII validation
- 🔧 Updated to support all B2B enterprise features
- 🔧 Enhanced async/sync method coverage
### v1.0.0
- 🎉 Initial release
- ✨ Basic chat completions and embeddings
- ✨ Multi-provider support
- ✨ Content redaction and policy enforcement
- ✨ Streaming support
- ✨ OpenAI-compatible endpoints
- ✨ Async/sync interfaces
## Support
- Documentation: https://docs.doopal.com
- GitHub Issues: https://github.com/doopal-ai/doopal/issues
- Email: info@doopal.com
- Enterprise Support: info@doopal.com
- Customer Success: info@doopal.com
## License
MIT License - see LICENSE file for details.
Raw data
{
"_id": null,
"home_page": "https://github.com/doopal-ai/doopal-governance",
"name": "doopal",
"maintainer": null,
"docs_url": null,
"requires_python": ">=3.8",
"maintainer_email": null,
"keywords": "ai governance llm security redaction policy enterprise compliance analytics monitoring rbac sso audit",
"author": "Doopal Team",
"author_email": "info@doopal.com",
"download_url": "https://files.pythonhosted.org/packages/de/f3/a41cd53c01500f199f8a5a45e4c3da075e9de4ee010eb099970cb847787b/doopal-1.1.2.tar.gz",
"platform": null,
"description": "# Doopal AI Governance Python SDK\n\nThe Doopal Python SDK provides a simple and powerful way to integrate AI governance, redaction, and policy enforcement into your Python applications. Route your LLM API calls through Doopal to ensure compliance, security, and cost control.\n\n## Installation\n\n```bash\npip install doopal\n```\n\n## Quick Start\n\n### Async Usage (Recommended)\n\n```python\nimport asyncio\nfrom doopal_client import DoopalClient\n\nasync def main():\n async with DoopalClient(api_key=\"your-api-key\") as client:\n response = await client.chat_completion(\n provider=\"openai\",\n model=\"gpt-3.5-turbo\",\n messages=[\n {\"role\": \"user\", \"content\": \"Hello, how are you?\"}\n ]\n )\n print(response.response)\n\nasyncio.run(main())\n```\n\n### Synchronous Usage\n\n```python\nfrom doopal_client import DoopalSyncClient\n\nclient = DoopalSyncClient(api_key=\"your-api-key\")\n\nresponse = client.chat_completion(\n provider=\"openai\",\n model=\"gpt-3.5-turbo\",\n messages=[\n {\"role\": \"user\", \"content\": \"Hello, how are you?\"}\n ]\n)\n\nprint(response.response)\nclient.close()\n```\n\n## Features\n\n### Core AI Gateway\n- **Multi-Provider Support**: Works with OpenAI, Anthropic, Azure OpenAI, Cohere, and more\n- **Governance & Compliance**: Automatic policy enforcement and compliance checking\n- **Content Redaction**: Sensitive data detection and redaction\n- **Cost Control**: Budget management and usage tracking\n- **Streaming Support**: Real-time streaming responses\n- **Error Handling**: Comprehensive error handling with specific exception types\n- **Async/Sync**: Both asynchronous and synchronous interfaces\n\n### Enterprise Features (v1.1.0+)\n- **Organization Management**: Multi-tenant organization administration\n- **Role-Based Access Control (RBAC)**: User roles and permissions management\n- **Single Sign-On (SSO)**: SAML/OIDC enterprise authentication\n- **Advanced Analytics**: Compliance, threat detection, performance, and cost analytics\n- **Audit Logging**: Comprehensive audit trails and compliance reporting\n- **Security Monitoring**: Real-time threat detection and alerting\n- **Policy Management**: Advanced policy creation, testing, and management\n- **Provider Management**: AI provider configuration and monitoring\n- **Comprehensive Health Checks**: Kubernetes-ready health, readiness, and liveness probes\n- **Data Validation**: Structured data and PII validation capabilities\n\n## Configuration\n\n### Environment Variables\n\n```bash\nexport DOOPAL_API_KEY=\"your-api-key\"\nexport DOOPAL_BASE_URL=\"https://api.doopal.com\" # Optional\nexport DOOPAL_ORG_ID=\"your-org-id\" # Optional for multi-tenant setups\n```\n\n### Client Configuration\n\n```python\nclient = DoopalClient(\n api_key=\"your-api-key\",\n base_url=\"https://api.doopal.com\", # Default\n timeout=30, # Request timeout in seconds\n max_retries=3, # Maximum retry attempts\n organization_id=\"your-org-id\" # Optional\n)\n```\n\n## API Reference\n\n### Chat Completions\n\n```python\nresponse = await client.chat_completion(\n provider=\"openai\",\n model=\"gpt-3.5-turbo\",\n messages=[\n {\"role\": \"system\", \"content\": \"You are a helpful assistant.\"},\n {\"role\": \"user\", \"content\": \"What is the capital of France?\"}\n ],\n temperature=0.7,\n max_tokens=100,\n stream=False\n)\n```\n\n### Streaming Chat Completions\n\n```python\nasync for chunk in await client.chat_completion(\n provider=\"openai\",\n model=\"gpt-3.5-turbo\",\n messages=[{\"role\": \"user\", \"content\": \"Tell me a story\"}],\n stream=True\n):\n print(chunk, end=\"\")\n```\n\n### Text Completions\n\n```python\nresponse = await client.completion(\n provider=\"openai\",\n model=\"gpt-3.5-turbo-instruct\",\n prompt=\"The capital of France is\",\n max_tokens=50\n)\n```\n\n### Embeddings\n\n```python\nresponse = await client.embeddings(\n provider=\"openai\",\n model=\"text-embedding-ada-002\",\n input_text=\"Hello world\"\n)\n```\n\n### Usage Statistics\n\n```python\nstats = await client.get_usage_stats()\nprint(f\"Total requests: {stats['total_requests']}\")\nprint(f\"Total cost: ${stats['total_cost']}\")\n```\n\n### Health Check\n\n```python\n# Basic health check\nhealth = await client.health_check()\nprint(f\"Status: {health['status']}\")\n\n# Detailed health status (includes database, redis, etc.)\ndetailed_health = await client.get_detailed_health()\nprint(f\"Database: {detailed_health['database']['status']}\")\nprint(f\"Redis: {detailed_health['redis']['status']}\")\n\n# Kubernetes readiness probe\nreadiness = await client.get_readiness_status()\nprint(f\"Ready: {readiness['status']}\")\n\n# Kubernetes liveness probe\nliveness = await client.get_liveness_status()\nprint(f\"Live: {liveness['status']}\")\n```\n\n### Enterprise Organization Management\n\n```python\n# Get organization information\norg = await client.get_organization()\nprint(f\"Organization: {org['name']}\")\n\n# Update organization settings\nupdated_org = await client.update_organization({\n 'name': 'Acme Corp',\n 'settings': {\n 'enableAdvancedAnalytics': True,\n 'complianceFrameworks': ['gdpr', 'hipaa']\n }\n})\n\n# Get user roles and permissions\nroles = await client.get_user_roles()\nprint(f\"User role: {roles['role']}\")\nprint(f\"Permissions: {roles['permissions']}\")\n\n# Get organization members\nmembers = await client.get_organization_members()\nprint(f\"{len(members)} members in organization\")\n\n# Invite new user\ninvitation = await client.invite_user({\n 'email': 'user@company.com',\n 'role': 'manager'\n})\n\n# Configure SSO\nsso_config = await client.configure_sso({\n 'provider': 'okta',\n 'domain': 'company.okta.com',\n 'clientId': 'your-client-id',\n 'clientSecret': 'your-client-secret'\n})\n```\n\n### Advanced Analytics\n\n```python\n# Compliance analytics\ncompliance_data = await client.get_compliance_analytics({\n 'framework': 'gdpr',\n 'startDate': '2024-01-01',\n 'endDate': '2024-12-31'\n})\n\n# Threat detection analytics\nthreats = await client.get_threat_analytics({\n 'severity': 'high',\n 'timeframe': '24h'\n})\n\n# Performance analytics\nperformance = await client.get_performance_analytics({\n 'metric': 'response_time',\n 'aggregation': 'avg'\n})\n\n# Cost analytics\ncosts = await client.get_cost_analytics({\n 'provider': 'openai',\n 'groupBy': 'model'\n})\n```\n\n### Compliance Reporting\n\n```python\n# Get compliance status\nstatus = await client.get_compliance_status('gdpr')\nprint(f\"GDPR compliance: {status['score']}%\")\n\n# Generate compliance report\nreport = await client.generate_compliance_report({\n 'framework': 'hipaa',\n 'format': 'pdf',\n 'period': 'quarterly'\n})\n\n# Get compliance violations\nviolations = await client.get_compliance_violations({\n 'severity': 'high',\n 'status': 'open'\n})\n```\n\n### Policy Management\n\n```python\n# Get all policies\npolicies = await client.get_policies()\n\n# Create new policy\nnew_policy = await client.create_policy({\n 'name': 'Content Safety Policy',\n 'description': 'Prevent harmful content generation',\n 'policyType': 'rego',\n 'policyContent': 'package content.safety\\n\\ndefault allow = false...',\n 'enabled': True,\n 'priority': 1\n})\n\n# Update policy\nupdated_policy = await client.update_policy('policy-id', {\n 'enabled': False,\n 'priority': 2\n})\n\n# Delete policy\ndeleted = await client.delete_policy('policy-id')\n\n# Test policy\ntest_result = await client.test_policy({\n 'policyId': 'policy-id',\n 'testInput': {\n 'content': 'Test content',\n 'user': {'role': 'user'}\n }\n})\n```\n\n### Provider Management\n\n```python\n# Get available providers\nproviders = await client.get_providers()\n\n# Add new provider\nnew_provider = await client.add_provider({\n 'name': 'OpenAI Production',\n 'providerType': 'openai',\n 'apiKey': 'sk-...',\n 'modelConfigs': {\n 'gpt-4': {\n 'maxTokens': 4000,\n 'temperature': 0.7,\n 'costPerToken': 0.00003\n }\n },\n 'rateLimits': {\n 'requestsPerMinute': 3500,\n 'tokensPerMinute': 90000\n }\n})\n\n# Update provider\nupdated_provider = await client.update_provider('provider-id', {\n 'rateLimits': {\n 'requestsPerMinute': 5000\n }\n})\n```\n\n### Security & Monitoring\n\n```python\n# Get security threats\nthreats = await client.get_security_threats({\n 'severity': 'high',\n 'timeframe': '1h'\n})\n\n# Get observability metrics\nmetrics = await client.get_observability_metrics({\n 'metric': 'request_rate',\n 'timeframe': '5m'\n})\n\n# Get system alerts\nalerts = await client.get_alerts({\n 'status': 'active',\n 'severity': 'critical'\n})\n```\n\n### Integrations\n\n```python\n# Get available integrations\nintegrations = await client.get_integrations()\n\n# Configure integration\nconfigured_integration = await client.configure_integration({\n 'type': 'slack',\n 'config': {\n 'webhookUrl': 'https://hooks.slack.com/...',\n 'channel': '#ai-governance'\n }\n})\n```\n\n### Data Validation\n\n```python\n# Validate structured data\nvalidation = await client.validate_structured_data({\n 'schema': {\n 'type': 'object',\n 'properties': {\n 'name': {'type': 'string'},\n 'age': {'type': 'number'}\n }\n },\n 'data': {'name': 'John', 'age': 30}\n})\n\n# Validate PII detection\npii_validation = await client.validate_pii({\n 'content': 'My email is john@example.com'\n})\nprint(f\"PII detected: {pii_validation['piiDetected']}\")\n```\n\n### Audit Logging\n\n```python\n# Get audit logs\naudit_logs = await client.get_audit_logs({\n 'action': 'policy_violation',\n 'startDate': '2024-01-01',\n 'endDate': '2024-01-31',\n 'userId': 'user123'\n})\n\nprint(f\"Found {len(audit_logs)} audit entries\")\n```\n\n## Error Handling\n\nThe SDK provides specific exception types for different error scenarios:\n\n```python\nfrom doopal_client import DoopalError, PolicyViolationError, RedactionError\n\ntry:\n response = await client.chat_completion(\n provider=\"openai\",\n model=\"gpt-3.5-turbo\",\n messages=[{\"role\": \"user\", \"content\": \"Sensitive content here\"}]\n )\nexcept PolicyViolationError as e:\n print(f\"Policy violation: {e}\")\nexcept RedactionError as e:\n print(f\"Content blocked: {e}\")\nexcept DoopalError as e:\n print(f\"API error: {e}\")\n```\n\n## Advanced Usage\n\n### Custom Metadata\n\n```python\nresponse = await client.chat_completion(\n provider=\"openai\",\n model=\"gpt-3.5-turbo\",\n messages=[{\"role\": \"user\", \"content\": \"Hello\"}],\n metadata={\n \"user_id\": \"user123\",\n \"session_id\": \"session456\",\n \"department\": \"engineering\"\n }\n)\n```\n\n### Multiple Providers\n\n```python\n# OpenAI\nopenai_response = await client.chat_completion(\n provider=\"openai\",\n model=\"gpt-3.5-turbo\",\n messages=[{\"role\": \"user\", \"content\": \"Hello\"}]\n)\n\n# Anthropic\nanthropic_response = await client.chat_completion(\n provider=\"anthropic\",\n model=\"claude-3-sonnet-20240229\",\n messages=[{\"role\": \"user\", \"content\": \"Hello\"}]\n)\n\n# Azure OpenAI\nazure_response = await client.chat_completion(\n provider=\"azure_openai\",\n model=\"gpt-35-turbo\",\n messages=[{\"role\": \"user\", \"content\": \"Hello\"}]\n)\n```\n\n## Response Format\n\nAll responses include governance and redaction information:\n\n```python\n{\n \"response\": \"The generated text response\",\n \"provider\": \"openai\",\n \"model\": \"gpt-3.5-turbo\",\n \"usage\": {\n \"prompt_tokens\": 10,\n \"completion_tokens\": 20,\n \"total_tokens\": 30\n },\n \"metadata\": {\n \"request_id\": \"req_123\",\n \"processing_time\": 1.5,\n \"policies_applied\": [\"content_filter\", \"rate_limit\"],\n \"cost\": 0.0001\n },\n \"redacted_content\": [\n \"email@example.com was redacted\",\n \"SSN 123-45-6789 was blocked\"\n ]\n}\n```\n\n## Enterprise Integration Examples\n\n### Multi-Tenant Setup\n\n```python\n# Initialize client with organization context\nclient = DoopalClient(\n api_key='your-api-key',\n base_url='https://api.your-domain.com',\n organization_id='org-123' # Important for multi-tenant deployments\n)\n\n# All subsequent calls will be scoped to this organization\norg_data = await client.get_organization()\ncompliance = await client.get_compliance_status('gdpr')\n```\n\n### Production Monitoring\n\n```python\nimport asyncio\nfrom datetime import datetime\n\n# Health monitoring for production deployments\nhealth_checks = {\n 'basic': await client.health_check(),\n 'detailed': await client.get_detailed_health(),\n 'ready': await client.get_readiness_status(),\n 'live': await client.get_liveness_status()\n}\n\nprint('Production health status:', health_checks)\n\n# Real-time threat monitoring\nasync def monitor_threats():\n while True:\n threats = await client.get_security_threats({'timeframe': '5m'})\n if threats:\n print(f\"{len(threats)} security threats detected!\")\n await asyncio.sleep(30) # Check every 30 seconds\n\n# Run monitoring in background\nasyncio.create_task(monitor_threats())\n```\n\n### Compliance Automation\n\n```python\n# Automated compliance reporting\ncompliance_report = await client.generate_compliance_report({\n 'framework': 'sox',\n 'format': 'json',\n 'period': 'monthly',\n 'includeViolations': True,\n 'includeRemediation': True\n})\n\n# Send to compliance team\nprint(f\"Generated SOX report: {compliance_report['reportId']}\")\n```\n\n### Enterprise Policy Management\n\n```python\n# Bulk policy management for enterprise deployments\npolicies_config = [\n {\n 'name': 'GDPR Data Protection',\n 'description': 'Ensure GDPR compliance for EU data',\n 'policyType': 'rego',\n 'policyContent': open('policies/gdpr.rego').read(),\n 'enabled': True,\n 'priority': 1\n },\n {\n 'name': 'HIPAA Healthcare Data',\n 'description': 'Protect healthcare information',\n 'policyType': 'rego', \n 'policyContent': open('policies/hipaa.rego').read(),\n 'enabled': True,\n 'priority': 2\n }\n]\n\n# Deploy policies\nfor policy_config in policies_config:\n policy = await client.create_policy(policy_config)\n print(f\"Created policy: {policy['id']}\")\n \n # Test policy\n test_result = await client.test_policy({\n 'policyId': policy['id'],\n 'testInput': {'content': 'Test healthcare data: Patient ID 12345'}\n })\n print(f\"Policy test result: {test_result['allowed']}\")\n```\n\n## Development\n\n### Running Tests\n\n```bash\npip install -e \".[dev]\"\npytest\n```\n\n### Code Formatting\n\n```bash\nblack .\nisort .\n```\n\n### Type Checking\n\n```bash\nmypy .\n```\n\n## Changelog\n\n### v1.1.0 (Latest)\n- \u2728 Added enterprise organization management\n- \u2728 Implemented RBAC and user management \n- \u2728 Added advanced compliance analytics\n- \u2728 Comprehensive health checks for Kubernetes\n- \u2728 Security threat detection and monitoring\n- \u2728 Policy management and testing capabilities\n- \u2728 Provider management and configuration\n- \u2728 Audit logging and compliance reporting\n- \u2728 Integration management\n- \u2728 Structured data and PII validation\n- \ud83d\udd27 Updated to support all B2B enterprise features\n- \ud83d\udd27 Enhanced async/sync method coverage\n\n### v1.0.0\n- \ud83c\udf89 Initial release\n- \u2728 Basic chat completions and embeddings\n- \u2728 Multi-provider support\n- \u2728 Content redaction and policy enforcement\n- \u2728 Streaming support\n- \u2728 OpenAI-compatible endpoints\n- \u2728 Async/sync interfaces\n\n## Support\n\n- Documentation: https://docs.doopal.com\n- GitHub Issues: https://github.com/doopal-ai/doopal/issues\n- Email: info@doopal.com\n- Enterprise Support: info@doopal.com\n- Customer Success: info@doopal.com\n\n## License\n\nMIT License - see LICENSE file for details.\n",
"bugtrack_url": null,
"license": null,
"summary": "Python SDK for Doopal AI Governance Platform",
"version": "1.1.2",
"project_urls": {
"Bug Reports": "https://github.com/doopal-ai/doopal-governance/issues",
"Documentation": "https://docs.doopal.com",
"Homepage": "https://github.com/doopal-ai/doopal-governance",
"Source": "https://github.com/doopal-ai/doopal-governance"
},
"split_keywords": [
"ai",
"governance",
"llm",
"security",
"redaction",
"policy",
"enterprise",
"compliance",
"analytics",
"monitoring",
"rbac",
"sso",
"audit"
],
"urls": [
{
"comment_text": null,
"digests": {
"blake2b_256": "51f816b602e15b51565e091bf9eab0c6f11251ec7d031637f476bb4b7916c94d",
"md5": "c37619dd4f7d95b76bdd3a23fa819458",
"sha256": "dc40096995a3305d72c9d8a567964935608d222acde47adc6f4e23f85e4ce147"
},
"downloads": -1,
"filename": "doopal-1.1.2-py3-none-any.whl",
"has_sig": false,
"md5_digest": "c37619dd4f7d95b76bdd3a23fa819458",
"packagetype": "bdist_wheel",
"python_version": "py3",
"requires_python": ">=3.8",
"size": 12096,
"upload_time": "2025-08-26T05:01:40",
"upload_time_iso_8601": "2025-08-26T05:01:40.923487Z",
"url": "https://files.pythonhosted.org/packages/51/f8/16b602e15b51565e091bf9eab0c6f11251ec7d031637f476bb4b7916c94d/doopal-1.1.2-py3-none-any.whl",
"yanked": false,
"yanked_reason": null
},
{
"comment_text": null,
"digests": {
"blake2b_256": "def3a41cd53c01500f199f8a5a45e4c3da075e9de4ee010eb099970cb847787b",
"md5": "80e41971edc44e74913c6b27c6b35d20",
"sha256": "ae2e1946593c4c26d575be65cf02c9238731131d5739e08cb9da7d3351ae9e3f"
},
"downloads": -1,
"filename": "doopal-1.1.2.tar.gz",
"has_sig": false,
"md5_digest": "80e41971edc44e74913c6b27c6b35d20",
"packagetype": "sdist",
"python_version": "source",
"requires_python": ">=3.8",
"size": 17979,
"upload_time": "2025-08-26T05:01:42",
"upload_time_iso_8601": "2025-08-26T05:01:42.295558Z",
"url": "https://files.pythonhosted.org/packages/de/f3/a41cd53c01500f199f8a5a45e4c3da075e9de4ee010eb099970cb847787b/doopal-1.1.2.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2025-08-26 05:01:42",
"github": true,
"gitlab": false,
"bitbucket": false,
"codeberg": false,
"github_user": "doopal-ai",
"github_project": "doopal-governance",
"github_not_found": true,
"lcname": "doopal"
}