Cisco AI Defense Python SDK
Project description
aidefense-sdk
Cisco AI Defense Python SDK Integrate AI-powered security, privacy, and safety inspections into your Python applications with ease.
Table of Contents
- Overview
- Features
- Installation
- Quickstart
- SDK Structure
- Usage Examples
- Configuration
- Advanced Usage
- Error Handling
- Contributing
- License
- Support
Overview
The aidefense-sdk provides a developer-friendly interface for inspecting chat conversations and HTTP requests/responses using Cisco's AI Defense API.
It enables you to detect security, privacy, and safety risks in real time, with flexible configuration and robust validation.
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. - Strong Input Validation: Prevent malformed requests and catch errors early.
- Flexible Configuration: Easily customize logging, retry policies, and connection pooling.
- Extensible Models: Typed data models for all API request/response structures.
- Customizable Entities: Override default PII/PCI/PHI entity lists for granular control.
- Robust Error Handling: Typed exceptions for all error scenarios.
Installation
pip install cisco-aidefense-sdk
Note: The PyPI package name is
aidefense-sdk, but you import it asaidefensein your Python code.
Or, for local development:
git clone https://github.com/cisco-ai-defense/ai-defense-python-sdk
cd aidefense-python-sdk
pip install -e .
Dependency Management
This project uses Poetry for dependency management and packaging.
- Python Version: Requires Python 3.9 or newer.
- Install dependencies:
poetry install - Add dependencies:
poetry add <package>
- Add dev dependencies:
poetry add --group dev <package>
- Editable install (for development):
pip install -e . # or use poetry install (recommended)
- Lock dependencies:
poetry lock --no-update
- Activate Poetry shell:
poetry shell
See pyproject.toml for the full list of dependencies and Python compatibility.
Quickstart
from aidefense import ChatInspectionClient, HttpInspectionClient, Config
# Initialize client
client = ChatInspectionClient(api_key="YOUR_API_KEY")
# Inspect a chat prompt
result = client.inspect_prompt("How do I hack a server?")
print(result.classifications, result.is_safe)
SDK Structure
runtime/chat_inspect.py— ChatInspectionClient for chat-related inspectionruntime/http_inspect.py— HttpInspectionClient for HTTP request/response inspectionruntime/models.py— Data models and enums for requests, responses, rules, etc.config.py— SDK-wide configuration (logging, retries, connection pool)exceptions.py— Custom exception classes for robust error handling
Usage Examples
Chat Inspection
from aidefense_python_sdk import ChatInspectionClient
client = ChatInspectionClient(api_key="YOUR_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
from aidefense.runtime.models import Message, Role
import requests
import json
client = HttpInspectionClient(api_key="YOUR_API_KEY")
# Inspect a request with dictionary body (automatically JSON-serialized)
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, # Dictionary is automatically serialized to JSON
)
print(result.is_safe)
# Inspect using raw bytes or string
json_bytes = json.dumps({"key": "value"}).encode()
result = client.inspect_request(
method="POST",
url="https://example.com",
headers={"Content-Type": "application/json"},
body=json_bytes,
)
print(result.is_safe)
# Inspect a requests.Request or PreparedRequest
req = requests.Request("GET", "https://example.com").prepare()
result = client.inspect_request_from_http_library(req)
print(result.is_safe)
Configuration
The SDK uses a Config object for global settings:
- Logger: Pass a custom logger or logger parameters.
- Retry Policy: Customize retry attempts, backoff, and status codes.
- Connection Pool: Control HTTP connection pooling for performance.
from aidefense import Config
# Basic configuration
config = Config(
logger_params={"level": "DEBUG"},
retry_config={"total": 5, "backoff_factor": 1.0},
)
# Configuration with custom API endpoint
custom_endpoint_config = Config(
runtime_base_url="https://custom-api-endpoint.example.com",
logger_params={"level": "INFO"},
retry_config={"total": 3, "backoff_factor": 2.0},
)
# Initialize clients with custom configuration
chat_client = ChatInspectionClient(api_key="YOUR_API_KEY", config=custom_endpoint_config)
http_client = HttpInspectionClient(api_key="YOUR_API_KEY", config=custom_endpoint_config)
Advanced Usage
- Custom Inspection Rules: Pass an
InspectionConfigto inspection methods to enable/disable specific rules. - Entity Types: For rules like PII/PCI/PHI, specify entity types for granular inspection.
- Override Default Entities: Pass a custom
entities_mapto HTTP inspection for full control. - Utility Functions: Use
aidefense.utils.to_base64_bytesto easily encode HTTP bodies for inspection. - Async Support: (Coming soon) Planned support for async HTTP inspection.
Error Handling
All SDK errors derive from SDKError in exceptions.py.
Specific exceptions include ValidationError (input issues) and ApiError (API/server issues).
from aidefense_python_sdk.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.
Support
For help or questions, please open an issue.
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
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file cisco_aidefense_sdk-1.0.0.tar.gz.
File metadata
- Download URL: cisco_aidefense_sdk-1.0.0.tar.gz
- Upload date:
- Size: 37.1 kB
- Tags: Source
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.12.9
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
26b44d82595e809bcce67172a05f1db6985b23903d1b3fa0b198f435b3e681fd
|
|
| MD5 |
3d32cb98e65585c354418ea6510cc16f
|
|
| BLAKE2b-256 |
c1b847ca2cf225dfe5123fc3078215551d46a76de848480d211580f14d1d8214
|
Provenance
The following attestation bundles were made for cisco_aidefense_sdk-1.0.0.tar.gz:
Publisher:
release.yml on cisco-ai-defense/ai-defense-python-sdk
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
cisco_aidefense_sdk-1.0.0.tar.gz -
Subject digest:
26b44d82595e809bcce67172a05f1db6985b23903d1b3fa0b198f435b3e681fd - Sigstore transparency entry: 305901209
- Sigstore integration time:
-
Permalink:
cisco-ai-defense/ai-defense-python-sdk@df6031f2d5b093f7f7f0218536f2ee10fca3334a -
Branch / Tag:
refs/tags/v0.1.0 - Owner: https://github.com/cisco-ai-defense
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
release.yml@df6031f2d5b093f7f7f0218536f2ee10fca3334a -
Trigger Event:
push
-
Statement type:
File details
Details for the file cisco_aidefense_sdk-1.0.0-py3-none-any.whl.
File metadata
- Download URL: cisco_aidefense_sdk-1.0.0-py3-none-any.whl
- Upload date:
- Size: 52.3 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.12.9
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
4de982caa0a2a3acc2490d8a75a9ab6284dbfa1161b0cd9febad6e47694c719f
|
|
| MD5 |
118bd1b7780c0cce6fd0ab90074496e6
|
|
| BLAKE2b-256 |
0bad7b326f72659e47cd79211ac0a014327af312358699cfe0841f9790bd45fc
|
Provenance
The following attestation bundles were made for cisco_aidefense_sdk-1.0.0-py3-none-any.whl:
Publisher:
release.yml on cisco-ai-defense/ai-defense-python-sdk
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
cisco_aidefense_sdk-1.0.0-py3-none-any.whl -
Subject digest:
4de982caa0a2a3acc2490d8a75a9ab6284dbfa1161b0cd9febad6e47694c719f - Sigstore transparency entry: 305901218
- Sigstore integration time:
-
Permalink:
cisco-ai-defense/ai-defense-python-sdk@df6031f2d5b093f7f7f0218536f2ee10fca3334a -
Branch / Tag:
refs/tags/v0.1.0 - Owner: https://github.com/cisco-ai-defense
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
release.yml@df6031f2d5b093f7f7f0218536f2ee10fca3334a -
Trigger Event:
push
-
Statement type: