Configuration
Configuration
Section titled “Configuration”This reference covers all configuration options available in UniCraft, including API settings, provider configuration, routing rules, and more.
API Configuration
Section titled “API Configuration”Base Configuration
Section titled “Base Configuration”const unicraft = new UniCraft({ apiKey: process.env.UNICRAFT_API_KEY, baseURL: "https://api.unicraft.com/v1", timeout: 30000, retries: 3, retryDelay: 1000,});Environment Variables
Section titled “Environment Variables”# RequiredUNICRAFT_API_KEY=your-unicraft-api-key
# OptionalUNICRAFT_BASE_URL=https://api.unicraft.com/v1UNICRAFT_TIMEOUT=30000UNICRAFT_RETRIES=3UNICRAFT_RETRY_DELAY=1000Provider Configuration
Section titled “Provider Configuration”Adding Providers
Section titled “Adding Providers”const provider = await unicraft.providers.create({ name: "OpenAI Production", type: "openai", api_key: process.env.OPENAI_API_KEY, models: ["gpt-4", "gpt-3.5-turbo"], priority: 1, enabled: true, rate_limits: { requests_per_minute: 60, requests_per_hour: 1000, tokens_per_minute: 100000, }, cost_limits: { max_cost_per_request: 0.05, daily_cost_limit: 100.0, },});Provider Types
Section titled “Provider Types”OpenAI
Section titled “OpenAI”const openaiProvider = { type: "openai", api_key: process.env.OPENAI_API_KEY, models: ["gpt-4", "gpt-3.5-turbo", "gpt-3.5-turbo-16k"], organization: "org-123456789", // Optional project: "proj-123456789", // Optional};Anthropic
Section titled “Anthropic”const anthropicProvider = { type: "anthropic", api_key: process.env.ANTHROPIC_API_KEY, models: ["claude-3-opus", "claude-3-sonnet", "claude-3-haiku"], version: "2023-06-01", // Optional};const googleProvider = { type: "google", api_key: process.env.GOOGLE_API_KEY, models: ["gemini-pro", "gemini-pro-vision", "palm-2-text-bison"], project_id: "your-project-id", // Optional};Cohere
Section titled “Cohere”const cohereProvider = { type: "cohere", api_key: process.env.COHERE_API_KEY, models: ["command", "command-light", "embed-english-v2.0"],};Hugging Face
Section titled “Hugging Face”const huggingfaceProvider = { type: "huggingface", api_key: process.env.HUGGINGFACE_API_KEY, models: [ "meta-llama/Llama-2-70b-chat-hf", "mistralai/Mistral-7B-Instruct-v0.1", ],};Custom Provider
Section titled “Custom Provider”const customProvider = { type: "custom", base_url: "https://your-api.com/v1", api_key: process.env.CUSTOM_API_KEY, models: ["custom-model"], headers: { Authorization: "Bearer your-token", "Custom-Header": "value", },};Routing Configuration
Section titled “Routing Configuration”Smart Routing
Section titled “Smart Routing”const routingConfig = { strategy: "cost_optimized", // "cost_optimized", "performance_optimized", "quality_optimized", "balanced" max_cost_per_request: 0.01, quality_threshold: 0.8, response_time_limit: 5000, preferred_providers: ["openai", "anthropic"], fallback_providers: ["google", "cohere"],};Custom Routing Rules
Section titled “Custom Routing Rules”const customRules = { content_generation: { condition: "request_type === 'content_generation'", preferred_models: ["gpt-4", "claude-3-sonnet"], max_cost: 0.05, quality_threshold: 0.9, }, code_generation: { condition: "request_type === 'code_generation'", preferred_models: ["gpt-4", "claude-3-sonnet"], max_cost: 0.03, quality_threshold: 0.8, }, simple_qa: { condition: "request_type === 'simple_qa'", preferred_models: ["gpt-3.5-turbo", "claude-3-haiku"], max_cost: 0.01, quality_threshold: 0.7, },};Load Balancing
Section titled “Load Balancing”const loadBalancing = { enabled: true, strategy: "weighted_round_robin", // "round_robin", "weighted_round_robin", "least_connections" weights: { openai: 0.5, anthropic: 0.3, google: 0.2, }, health_check_interval: 60000, failure_threshold: 3,};Failover Configuration
Section titled “Failover Configuration”Automatic Failover
Section titled “Automatic Failover”const failoverConfig = { enabled: true, strategy: "next_available", // "next_available", "round_robin", "weighted" retry_attempts: 3, retry_delay: 1000, retry_delay_multiplier: 2, max_retry_delay: 10000, circuit_breaker: { enabled: true, failure_threshold: 5, recovery_timeout: 30000, half_open_max_calls: 3, },};Health Checks
Section titled “Health Checks”const healthCheckConfig = { enabled: true, interval: 60000, timeout: 5000, endpoints: { openai: "https://api.openai.com/v1/models", anthropic: "https://api.anthropic.com/v1/messages", google: "https://generativelanguage.googleapis.com/v1/models", }, retry_attempts: 3, retry_delay: 1000,};Cost Management
Section titled “Cost Management”Budget Configuration
Section titled “Budget Configuration”const budgetConfig = { daily_limit: 100.0, weekly_limit: 500.0, monthly_limit: 2000.0, alerts: [0.5, 0.8, 0.9, 1.0], // Alert at 50%, 80%, 90%, and 100% alert_channels: ["email", "slack", "webhook"], auto_pause: true, pause_threshold: 0.95,};Cost Optimization
Section titled “Cost Optimization”const costOptimization = { enabled: true, strategy: "aggressive", // "conservative", "balanced", "aggressive" max_cost_per_request: 0.01, quality_threshold: 0.8, cost_weight: 0.6, quality_weight: 0.4, performance_weight: 0.0,};Monitoring Configuration
Section titled “Monitoring Configuration”Metrics Collection
Section titled “Metrics Collection”const metricsConfig = { enabled: true, collection_interval: 60000, retention_period: 30, // days metrics: [ "response_time", "success_rate", "cost_per_request", "provider_availability", "error_rate", "throughput", ], aggregation: { enabled: true, intervals: ["1m", "5m", "15m", "1h", "1d"], },};Alerts Configuration
Section titled “Alerts Configuration”const alertsConfig = { enabled: true, channels: { email: { enabled: true, recipients: ["admin@company.com", "team@company.com"], }, slack: { enabled: true, webhook_url: "https://hooks.slack.com/services/...", channel: "#ai-alerts", }, webhook: { enabled: true, url: "https://your-app.com/webhooks/unicraft-alerts", headers: { Authorization: "Bearer your-token", }, }, }, rules: [ { name: "High Error Rate", condition: "error_rate > 0.05", duration: "5m", channels: ["email", "slack"], }, { name: "Budget Exceeded", condition: "daily_cost > daily_limit", duration: "1m", channels: ["email", "webhook"], }, ],};Security Configuration
Section titled “Security Configuration”Authentication
Section titled “Authentication”const authConfig = { api_key_rotation: { enabled: true, rotation_interval: 90, // days notification_days: [30, 7, 1], // Notify 30, 7, and 1 days before expiration }, rate_limiting: { enabled: true, requests_per_minute: 100, requests_per_hour: 1000, burst_limit: 200, }, ip_whitelisting: { enabled: true, allowed_ips: ["192.168.1.0/24", "10.0.0.0/8"], blocked_ips: ["192.168.1.100"], },};Data Protection
Section titled “Data Protection”const dataProtection = { encryption: { enabled: true, algorithm: "AES-256-GCM", key_rotation_interval: 30, // days }, data_retention: { logs: 90, // days metrics: 365, // days requests: 30, // days }, anonymization: { enabled: true, fields: ["user_id", "email", "phone"], },};Performance Configuration
Section titled “Performance Configuration”Caching
Section titled “Caching”const cacheConfig = { enabled: true, type: "redis", // "memory", "redis", "memcached" ttl: 3600, // seconds max_size: 1000, // MB compression: true, key_prefix: "unicraft:", redis: { host: "localhost", port: 6379, password: process.env.REDIS_PASSWORD, db: 0, },};Connection Pooling
Section titled “Connection Pooling”const connectionPool = { enabled: true, max_connections: 100, min_connections: 10, connection_timeout: 5000, idle_timeout: 30000, max_lifetime: 3600000,};A/B Testing Configuration
Section titled “A/B Testing Configuration”Experiment Configuration
Section titled “Experiment Configuration”const abTesting = { enabled: true, experiments: [ { name: "cost_vs_quality", variants: [ { name: "cost_optimized", weight: 0.5, config: { strategy: "cost_optimized", max_cost_per_request: 0.01, }, }, { name: "quality_optimized", weight: 0.5, config: { strategy: "quality_optimized", quality_threshold: 0.9, }, }, ], duration: "7d", metrics: ["cost", "quality_score", "user_satisfaction"], }, ],};Webhook Configuration
Section titled “Webhook Configuration”Webhook Settings
Section titled “Webhook Settings”const webhookConfig = { enabled: true, secret: process.env.WEBHOOK_SECRET, timeout: 5000, retries: 3, retry_delay: 1000, events: [ "request.completed", "request.failed", "cost.exceeded", "provider.unavailable", ], endpoints: [ { name: "Production Alerts", url: "https://your-app.com/webhooks/unicraft", events: ["request.failed", "cost.exceeded"], enabled: true, }, ],};Configuration Validation
Section titled “Configuration Validation”Schema Validation
Section titled “Schema Validation”const configSchema = { type: "object", required: ["apiKey"], properties: { apiKey: { type: "string" }, baseURL: { type: "string", format: "uri" }, timeout: { type: "number", minimum: 1000 }, retries: { type: "number", minimum: 0, maximum: 10 }, providers: { type: "array", items: { type: "object", required: ["name", "type", "api_key"], }, }, },};Configuration Testing
Section titled “Configuration Testing”const testConfig = async (config) => { try { // Test API connection const response = await fetch(`${config.baseURL}/health`, { headers: { Authorization: `Bearer ${config.apiKey}` }, });
if (!response.ok) { throw new Error(`API connection failed: ${response.status}`); }
// Test providers for (const provider of config.providers) { const testResult = await testProvider(provider); if (!testResult.success) { throw new Error( `Provider ${provider.name} test failed: ${testResult.error}` ); } }
return { success: true, message: "Configuration is valid" }; } catch (error) { return { success: false, error: error.message }; }};Environment-Specific Configuration
Section titled “Environment-Specific Configuration”Development
Section titled “Development”const devConfig = { apiKey: process.env.UNICRAFT_DEV_API_KEY, baseURL: "https://api-dev.unicraft.com/v1", providers: [ { name: "OpenAI Dev", type: "openai", api_key: process.env.OPENAI_DEV_API_KEY, models: ["gpt-3.5-turbo"], }, ], routing: { strategy: "cost_optimized", max_cost_per_request: 0.001, },};Staging
Section titled “Staging”const stagingConfig = { apiKey: process.env.UNICRAFT_STAGING_API_KEY, baseURL: "https://api-staging.unicraft.com/v1", providers: [ { name: "OpenAI Staging", type: "openai", api_key: process.env.OPENAI_STAGING_API_KEY, models: ["gpt-3.5-turbo", "gpt-4"], }, ], routing: { strategy: "balanced", max_cost_per_request: 0.01, },};Production
Section titled “Production”const prodConfig = { apiKey: process.env.UNICRAFT_PROD_API_KEY, baseURL: "https://api.unicraft.com/v1", providers: [ { name: "OpenAI Production", type: "openai", api_key: process.env.OPENAI_PROD_API_KEY, models: ["gpt-4", "gpt-3.5-turbo"], }, { name: "Anthropic Production", type: "anthropic", api_key: process.env.ANTHROPIC_PROD_API_KEY, models: ["claude-3-sonnet", "claude-3-haiku"], }, ], routing: { strategy: "quality_optimized", max_cost_per_request: 0.05, }, failover: { enabled: true, retry_attempts: 3, },};Best Practices
Section titled “Best Practices”1. Configuration Management
Section titled “1. Configuration Management”- Use environment variables for sensitive data
- Implement configuration validation
- Use different configs for different environments
- Document all configuration options
2. Security
Section titled “2. Security”- Rotate API keys regularly
- Use IP whitelisting when possible
- Implement proper authentication
- Monitor for unusual activity
3. Performance
Section titled “3. Performance”- Configure appropriate timeouts
- Use connection pooling
- Implement caching where appropriate
- Monitor performance metrics
4. Reliability
Section titled “4. Reliability”- Set up failover mechanisms
- Configure health checks
- Implement retry logic
- Monitor system health
Troubleshooting
Section titled “Troubleshooting”Common Configuration Issues
Section titled “Common Configuration Issues”-
Invalid API Keys
- Check API key format
- Verify key permissions
- Test key validity
-
Provider Connection Issues
- Check provider API keys
- Verify network connectivity
- Test provider endpoints
-
Routing Problems
- Verify routing configuration
- Check provider availability
- Test routing rules
-
Performance Issues
- Check timeout settings
- Verify connection limits
- Monitor resource usage
Debug Configuration
Section titled “Debug Configuration”const debugConfig = { enabled: true, log_level: "debug", log_requests: true, log_responses: true, log_errors: true, log_performance: true,};Support
Section titled “Support”For configuration-related support:
- Documentation: UniCraft Docs
- Configuration Guide: UniCraft Configuration Guide
- Community: UniCraft Community
- Support: support@unicraft.com
Next Steps
Section titled “Next Steps”After configuring UniCraft:
- Test Configuration: Validate all settings
- Monitor Performance: Set up monitoring and alerts
- Optimize Settings: Tune configuration based on usage
- Document Changes: Keep configuration documentation updated
- Regular Reviews: Periodically review and update configuration