@bernierllc/chat-ai-router
v1.2.2
Published
AI-powered message routing and intent analysis for chat orchestration
Readme
@bernierllc/chat-ai-router
AI-powered message routing and intent analysis for intelligent chat orchestration across multiple providers.
Overview
@bernierllc/chat-ai-router provides intelligent routing for chat messages, analyzing user intent and directing messages to the most appropriate handler—whether that's ChatKit for conversational AI, slash commands for task management, or external platforms for specific workflows.
Features
- AI-Powered Intent Analysis: Automatically detects task, calendar, general chat, and platform routing intents
- Intelligent Message Routing: Routes to appropriate handlers based on confidence and provider priority
- Multi-Provider Support: Works with ChatKit, slash commands, and external platforms (Slack, Discord, Teams)
- Fallback Strategies: Graceful degradation with configurable fallback routing
- Context Awareness: Maintains conversation history for better routing decisions
- NeverHub Integration: Optional service discovery and event publishing
- ML-Driven Optimization: Learns from routing patterns to improve performance over time
- Comprehensive Metrics: Tracks routing performance, confidence scores, and provider usage
Installation
npm install @bernierllc/chat-ai-routerBasic Usage
import { ChatAIRouter } from '@bernierllc/chat-ai-router';
import { defaultConfig } from '@bernierllc/chat-ai-router/config/router-config';
// Initialize router with default config
const router = new ChatAIRouter(defaultConfig);
// Route a message
const result = await router.route({
message: 'Create a task for reviewing PR #123',
context: {
user: { id: 'user123' },
previousMessages: []
}
});
console.log(result);
// {
// success: true,
// intent: 'task-creation',
// route: 'slash-commands-tasks',
// command: '/task create',
// confidence: 0.95,
// parameters: {
// title: 'reviewing PR #123',
// priority: 'medium'
// }
// }Intent Analysis Examples
Task Intent
// Task Creation
await router.route({ message: 'Create a task for testing' });
// → Routes to: slash-commands-tasks, command: /task create
// Task Management
await router.route({ message: 'Complete task #123' });
// → Routes to: slash-commands-tasks, command: /task update
// Task Query
await router.route({ message: 'Show me my tasks' });
// → Routes to: slash-commands-tasks, command: /task listCalendar Intent
// Calendar Scheduling
await router.route({ message: 'Schedule a meeting with Bob tomorrow at 2pm' });
// → Routes to: slash-commands-calendar, command: /schedule
// Calendar Query
await router.route({ message: 'When is my next meeting?' });
// → Routes to: slash-commands-calendar, command: /schedule listGeneral Chat Intent
// Conversational Messages
await router.route({ message: 'How do I deploy this application?' });
// → Routes to: chatkit-adapter, provider: chatkit
// Greetings
await router.route({ message: 'Hello, how are you?' });
// → Routes to: chatkit-adapter, provider: chatkitPlatform Routing Intent
// External Platform Messages
await router.route({ message: 'Send this to the team in Slack' });
// → Routes to: slack-integration, provider: slack
// Channel Messages
await router.route({ message: 'Post to #general channel' });
// → Routes to: slack-integration, provider: slackConfiguration
Custom Configuration
import { ChatAIRouter } from '@bernierllc/chat-ai-router';
import { mergeConfig, defaultConfig } from '@bernierllc/chat-ai-router/config/router-config';
const customConfig = mergeConfig({
intentAnalysis: {
confidenceThreshold: 0.9, // Increase threshold
fallbackToHuman: true,
},
routing: {
providers: {
chatkit: {
id: 'chatkit',
priority: 1,
enabled: true,
capabilities: ['conversational-ai', 'general-chat'],
},
// Add custom providers...
},
},
});
const router = new ChatAIRouter(customConfig);Environment Variables
# Router Configuration
CHAT_AI_ROUTER_ENABLED=true
CHAT_AI_ROUTER_CONFIDENCE_THRESHOLD=0.8
CHAT_AI_ROUTER_FALLBACK_TO_HUMAN=true
# ML Integration
CHAT_AI_ROUTER_ML_ENABLED=true
CHAT_AI_ROUTER_LEARNING_RATE=0.01
# NeverHub Integration
NEVERHUB_ENABLED=true
NEVERHUB_SERVICE_NAME=chat-ai-routerAdvanced Usage
Context-Aware Routing
const result = await router.route({
message: 'And one for Bob too',
context: {
previousMessages: [
{
content: 'Create a task for Alice',
role: 'user',
timestamp: new Date(),
},
],
user: { id: 'user123' },
},
});
// Router understands this is a follow-up task creation
// → Routes to: slash-commands-tasksCustom Analyzers
import type { IntentAnalyzer } from '@bernierllc/chat-ai-router';
const customAnalyzer: IntentAnalyzer = {
analyze: async (message, context) => ({
intent: 'custom-intent',
confidence: 0.9,
route: 'custom-provider',
}),
getPriority: () => 1,
getName: () => 'custom-analyzer',
isEnabled: () => true,
setEnabled: (enabled) => {},
};
router.addAnalyzer(customAnalyzer);Dynamic Provider Management
// Add provider at runtime
router.addProvider({
id: 'new-provider',
priority: 10,
enabled: true,
capabilities: ['custom-capability'],
});
// Update provider status
router.updateProviderStatus('chatkit', false); // Disable
// Remove provider
router.removeProvider('discord');Metrics Tracking
const metrics = router.getMetrics();
console.log(metrics);
// {
// totalMessages: 100,
// successfulRoutes: 95,
// failedRoutes: 5,
// averageConfidence: 0.87,
// routesByIntent: {
// 'task-creation': 40,
// 'calendar-scheduling': 25,
// 'general-chat': 30
// },
// routesByProvider: {
// 'slash-commands-tasks': 40,
// 'slash-commands-calendar': 25,
// 'chatkit': 30
// }
// }
// Reset metrics
router.resetMetrics();NeverHub Integration
Service Registration
import { NeverHubAdapter } from '@bernierllc/neverhub-adapter';
import { buildServiceRegistration } from '@bernierllc/chat-ai-router/neverhub';
// Auto-detect NeverHub
if (await NeverHubAdapter.detect()) {
const neverhub = new NeverHubAdapter();
const registration = buildServiceRegistration(config);
await neverhub.register({
type: registration.type,
name: registration.name,
version: registration.version,
capabilities: registration.capabilities,
dependencies: registration.dependencies,
});
}Event Publishing
import { buildMessageRoutedEvent } from '@bernierllc/chat-ai-router/neverhub';
const result = await router.route({ message: 'Create a task' });
if (result.success) {
const event = buildMessageRoutedEvent(result);
await neverhub.publishEvent(event);
}Service Discovery
import { buildProvidersFromDiscovery } from '@bernierllc/chat-ai-router/neverhub';
// Discover chat providers
const services = await neverhub.discover({
capabilityTypes: ['chat', 'slash-commands'],
});
// Convert to provider configs
const providers = buildProvidersFromDiscovery(services);
// Add to router
providers.forEach(provider => router.addProvider(provider));API Reference
ChatAIRouter
Main router class for intelligent message routing.
Constructor
new ChatAIRouter(config: ChatAIRouterConfig)Methods
route(input: RouterInput): Promise<RouterOutput>- Route a message to appropriate handlergetMetrics(): RouterMetrics- Get current routing metricsresetMetrics(): void- Reset routing metricsupdateConfig(config: Partial<ChatAIRouterConfig>): void- Update configurationaddAnalyzer(analyzer: IntentAnalyzer): void- Add custom intent analyzerremoveAnalyzer(name: string): void- Remove analyzer by namegetAnalyzers(): IntentAnalyzer[]- Get all registered analyzersaddProvider(provider: ProviderConfig): void- Add routing providerremoveProvider(providerId: string): void- Remove providerupdateProviderStatus(providerId: string, enabled: boolean): void- Enable/disable provider
Intent Analyzers
Built-in analyzers for different intent types:
TaskIntentAnalyzer- Detects task creation, management, and query intentsCalendarIntentAnalyzer- Detects calendar scheduling and query intentsGeneralIntentAnalyzer- Detects conversational chat intentsPlatformIntentAnalyzer- Detects external platform routing intents
Services
RouteResolver- Resolves routes based on intent and provider capabilitiesFallbackHandler- Handles fallback routing when primary routes failMessageClassifier- Classifies messages into categories for better routingContextManager- Manages conversation context for context-aware routing
Performance
- Routing Time: < 1000ms (configurable threshold)
- Analysis Time: < 500ms (configurable threshold)
- Confidence Threshold: 0.7-0.9 (configurable)
- Test Coverage: 90%+ (branches, functions, lines, statements)
Integration Status
- Logger: Optional - Can integrate with
@bernierllc/loggerfor structured logging - Docs-Suite: Ready - Full API documentation and examples available
- NeverHub: Optional - Full service discovery and event integration support
Dependencies
@bernierllc/neverhub-adapter- NeverHub integration (optional)@bernierllc/retry-policy- Retry logic for failed routes@bernierllc/rate-limiter- Rate limiting for provider requests@bernierllc/logger- Structured logging (optional)@bernierllc/config-manager- Configuration managementzod- Runtime type validation
Contributing
This package follows BernierLLC quality standards:
- Strict TypeScript (zero errors, no implicit
any) - 90%+ test coverage with real data
- Comprehensive documentation with examples
- License headers in all files
- Zero linting errors or warnings
License
Copyright (c) 2025 Bernier LLC
This file is licensed to the client under a limited-use license. The client may use and modify this code only within the scope of the project it was delivered for. Redistribution or use in other products or commercial offerings is not permitted without written consent from Bernier LLC.
See Also
- @bernierllc/chatkit-adapter - ChatKit AI integration
- @bernierllc/neverhub-adapter - NeverHub service discovery
- @bernierllc/retry-policy - Retry logic for failed operations
- @bernierllc/rate-limiter - Rate limiting utilities
