npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@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-router

Basic 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 list

Calendar 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 list

General 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: chatkit

Platform 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: slack

Configuration

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-router

Advanced 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-tasks

Custom 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 handler
  • getMetrics(): RouterMetrics - Get current routing metrics
  • resetMetrics(): void - Reset routing metrics
  • updateConfig(config: Partial<ChatAIRouterConfig>): void - Update configuration
  • addAnalyzer(analyzer: IntentAnalyzer): void - Add custom intent analyzer
  • removeAnalyzer(name: string): void - Remove analyzer by name
  • getAnalyzers(): IntentAnalyzer[] - Get all registered analyzers
  • addProvider(provider: ProviderConfig): void - Add routing provider
  • removeProvider(providerId: string): void - Remove provider
  • updateProviderStatus(providerId: string, enabled: boolean): void - Enable/disable provider

Intent Analyzers

Built-in analyzers for different intent types:

  • TaskIntentAnalyzer - Detects task creation, management, and query intents
  • CalendarIntentAnalyzer - Detects calendar scheduling and query intents
  • GeneralIntentAnalyzer - Detects conversational chat intents
  • PlatformIntentAnalyzer - Detects external platform routing intents

Services

  • RouteResolver - Resolves routes based on intent and provider capabilities
  • FallbackHandler - Handles fallback routing when primary routes fail
  • MessageClassifier - Classifies messages into categories for better routing
  • ContextManager - 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/logger for 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 management
  • zod - 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