@ethicalzen/sdk
Version:
Official EthicalZen SDK for Node.js - AI safety guardrails made simple
422 lines (322 loc) โข 10.9 kB
Markdown
# @ethicalzen/sdk
> Official EthicalZen SDK for Node.js - AI safety guardrails made simple
[](https://www.npmjs.com/package/@ethicalzen/sdk)
[](https://opensource.org/licenses/MIT)
## ๐ Quick Start
```bash
npm install @ethicalzen/sdk
```
```javascript
const { EthicalZenMiddleware } = require('@ethicalzen/sdk');
// Add one line to your Express app
app.use(EthicalZenMiddleware({
apiKey: process.env.ETHICALZEN_API_KEY,
tenantId: process.env.ETHICALZEN_TENANT_ID,
contractId: 'my-service/general/us/v1.0',
enforceOn: 'response'
}));
// Your routes are now automatically protected! โ
app.post('/chat', async (req, res) => {
const aiResponse = await generateAIResponse(req.body);
res.json({ message: aiResponse }); // Validated automatically
});
```
## โจ Features
- **Zero-friction integration** - One line of middleware
- **Automatic enforcement** - No manual validation code
- **Multi-guardrail support** - PII, toxicity, hallucination, etc.
- **TypeScript support** - Full type definitions
- **Flexible failure modes** - Block, log, or pass through
- **Production-ready** - Battle-tested in real-world deployments
## ๐ฆ Installation
```bash
npm install @ethicalzen/sdk
```
Or with yarn:
```bash
yarn add @ethicalzen/sdk
```
## ๐ Get API Key
1. Sign up at [https://ethicalzen.ai/enterprise-access.html](https://ethicalzen.ai/enterprise-access.html)
2. Go to your [Dashboard](https://ethicalzen.ai/dashboard.html)
3. Navigate to Settings โ API Keys
4. Generate your API key
5. Get your OpenAI key from [OpenAI Platform](https://platform.openai.com/api-keys) (for simulations)
## ๐ Usage Examples
### 1. Express Middleware (Recommended)
**Automatic enforcement on all responses:**
```javascript
const express = require('express');
const { EthicalZenMiddleware } = require('@ethicalzen/sdk');
const app = express();
app.use(express.json());
// Add EthicalZen middleware
app.use(EthicalZenMiddleware({
apiKey: process.env.ETHICALZEN_API_KEY,
tenantId: process.env.ETHICALZEN_TENANT_ID,
contractId: 'chatbot/general/us/v1.0',
enforceOn: 'response', // Validate AI outputs
failureMode: 'block' // Block unsafe responses
}));
app.post('/api/chat', async (req, res) => {
const aiResponse = await callOpenAI(req.body.message);
res.json({ response: aiResponse }); // โ
Automatically validated!
});
app.listen(3000);
```
### 2. Route-Specific Enforcement
**Enforce only on specific routes:**
```javascript
const { enforceRoute } = require('@ethicalzen/sdk');
// Unprotected route (no enforcement)
app.get('/api/health', (req, res) => {
res.json({ status: 'ok' });
});
// Protected route (with enforcement)
app.post('/api/chat',
enforceRoute({
apiKey: process.env.ETHICALZEN_API_KEY,
tenantId: process.env.ETHICALZEN_TENANT_ID,
contractId: 'chatbot/general/us/v1.0',
enforceOn: 'response'
}),
async (req, res) => {
const aiResponse = await generateResponse(req.body);
res.json({ response: aiResponse });
}
);
```
### 3. Direct Client Usage
**Manual enforcement with full control:**
```javascript
const { EthicalZenClient } = require('@ethicalzen/sdk');
const client = new EthicalZenClient({
apiKey: process.env.ETHICALZEN_API_KEY
});
app.post('/api/chat', async (req, res) => {
const aiResponse = await generateResponse(req.body.message);
// Manually enforce
const result = await client.enforce({
contractId: 'chatbot/general/us/v1.0',
payload: { output: aiResponse }
});
if (!result.passed) {
return res.status(400).json({
error: 'Safety violation',
violations: result.violations
});
}
res.json({ response: aiResponse });
});
```
### 4. Custom Violation Handler
**Custom logic for violations:**
```javascript
app.use(EthicalZenMiddleware({
apiKey: process.env.ETHICALZEN_API_KEY,
contractId: 'chatbot/general/us/v1.0',
enforceOn: 'response',
onViolation: (result, req, res) => {
// Log to your monitoring system
logger.warn('Safety violation', {
violations: result.violations,
path: req.path,
user: req.user?.id
});
// Return custom error
res.status(400).json({
error: 'Response blocked for safety',
reason: result.violations[0].message
});
}
}));
```
### 5. TypeScript Example
```typescript
import express, { Request, Response } from 'express';
import { EthicalZenMiddleware, EnforcementResponse } from '@ethicalzen/sdk';
const app = express();
app.use(EthicalZenMiddleware({
apiKey: process.env.ETHICALZEN_API_KEY!,
tenantId: process.env.ETHICALZEN_TENANT_ID!,
contractId: 'chatbot/general/us/v1.0',
enforceOn: 'response',
onViolation: (result: EnforcementResponse, req: Request, res: Response) => {
console.error('Violation detected:', result.violations);
res.status(400).json({ error: 'Unsafe content detected' });
}
}));
app.post('/chat', async (req: Request, res: Response) => {
const response = await generateAIResponse(req.body.message);
res.json({ message: response });
});
```
## โ๏ธ Configuration Options
### Middleware Config
| Option | Type | Default | Description |
|--------|------|---------|-------------|
| `apiKey` | `string` | **required** | Your EthicalZen API key |
| `tenantId` | `string` | **required** | Your tenant ID |
| `contractId` | `string` | **required** | Contract ID (format: `service/domain/region/version`) |
| `enforceOn` | `'request'` \| `'response'` \| `'both'` | `'response'` | When to enforce guardrails |
| `failureMode` | `'block'` \| `'log'` \| `'pass'` | `'block'` | How to handle violations |
| `baseURL` | `string` | `http://localhost:8443` | ACVPS Gateway endpoint |
| `timeout` | `number` | `30000` | Request timeout (ms) |
| `onViolation` | `function` | `undefined` | Custom violation handler |
| `extractPayload` | `function` | `undefined` | Custom payload extractor |
### Failure Modes
- **`block`**: Return 400 error and block request/response (recommended for production)
- **`log`**: Log violation but allow request/response (useful for testing)
- **`pass`**: Silent mode, no action taken (not recommended)
## ๐ก๏ธ What Gets Validated?
The SDK enforces all guardrails defined in your contract:
- **PII Detection** - Social Security Numbers, credit cards, phone numbers
- **Toxicity** - Hate speech, harassment, profanity
- **Hallucination** - Ungrounded claims, factual errors
- **Bias** - Discriminatory or unfair statements
- **Medical Claims** - Unlicensed medical advice
- **Legal Claims** - Unlicensed legal advice
- **Financial Claims** - Unlicensed financial advice
- **Prompt Injection** - Jailbreak attempts
## ๐ Response Format
### Successful Enforcement (Passed)
```json
{
"success": true,
"passed": true,
"contractId": "chatbot/general/us/v1.0",
"tenantId": "acme-corp",
"violations": [],
"timestamp": "2025-11-09T12:34:56Z",
"latencyMs": 45
}
```
### Failed Enforcement (Violations Detected)
```json
{
"success": true,
"passed": false,
"contractId": "chatbot/general/us/v1.0",
"tenantId": "acme-corp",
"violations": [
{
"policyId": "pii_detection",
"guardrail": "no_pii",
"message": "Social Security Number detected",
"severity": "critical",
"details": {
"type": "SSN",
"location": "output.message"
}
}
],
"timestamp": "2025-11-09T12:34:56Z",
"latencyMs": 52
}
```
## ๐ Service Registration (Optional)
Register your service to get a contract:
```javascript
const { EthicalZenClient } = require('@ethicalzen/sdk');
const client = new EthicalZenClient({
apiKey: process.env.ETHICALZEN_API_KEY
});
const result = await client.registerService({
name: 'customer-support-bot',
description: 'AI chatbot for customer support',
domain: 'general',
region: 'us',
endpoint: 'https://api.example.com/chat'
});
console.log('Evaluation ID:', result.evaluationId);
// Use evaluation ID to track certification process
```
## ๐งช Testing
### Local Development
Use `failureMode: 'log'` during development:
```javascript
app.use(EthicalZenMiddleware({
apiKey: process.env.ETHICALZEN_API_KEY,
contractId: 'chatbot/general/us/v1.0',
failureMode: process.env.NODE_ENV === 'production' ? 'block' : 'log'
}));
```
### Unit Tests
Mock the client for unit tests:
```javascript
jest.mock('@ethicalzen/sdk', () => ({
EthicalZenClient: jest.fn().mockImplementation(() => ({
enforce: jest.fn().mockResolvedValue({
success: true,
passed: true,
violations: []
})
}))
}));
```
## ๐จ Error Handling
The SDK handles errors gracefully:
```javascript
try {
const result = await client.enforce({
contractId: 'chatbot/general/us/v1.0',
payload: { output: aiResponse }
});
} catch (error) {
console.error('Enforcement failed:', error.message);
// SDK returns { success: false, passed: false } on errors
}
```
## ๐ Gateway Options
### Managed Gateway (SaaS)
Default configuration uses EthicalZen's managed gateway:
```javascript
const client = new EthicalZenClient({
apiKey: process.env.ETHICALZEN_API_KEY
// Uses https://gateway.ethicalzen.ai by default
});
```
### Customer VPC Gateway (Enterprise)
Point to your self-hosted gateway:
```javascript
const client = new EthicalZenClient({
apiKey: process.env.ETHICALZEN_API_KEY,
baseURL: 'https://gateway.your-domain.com' // Your private gateway
});
```
## ๐งช Testing
The SDK includes comprehensive test coverage (76%+):
```bash
# Run all tests
npm test
# Run tests in watch mode
npm run test:watch
# Run integration tests (requires running gateway)
INTEGRATION_TEST=true npm test
```
**Test Results:**
- โ
**25 passing tests** covering all major functionality
- โ
**Unit tests** for client and middleware
- โ
**Integration tests** for end-to-end flows
- โ
**Error handling tests** for all failure modes
See [TESTING.md](./TESTING.md) for detailed testing guide.
## ๐ Examples
See the `/examples` directory for complete working examples:
- **full-featured-app/** - Comprehensive example showing all SDK features
- **express-chatbot/** - Simple chatbot with safety enforcement
- **openai-integration/** - Protect GPT-4 responses
- **typescript-app/** - Fully typed implementation
Each example includes:
- Complete source code
- README with instructions
- package.json for dependencies
- Real-world use cases
## ๐ค Support
- **Documentation**: [https://docs.ethicalzen.ai](https://docs.ethicalzen.ai)
- **Dashboard**: [https://portal.ethicalzen.ai](https://portal.ethicalzen.ai)
- **Email**: support@ethicalzen.ai
- **GitHub Issues**: [github.com/ethicalzen/sdk-node/issues](https://github.com/ethicalzen/sdk-node/issues)
## ๐ License
MIT ยฉ EthicalZen
---
**Made with โค๏ธ by EthicalZen - Making AI Safe, One API Call at a Time**