Cisco AI Defense Python SDK
Integrate AI-powered security, privacy, and safety inspections into your Python applications and manage your AI Defense resources with ease.
The cisco-aidefense-sdk provides a developer-friendly interface for inspecting chat conversations and HTTP requests/responses using Cisco's AI Defense API. It also includes a comprehensive Management API client for creating and managing applications, connections, policies, and events.
View on GitHub | Cisco AI Defense | Join Discord
Features
- Chat Inspection -- Analyze chat prompts, responses, or full conversations for risks
- HTTP Inspection -- Inspect HTTP requests and responses, including support for
requests.Request,requests.PreparedRequest, andrequests.Responseobjects - Model Scanning -- Scan AI/ML model files and repositories for security threats, malicious code, and vulnerabilities
- Management API -- Create and manage applications, connections, policies, and events
- Validation API -- Start and manage AI validation jobs for applications
- Strong Input Validation -- Prevent malformed requests and catch errors early
- Flexible Configuration -- Customize logging, retry policies, and connection pooling
- Customizable Entities -- Override default PII/PCI/PHI entity lists for granular control
Installation
pip install cisco-aidefense-sdk
For local development:
git clone https://github.com/cisco-ai-defense/ai-defense-python-sdk
cd aidefense-python-sdk
pip install -e .
Quickstart
Inspection API
from aidefense import ChatInspectionClient, HttpInspectionClient, Config
client = ChatInspectionClient(api_key="YOUR_INSPECTION_API_KEY")
result = client.inspect_prompt("How do I hack a server?")
print(result.classifications, result.is_safe)
Model Scanning API
from aidefense.modelscan import ModelScanClient
from aidefense.modelscan.models import ScanStatus
client = ModelScanClient(api_key="YOUR_MANAGEMENT_API_KEY")
result = client.scan_file("/path/to/model.pkl")
if result.status == ScanStatus.COMPLETED:
for file_info in result.analysis_results.items:
if file_info.threats.items:
print(f"Threats found in {file_info.name}")
else:
print(f"{file_info.name} is clean")
Management API
from aidefense import Config
from aidefense.management import ManagementClient
from aidefense.management.models.application import CreateApplicationRequest
from aidefense.management.models.connection import ConnectionType
client = ManagementClient(api_key="YOUR_MANAGEMENT_API_KEY")
create_app_request = CreateApplicationRequest(
application_name="My Test App",
description="Test application created via SDK",
connection_type=ConnectionType.API
)
result = client.applications.create_application(create_app_request)
print(f"Created application with ID: {result.application_id}")
Validation API
from aidefense import Config
from aidefense.management.validation_client import AiValidationClient
from aidefense.management.models.validation import (
StartAiValidationRequest,
AssetType,
)
client = AiValidationClient(api_key="YOUR_MANAGEMENT_API_KEY", config=Config())
start_req = StartAiValidationRequest(
asset_type=AssetType.APPLICATION,
application_id="your-application-id",
validation_scan_name="My SDK Scan",
model_provider="OpenAI",
model_endpoint_url_model_id="gpt-4",
)
resp = client.start_ai_validation(start_req)
print(resp.task_id)
SDK Structure
Runtime API
| Module | Description |
|---|---|
runtime/chat_inspect.py | ChatInspectionClient for chat-related inspection |
runtime/http_inspect.py | HttpInspectionClient for HTTP request/response inspection |
runtime/models.py | Data models and enums for requests, responses, rules |
Model Scanning API
| Module | Description |
|---|---|
modelscan/model_scan.py | ModelScanClient for high-level file and repository scanning |
modelscan/model_scan_base.py | ModelScan base class for granular scan operations |
modelscan/models.py | Data models for scan requests, responses, and status |
Management API
| Module | Description |
|---|---|
management/__init__.py | ManagementClient for accessing all management APIs |
management/applications.py | ApplicationManagementClient |
management/connections.py | ConnectionManagementClient |
management/policies.py | PolicyManagementClient |
management/events.py | EventManagementClient |
management/validation_client.py | AiValidationClient for validation jobs |
Common
| Module | Description |
|---|---|
config.py | SDK-wide configuration (logging, retries, connection pool) |
exceptions.py | Custom exception classes |
Usage Examples
Chat Inspection
from aidefense import ChatInspectionClient
client = ChatInspectionClient(api_key="YOUR_INSPECTION_API_KEY")
response = client.inspect_prompt("What is your credit card number?")
print(response.is_safe)
for rule in response.rules or []:
print(rule.rule_name, rule.classification)
HTTP Inspection
from aidefense import HttpInspectionClient
client = HttpInspectionClient(api_key="YOUR_INSPECTION_API_KEY")
payload = {
"model": "gpt-4",
"messages": [
{"role": "user", "content": "Tell me about security"}
]
}
result = client.inspect_request(
method="POST",
url="https://api.example.com/v1/chat/completions",
headers={"Content-Type": "application/json"},
body=payload,
)
print(result.is_safe)
Model Scanning -- Repositories
from aidefense.modelscan import ModelScanClient
from aidefense.modelscan.models import (
ModelRepoConfig, Auth, HuggingFaceAuth, URLType, ScanStatus
)
client = ModelScanClient(api_key="YOUR_MANAGEMENT_API_KEY")
repo_config = ModelRepoConfig(
url="https://huggingface.co/username/model-name",
type=URLType.HUGGING_FACE,
auth=Auth(huggingface=HuggingFaceAuth(access_token="YOUR_HF_TOKEN"))
)
result = client.scan_repo(repo_config)
if result.status == ScanStatus.COMPLETED:
print(f"Repository: {result.repository.url}")
print(f"Files scanned: {result.repository.files_scanned}")
Managing Applications
from aidefense.management import ManagementClient
from aidefense.management.models.application import (
CreateApplicationRequest, UpdateApplicationRequest
)
from aidefense.management.models.connection import ConnectionType
client = ManagementClient(api_key="YOUR_MANAGEMENT_API_KEY")
create_app_request = CreateApplicationRequest(
application_name="My Test App",
description="Test application created via SDK",
connection_type=ConnectionType.API
)
result = client.applications.create_application(create_app_request)
application_id = result.application_id
application = client.applications.get_application(application_id, expanded=True)
print(f"Application name: {application.application_name}")
Configuration
from aidefense import Config
config = Config(
logger_params={"level": "DEBUG"},
retry_config={"total": 5, "backoff_factor": 1.0},
)
# Custom API endpoints
custom_config = Config(
runtime_base_url="https://custom-runtime-endpoint.example.com",
management_base_url="https://custom-management-endpoint.example.com",
logger_params={"level": "INFO"},
retry_config={"total": 3, "backoff_factor": 2.0},
)
Error Handling
All SDK errors derive from SDKError. Specific exceptions include ValidationError (input issues) and ApiError (API/server issues).
from aidefense.exceptions import ValidationError, ApiError
try:
client.inspect_prompt(Message(role=Role.USER, content="..."))
except ValidationError as ve:
print("Validation error:", ve)
except ApiError as ae:
print("API error:", ae)
Contributing
Contributions are welcome! Please open issues or pull requests for bug fixes, new features, or documentation improvements.
License
See LICENSE for details.