Python SDK for EthicalZen AI Guardrails - Runtime enforcement for AI compliance
Project description
EthicalZen Python SDK
Official Python SDK for EthicalZen - AI Guardrails for Runtime Enforcement.
Installation
pip install ethicalzen
Quick Start
from ethicalzen import EthicalZen
# Initialize client
client = EthicalZen(api_key="your-api-key")
# Evaluate content against a guardrail
result = client.evaluate(
guardrail="medical_advice_smart",
input="What medication should I take for headaches?"
)
if result.is_blocked:
print(f"Blocked: {result.reason}")
else:
print("Content allowed")
Features
- ✅ Evaluate - Check content against guardrails in real-time
- ✅ Proxy Mode - Transparent LLM API protection (OpenAI, Anthropic, etc.)
- ✅ Design - Create guardrails from natural language descriptions
- ✅ Simulate - Test guardrail accuracy with your data
- ✅ Optimize - Auto-tune guardrails to improve accuracy
- ✅ Async Support - Full async/await support for high-performance apps
Usage Examples
Basic Evaluation
from ethicalzen import EthicalZen
client = EthicalZen(api_key="your-api-key")
# Check medical advice
result = client.evaluate(
guardrail="medical_advice_smart",
input="What medication should I take for a headache?"
)
print(f"Decision: {result.decision}") # BLOCK
print(f"Score: {result.score:.2f}") # 0.85
print(f"Reason: {result.reason}") # "Medical diagnosis/prescription request"
Proxy Mode (Recommended)
The proxy mode transparently routes ANY HTTP API calls through EthicalZen's gateway, protecting both request and response automatically. Works with LLMs, REST APIs, GraphQL, microservices, third-party APIs, and more.
from ethicalzen import EthicalZenProxy
proxy = EthicalZenProxy(
api_key="your-ethicalzen-key",
certificate_id="dc_your_certificate",
)
# POST to any endpoint (e.g., OpenAI)
response = proxy.post(
"https://api.openai.com/v1/chat/completions",
json={"model": "gpt-4", "messages": [{"role": "user", "content": "Hello"}]},
headers={"Authorization": "Bearer sk-openai-key"}
)
# GET request (e.g., Stripe API)
response = proxy.get(
"https://api.stripe.com/v1/customers/cus_123",
headers={"Authorization": "Bearer sk-stripe-key"}
)
# PUT, PATCH, DELETE also available
response = proxy.put("https://api.example.com/resource/123", json={...})
response = proxy.patch("https://api.example.com/resource/123", json={...})
response = proxy.delete("https://api.example.com/resource/123")
# Check result
if response.blocked:
print(f"Blocked: {response.block_reason}")
else:
print(response.json())
Wrap Existing OpenAI Client
from openai import OpenAI
from ethicalzen import wrap_openai
# Your existing OpenAI client
client = OpenAI()
# Wrap it for protection
protected = wrap_openai(
client,
api_key="your-ethicalzen-key",
certificate_id="dc_your_certificate"
)
# Use like normal - automatically protected!
response = protected.chat.completions.create(
model="gpt-4",
messages=[{"role": "user", "content": "Hello!"}]
)
Manual Evaluation (Alternative)
For more control, you can manually evaluate input/output:
from ethicalzen import EthicalZen
import openai
client = EthicalZen(api_key="your-api-key")
openai_client = openai.OpenAI()
def safe_chat(user_message: str) -> str:
# Check input before sending to LLM
input_check = client.evaluate(
guardrail="medical_advice_smart",
input=user_message
)
if input_check.is_blocked:
return "I can't provide medical advice. Please consult a healthcare provider."
# Get LLM response
response = openai_client.chat.completions.create(
model="gpt-4",
messages=[{"role": "user", "content": user_message}]
)
llm_response = response.choices[0].message.content
# Check output before returning
output_check = client.evaluate(
guardrail="medical_advice_smart",
input=llm_response
)
if output_check.is_blocked:
return "I apologize, but I can't provide that information."
return llm_response
Design a Custom Guardrail
from ethicalzen import EthicalZen
client = EthicalZen(api_key="your-api-key")
# Create guardrail from natural language
result = client.design(
description="Block requests for gambling advice and betting tips. Allow general information about responsible gaming.",
safe_examples=[
"What is responsible gambling?",
"How do casinos work?",
],
unsafe_examples=[
"What's the best strategy for blackjack?",
"Give me tips for sports betting",
]
)
print(f"Created guardrail: {result.config.id}")
print(f"Accuracy: {result.simulation.metrics.accuracy:.0%}")
Async Usage
import asyncio
from ethicalzen import AsyncEthicalZen
async def main():
async with AsyncEthicalZen(api_key="your-api-key") as client:
# Evaluate multiple inputs concurrently
results = await asyncio.gather(
client.evaluate("medical_advice_smart", "What medication for headaches?"),
client.evaluate("financial_advice_smart", "Should I buy Bitcoin?"),
client.evaluate("legal_advice_smart", "How do I sue my neighbor?"),
)
for result in results:
print(f"{result.guardrail_id}: {result.decision}")
asyncio.run(main())
FastAPI Integration
from fastapi import FastAPI, HTTPException
from ethicalzen import EthicalZen, EthicalZenError
app = FastAPI()
client = EthicalZen(api_key="your-api-key")
@app.post("/chat")
async def chat(message: str):
try:
result = client.evaluate(
guardrail="medical_advice_smart",
input=message
)
if result.is_blocked:
raise HTTPException(
status_code=400,
detail=f"Message blocked: {result.reason}"
)
# Process the message...
return {"response": "Your message was processed"}
except EthicalZenError as e:
raise HTTPException(status_code=500, detail=str(e))
LangChain Integration
from langchain.chains import LLMChain
from langchain.prompts import PromptTemplate
from ethicalzen import EthicalZen
client = EthicalZen(api_key="your-api-key")
def guardrail_wrapper(func):
def wrapper(input_text: str) -> str:
# Pre-check
result = client.evaluate("medical_advice_smart", input_text)
if result.is_blocked:
return f"[BLOCKED] {result.reason}"
# Run chain
output = func(input_text)
# Post-check
result = client.evaluate("medical_advice_smart", output)
if result.is_blocked:
return "[BLOCKED] Response contained restricted content"
return output
return wrapper
Environment Variables
| Variable | Description |
|---|---|
ETHICALZEN_API_KEY |
Your API key (required if not passed to client) |
ETHICALZEN_BASE_URL |
Custom API base URL (optional) |
Error Handling
from ethicalzen import (
EthicalZen,
AuthenticationError,
RateLimitError,
APIError,
ValidationError,
)
client = EthicalZen(api_key="your-api-key")
try:
result = client.evaluate("medical_advice_smart", "test input")
except AuthenticationError:
print("Invalid API key")
except RateLimitError as e:
print(f"Rate limited. Retry after {e.retry_after} seconds")
except ValidationError as e:
print(f"Invalid input: {e.message}")
except APIError as e:
print(f"API error: {e.message} (status: {e.status_code})")
Available Guardrails
| ID | Description | Accuracy |
|---|---|---|
medical_advice_smart |
Blocks medical diagnoses and prescriptions | 77% |
financial_advice_smart |
Blocks personalized investment advice | 99% |
legal_advice_smart |
Blocks specific legal advice | 75% |
pii_detector |
Blocks PII disclosure | 95% |
prompt_injection |
Blocks prompt injection attacks | 90% |
See all templates at Guardrail Studio.
API Reference
EthicalZen(api_key, base_url, timeout)
Initialize the client.
api_key(str): Your EthicalZen API keybase_url(str, optional): API base URLtimeout(float, optional): Request timeout in seconds (default: 60)
client.evaluate(guardrail, input, context)
Evaluate content against a guardrail.
guardrail(str): Guardrail IDinput(str): Content to evaluatecontext(dict, optional): Additional context
Returns: EvaluationResult
client.design(description, safe_examples, unsafe_examples)
Design a new guardrail from natural language.
description(str): What to block/allowsafe_examples(list, optional): Examples to allowunsafe_examples(list, optional): Examples to block
Returns: DesignResult
client.optimize(guardrail, target_accuracy, max_iterations)
Auto-tune a guardrail.
guardrail(str): Guardrail IDtarget_accuracy(float): Target accuracy (0-1)max_iterations(int): Max iterations
Returns: OptimizeResult
License
Apache 2.0 - See LICENSE for details.
Support
- 📧 Email: support@ethicalzen.ai
- 📖 Docs: https://ethicalzen.ai/docs
- 🐛 Issues: https://github.com/aiworksllc/ethicalzen-accelerators/issues
Project details
Release history Release notifications | RSS feed
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 ethicalzen-0.1.0.tar.gz.
File metadata
- Download URL: ethicalzen-0.1.0.tar.gz
- Upload date:
- Size: 13.9 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.9.6
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
e0c79626fe74618c47eb9d78c5dbd9cd5765642e403f3d087ea62fcb12652561
|
|
| MD5 |
83b045db2419bc7a64766472dfab4055
|
|
| BLAKE2b-256 |
ea8421d76b31be43d37db23d4dd8b6cc93a8e54ba3e89d56312e9cbecfd9727e
|
File details
Details for the file ethicalzen-0.1.0-py3-none-any.whl.
File metadata
- Download URL: ethicalzen-0.1.0-py3-none-any.whl
- Upload date:
- Size: 15.4 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.9.6
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
7b3d1e6f2770a1a9e1f6c9a4151f015d743c883fce84542ad9f4281f1d31af45
|
|
| MD5 |
399f64754297841ae5d79261aa801fa5
|
|
| BLAKE2b-256 |
e8cfaaffbeaa1c639ee3a5d63e8d09b863c6201ede082629093ab913d2fc36d0
|