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 🙏

© 2025 – Pkg Stats / Ryan Hefner

@bernierllc/ai-provider-router

v1.0.1

Published

Intelligent AI provider routing service with load balancing, cost optimization, and automatic failover

Readme

@bernierllc/ai-provider-router

Intelligent AI provider routing service with load balancing, cost optimization, and automatic failover.

Installation

npm install @bernierllc/ai-provider-router

Features

  • Multiple Routing Strategies: Round-robin, least-cost, fastest-response, load-balanced, quality-based, priority
  • Automatic Failover: Seamlessly switch to alternate providers when one fails
  • Cost Tracking: Track token usage and costs across providers
  • Load Balancing: Distribute requests based on configurable weights
  • Quota Management: Track and enforce usage limits
  • Health Monitoring: Real-time provider health status

Usage

import { AIProviderRouter } from '@bernierllc/ai-provider-router';

const router = new AIProviderRouter({
  strategy: 'load-balanced',
  enableFailover: true,
  enableCostOptimization: true,
  providers: [
    {
      name: 'openai',
      priority: 10,
      weight: 2,
      enabled: true,
      costPer1kTokens: 0.002,
    },
    {
      name: 'anthropic',
      priority: 9,
      weight: 1,
      enabled: true,
      costPer1kTokens: 0.003,
    },
  ],
});

// Initialize (loads provider clients)
await router.initialize();

// Route a request
const result = await router.route({
  prompt: 'Write a haiku about coding',
  maxTokens: 100,
  temperature: 0.7,
});

if (result.success) {
  console.log(`Response from ${result.provider}:`, result.response?.content);
  console.log(`Cost: $${result.metadata.cost.toFixed(4)}`);
}

Routing Strategies

Round-Robin

Distributes requests evenly across available providers.

const router = new AIProviderRouter({
  strategy: 'round-robin',
  providers: [...],
});

Least-Cost

Selects the cheapest provider based on cost per 1K tokens.

const router = new AIProviderRouter({
  strategy: 'least-cost',
  enableCostOptimization: true,
  providers: [
    { name: 'openai', costPer1kTokens: 0.002, ... },
    { name: 'anthropic', costPer1kTokens: 0.003, ... },
  ],
});

Fastest-Response

Selects the provider with the lowest average latency.

const router = new AIProviderRouter({
  strategy: 'fastest-response',
  providers: [...],
});

Load-Balanced

Distributes requests based on configured weights.

const router = new AIProviderRouter({
  strategy: 'load-balanced',
  providers: [
    { name: 'openai', weight: 2, ... },    // Gets ~66% of requests
    { name: 'anthropic', weight: 1, ... }, // Gets ~33% of requests
  ],
});

Quality-Based

Selects the provider with the highest success rate.

const router = new AIProviderRouter({
  strategy: 'quality-based',
  providers: [...],
});

Priority

Selects the highest priority provider.

const router = new AIProviderRouter({
  strategy: 'priority',
  providers: [
    { name: 'openai', priority: 10, ... },    // Primary
    { name: 'anthropic', priority: 5, ... },  // Fallback
  ],
});

Request Preferences

Override the routing strategy per-request:

// Force a specific provider
await router.route({
  prompt: '...',
  maxTokens: 100,
  preferences: { preferredProvider: 'anthropic' },
});

// Exclude providers
await router.route({
  prompt: '...',
  maxTokens: 100,
  preferences: { excludeProviders: ['openai'] },
});

// Override strategy for this request
await router.route({
  prompt: '...',
  maxTokens: 100,
  preferences: { prioritizeCost: true }, // Use least-cost strategy
});

Failover

When a provider fails, the router automatically tries alternate providers:

const router = new AIProviderRouter({
  enableFailover: true, // Default: true
  providers: [
    { name: 'openai', priority: 10, ... },
    { name: 'anthropic', priority: 5, ... },
  ],
});

const result = await router.route(request);

console.log(`Failover attempts: ${result.metadata.failoverAttempts}`);
console.log(`Alternatives tried: ${result.metadata.alternativesConsidered}`);

Cost Tracking

Track costs across providers:

const router = new AIProviderRouter({
  enableCostOptimization: true,
  providers: [...],
});

// After some requests
const totalCost = router.getTotalCost();
const breakdown = router.getCostBreakdown();

console.log(`Total cost: $${totalCost.toFixed(4)}`);
console.log('By provider:', breakdown);

Quota Management

Enforce usage limits:

const router = new AIProviderRouter({
  providers: [
    {
      name: 'openai',
      enabled: true,
      quotaLimit: {
        daily: 100000,  // 100K tokens per day
        hourly: 10000,  // 10K tokens per hour
      },
    },
  ],
});

// Reset quotas (e.g., at start of new day)
router.resetQuota('openai');
router.resetAllQuotas();

Health Monitoring

Check provider health status:

const health = router.getHealth();

console.log(`Status: ${health.status}`); // 'healthy', 'degraded', or 'unhealthy'
console.log(`Available: ${health.availableProviders}/${health.totalProviders}`);

// Per-provider health
for (const [name, info] of Object.entries(health.providers)) {
  console.log(`${name}: ${info.available ? 'up' : 'down'}, success rate: ${info.successRate}`);
}

Metrics

Access detailed provider metrics:

const metrics = router.getProviderMetrics('openai');

console.log(`Success rate: ${metrics?.successRate}`);
console.log(`Avg latency: ${metrics?.averageLatency}ms`);
console.log(`Total requests: ${metrics?.totalRequests}`);
console.log(`Failed requests: ${metrics?.failedRequests}`);

Custom Providers

Register custom AI providers:

const customClient = {
  complete: async (request) => {
    // Your custom implementation
    return { success: true, data: { content: '...', model: '...', tokensUsed: 100 } };
  },
};

router.registerProvider('custom', customClient, {
  priority: 20,
  costPer1kTokens: 0.001,
});

API Reference

RouterConfig

| Property | Type | Default | Description | |----------|------|---------|-------------| | strategy | RoutingStrategy | 'round-robin' | Default routing strategy | | enableFailover | boolean | true | Enable automatic failover | | enableCostOptimization | boolean | false | Enable cost tracking | | enableLoadBalancing | boolean | false | Enable load balancing | | providers | ProviderConfig[] | - | List of provider configurations | | defaultTimeoutMs | number | 30000 | Default request timeout | | maxRetries | number | 3 | Maximum retry attempts |

ProviderConfig

| Property | Type | Description | |----------|------|-------------| | name | string | Provider name ('openai', 'anthropic', or custom) | | priority | number | Priority for failover (higher = more preferred) | | weight | number | Weight for load balancing | | enabled | boolean | Whether provider is enabled | | costPer1kTokens | number | Cost per 1K tokens | | quotaLimit | QuotaLimit | Usage limits |

Integration Status

  • Logger: planned
  • Docs-Suite: ready (typedoc)
  • NeverHub: planned

License

Copyright (c) 2025 Bernier LLC. All rights reserved.