API Reference
Comprehensive documentation of the Akioudai Safety SDK API, including modules, methods, and configuration options.
Overview
The Akioudai Safety SDK provides a set of modules and utilities for implementing robust AI safety measures. This API reference documents the available modules, their methods, and configuration options.
Module Structure
The SDK is organized into several core modules, each focused on a specific aspect of AI safety:
// Main SDK import
import {
AgentAlignment,
SafetyGuard,
RuntimeValidator,
BehaviorTest,
SafeDeploy
} from '@akioudai/safety-sdk';
// Individual module imports
import { AgentAlignment } from '@akioudai/safety-sdk/agent-alignment';
import { SafetyGuard } from '@akioudai/safety-sdk/safety-guard';
import { RuntimeValidator } from '@akioudai/safety-sdk/runtime-validator';
import { BehaviorTest } from '@akioudai/safety-sdk/behavior-test';
import { SafeDeploy } from '@akioudai/safety-sdk/safe-deploy';
Agent Alignment
Agent Alignment
Fine-tune LLMs with robust safety and alignment techniques to ensure reliable and appropriate model behavior.
Properties
Name | Type | Description |
---|---|---|
objectives | string[] | Array of alignment objectives (e.g., "task_completion", "safety") |
frameworks | string[] | Regulatory frameworks to align with (e.g., "hipaa", "gdpr") |
threshold | number | Minimum alignment score threshold (0-1) |
Methods
Apply alignment techniques to an agent model
- model (Object): The agent model to align
- options (Object): Alignment options
Evaluate the alignment of a model against test cases
- model (Object): The model to evaluate
- testCases (Array): Array of test cases
Example Usage
import { AgentAlignment } from '@akioudai/safety-sdk';
// Initialize with alignment parameters
const aligner = new AgentAlignment({
objectives: ['task_completion', 'safety', 'truthfulness'],
frameworks: ['hipaa', 'gdpr', 'nist'],
threshold: 0.98
});
// Apply alignment to agent model
const alignedModel = await aligner.alignAgent(myAIModel, {
realtime: true,
callbacks: {
onDrift: (violation) => {
console.log('Alignment drift detected:', violation);
// Take corrective action
}
}
});
// Use the aligned model with added safety controls
const response = await alignedModel.generateResponse(userPrompt);
Safety Guardrails
Safety Guardrails
Implement robust safety boundaries and monitoring to prevent misuse and unsafe outputs.
Properties
Name | Type | Description |
---|---|---|
boundaries | string[] | Types of safety boundaries to enforce (e.g., "ethics", "bias") |
threshold | number | Safety violation threshold (0-1) |
mode | string | Operating mode: "monitor", "filter", or "block" |
Methods
Monitor content for safety violations
- content (string): Content to monitor
- options (Object): Monitoring options
Filter unsafe content based on safety boundaries
- content (string): Content to filter
- options (Object): Filtering options
Example Usage
import { SafetyGuard } from '@akioudai/safety-sdk';
// Initialize with safety parameters
const guard = new SafetyGuard({
boundaries: ['ethics', 'bias', 'toxicity'],
threshold: 0.95,
mode: 'filter' // 'monitor', 'filter', or 'block'
});
// Monitor content for safety violations
const result = await guard.monitor(aiModelOutput, {
realtime: true,
context: {
user: userInfo,
conversation: conversationHistory
},
callbacks: {
onViolation: (violation) => {
console.log('Safety violation detected:', violation);
// Log the violation for review
}
}
});
// Check if the content is safe
if (result.safe) {
// Proceed with the content
displayToUser(aiModelOutput);
} else {
// Handle unsafe content
console.log('Violations detected:', result.violations);
displayToUser(result.filteredOutput || 'Content not available');
}
Runtime Validation
Runtime Validation
Validate model behavior during execution to ensure compliance with safety parameters.
Properties
Name | Type | Description |
---|---|---|
checkpoints | string[] | Execution checkpoints to validate (e.g., "input", "processing", "output") |
metrics | string[] | Validation metrics (e.g., "consistency", "reliability") |
threshold | number | Validation threshold (0-1) |
Methods
Validate an execution process at defined checkpoints
- execution (Object): Execution context to validate
- options (Object): Validation options
Add a custom validation checkpoint
- name (string): Checkpoint name
- validationFn (Function): Validation function
Example Usage
import { RuntimeValidator } from '@akioudai/safety-sdk';
// Initialize with validation parameters
const validator = new RuntimeValidator({
checkpoints: ['input', 'processing', 'output'],
metrics: ['consistency', 'reliability'],
threshold: 0.95
});
// Create execution context
const execution = {
input: userQuery,
model: myAIModel,
parameters: modelParameters,
output: null // Will be filled during processing
};
// Validate throughout execution
validator.validate(execution, {
realtime: true,
callbacks: {
onCheckpoint: (checkpoint, result) => {
console.log(`Checkpoint ${checkpoint} validation: ${result.valid ? 'passed' : 'failed'}`);
},
onViolation: (issue) => {
console.log('Validation issue detected:', issue);
// Address the issue
}
}
});
// Process the execution with validation
execution.output = await myAIModel.process(execution.input, execution.parameters);
// Complete validation
const validationResult = await validator.validate(execution);
// Check validation results
if (validationResult.valid) {
return execution.output;
} else {
console.log('Validation issues:', validationResult.issues);
if (validationResult.critical) {
throw new Error('Critical validation failure');
} else {
// Apply automatic corrections if available
return validationResult.corrections?.output || execution.output;
}
}
Behavioral Testing
Behavioral Testing
Comprehensive testing of model behaviors across a wide range of scenarios and edge cases.
Properties
Name | Type | Description |
---|---|---|
scenarios | string[] | Test scenario types (e.g., "edge-cases", "adversarial") |
coverage | number | Target test coverage percentage (0-1) |
threshold | number | Pass/fail threshold (0-1) |
Methods
Run a comprehensive test suite on a model
- model (Object): The model to test
- options (Object): Testing options
Generate test cases for a specific domain
- domain (string): Domain for test case generation
- count (number): Number of test cases to generate
Example Usage
import { BehaviorTest } from '@akioudai/safety-sdk';
// Initialize with testing parameters
const tester = new BehaviorTest({
scenarios: ['edge-cases', 'adversarial', 'fairness'],
coverage: 0.95,
threshold: 0.9
});
// Generate test cases for a specific domain
const testCases = await tester.generateTestCases('customer-service', 50);
// Run the test suite
const results = await tester.runSuite(myAIModel, {
testCases,
includeBuiltIn: true, // Include built-in test cases
callbacks: {
onProgress: (progress) => {
console.log(`Testing progress: ${progress.completed}/${progress.total}`);
},
onFailure: (failure) => {
console.log('Test case failed:', failure);
// Log the failure for analysis
}
}
});
// Analyze test results
console.log(`Overall pass rate: ${results.passRate}`);
console.log(`Failed scenarios: ${results.failedScenarios.length}`);
// Get recommendations for model improvements
const recommendations = results.recommendations;
for (const rec of recommendations) {
console.log(`Recommendation: ${rec.description}`);
console.log(`Priority: ${rec.priority}`);
console.log(`Related test cases: ${rec.testCases.join(', ')}`);
}
Deployment Safety
Deployment Safety
Secure deployment with continuous monitoring and safety checks throughout the model lifecycle.
Properties
Name | Type | Description |
---|---|---|
stages | string[] | Deployment stages (e.g., "canary", "staging", "production") |
metrics | string[] | Safety and performance metrics to monitor |
threshold | number | Safety threshold for automatic rollbacks (0-1) |
Methods
Release a model with safety checks
- model (Object): The model to release
- options (Object): Release options
Monitor a deployed model for safety issues
- deploymentId (string): ID of the deployment to monitor
- options (Object): Monitoring options
Example Usage
import { SafeDeploy } from '@akioudai/safety-sdk';
// Initialize with deployment parameters
const deployer = new SafeDeploy({
stages: ['canary', 'staging', 'production'],
metrics: ['safety', 'performance', 'reliability'],
threshold: 0.95
});
// Release a model with safety checks
const deployment = await deployer.release(myAIModel, {
name: 'customer-support-assistant',
version: '1.2.0',
rolloutStrategy: 'gradual', // 'immediate', 'gradual', or 'blue-green'
callbacks: {
onStageComplete: (stage, metrics) => {
console.log(`Deployment stage ${stage} completed with safety score: ${metrics.safetyScore}`);
},
onRiskDetected: (risk) => {
console.log('Deployment risk detected:', risk);
// Address the risk
}
}
});
// Monitor the deployed model
const monitoringSession = await deployer.monitor(deployment.id, {
interval: 60 * 1000, // Check every minute
metrics: ['safety-violations', 'performance', 'user-feedback'],
callbacks: {
onAlert: (alert) => {
console.log('Deployment alert:', alert);
// Take appropriate action
},
onThresholdViolation: (violation) => {
console.log('Threshold violation:', violation);
// Consider rollback or other mitigation
}
}
});
// Stop monitoring when no longer needed
monitoringSession.stop();
Configuration Options
The SDK provides flexible configuration options that can be applied across all modules. These global configuration options control authentication, logging, performance, and other common settings.
import { SafetySDK } from '@akioudai/safety-sdk';
// Initialize the SDK with global configuration
const sdk = new SafetySDK({
// Authentication
apiKey: process.env.AKIOUDAI_API_KEY,
// Environment
environment: 'production', // 'development', 'staging', or 'production'
// Logging
logging: {
level: 'info', // 'debug', 'info', 'warn', or 'error'
format: 'json', // 'json' or 'text'
destination: 'console' // 'console' or 'file'
},
// Performance
caching: {
enabled: true,
ttl: 3600 // Cache time-to-live in seconds
},
// Retry behavior
retry: {
maxRetries: 3,
initialDelay: 1000, // Initial delay in milliseconds
maxDelay: 5000, // Maximum delay in milliseconds
retryableErrors: ['rate_limit_exceeded', 'temporary_error']
},
// Timeout
timeout: 30000, // Request timeout in milliseconds
// Proxy configuration (if needed)
proxy: {
host: 'proxy.example.com',
port: 8080,
auth: {
username: 'proxyuser',
password: 'proxypass'
}
}
});
// Access SDK modules with shared configuration
const alignment = sdk.getAgentAlignment();
const guard = sdk.getSafetyGuard();
Configuration Best Practices
- Always use environment variables for sensitive information like API keys
- Adjust logging settings based on the environment (verbose in development, minimal in production)
- Configure appropriate timeouts and retry policies for your specific use case
- Enable caching for frequently accessed resources to improve performance
Events & Callbacks
The SDK provides a comprehensive event system that allows you to react to various events during the lifecycle of your AI system. You can register callbacks for these events to implement custom behavior.
import { SafetySDK } from '@akioudai/safety-sdk';
const sdk = new SafetySDK({
apiKey: process.env.AKIOUDAI_API_KEY
});
// Register global event handlers
sdk.on('error', (error) => {
console.error('SDK error:', error);
// Log to your error monitoring system
});
sdk.on('warning', (warning) => {
console.warn('SDK warning:', warning);
// Log to your monitoring system
});
// Module-specific event handlers
const guard = sdk.getSafetyGuard();
guard.on('violation', (violation) => {
console.log('Safety violation detected:', violation);
// Take appropriate action
});
guard.on('filter', (filter) => {
console.log('Content filtered:', filter);
// Log the filter event
});
// One-time event handler
guard.once('violation', (firstViolation) => {
console.log('First safety violation detected:', firstViolation);
// Take special action for the first violation
});
// Remove event handler
const warningHandler = (warning) => {
console.log('Warning:', warning);
};
sdk.on('warning', warningHandler);
// Later, when no longer needed
sdk.off('warning', warningHandler);
Common Events
Emitted when an error occurs in the SDK
Emitted for non-critical issues
Emitted when a safety violation is detected
Emitted when content is filtered
Emitted for validation results
Emitted for deployment events
Error Handling
The SDK uses a consistent error handling approach across all modules. All asynchronous methods return promises that can be caught to handle errors.
import { SafetySDK, SafetyGuardError, AlignmentError } from '@akioudai/safety-sdk';
const sdk = new SafetySDK({
apiKey: process.env.AKIOUDAI_API_KEY
});
const guard = sdk.getSafetyGuard();
// Using async/await with try/catch
async function monitorContent(content) {
try {
const result = await guard.monitor(content);
return result;
} catch (error) {
if (error instanceof SafetyGuardError) {
// Handle specific error type
console.error('Safety guard error:', error.message);
console.error('Error code:', error.code);
console.error('Error details:', error.details);
// Take appropriate action based on error code
switch (error.code) {
case 'invalid_content':
return { safe: false, reason: 'Invalid content format' };
case 'rate_limit_exceeded':
// Wait and retry
await new Promise(resolve => setTimeout(resolve, 1000));
return monitorContent(content);
default:
// Return safe default for other errors
return { safe: false, reason: 'Error during safety check' };
}
} else {
// Handle generic error
console.error('Unexpected error:', error);
return { safe: false, reason: 'Unexpected error' };
}
}
}
// Using promise chaining
function alignAgent(model) {
const alignment = sdk.getAgentAlignment();
return alignment.alignAgent(model)
.then(alignedModel => {
console.log('Model aligned successfully');
return alignedModel;
})
.catch(error => {
if (error instanceof AlignmentError) {
console.error('Alignment error:', error.message);
// Return original model with additional safety measures
return alignment.applyBasicSafety(model);
} else {
console.error('Unexpected error during alignment:', error);
throw error; // Re-throw unexpected errors
}
});
}
Error Handling Best Practices
- Always catch and handle errors from SDK methods
- Use specific error types for more precise error handling
- Implement appropriate fallback behavior for different error scenarios
- Consider retry logic for temporary errors like rate limiting
- Log errors with sufficient context for debugging