@ethicalzen/sdk
v2.0.0
Published
Official EthicalZen SDK for Node.js - AI safety guardrails made simple
Maintainers
Readme
@ethicalzen/sdk
AI Safety Guardrails Made Simple - Protect your AI applications in 3 lines of code
🚀 Quick Start (3 Lines!)
npm install @ethicalzen/sdkconst { EthicalZen } = require('@ethicalzen/sdk');
const ez = new EthicalZen('your-api-key');
const response = await ez.call('https://api.openai.com/v1/chat/completions', {
model: 'gpt-4',
messages: [{ role: 'user', content: 'Hello' }]
}, {
headers: { 'Authorization': `Bearer ${process.env.OPENAI_API_KEY}` }
});That's it! Your OpenAI calls are now protected by EthicalZen guardrails. 🎉
✨ Features
- 3-Line Integration - Initialize once, use everywhere
- Zero-Config Defaults - Works out of the box
- LLM SDK Wrappers - Drop-in protection for OpenAI, Groq, Anthropic
- Express Middleware - Automatic request/response validation
- TypeScript Support - Full type definitions included
- Flexible Failure Modes - Block, log, or pass through
📦 Installation
npm install @ethicalzen/sdk
# or
yarn add @ethicalzen/sdk
# or
pnpm add @ethicalzen/sdk🔑 Get Your API Key
- Sign up at ethicalzen.ai
- Go to your Dashboard
- Navigate to Settings → API Keys
- Generate your API key
📖 Usage Examples
1. Basic Usage (Simplest)
const { EthicalZen } = require('@ethicalzen/sdk');
// Initialize once
const ez = new EthicalZen('your-api-key');
// Make protected API calls
const response = await ez.call('https://api.openai.com/v1/chat/completions', {
model: 'gpt-4',
messages: [{ role: 'user', content: 'Hello' }]
}, {
headers: { 'Authorization': `Bearer ${process.env.OPENAI_API_KEY}` }
});
console.log(response.choices[0].message.content);2. Protect OpenAI SDK (Recommended for OpenAI Users)
const OpenAI = require('openai');
const { protectOpenAI } = require('@ethicalzen/sdk');
// Wrap your OpenAI client
const openai = protectOpenAI(
new OpenAI({ apiKey: process.env.OPENAI_API_KEY }),
'your-ethicalzen-api-key'
);
// Use exactly like normal OpenAI SDK!
const response = await openai.chat.completions.create({
model: 'gpt-4',
messages: [{ role: 'user', content: 'Hello' }]
});3. Protect Groq SDK
const Groq = require('groq-sdk');
const { protectGroq } = require('@ethicalzen/sdk');
const groq = protectGroq(
new Groq({ apiKey: process.env.GROQ_API_KEY }),
'your-ethicalzen-api-key'
);
const response = await groq.chat.completions.create({
model: 'llama-3.3-70b-versatile',
messages: [{ role: 'user', content: 'Hello' }]
});4. Protect Anthropic SDK
const Anthropic = require('@anthropic-ai/sdk');
const { protectAnthropic } = require('@ethicalzen/sdk');
const anthropic = protectAnthropic(
new Anthropic({ apiKey: process.env.ANTHROPIC_API_KEY }),
'your-ethicalzen-api-key'
);
const response = await anthropic.messages.create({
model: 'claude-3-opus-20240229',
max_tokens: 1024,
messages: [{ role: 'user', content: 'Hello' }]
});5. Express Middleware
const express = require('express');
const { EthicalZen } = require('@ethicalzen/sdk');
const app = express();
const ez = new EthicalZen('your-api-key');
// Protect all routes
app.use(ez.middleware());
// Or protect specific routes
app.post('/chat', ez.middleware({ certificate: 'chat-cert' }), async (req, res) => {
const aiResponse = await generateResponse(req.body);
res.json({ response: aiResponse }); // Automatically validated!
});6. Simplified LLM Clients (No SDK Required)
const { createProtectedOpenAI, createProtectedGroq } = require('@ethicalzen/sdk');
// OpenAI without the SDK
const ai = createProtectedOpenAI(
process.env.OPENAI_API_KEY,
'your-ethicalzen-api-key'
);
const response = await ai.chat({
model: 'gpt-4',
messages: [{ role: 'user', content: 'Hello' }]
});
// Groq without the SDK
const groq = createProtectedGroq(
process.env.GROQ_API_KEY,
'your-ethicalzen-api-key'
);
const groqResponse = await groq.chat({
model: 'llama-3.3-70b-versatile',
messages: [{ role: 'user', content: 'Hello' }]
});7. TypeScript
import { EthicalZen, CallOptions } from '@ethicalzen/sdk';
const ez = new EthicalZen('your-api-key', {
gateway: 'https://gateway.ethicalzen.ai',
certificate: 'my-cert-v1',
timeout: 30000,
onError: 'block'
});
interface ChatResponse {
choices: Array<{ message: { content: string } }>;
}
const response = await ez.call<ChatResponse>(
'https://api.openai.com/v1/chat/completions',
{ model: 'gpt-4', messages: [{ role: 'user', content: 'Hello' }] },
{ headers: { 'Authorization': `Bearer ${process.env.OPENAI_API_KEY}` } }
);
console.log(response.choices[0].message.content);⚙️ Configuration
EthicalZen Options
| Option | Type | Default | Description |
|--------|------|---------|-------------|
| gateway | string | Auto-detected | Gateway URL |
| certificate | string | undefined | Default certificate for guardrails |
| timeout | number | 30000 | Request timeout (ms) |
| onError | 'block' | 'log' | 'pass' | 'block' | How to handle violations |
Call Options
| Option | Type | Default | Description |
|--------|------|---------|-------------|
| method | string | 'POST' | HTTP method |
| headers | object | {} | Additional headers |
| certificate | string | Default cert | Override certificate |
| timeout | number | Default timeout | Override timeout |
Middleware Options
| Option | Type | Default | Description |
|--------|------|---------|-------------|
| certificate | string | Default cert | Certificate for validation |
| validate | 'request' | 'response' | 'both' | 'response' | When to validate |
| onError | 'block' | 'log' | 'pass' | 'block' | Failure mode |
| onViolation | function | undefined | Custom violation handler |
🛡️ What Gets Validated?
EthicalZen guardrails protect against:
| Category | Examples | |----------|----------| | PII Detection | SSN, credit cards, phone numbers, emails | | Toxicity | Hate speech, harassment, profanity | | Hallucination | Ungrounded claims, factual errors | | Prompt Injection | Jailbreak attempts, system prompt leaks | | Medical Claims | Unlicensed medical advice | | Legal Claims | Unlicensed legal advice | | Financial Claims | Unlicensed financial advice | | Bias | Discriminatory or unfair statements |
🚨 Error Handling
const { EthicalZen } = require('@ethicalzen/sdk');
const ez = new EthicalZen('your-api-key');
try {
const response = await ez.call('https://api.openai.com/v1/...', data);
} catch (error) {
if (error.name === 'EthicalZenViolation') {
// Request was blocked by guardrails
console.log('Violations:', error.violations);
console.log('Trace ID:', error.traceId);
} else {
// Other error (network, etc.)
console.error('Error:', error.message);
}
}🧪 Testing
# Run tests
npm test
# Run tests with coverage
npm run test:coverage
# Run integration tests (requires gateway)
INTEGRATION_TEST=true npm test📁 Examples
See the /examples directory:
- quick-start/ - Minimal 3-line example
- openai-protected/ - OpenAI SDK with EthicalZen
- groq-protected/ - Groq SDK with EthicalZen
- express-app/ - Express middleware integration
- multi-provider/ - Using multiple LLM providers
🔄 Migration from v1.x
Before (v1.x)
const { EthicalZenClient } = require('@ethicalzen/sdk');
const client = new EthicalZenClient({
apiKey: process.env.ETHICALZEN_API_KEY,
tenantId: process.env.ETHICALZEN_TENANT_ID,
baseURL: 'http://gateway:8080'
});
const result = await client.enforce({
contractId: 'my-service/general/us/v1.0',
payload: { output: aiResponse }
});After (v2.0)
const { EthicalZen } = require('@ethicalzen/sdk');
const ez = new EthicalZen(process.env.ETHICALZEN_API_KEY);
const response = await ez.call('https://api.openai.com/v1/...', data);
// Validation happens automatically!🤝 Support
- Documentation: ethicalzen.ai/docs
- Dashboard: ethicalzen.ai/dashboard
- Email: [email protected]
- Issues: GitHub Issues
📄 License
MIT © EthicalZen
Made with ❤️ by EthicalZen - Making AI Safe, One API Call at a Time
