New
Apps 6,419Makers 6,403This week 7
Promote your app−30%
2views in
the last 30 days

@stackbilt/llm-providers

Multi-LLM failover with circuit breakers, cost tracking, and intelligent retry

Built with Claude/Claude Code

by stackbilt-dev · Unclaimed · added Nov 3, 2026
no ratings0 comments

@stackbilt/llm-providers

Development status and resume notes: issue sweep checkpoint. The checkpoint records what has shipped and the next targets.

A Cloudflare-first LLM router: Workers AI models are the primary route, and OpenAI, Anthropic, Cerebras, Groq and NVIDIA NIM serve as secondary providers behind the same interface, with automatic failover, graduated circuit breakers, cost tracking, and intelligent retry. When Workers AI is configured and healthy, catalog routing ranks a Workers AI model first for every use case; breaker state, ledger pressure and request requirements (for example vision) can still move a request to another provider. Built for Cloudflare Workers but runs anywhere with a standard fetch API. Extracted from a production orchestration platform handling 80K+ LOC across multiple services.

Features

  • Multi-provider failover -- OpenAI, Anthropic, Cloudflare Workers AI, Cerebras, Groq, and NVIDIA NIM behind a single interface
  • Graduated circuit breaker -- 4-state machine (closed / degraded / recovering / open) with probabilistic traffic routing prevents cascading failures
  • Exponential backoff retry -- configurable delays, jitter, and per-error-class behavior
  • Cost tracking and optimization -- per-provider cost attribution, budget alerts with CreditLedger, automatic routing to cheaper providers
  • Declarative model catalog -- semantic model metadata drives recommendations, provider defaults, and fallback routing
  • Workload-aware model defaults -- gateways can request provider-tuned defaults for summary, planning, code_draft, long_context, tool_loop, and related workload classes
  • Rate limit enforcement -- CreditLedger tracks RPM/RPD/TPM/TPD per provider; factory skips providers that exceed limits
  • Streaming with fallback and usage accounting -- SSE streaming on all providers; factory-level streaming routes through the same circuit-breaker and fallback chain as non-streaming requests and records final usage after the stream drains
  • Tool/function calling -- OpenAI, Anthropic, Cerebras, and Cloudflare tool use with unified response format
  • Tool-use loop helper -- generateResponseWithTools owns the request → parse → execute → repeat cycle with iteration caps, cost limits, abort signal support, and onIteration early-exit via { abort: true }
  • Server-side built-in tools -- LLMRequest.builtInTools (e.g. [{ type: 'web_search' }]) drives Groq's Compound systems and GPT-OSS 120B to run web search / code interpreter server-side; capability-gated per model and routed to the capable provider automatically
  • Routing introspection -- getRoutingInfo() returns a pre-flight routing snapshot (use case, provider, model, token estimate, lifecycle, deprecation warning) without dispatching the request; pairs with request.metadata.useCase to pre-classify intent at the gateway and let the catalog drive dispatch
  • Deprecation annotations -- generateResponse() attaches metadata.llmProvidersDeprecationWarning to every response that uses a non-active-lifecycle model
  • Provider-agnostic cache hints -- LLMRequest.cache translates to provider-native caching (Anthropic cache_control breakpoints; automatic on OpenAI/Groq/Cerebras); cached token counts normalized into TokenUsage
  • Schema drift detection -- envelope validation on every provider response; streaming frames validated per-chunk; SchemaDriftError routes through fallback chain and fires onSchemaDrift hook
  • Schema canary -- runCanaryCheck / extractShape / compareShapes for comparing live response shapes against committed golden fixtures
  • Image generation -- ImageProvider is deprecated; use img-forge instead
  • Health monitoring -- per-provider health checks, metrics, and circuit breaker state
  • Structured logging -- injectable Logger interface; silent by default, opt-in to console or custom loggers
  • Zero runtime dependencies -- no transitive dependency tree to audit

Deprecated APIs

ImageProvider is deprecated. It was extracted from img-forge during an earlier phase when llm-providers and img-forge were more tightly coupled. img-forge is now the dedicated imagegen service with a full quality-tier registry, async orchestration, and quota metering. Use the img-forge API or MCP tools for image generation. llm-providers handles text inference and vision understanding only.

ImageProvider, ImageProviderConfig, and IMAGE_MODELS will be removed in the next major version. The normalizeAiResponse utility is under audit and may be retained as a standalone export.

Installation

npm install @stackbilt/llm-providers

Quick Start

import { LLMProviders, MODELS } from '@stackbilt/llm-providers';

const llm = new LLMProviders({
  openai: { apiKey: process.env.OPENAI_API_KEY },
  anthropic: { apiKey: process.env.ANTHROPIC_API_KEY },
  cloudflare: { ai: env.AI }, // Cloudflare Workers AI binding
  defaultProvider: 'auto',
  costOptimization: true,
  enableCircuitBreaker: true,
});

const response = await llm.generateResponse({
  messages: [
    { role: 'system', content: 'You are a helpful assistant.' },
    { role: 'user', content: 'Summarize the circuit breaker pattern.' },
  ],
  maxTokens: 1000,
  temperature: 0.7,
});

console.log(response.message);
console.log(`Provider: ${response.provider}, Cost: $${response.usage.cost}`);

Canonical Provider Contract

llm-providers now exposes an explicit canonical boundary for downstream gateways and coding-agent orchestrators:

import {
  canonicalToLLMRequest,
  normalizeLLMRequest,
  normalizeLLMResponse,
  type CanonicalLLMRequest,
} from '@stackbilt/llm-providers';

The intended architecture is:

client protocol -> gateway adapter -> CanonicalLLMRequest -> llm-providers -> vendor API

Gateways should terminate Anthropic Messages, OpenAI Chat/Responses, Ollama-style local proxy calls, or other client protocols at their own boundary, then normalize into CanonicalLLMRequest. Provider selection and vendor translation remain inside this package.

The canonical request is capability-oriented rather than vendor-oriented:

  • messages and system separate normalized chat history from system instructions
  • sampling carries temperature, maxTokens, and seed
  • tools, toolMode, and builtInTools describe requested tool behavior
  • output describes text, JSON-object, or JSON-schema structured output
  • media carries vision inputs independently of provider wire format
  • workload and requirements describe routing intent and required capabilities
  • providerOptions contains namespaced vendor-specific extensions such as Cloudflare lora or Cerebras reasoning
  • metadata carries request identity, tenancy, gateway metadata, cache hints, and custom caller metadata

Existing LLMRequest fields are still supported as compatibility input. normalizeLLMRequest() maps legacy aliases such as response_format, toolChoice, images, lora, topP, frequencyPenalty, reasoning, and prediction into the canonical shape. canonicalToLLMRequest() converts canonical requests back into the existing adapter input while providers migrate internally.

normalizeLLMResponse() provides a stable canonical response shape with normalized routing metadata (selectedProvider, selectedModel, fallback chain, and capability degradations) while preserving raw provider extras under metadata.

Use normalizeCanonicalRequest() when the input is canonical, especially when it contains only messages and metadata. Use normalizeLegacyRequest() when converting LLMRequest. The compatibility helper normalizeLLMRequest() detects canonical input from canonical-specific fields; ambiguous shapes default to legacy, so nested identity in a metadata-only canonical request requires the explicit canonical boundary. Legacy system messages are joined in order with blank lines; an explicit systemPrompt takes precedence. Canonical conversion remains a compatibility helper: it does not enforce every canonical requirement at execution.

llm.getRoutingInfo(request) uses the client's dispatch planner and current provider admission state. It resolves shared model IDs against configured hosts and throws NoRouteError when no route is available. The exported catalog-level getRoutingInfo(request, availableProviders) prefers configured hosts for pinned models and never throws: when no configured provider matches it describes the catalog host, as in 1.21. These are preflight snapshots; health, quota and capacity can change before dispatch. Full hard-requirement enforcement across every fallback remains future work.

Image Analysis Observability

analyzeImage has a Worker-safe, sanitized COGS surface on the existing public package entrypoint:

import { LLMProviders, type ImageAnalysisAttemptEvent } from '@stackbilt/llm-providers';

const llm = new LLMProviders({
  cloudflare: { ai: env.AI },
  hooks: {
    onImageAnalysisAttempt(event: ImageAnalysisAttemptEvent) {
      console.log(event);
    },
    onImageAnalysisComplete(event) {
      console.log(event);
    },
  },
});

await llm.analyzeImage({
  image: { data: base64Image, mimeType: 'image/jpeg' },
  prompt: 'Extract this page',
  requestId: crypto.randomUUID(),
  metadata: { captureId: 'capture-123', pageNumber: 1 }, // non-PII scalars only
});

Hooks are observers only. The factory and directly constructed adapters isolate every lifecycle hook: a handler that throws or returns a rejected promise cannot trigger fallback, replay a completed request, change breaker health, skip usage/quota recording or raise an unhandled rejection. Each failing hook is reported once through logger.warn. Handlers are called with your hooks object as this. onRetry, onCircuitStateChange and onBudgetThreshold are declared but not yet emitted (#116).

Each physical provider call produces an ImageAnalysisAttemptEvent; provider retries and cross-provider fallbacks are separate attempts. ImageAnalysisCompleteEvent totals tokens, attempt latency, provider-reported cost, catalog-estimated cost, and unknown-cost attempts. Prompts, image content, credentials, raw provider payloads, and error messages are not included. Sensitive metadata keys and non-scalar values are dropped.

TokenUsage.cost remains a number for compatibility. Read costProvenance: catalog-derived values are catalog_estimate, zero-placeholder or unavailable prices are unknown, and only an actual charge supplied by a provider is provider_reported. Cloudflare image telemetry reports cost as unknown because Workers AI does not expose a complete billable image-unit value; decoded image bytes remain available for COGS evidence.

Auto-Discovery from Environment

import { LLMProviders } from '@stackbilt/llm-providers';

// Scans env for ANTHROPIC_API_KEY, OPENAI_API_KEY, GROQ_API_KEY,
// CEREBRAS_API_KEY, NVIDIA_API_KEY, and AI binding — configures only what's present
const llm = LLMProviders.fromEnv(env, {
  costOptimization: true,
  enableCircuitBreaker: true,
});

Providers

Provider Models Streaming Tools Notes
Cloudflare (primary) GLM-5.3 / 5.3 Flash / 5.2 / 4.7 Flash, Kimi K2.6 / K2.7 Code, DeepSeek V4 Flash / Pro, GPT-OSS 120B / 20B, Gemma 4 26B, Qwen 3.8 27B / 3 30B / 2.5 Coder, Llama 4 Scout / 3.3 70B Fast / 3.2 / 3.1 8B FP8, Nemotron-3 120B, Granite 4.0 Micro, Mistral Small 3.1, SEA-LION v4 (explicit requests only), DeepSeek-R1-Distill, QwQ-32B; plus deepseek/deepseek-v4-pro and anthropic/claude-opus-4.8 from the AI Gateway unified catalog Yes Most current models (see catalog supportsTools) Default is request-aware and catalog-driven; thinking models (DeepSeek-R1, QwQ, GLM-4.7 Flash) are RESEARCH-only. Kimi, GLM-5.x and DeepSeek V4 need a Workers Paid plan or AI Gateway credits. Models Cloudflare deprecated (Llama 3.1/3 8B, Llama 3.1 70B, Llama 2 7B, Mistral 7B, Phi-2, Qwen 1.5, TinyLlama, OpenChat) are still accepted when named but are never auto-routed; Kimi K2.5 and Gemma 3 12B are no longer accepted
OpenAI GPT-4o Mini (shutdown 2027-01-14); GPT-6 Astra, GPT-5.6 Sol / Terra / Luna, GPT-5.5 (explicit requests only); GPT-4, GPT-4 Turbo, GPT-3.5 Turbo (shutdown 2026-10-23, no longer auto-routed) Yes Yes Default: gpt-4o-mini. GPT-5 and later get max_completion_tokens (which includes reasoning tokens) and no temperature
Anthropic Opus 4.6, Sonnet 4.6, Haiku 4.5 (legacy at Anthropic); Fable 5.1, Opus 5.5, Sonnet 5.5, Haiku 5.5 (explicit requests only); retired 4 / 3.x IDs Yes Yes Default: catalog-driven by request shape: claude-haiku-4-5-20251001 for plain requests, claude-sonnet-4-6 for tools, JSON mode (response_format), vision and long context. claude-opus-4-6 is picked only when a caller asks for the high-performance or research workload (metadata.useCase on factory requests, or the workload helpers). Claude 5.x requests omit temperature and default max_tokens to 16,000; a non-streaming request can exceed the 30-second default timeout, which is then retried (maxRetries, default 3), so raise timeout or stream for long thinking responses; Fable 5.1, Opus 5.5 and Sonnet 5.5 reject forced tool choice. JSON mode prefills { only on models that accept it
Cerebras GPT-OSS 120B, ZAI-GLM 4.7, LLaMA 3.1 8B (deprecated 2026-05-27), Qwen 3 235B (deprecated 2026-05-27) Yes GLM, Qwen, GPT-OSS ~2,200 tok/s
Groq LLaMA 3.3 70B Versatile, LLaMA 3.1 8B Instant, GPT-OSS 120B, Compound, Compound Mini Yes LLaMA 3.3 70B, GPT-OSS 120B Ultra-fast inference; Compound systems run built-in tools
NVIDIA NIM Llama 3.3/3.1 70B, Llama 4 Maverick, Nemotron 70B/49B/253B, Mistral Large 2, DeepSeek V4 Flash/Pro Yes Llama, Nemotron, Mistral Large 2 Costs $0 placeholder — dev-tier credits; set real rates in CreditLedger

Provider Configuration

// OpenAI
{ apiKey: 'sk-...', organization: 'org-...', project: 'proj-...' }

// Anthropic
{ apiKey: 'sk-ant-...', version: '2023-06-01' }

// Cloudflare Workers AI
{ ai: env.AI, accountId: '...' }

// Cerebras
{ apiKey: 'csk-...' }

// Groq
{ apiKey: 'gsk_...' }

// NVIDIA NIM
{ apiKey: 'nvapi-...' }

Cloudflare AI Gateway Passthrough

Each HTTP provider (OpenAI, Anthropic, Cerebras, Groq, NVIDIA) accepts a cfGateway option that routes requests through a Cloudflare AI Gateway without you hand-building the gateway URL:

const provider = new OpenAIProvider({
  apiKey: 'sk-...',
  cfGateway: { accountId: 'YOUR_ACCOUNT_ID', gatewayId: 'my-gateway' },
});
// baseUrl is derived as:
//   https://gateway.ai.cloudflare.com/v1/YOUR_ACCOUNT_ID/my-gateway/openai/v1

Per-provider gateway suffixes: openai/v1, anthropic, cerebras/v1, groq/openai/v1, nvidia-nim/v1.

When cfGateway is active, the provider injects cf-aig-* headers from request.gatewayMetadata on each call (each header only when its field is set):

gatewayMetadata field Header Wire value
cacheTtl (number) cf-aig-cache-ttl "300"
cacheKey (string) cf-aig-cache-key passthrough
skipCache (boolean) cf-aig-skip-cache "true"/"false"

An explicit baseUrl always wins: if you set both baseUrl and cfGateway, the baseUrl is used verbatim and no cf-aig-* headers are injected. Empty accountId or gatewayId throws CfGatewayInvalidConfigError (CF_GATEWAY_INVALID_CONFIG) synchronously in the constructor.

Composable with semantic routing

cfGateway is network-layer infrastructure and composes with this package's application-layer concerns rather than replacing them. Use llm-providers for semantic routing (use-case → model selection) and per-provider circuit breakers; use Cloudflare AI Gateway for network-layer load balancing, response caching, and upstream 429 interception. The factory still picks the provider/model and trips its breaker on failures; the gateway sits underneath each provider's outbound HTTP and handles caching and rate-limit absorption transparently.

Vision Inputs

Vision requests use request.images. The factory routes image inputs only to providers that advertise supportsVision === true; providers that cannot see images reject the request instead of silently dropping image content.

await llm.generateResponse({
  messages: [{ role: 'user', content: 'What is in this image?' }],
  images: [{ data: base64Png, mimeType: 'image/png' }],
});

Provider notes:

  • OpenAI-compatible providers that support URL images may accept images: [{ url }].
  • Anthropic requires base64 image bytes. URL images throw ConfigurationError; convert the URL to bytes before dispatch or route URL-based vision to an OpenAI-compatible provider.
  • Cerebras, Groq, and NVIDIA currently advertise supportsVision = false, so the factory skips them for image requests.

Logging

The library is silent by default. Opt in to logging by passing a Logger:

import { LLMProviders, consoleLogger } from '@stackbilt/llm-providers';

const llm = new LLMProviders({
  anthropic: { apiKey: '...', logger: consoleLogger },
  logger: consoleLogger, // factory-level logging
});

Or implement your own Logger interface (debug, info, warn, error).

Circuit Breaker

Each provider gets a graduated circuit breaker that routes traffic away from failing providers with probabilistic degradation.

State Behavior
Closed 100% traffic to primary. Failures increment counter.
Degraded Traffic splits probabilistically (90% → 70% → 40% → 10%) as failures accumulate.
Recovering Success steps traffic back up one level at a time.
Open 0% traffic. After resetTimeout ms, failures decay and traffic resumes.

Default: 5-step degradation curve [1.0, 0.9, 0.7, 0.4, 0.1], 60s reset timeout, 5-minute monitoring window.

import { CircuitBreakerManager } from '@stackbilt/llm-providers';

const manager = new CircuitBreakerManager({
  failureThreshold: 5,
  resetTimeout: 60000,
  monitoringPeriod: 300000,
  degradationCurve: [1.0, 0.9, 0.7, 0.4, 0.1],
});

const breaker = manager.getBreaker('openai');
console.log(breaker.getHealth());

Workers State Persistence

For independent clients in the same process or Worker isolate, set stateScope: 'client'. This isolates breakers, provider exhaustion, cost analytics and latency history. Alternatively, allocate a ResilienceContext and pass it as resilienceContext to clients or direct providers that intentionally share one account's health. Use application-defined account identifiers to choose contexts; keep credentials out of identifiers and logs. The global default remains for compatibility. Resetting a shared context affects its participating clients.

enableCircuitBreaker: false bypasses admission and health recording in adapters as well as factory prechecks. A provider-level enableCircuitBreaker takes precedence over the factory setting. Leaving both unset keeps the 1.21 behavior: adapter breakers on, factory prechecks and health reporting off. Non-streaming retry precedence remains compatible: an explicit provider maxRetries wins; otherwise enableRetries: false sets it to zero. To guarantee no retries, set maxRetries: 0 on each provider. Breaker failures exclude authentication, invalid input, content polic

Description taken from the repository README.

Ratings

–
0 ratings
5 0
4 0
3 0
2 0
1 0

Rate this app

Sign in to rate

Comments 0

Sign in to comment

No comments yet.

Related apps

#llm · #failover · #typescript