UNPKG

@ethicalzen/sdk

Version:

Official EthicalZen SDK for Node.js - AI safety guardrails made simple

422 lines (322 loc) โ€ข 10.9 kB
# @ethicalzen/sdk > Official EthicalZen SDK for Node.js - AI safety guardrails made simple [![npm version](https://badge.fury.io/js/%40ethicalzen%2Fsdk.svg)](https://www.npmjs.com/package/@ethicalzen/sdk) [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](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**