Skip to content

About

Multi-LLM failover with circuit breakers, cost tracking, and intelligent retry. Cloudflare Workers native.

Resources

Contributing

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

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

Since 1.28.0, Cloudflare JSON Schema requests use native structured output on supported models (before, the schema was dropped): those on Cloudflare's JSON mode list, plus @cf/zai-org/glm-5.3 and @cf/zai-org/glm-5.3-flash. When no model is pinned, the factory plans only those Cloudflare models for a json_schema request, unless emulation is allowed. A request that a Cloudflare model can't serve throws StructuredOutputUnsupportedError before any Workers AI call; the factory falls back to the next provider (unless allowFallback: false), and the error doesn't count against the Cloudflare circuit breaker. For other models, set allowStructuredOutputEmulation: true on an LLMRequest, or providerOptions.cloudflare.allowStructuredOutputEmulation: true on a canonical request, to permit prompt-only emulation. Emulation does not enforce the schema. Cloudflare JSON Schema requests cannot stream, including when emulation is enabled. json_object uses prompt instructions.

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 (ReasoningEffortUnsupportedError for a reasoning.strict request no Cloudflare provider can serve; with allowFallback: false, a pin no configured provider can serve still throws NoRouteError; with contextWindowPinCheck, a pin too small for the input throws ContextWindowExceededError, a NoRouteError, when nothing else may serve the request). 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 / V4.1 Flash / V4 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 / V4.1 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 Workers AI timeouts

Since 1.27.0, non-streaming Workers AI binding calls also use BaseProvider's default timeout of 30,000 ms, so calls without an explicit deadline are limited to 30 seconds per attempt (before 1.27.0 they had no limit). The deadline applies per attempt, not to the whole operation: TimeoutError is retryable, and the default of three retries means one logical request can take four attempts plus backoff. Timeouts count as circuit-breaker failures; after three failures, a pinned slow model with allowFallback: false raises CircuitBreakerOpenError. The factory may also fall back to another provider after a TIMEOUT.

For Workers AI, timeout: 0 or a negative value disables the deadline. HTTP providers treat timeout: 0 as their 30-second default. The binding API documents no abort signal, so a timed-out call stops being awaited but may continue running alongside retries and may still incur charges. For long generations, raise timeout, lower maxRetries, or use streaming.

Cloudflare Workers AI output limits

When a request sets no maxTokens, the adapter sends no max_tokens, and Workers AI applies the model's own default. On 13 of the catalog's Workers AI models that default is 256 tokens, which cuts off longer answers, and reasoning models such as gpt-oss and QwQ can spend all of it before answering. Each model's documented default is in its capabilities:

getCatalogEntry('@cf/meta/llama-3.3-70b-instruct-fp8-fast')?.capabilities.defaultMaxTokens; // 256
getCatalogEntry('@cf/qwen/qwen3-30b-a3b-fp8')?.capabilities.defaultMaxTokens;             // 2000
getCatalogEntry('@cf/zai-org/glm-5.3')?.capabilities.defaultMaxTokens;                    // undefined: not documented
  • defaultMaxTokens is the default from the model's API schema on Cloudflare's model page, for every active @cf/ model in the catalog (the AI Gateway entries such as anthropic/claude-opus-4.8 have none). It is absent where the schema states none (the Kimi, Qwen3.8, GLM, DeepSeek V4, Gemma 4 and Nemotron models). Cloudflare documents no maximum output for any of them; the context window is the only ceiling.
  • Cut-off answers: many of these models (Llama, Mistral, Granite, QwQ and others) return no finish reason, so a cut-off answer used to read as finishReason: 'stop'. When such a model reports its output tokens and they reach the limit in effect (your maxTokens, else defaultMaxTokens below, else the 512 sent on the Llama 3.2 Vision image path, else the model's documented default), the response now says finishReason: 'length', with lengthCause. An answer that ends at exactly the limit is reported the same way. A finish reason the model does report is kept, and nothing is inferred without reported usage, after a tool call, or on streams (StreamCompletion has no finish reason).
  • outputTokensParameter is 'max_completion_tokens' where the schema marks max_tokens as deprecated in favour of it. The adapter still sends max_tokens, which those models accept.
  • A warning: when a request sets no maxTokens on a model whose documented default is 1,024 tokens or fewer, the adapter logs one warning per model, naming the model and its default (never the prompt). It is once per provider instance: updateConfig({ cloudflare }) builds a new one, so the warning can appear again.
  • A client-wide default: set defaultMaxTokens in the Cloudflare config to send that limit whenever a request sets none. A request's own maxTokens always wins. It is off by default, so nothing sent changes unless you set it; a larger limit can cost more. It is also used for pre-call cost estimates (a request's maxTokens: 0 still prices the default, as before), replaces the 512 the adapter sends on the Llama 3.2 Vision image path, and is part of the response cache key when set. It must be a positive safe integer: otherwise new LLMProviders(...) and updateConfig throw ConfigurationError, so a bad value never silently moves traffic to your other providers. updateConfig({ cloudflare }) replaces the whole Cloudflare config, so pass defaultMaxTokens again with it. The router doesn't count it: use-case inference and the contextWindowModelSwitch target (input plus maxTokens) look only at the request's own maxTokens, so set maxTokens on long-output requests if those matter.
const llm = new LLMProviders({ cloudflare: { ai: env.AI, defaultMaxTokens: 4096 } });

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.

Reasoning Control

reasoning.effort ('low' | 'medium' | 'high' | 'none') limits how much a reasoning model thinks before answering. Reasoning tokens count against maxTokens, so a high effort can use the whole budget and leave no answer.

On Workers AI, each model documents its own levels, and some document aliases that turn a "lower" value into the model's maximum (GLM-5.3 and GLM-5.3 Flash map none and medium to max). The Cloudflare provider therefore maps effort per model, from each model's Cloudflare docs page, and never forwards an alias it hasn't checked:

High reasoning effort on Workers AI can run past the 30-second default timeout; raise timeout or stream long reasoning requests.

Model Sent as requested Mapped Not sent
@cf/openai/gpt-oss-20b, -120b low, medium, high none
@cf/zai-org/glm-5.3, -5.3-flash low, high medium → high none
@cf/zai-org/glm-5.2 none, high low, medium → high
@cf/deepseek-ai/deepseek-v4-flash-0731, deepseek-v4.1-flash-1017, deepseek-v4-pro-0813 none, low, high medium → high
@cf/moonshotai/kimi-k2.6 none, high low, medium → high
@cf/qwen/qwen3.8-27b low, medium high → xhigh none
@cf/nvidia/nemotron-3-120b-a12b none, low (via chat_template_kwargs) medium, high → normal reasoning (enable_thinking: true)

Nemotron's page documents three modes (normal reasoning, low reasoning, reasoning off) and does not say which is the default, so medium and high send normal reasoning explicitly. Other Workers AI models get nothing sent. The response reports what happened:

const response = await llm.generateResponse({
  model: '@cf/zai-org/glm-5.3-flash',
  messages,
  maxTokens: 4000,
  reasoning: { effort: 'medium' },
});
response.reasoningEffort; // { requested: 'medium', applied: 'high', exact: false }

Set reasoning: { effort, strict: true } to get a ReasoningEffortUnsupportedError (a subclass of InvalidRequestError) before the call whenever the level can't be sent exactly. Strict mode is enforced by the Cloudflare provider only, so a strict request with an effort is served only by Cloudflare: other providers would drop or reinterpret the level. A strict request pinned to a model on another provider, pinned to a model no configured Cloudflare provider can serve (an unknown model, or a model that can't take the request's images), or made when no Cloudflare provider is configured, throws ReasoningEffortUnsupportedError before any call; a strict pin is never replaced by a default model. An unpinned strict request goes to Cloudflare even when another provider is preferred, and uses the default Workers AI model for the request, which may not take the level exactly (GLM-5.3 Flash has no exact none or medium). Pin a model when using strict. The factory never falls back on this error, and when the Cloudflare call fails for another reason, the error is thrown rather than the request being served elsewhere, even under the default any-error fallback rule. getModelCapabilities() and the model catalog expose the mapping as capabilities.reasoningEffort ({ exact, source, verifiedAt }).

Two related fields help with budget planning:

  • usage.reasoningTokens: reasoning tokens, when the provider reports them separately (Workers AI: completion_tokens_details.reasoning_tokens). They are part of outputTokens.
  • lengthCause: set when finishReason is 'length'. 'reasoning' means the budget ran out before any answer text: a <think> block left open at the start of the message (after any closed ones), nothing after the leading think blocks, or, for models whose chat template opens the think block itself (QwQ, R1-Distill), text up to the first </think>, or untagged text with no separate reasoning field. 'answer' means the answer was cut off.

Stream completions report provider and model but not reasoningEffort; the level sent is the same as for generateResponse().

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 policy, configuration and quota errors. Concurrent successes and failures settle in completion order; each success reduces accumulated consecutive failures by one. Rejected requests do not reset the recovery clock.

The default circuit breaker manager, exhaustion registry, and CreditLedger keep state in memory. In Cloudflare Workers that state is per isolate and can reset between requests. Persist snapshots to KV, D1, Redis, Durable Objects, or another store when you need circuit state, quota exhaustion, or budget spend to survive across invocations.

The KV example below illustrates approximate snapshot persistence, not atomic budget admission. Concurrent restore/write operations can overwrite newer history. Do not use it to enforce tenant spend or reserve in-flight requests; an atomic coordinator is still outstanding in #109. CreditLedger tracks spend and influences routing; configured monetary budgets do not guarantee a hard cap.

import {
  CreditLedger,
  defaultCircuitBreakerManager,
  defaultExhaustionRegistry,
} from '@stackbilt/llm-providers';

interface Env {
  LLM_STATE: KVNamespace;
}

const ledger = new CreditLedger();

export default {
  async fetch(request: Request, env: Env): Promise<Response> {
    const [breakersJson, exhaustionJson, ledgerJson] = await Promise.all([
      env.LLM_STATE.get('circuit-breakers'),
      env.LLM_STATE.get('exhaustion'),
      env.LLM_STATE.get('credit-ledger'),
    ]);

    if (breakersJson) defaultCircuitBreakerManager.restore(breakersJson);
    if (exhaustionJson) defaultExhaustionRegistry.restore(exhaustionJson);
    if (ledgerJson) ledger.restore(JSON.parse(ledgerJson));

    try {
      // Create/use LLMProviders here with { ledger, enableCircuitBreaker: true }.
      return new Response('ok');
    } finally {
      await Promise.all([
        env.LLM_STATE.put('circuit-breakers', defaultCircuitBreakerManager.serialize()),
        env.LLM_STATE.put('exhaustion', defaultExhaustionRegistry.serialize()),
        env.LLM_STATE.put('credit-ledger', JSON.stringify(ledger.snapshot())),
      ]);
    }
  },
};

For standalone lower-level use, CircuitBreaker.deserialize(json), CircuitBreakerManager.deserialize(json), and ExhaustionRegistry.deserialize(json) reconstruct fresh instances from persisted JSON.

Cost Tracking & Budget Management

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

const ledger = new CreditLedger({
  budgets: [
    { provider: 'openai', monthlyBudget: 50, rateLimits: { rpm: 60, rpd: 10000 } },
    { provider: 'anthropic', monthlyBudget: 100 },
  ],
});

// Threshold alerts fire at 80%, 90%, 95% utilization
ledger.on((event) => {
  if (event.type === 'threshold_crossed') {
    console.warn(`${event.provider}: ${event.tier} — ${event.utilizationPct.toFixed(0)}% of budget`);
  }
});

const llm = new LLMProviders({
  openai: { apiKey: '...' },
  anthropic: { apiKey: '...' },
  costOptimization: true,
  ledger, // Completed-use rate counters, spend analytics and routing signals
});

Server-side built-in tool surcharges are not token-tracked. Costs in TokenUsage and the ledger cover token spend only. Groq's built-in tools bill separately per use (web search ~$5/1k requests, code interpreter ~$0.18/hr, browser automation ~$0.08/hr) and are not attributed per call in v1. If you run builtInTools workloads, account for these surcharges out of band (e.g. a manual ledger adjustment or a separate budget line).

Model Catalog & Runtime Selection

Model selection is driven by a declarative catalog rather than a hardcoded fallback array. The selector intersects:

  • requested use case and capabilities
  • configured providers
  • circuit breaker state (CLOSED, DEGRADED, RECOVERING, OPEN)
  • CreditLedger utilization and projected burn/depletion pressure

The catalog also distinguishes active, compatibility, and retired models. Retired IDs can remain exported for compatibility, but they are not recommendation targets. Entries marked explicitOnly are served only when a request names them; recommendations and automatic routing skip them. In 1.28.0 these are the Claude 5.x models (until the remaining routing steps tracked on #112 are done: keeping tools on toolChoice: 'none' turns and handling a mid-loop fallback onto a thinking model), gpt-6-astra, gpt-5.6-sol, gpt-5.6-terra, gpt-5.6-luna and gpt-5.5 (so the OpenAI default stays gpt-4o-mini), and @cf/aisingapore/gemma-sea-lion-v4-27b-it.

import {
  MODEL_CATALOG,
  MODEL_RECOMMENDATIONS,
  getRecommendedModel,
  inferUseCaseFromRequest
} from '@stackbilt/llm-providers';

const useCase = inferUseCaseFromRequest({
  messages: [{ role: 'user', content: 'Call the weather tool' }],
  tools: [{
    type: 'function',
    function: {
      name: 'get_weather',
      description: 'Get weather',
      parameters: { type: 'object' }
    }
  }]
});

const model = getRecommendedModel('TOOL_CALLING', ['cloudflare', 'openai']);

For runtime-aware recommendations from a configured instance:

const recommended = llm.getRecommendedModel({
  messages: [{ role: 'user', content: 'Summarize this incident' }],
  maxTokens: 800
});

Gateway layers can also ask directly by workload class instead of carrying their own provider/model maps:

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

const fastSummaryModel = getProviderDefaultModelForWorkload('groq', 'summary');
const toolLoopModel = getProviderDefaultModelForWorkload('groq', 'tool_loop', {
  modelPreferences: {
    tool_loop: { groq: 'openai/gpt-oss-120b' },
  },
});

Routing Introspection

getRoutingInfo() lets gateways and agent orchestrators inspect what the catalog engine would do — without dispatching the request. Use this at ingress to classify intent once, log the routing decision, enforce policies, or pre-warm the right provider.

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

// Standalone — pass the providers you have configured
const info = getRoutingInfo(
  { messages: [{ role: 'user', content: 'Call the weather tool' }], tools: [...] },
  ['cloudflare', 'cerebras', 'groq']
);

// info.useCase              → 'TOOL_CALLING'
// info.provider             → 'cerebras'
// info.model                → 'zai-glm-4.7'
// info.estimatedInputTokens → heuristic count
// info.modelLifecycle       → 'active'
// info.deprecationWarning   → undefined (or a warning string for non-active models)

metadata.useCase passthrough

After calling getRoutingInfo(), set request.metadata.useCase to the classified value before dispatching. The factory's resolveUseCase() reads this field directly, skipping re-inference and ensuring the gateway's classification is honored:

const info = getRoutingInfo(request, configuredProviders);

// Attach the gateway's classification so the factory doesn't re-infer it
const annotatedRequest = {
  ...request,
  metadata: { ...request.metadata, useCase: info.useCase },
};

const response = await llm.generateResponse(annotatedRequest);

Worker Gateway Route Plans

getGatewayRoutePlan() packages canonical normalization, catalog routing, cache hints, and capability checks into one Worker-friendly object. Use it behind OpenAI-compatible, Ollama-style, or Anthropic-compatible API routers before dispatching the request. The helper accepts either compatibility LLMRequest input, as shown below, or CanonicalLLMRequest.

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

const plan = getGatewayRoutePlan({
  messages: [{ role: 'user', content: 'Call tools and return JSON.' }],
  stream: true,
  tools: [weatherTool],
  response_format: { type: 'json_object' },
  cache: { strategy: 'both', key: 'agent:weather:v1', ttl: 300 },
}, ['cloudflare', 'groq', 'anthropic']);

console.log(plan.selectedProvider, plan.selectedModel, plan.degradations);
if (!plan.executable) throw new Error('Required capability is unavailable');

The route plan intentionally does not read or write a cache. A Worker should map plan.cache onto its own storage implementation, such as KV, Cache API, D1, or R2. Provider prompt-cache hints and response-cache hints stay separate so gateways can decide which storage tier owns each policy.

The plan is diagnostic: executable: false marks a failed required-capability check or a selected host outside availableProviders, including built-in-tool mismatches on a configured pinned host. A true value does not guarantee native JSON-schema support or complete execution-time requirement enforcement. For metadata-only canonical requests, call getGatewayRoutePlan(normalizeCanonicalRequest(request), providers) to preserve identity. Use llm.getRoutingInfo() for the actual client's planner/admission snapshot; catalog diagnostics do not have the client's complete configuration.

When lora is present, the route plan warns that the adapter id is forwarded to Workers AI without validation. If routing selects a non-Cloudflare provider, the plan reports a lora degradation so the gateway can fail, reroute, or explain the downgrade before dispatch.

Deprecation warnings on responses

When generateResponse() routes to a model on compatibility or retired lifecycle, the response includes a warning:

const response = await llm.generateResponse({ model: 'llama-3.1-8b', ... });

if (response.metadata?.llmProvidersDeprecationWarning) {
  console.warn(response.metadata.llmProvidersDeprecationWarning);
  // → "llama-3.1-8b deprecates 2026-05-27 — plan migration"
}

This fires automatically — no opt-in required. The warning surface is the response, so any layer that handles responses (the gateway, the caller) sees it regardless of which layer made the call.

Fallback Rules

Customize when and how the factory falls back between providers:

const llm = new LLMProviders({
  openai: { apiKey: '...' },
  anthropic: { apiKey: '...' },
  cloudflare: { ai: env.AI },
  cerebras: { apiKey: '...' },
  fallbackRules: [
    { condition: 'rate_limit', fallbackProvider: 'cloudflare' },
    { condition: 'cost', threshold: 10, fallbackProvider: 'cloudflare' },
    { condition: 'error', fallbackProvider: 'anthropic' },
  ],
});

Default provider precedence remains Cloudflare → Cerebras → Groq → NVIDIA → Anthropic → OpenAI, but actual dispatch is catalog-driven and can be reordered at runtime by request fit, circuit-breaker state, and ledger burn-rate pressure.

Context windows (opt-in)

By default, a request too large for a provider's model is still sent to it. The overflow error then falls back like any other error, through the built-in catch-all fallback rule, which costs a failed call that may be billed or rate-limited. Set contextWindowRouting: true to skip those calls.

const llm = new LLMProviders({ cloudflare: { ai: env.AI }, groq: { apiKey }, preferredProvider: 'groq', contextWindowRouting: true });
const response = await llm.generateResponse({ messages: longDocument }); // ~150k tokens
response.provider; // 'cloudflare'
response.fallback;
// { requestedProvider: 'groq', requestedModel: 'llama-3.3-70b-versatile',
//   failedAttempts: [{ provider: 'groq', model: 'llama-3.3-70b-versatile', errorCode: 'CONTEXT_WINDOW' }] }

How it works

  • The estimate: the factory estimates the request's input as characters divided by four. It counts the system prompt and each message's text (or the text and thinking of its provider-native content, when that is larger), tool-call arguments, and tool results and errors.
  • Your own count: if you have a count, for example from a tokenizer, set inputTokenCount on the request and it replaces the estimate. It also feeds getRoutingInfo, getGatewayRoutePlan and pre-call cost estimates: each provider's estimateCost, which is the estimatedCost a quotaHook sees, and CostTracker.calculateRequestCost. It is never sent to a provider. When usage has to be estimated because the provider reported none (a Workers AI response without usage, or a stream), the estimate uses your count too. It doesn't change the use case (including LONG_CONTEXT) or the default models, which still come from message length and maxTokens; only contextWindowModelSwitch, when on, can move a provider to a larger model because of it. The same count is used for every provider in the fallback chain, although their tokenizers differ, so use the largest count you have. It must be a positive safe integer: otherwise the factory's generateResponse, streaming, tool-loop, classify and getRoutingInfo methods, and every provider's generateResponse and streamResponse, throw ConfigurationError before any call, while catalog helpers, route plans, getRecommendedModel and cost estimates ignore it. In generateResponseWithTools, later calls use your count plus an estimate of the assistant turns and tool results the loop has added (or drop the count if the sum would pass Number.MAX_SAFE_INTEGER), and classify adds an estimate of any system prompt it supplies.
  • When providers are skipped: a provider "can be relied on right now" if it is configured, not quota-exhausted or ledger-limited, and its circuit breaker is fully closed. When such a provider has a planned model whose context window holds the estimate, providers whose planned model can't are skipped when their turn comes.
  • How a skip is reported: like a quota-exhausted provider, as errorCode: 'CONTEXT_WINDOW' in fallback.failedAttempts on the response or StreamCompletion.
  • Where it applies: on the response and streaming paths, and to each turn of generateResponseWithTools as tool results accumulate.
  • What doesn't change: the fallback chain, planned models (unless contextWindowModelSwitch is also on, below) and catalog ranking (rankModels, catalog getRoutingInfo, getProviderDefaultModel, getRecommendedModel). When no available provider's model fits, nothing is skipped.

Trade-offs and rules

  • Trade-off: a skipped provider can no longer absorb a transient failure of the provider that fits. If that provider returns a 503, the request fails instead of being sent to the smaller model, which might have held it. Because the estimate is approximate, a provider near the edge of its window may be skipped when it would have worked.
  • Pins and rules: a pinned model is never skipped; its provider decides whether the request fits (see contextWindowPinCheck below to check pins too). A provider that one of your own fallbackRules sends the request to is tried as usual, even if it was skipped earlier in the chain, except a pinned provider contextWindowPinCheck skipped, which comes back only with a different fallbackModel. The built-in default rules don't override a skip.
  • allowFallback: false: with allowFallback: false and no pinned model, if the first planned provider (for example a preferredProvider) is skipped, the request throws NoRouteError naming CONTEXT_WINDOW. Another provider is not substituted.
  • Input only: maxTokens is not checked, because providers differ on whether the requested output must also fit in the window.
  • Accuracy: the estimate leaves out tool definitions, images and redacted (encrypted) thinking. It undercounts text with more tokens per character, such as Chinese, Japanese or Korean, and overcounts text with fewer, such as heavily indented code. Models outside the catalog count as fitting. RoutingInfo.estimatedInputTokens reports the same estimate whether or not the option is on. The client llm.getRoutingInfo reports the first provider that wouldn't be skipped.

Switching to a larger model of the same provider

Set contextWindowModelSwitch: true to keep a provider whose planned model is too small, by sending the request to a larger model of its own instead. It is off by default, and it works with or without contextWindowRouting.

const llm = new LLMProviders({ cloudflare: { ai: env.AI }, nvidia: { apiKey }, preferredProvider: 'nvidia', contextWindowModelSwitch: true });
const response = await llm.generateResponse({ messages, inputTokenCount: 300_000 });
response.provider;            // 'nvidia'
response.model;               // 'meta/llama-4-maverick-17b-128e-instruct' (1M)
response.contextWindowSwitch; // { from: 'deepseek-ai/deepseek-v4-flash', to: 'meta/llama-4-maverick-17b-128e-instruct' }
  • When it switches: the provider's planned model can't hold the estimate (or your inputTokenCount).

  • Which model: the provider's highest-ranked catalog model that holds the estimate plus maxTokens. It must:

    • be active, not a deprecated compatibility model;
    • pass the same checks as any planned model (vision, tools, structured output; no retired, thinking-only or explicit-only models);
    • suit the use case the planned model was chosen for, or be tagged LONG_CONTEXT, so a plain request isn't moved onto a research-only model such as groq/compound;
    • for a reasoning.strict request, accept the effort exactly.

    The highest-ranked model isn't always the largest: a 100k-token request on NVIDIA goes to a 128k model, not the 1M one.

  • When nothing changes: the planned model already fits; the model is pinned (its provider decides); the planned model isn't in the catalog; or none of the provider's models fits.

  • With contextWindowRouting: the switch comes first, so a provider that switched isn't skipped. There is one exception: no switch is made when another provider that can be relied on right now, and that allowFallback: false doesn't remove from the chain, already has a fitting planned model with at least twice the target's window. That provider is skipped as usual, and the request goes to the larger model. Each provider is compared with its model as planned before any switch. With allowFallback: false, only the first provider remains, so it always switches when it can. With Workers AI configured, for example, a 100k-token request goes to its 1M-token model rather than to NVIDIA's 128k one.

  • How a switch is reported: as contextWindowSwitch: { from, to } on the response or StreamCompletion. It isn't set when a caller's fallbackRules entry sent another model. response.model and the client llm.getRoutingInfo show the switched model.

  • Where it applies: the response and streaming paths, and each turn of generateResponseWithTools, so a later turn can move to a larger model as tool results grow.

  • Cost: the larger model may cost much more per token. On Cerebras, for example, zai-glm-4.7 costs about 15 times as much per input token as gpt-oss-120b. The option is part of the response cache key when on.

  • Which providers it changes today:

    • Workers AI: it already plans a 1M-token model for every use case except RESEARCH, so only research requests switch.
    • NVIDIA: a plain request plans DeepSeek V4 Flash (64k) and moves to a 128k or 131k model, or to Llama 4 Maverick (1M) above that.
    • Cerebras: gpt-oss-120b (128k), or llama-3.1-8b for cost-effective requests, moves to zai-glm-4.7 (131k) for inputs that fit it.
    • Groq: has no larger model suited to general requests.

Checking pinned models

Set contextWindowPinCheck: true to check a pinned model (request.model) against its catalog context window before any call. It is off by default and independent of the two options above.

const llm = new LLMProviders({ cloudflare: { ai: env.AI }, contextWindowPinCheck: true });
try {
  await llm.generateResponse({ model: '@cf/meta/llama-3.3-70b-instruct-fp8-fast', messages, inputTokenCount: 30_000, allowFallback: false });
} catch (error) {
  if (error instanceof ContextWindowExceededError) {
    error.contextWindow;     // 24000
    error.inputTokens;       // 30000
    error.inputTokensSource; // 'caller' (your inputTokenCount), 'mixed' or 'estimate'
    error.reason;            // 'allowFallback-false' or 'no-other-provider'
  }
}
  • When the pin doesn't fit and nothing else may serve the request: the request throws ContextWindowExceededError and no call is made. That happens with allowFallback: false (reason: 'allowFallback-false'), and when no other provider with a planned model that holds the input can be called (reason: 'no-other-provider'): only one provider is configured; reasoning.strict or an image request removed the rest; the other providers' planned models are too small too (models outside the catalog count as fitting); or every provider that fits was skipped as unavailable (quota-exhausted, circuit open, ledger-limited) or, when streaming, unable to stream. The client getRoutingInfo throws it in the same cases. A quotaHook that denies the remaining provider still throws QuotaDeniedError, and a fallbackRules entry that would bring the pinned provider back on a larger model isn't considered here. model is the pinned model as sent, after any correction of an outdated model ID. It is a NoRouteError (code NO_ROUTE), so existing handling still catches it; its message names the model, window and token count but never the prompt.
  • Otherwise: the pinned provider is skipped as CONTEXT_WINDOW in fallback.failedAttempts, and so is every other provider whose planned model can't hold the input, with or without contextWindowRouting. The request then goes only to providers that fit; if none of them can be called (quota-exhausted, circuit open, ledger-limited), it throws ContextWindowExceededError as above. A provider skipped as too small can still be brought back by one of your own fallbackRules, as with contextWindowRouting. The trade-off is the same as for contextWindowRouting: if the provider that fits fails, for example with a 503 or 429, the request fails with its error instead of falling through to a smaller model that might have held it. One of your own fallbackRules that targets the pinned provider brings it back only when it names a different fallbackModel; a rule without one, or naming the pinned model (by any ID that resolves to it), is ignored, so the pinned model is never called. The different model is sent as is: it isn't checked, so make sure its window holds the input.
  • What counts: the input only, as for contextWindowRouting: your inputTokenCount when set, else the estimate. Pass inputTokenCount if a rejection based on the estimate would be a problem, since the estimate can be off near the edge of the window. inputTokensSource is 'mixed' when your count was combined with the package's estimate of what it added: the assistant turns and tool results of generateResponseWithTools, or a system prompt classify supplies.
  • Tool loops: each turn is checked. When tool results outgrow the pinned model, that turn throws ContextWindowExceededError if nothing else may serve it, after the tools of earlier turns have already run. Otherwise that turn and later ones fall back to another provider and model partway through the loop, which response.fallback reports; set allowFallback: false to keep a loop on the pinned model.
  • What isn't checked: pinned models outside the catalog, and unpinned requests.
  • Where it applies: the response and streaming paths, each turn of generateResponseWithTools, classify and analyzeImage (which pins the vision model it uses), and the client getRoutingInfo. The option is part of the response cache key when on.

Pinned models and allowFallback

A pinned model is tried first, but by default it is not a guarantee: on an eligible failure, or when the pinned provider is skipped (quota-exhausted, circuit open, ledger-limited), another provider and model can serve the request. fallbackRules: [] removes the rule-based fallbacks only; server errors, network errors, timeouts, schema drift and StructuredOutputUnsupportedError still fall back.

Set allowFallback: false on the request to forbid substitution entirely. Only the first planned provider is tried (the pinned model's provider) and its error is rethrown. NoRouteError is thrown if no configured provider can serve the pinned model, or if the pinned provider is skipped as quota-exhausted, circuit-open or ledger-limited; the message names the skip, for example cloudflare: QUOTA_EXHAUSTED. Without a pin, the same applies to the first planned provider, which with contextWindowRouting can also be skipped as too small for the input (CONTEXT_WINDOW). With contextWindowPinCheck, a pinned model too small for the input throws ContextWindowExceededError, a NoRouteError, before any call. With reasoning.strict and an effort, a pin on another configured provider (for example a Groq model) throws ReasoningEffortUnsupportedError; a pin no configured provider can serve still throws NoRouteError, because that check runs first. It applies to generateResponse, generateResponseWithTools and generateManagedResponseStream.

const response = await llm.generateResponse({
  model: '@cf/zai-org/glm-5.3-flash',
  messages,
  allowFallback: false,
});

When a substitution does happen, the response carries fallback, and so does StreamCompletion:

response.fallback;
// { requestedProvider: 'cloudflare', requestedModel: '@cf/zai-org/glm-5.3-flash',
//   failedAttempts: [{ provider: 'cloudflare', model: '@cf/zai-org/glm-5.3-flash', errorCode: 'TIMEOUT' }] }

normalizeLLMResponse() copies the failed attempts into routing.fallbackChain. requestedModel is the model planned before any fallback rule ran. A factory response-cache hit returns the stored response unchanged, including the fallback of the call that produced it, since the cached text is still the substitute's output.

Error Handling

Structured error classes for each failure mode:

import {
  RateLimitError,
  QuotaExceededError,
  AuthenticationError,
  CircuitBreakerOpenError,
  TimeoutError,
} from '@stackbilt/llm-providers';

try {
  await llm.generateResponse(request);
} catch (error) {
  if (error instanceof RateLimitError) {
    // Automatic retry already attempted; consider switching providers
  } else if (error instanceof CircuitBreakerOpenError) {
    // Provider is temporarily disabled
  } else if (error instanceof AuthenticationError) {
    // Check API key -- will NOT trigger fallback
  }
}

Model Constants

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

// Current-gen models
MODELS.CF_GLM_5_3_FLASH;        // '@cf/zai-org/glm-5.3-flash'
MODELS.CF_KIMI_K2_6;            // '@cf/moonshotai/kimi-k2.6'
MODELS.CF_GPT_OSS_120B;         // '@cf/openai/gpt-oss-120b'
MODELS.CF_GEMMA_4_26B;          // '@cf/google/gemma-4-26b-a4b-it'
MODELS.CLAUDE_SONNET_4_6;       // 'claude-sonnet-4-6'
MODELS.CLAUDE_HAIKU_4_5;        // 'claude-haiku-4-5-20251001'
MODELS.GPT_4O_MINI;             // 'gpt-4o-mini' (shutdown 2027-01-14)
MODELS.CLAUDE_OPUS_5_5;         // 'claude-opus-5-5' (explicit requests only)
MODELS.GPT_6_ASTRA;             // 'gpt-6-astra' (explicit requests only)
MODELS.CEREBRAS_ZAI_GLM_4_7;    // 'zai-glm-4.7'
MODELS.GROQ_COMPOUND;           // 'groq/compound' (RESEARCH; built-in tools)
MODELS.GROQ_COMPOUND_MINI;      // 'groq/compound-mini'
MODELS.NVIDIA_NEMOTRON_70B;     // 'nvidia/llama-3.1-nemotron-70b-instruct'
MODELS.NVIDIA_LLAMA_4_MAVERICK; // 'meta/llama-4-maverick-17b-128e-instruct'

// Get best active model for a use case given available providers
const model = getRecommendedModel('COST_EFFECTIVE', ['openai', 'cloudflare']);

Factory-Level Streaming

Factory streaming can fail over before the first text chunk on eligible provider failures. Authentication and configuration errors stop the request. After output begins, errors propagate to the caller without splicing another provider's answer into the stream.

All adapters decode byte SSE incrementally and read in response to consumer demand. Cancellation cancels the upstream reader and aborts HTTP fetches, including requests still waiting for headers. Workers AI binding calls do not expose an abort signal; if cancelled before the binding returns, the returned reader is cancelled as soon as it becomes available. Provider timeout covers opening the stream (until headers arrive or the binding returns); once output is flowing, long generations are not cut off. Set streamBodyTimeout on a provider for an opt-in total deadline that also covers the body; without it, a stream that opens but never sends a byte is not bounded (as in 1.21). Both deadlines start when the stream is first read, which is when the request is sent. Provider-level pre-output retries and a Workers runtime concurrency gate remain follow-up work.

Use the managed result when the request lifetime must include final accounting:

const { stream, completion } = await llm.generateManagedResponseStream(request);
ctx.waitUntil(completion);
await stream.pipeTo(new WritableStream({ write: text => console.log(text) }));
const result = await completion; // { outcome, emittedChars, usage, provider, model, fallback? }

provider and model name what served the stream, so streamed output can be checked against an allowlist the same way as generateResponse() results.

Do not await completion before consuming or cancelling the stream. Reported partial usage survives errors and cancellation; otherwise factory accounting retains the preflight cost estimate and marks it estimated. A stream that fails before producing output is charged only for usage the provider actually reported; estimates are not recorded, and the fallback provider that serves the request records its own usage. Quota recording is awaited. A settlement failure rejects completion (and is logged) but never errors text that was already delivered, so legacy generateResponseStream() callers are unaffected by a ledger outage; a settlement failure before output does not block fallback. For factory streams (managed or generateResponseStream()), onRequestEnd includes outcome and fires on success, error and cancellation once output has started; a provider that fails before output emits it only if it reported real usage, otherwise only onRequestError. Filter on outcome === 'success' to count successes. Streams are demand-driven, so a stream dropped without being read to the end or cancelled is never settled; cancellation leaves breaker health unchanged.

const stream = await llm.generateResponseStream({
  messages: [{ role: 'user', content: 'Tell me a story.' }],
  model: 'claude-haiku-4-5-20251001',
});

const reader = stream.getReader();
while (true) {
  const { done, value } = await reader.read();
  if (done) break;
  process.stdout.write(value); // string chunk
}

Tool-Use Loop

generateResponseWithTools owns the generateResponse → parse → execute → append → repeat cycle. It enforces iteration caps, cumulative cost limits, and abort-signal cancellation — no boilerplate needed on the caller side.

Set toolChoice to 'auto', 'none', 'required', or a named function constraint such as { type: 'function', function: { name: 'replace_in_file' } }. Named constraints must reference a tool in the request. A constrained tools array also acts as the execution allowlist: if a model hallucinates another tool name, the loop returns an unavailable-tool error to the model instead of invoking the executor. Cloudflare Workers AI continuations are translated to binding-safe plain string messages automatically.

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

const result = await llm.generateResponseWithTools(
  {
    messages: [{ role: 'user', content: 'What is 2 + 2 * 3?' }],
    tools: [{
      type: 'function',
      function: {
        name: 'calculate',
        description: 'Evaluate a math expression',
        parameters: { type: 'object', properties: { expr: { type: 'string' } }, required: ['expr'] }
      }
    }],
  },
  {
    execute: async (name, args) => {
      if (name === 'calculate') return eval((args as { expr: string }).expr);
      throw new Error(`Unknown tool: ${name}`);
    }
  },
  {
    maxIterations: 5,
    maxCostUSD: 0.10,
    onIteration: (iteration, state) => {
      // Return { abort: true, reason? } to stop the loop early and throw ToolLoopAbortedError.
      // Returning void (or nothing) continues to the next iteration.
      if (state.iteration >= 4) {
        return { abort: true, reason: 'found answer' };
      }
    },
  }
);

console.log(result.message); // final assistant response after tool execution

A failed tool call is sent back to the model as an error result carrying the error message, so the model can recover or explain the failure. Every provider carries the error. Anthropic puts it in the tool_result content with is_error: true; OpenAI, Groq, Cerebras and NVIDIA send { "output", "error" } JSON in the tool message; Workers AI includes it in its JSON tool-results message. A thrown string, or any thrown object with a non-blank message, is the error text; anything else is reported as Tool '<name>' failed without an error message, never as an empty success.

Anthropic. Claude 5.x models think by default, and Anthropic requires a tool-use turn's thinking blocks to be sent back complete and unmodified. An Anthropic response that calls tools therefore carries providerContent: the turn's content blocks (thinking with signatures, redacted_thinking, text, tool_use), in the order Claude returned them. generateResponseWithTools copies it onto the assistant message, and the Anthropic provider sends it back verbatim. Other providers ignore the field.

If you run the loop yourself, set providerContent on the assistant message from the response and don't edit it. When it is set, the provider sends it instead of the message's content and toolCalls: an edit made only to content, such as redacting or clearing text, is not sent (the provider logs a warning when content differs from the replayed text, including when content is blank). To change the turn, drop providerContent so the turn is rebuilt from content and toolCalls, at the cost of its thinking.

  • When it is set: only on responses that call tools, the turns whose thinking Anthropic requires back, so thinking from a final answer is not carried into later turns. It is left unset, and the turn is rebuilt instead, when a tool_use block fails validation (the call is dropped from toolCalls), when a thinking block has no signature, and on JSON-prefill responses, whose text starts after the prefilled {.
  • When replaying: content with no blocks, a user-turn block type (tool_result, image, document, search_result), a tool_use block without an id, name or input, a thinking block without a signature or string thinking text, a redacted_thinking block without data, or a text block without string text throws ConfigurationError before the call, so it isn't recorded in the provider's metrics or circuit breaker (the factory still logs it, fires onRequestError and reports the failed attempt); other block types pass through unchanged. If the tool_use ids no longer match the message's toolCalls, the turn is rebuilt. The shape is checked first, so malformed content throws even when the ids no longer match.
  • Cache: the factory response cache applies the same checks and treats a failing entry as a miss. Cache keys now start with llmp:v3:, so entries written by 1.24.x or earlier, which lack providerContent, are not reused.

Built-in Tools (Server-Side)

Some models run tools server-side — the provider executes web search, code interpretation, etc. inside a single completion call, no execute callback required. Set LLMRequest.builtInTools with normalized identifiers; the adapter translates to each model family's native wire shape and rejects unsupported combinations at the boundary.

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

const llm = LLMProviders.fromEnv(env);
const res = await llm.generateResponse({
  model: MODELS.GROQ_COMPOUND,                 // 'groq/compound'
  messages: [{ role: 'user', content: 'Find authoritative sources on topic X.' }],
  builtInTools: [{ type: 'web_search' }],
});

Normalized identifiers: web_search, visit_website, browser_automation, code_interpreter, wolfram_alpha.

Model Built-in tools Wire shape
groq/compound, groq/compound-mini all five compound_custom.tools.enabled_tools (identifiers verbatim)
openai/gpt-oss-120b (Groq) web_search, code_interpreter OpenAI-style tools: [{ type }], web_search → browser_search
all other models — rejected with ConfigurationError naming the capable models

Notes:

  • Capability-aware routing. openai/gpt-oss-120b is hosted by both Cerebras and Groq; only Groq runs built-in tools, so a builtInTools request is steered to Groq automatically. Plain requests keep the default routing.
  • Provenance. The Compound systems are tagged RESEARCH-only in the catalog and are not auto-selected for generic use cases — pin the model (or request the RESEARCH use case) to use them, since selecting a Compound model can incur per-search surcharges.
  • Cost. Built-in tool surcharges (e.g. web search ~$5/1k requests) are billed by the provider and are not attributed per-call in TokenUsage; track them via CreditLedger if needed.
  • Citations. Structured search results surface on LLMResponse.metadata.builtInToolResults — Array<{ type, name?, arguments?, results: [{ title, url, content, score }] }>. Only executions that ran a web search appear (e.g. code_interpreter runs, which carry no citations, are omitted); the field is absent when no search ran. The model often runs several searches in one call, so builtInToolResults is an array of executions — iterate all of them (don't read only [0]) to get the full citation set. Citation sub-fields are passed through as the provider returns them — treat them as best-effort and validate URLs before use. score is the provider's retrieval-relevance score, not an authority/quality ranking. Note also that the response content is the model's synthesized answer (it may cite a curated subset), while builtInToolResults holds the raw retrieved hits — they are different sets.
  • Reasoning. When the model exposes internal reasoning or thinking text, it surfaces on LLMResponse.reasoning as a string and is removed from LLMResponse.message. metadata.reasoning remains as a compatibility mirror where providers already exposed it. Absent when the model doesn't emit it.
  • Streaming. builtInTools is accepted on streaming requests and the search still runs server-side, but the streaming path emits content deltas only — structured metadata.builtInToolResults and reasoning are not surfaced while streaming. Use non-streaming generateResponse when you need the structured citations.
// Flatten across all executions — the model may run several searches per call.
const citations = (res.metadata?.builtInToolResults ?? []).flatMap(exec => exec.results);
// → [{ title, url, content, score }, …]

Prompt Cache Hints

Pass a provider-agnostic cache hint on any request. The library translates it to the appropriate provider-native mechanism.

const response = await llm.generateResponse({
  messages: [{ role: 'user', content: 'Summarize the context.' }],
  systemPrompt: 'You are an expert at analyzing long documents. [... 10KB of stable context ...]',
  model: 'claude-haiku-4-5-20251001',
  cache: {
    strategy: 'provider-prefix',   // mark the stable prefix for caching
    cacheablePrefix: 'auto',       // cache system prompt + tools (default)
  },
});

// Cached token counts are normalized in TokenUsage
console.log(response.usage.cacheReadInputTokens);    // Anthropic cache hit tokens
console.log(response.usage.cacheWriteInputTokens);   // Anthropic cache create/write tokens
console.log(response.usage.cachedInputTokens);       // OpenAI / Groq / Cerebras cache hit tokens
console.log(response.cache?.providerPrefix);         // Normalized cache observability

Cloudflare Workers AI prefix caching uses the same cache hint. When strategy is 'provider-prefix' or 'both', sessionId is sent to the Workers AI binding as x-session-affinity so repeated agent turns can route to the same model instance.

const llm = new CloudflareProvider({
  ai: env.AI,
  gateway: {
    id: 'default',
    skipCache: false,
  },
});

const response = await llm.generateResponse({
  messages: [{ role: 'user', content: 'Summarize the next patch.' }],
  systemPrompt: stableAgentInstructions,
  model: '@cf/openai/gpt-oss-120b',
  cache: {
    strategy: 'both',
    sessionId: 'agent:repo-123',
  },
  gatewayMetadata: {
    cacheKey: 'summary:repo-123:patch-456',
    cacheTtl: 300,
  },
});

console.log(response.usage.cachedInputTokens);
console.log(response.cache?.aiGateway?.status);      // HIT / MISS when the binding exposes it
Strategy Behavior
'off' No cache opt-in hints; bypass factory response-cache reads/writes
'provider-prefix' Provider prefix hints; bypass factory response caching
'response' Factory response caching when an adapter exists; AI Gateway controls remain in GatewayMetadata
'both' Provider prefix hints plus response policy; layers remain separately configured

Cache Observability and Cold/Warm Canaries

Every LLMResponse can carry response.cache, and factory-managed calls also pass the same object to observability hooks:

const llm = new LLMProviderFactory({
  cloudflare: { ai: env.AI, gateway: { id: 'default' } },
  responseCache: kvBackedResponseCache,
  responseCacheNamespace: 'my-app:v1',
  hooks: {
    onCache: event => console.log(event.layer, event.status, event.cache),
    onRequestEnd: event => console.log(event.cache),
  },
});

Factory response caching is opt-in through responseCache. Keys are versioned SHA-256 hashes of the semantic request, including tenant, system instructions, tools, images, sampling, metadata, provider transport options, and routing policy. Set responseCacheNamespace to separate applications, AI bindings, and policy revisions sharing a store. Custom cache.key values remain scoped by tenant and namespace. Version 2 keys ignore older entries, so the first requests after upgrading will miss the cache.

cache.strategy: 'off' and 'provider-prefix' bypass factory reads and writes; 'response' and 'both' enable them when an adapter is configured. Without a strategy, the configured adapter retains its default behavior. Circular or non-JSON metadata bypasses response caching. Request IDs and gateway tracing/cache controls are excluded from identity; custom gateway metadata is included conservatively.

Cache hits retain original provider usage for historical context and set cache.factory.usageKind: 'historical' and currentChargeUsd: 0. They do not record a new provider charge. quotaHook.check gates cached access too, with estimated new spend of zero. A local denial throws QuotaDeniedError and stops the request without fallback or provider exhaustion. quotaFailPolicy still controls quota-service failures. CreditLedger remains local spend analytics and a routing signal; these checks do not reserve concurrent spend or enforce a hard budget.

Use separate canaries for the two Cloudflare cache layers:

// Workers AI prefix-cache canary: same static prefix, same sessionId, new user tail.
const prefixCold = await llm.generateResponse({
  systemPrompt: stableAgentInstructions,   // no timestamps or per-request IDs
  tools: stableToolDefinitions,            // keep tool schemas byte-stable
  messages: [{ role: 'user', content: 'Summarize patch A.' }],
  model: '@cf/openai/gpt-oss-120b',
  cache: { strategy: 'provider-prefix', sessionId: 'agent:repo-123' },
});

const prefixWarm = await llm.generateResponse({
  systemPrompt: stableAgentInstructions,
  tools: stableToolDefinitions,
  messages: [{ role: 'user', content: 'Summarize patch B.' }],
  model: '@cf/openai/gpt-oss-120b',
  cache: { strategy: 'provider-prefix', sessionId: 'agent:repo-123' },
});

console.log(prefixCold.cache?.providerPrefix, prefixWarm.cache?.providerPrefix);
// AI Gateway response-cache canary: repeat the exact request and cache key.
const gatewayRequest = {
  systemPrompt: stableAgentInstructions,
  messages: [{ role: 'user', content: 'Summarize this exact patch.' }],
  model: '@cf/openai/gpt-oss-120b',
  cache: { strategy: 'response' as const },
  gatewayMetadata: { cacheKey: 'summary:repo-123:patch-456', cacheTtl: 300 },
};

const responseCold = await llm.generateResponse(gatewayRequest);
const responseWarm = await llm.generateResponse(gatewayRequest);

console.log(responseCold.cache?.aiGateway?.status, responseWarm.cache?.aiGateway?.status);

For prefix caching, keep static content first: system instructions, tool schemas, and long reusable context. Do not put timestamps, request IDs, or dynamic user content in the cacheable prefix; append per-request content at the end. For response caching, repeat the exact request and gatewayMetadata.cacheKey; this is a full-response cache, not a prefix optimization.

Schema Drift Canary

Use the canary utilities to compare a live provider response against a committed golden fixture and detect API shape drift before it reaches production.

import {
  extractShape, compareShapes, runCanaryCheck
} from '@stackbilt/llm-providers';

// 1. Load your committed golden fixture (flat path → type map)
import goldenShape from './fixtures/openai.json';

// 2. Fetch a raw response from the provider (your responsibility)
const liveResponse = await fetch('https://api.openai.com/v1/chat/completions', ...).then(r => r.json());

// 3. Check for drift
const report = runCanaryCheck('openai', goldenShape, liveResponse);

if (report.status === 'drift') {
  console.error('OpenAI response shape changed!', report.diff);
  // diff.added   — new fields (additive, usually safe)
  // diff.removed — missing fields (breaking, alert immediately)
  // diff.changed — type-changed fields (breaking, alert immediately)
}

Generate your initial golden fixture from a known-good response:

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

const shape = extractShape(knownGoodResponse);
fs.writeFileSync('fixtures/openai.json', JSON.stringify(shape, null, 2));

API Reference

Core Classes

Class Description
LLMProviders High-level facade -- initialize providers, generate responses, check health
LLMProviderFactory Lower-level factory with provider chain building, catalog-based routing, and fallback logic
OpenAIProvider OpenAI GPT models (streaming, tools)
AnthropicProvider Anthropic Claude models (streaming, tools)
CloudflareProvider Cloudflare Workers AI (streaming, tools on Kimi/GLM/GPT-OSS/Gemma 4/Llama 4, batch)
CerebrasProvider Cerebras fast inference (streaming, tools on GLM/Qwen)
GroqProvider Groq fast inference (streaming, tools on GPT-OSS/LLaMA 3.3 70B; server-side built-in tools on Compound systems and GPT-OSS)
NvidiaProvider NVIDIA NIM inference (streaming, tools on Llama/Nemotron/Mistral)
BaseProvider Abstract base with shared resiliency, metrics, and cost calculation
QuotaDeniedError Terminal local-policy denial; no fallback or provider exhaustion. Extends QuotaExceededError (code QUOTA_EXCEEDED) for 1.x compatibility; check instanceof QuotaDeniedError or localPolicy to tell it apart from vendor exhaustion
NoRouteError No configured route available; a nonretryable configuration error
ContextWindowExceededError With contextWindowPinCheck, a pinned model too small for the input when nothing else may serve the request. Extends NoRouteError (code NO_ROUTE); carries modelProvider, model, contextWindow, inputTokens, inputTokensSource and reason
ReasoningEffortUnsupportedError reasoning.strict can't be honoured: the model can't take the effort exactly, or no Cloudflare provider can serve the request. Extends InvalidRequestError; never triggers fallback

Utilities

Class / Export Description
CircuitBreaker Graduated 4-state circuit breaker with probabilistic degradation
CircuitBreakerManager Manages and serializes circuit breakers across multiple providers
ResilienceContext Explicitly owned/shared breakers, exhaustion, latency and factory cost analytics
RetryManager Exponential backoff retry with jitter
CostTracker Per-provider cost accumulation and budget alerts
CreditLedger Monthly budgets, rate limits, burn rate projection, threshold events
CostOptimizer Static methods for optimal provider selection
MODEL_CATALOG Declarative model metadata for routing and recommendation
ImageProvider [Deprecated] Multi-provider image generation — use img-forge instead
extractShape Walk a raw API response into a flat path → type shape map
compareShapes Diff two shape maps into { added, removed, changed }
runCanaryCheck One-shot canary: extract live shape, compare against golden, return CanaryReport
validateSchema Low-level envelope validator (for custom provider authors)

Logger

Export Description
Logger Interface: debug, info, warn, error methods
noopLogger Silent logger (default)
consoleLogger Forwards to console.* (opt-in)

Key Types

Type Description
LLMRequest Unified request: messages, model, temperature, tools, toolChoice, builtInTools, response_format, cache, lora
LLMResponse Unified response: message, optional reasoning, usage (with cost and optional reasoning tokens), provider, tool calls, providerContent, lengthCause, reasoningEffort, fallback, metadata (builtInToolResults)
ProviderContent { provider, blocks }: a turn's provider-native content blocks, replayed unchanged on LLMMessage.providerContent in tool loops (Anthropic)
BuiltInTool / BuiltInToolType Server-side tool request: { type } where type is web_search | visit_website | browser_automation | code_interpreter | wolfram_alpha
BuiltInToolResult A surfaced built-in execution: { type, name?, arguments?, results: [{ title, url, content, score }] } on metadata.builtInToolResults
TokenUsage Token counts, compatible cost, explicit costProvenance / tokenProvenance, and cached token fields
ImageAnalysisAttemptEvent Sanitized per-provider-attempt usage, image-byte, latency, retry/fallback, and error telemetry
ImageAnalysisCompleteEvent Terminal image-analysis aggregate with total attempts, tokens, latency, cost buckets, and final route
CacheHints Cache strategy, key, ttl, sessionId, cacheablePrefix for provider-agnostic prompt caching
ToolExecutor Interface for generateResponseWithTools: execute(name, args) => Promise<unknown>
ToolChoice Caller-defined tool constraint: auto, none, required, or a specific named function
ToolLoopOptions Loop config: maxIterations, maxCostUSD, onIteration, abortSignal
ToolLoopAbortSignal { abort: true; reason?: string } — return from onIteration to stop the loop and throw ToolLoopAbortedError
RoutingInfo Pre-flight routing snapshot: useCase, provider, model, estimatedInputTokens, lifecycle, deprecationWarning
ManagedTextStream / StreamCompletion Text stream plus awaited terminal accounting; outcome, emitted characters, usage, serving provider and model, and fallback when substituted
GatewayRoutePlan Gateway diagnostics and cache/capability reports; executable: false marks failed capability checks or a host outside availableProviders
ModelWorkloadClass Gateway-friendly workload class: summary, planning, code_draft, long_context, tool_loop, vision, research, cost_effective, balanced, high_performance
ModelPreferenceMap Optional provider+workload override map for workload-aware recommendation APIs
CircuitBreakerSnapshot / CircuitBreakerManagerSnapshot Serializable reliability state for external persistence
CanaryReport Schema canary result: provider, status ('ok'
ShapeMap Flat path → JSON-type map produced by extractShape
ProviderFactoryConfig Provider/routing settings, ledger, hooks, response cache/namespace, stateScope and shared context
CostAnalytics Cost breakdown, total, and recommendations
ProviderHealthEntry Health status, metrics, circuit breaker state, capabilities
ModelCatalogEntry Declarative model metadata: provider, lifecycle, capabilities, use cases

Factory Functions

Function Description
createLLMProviders(config) Create an LLMProviders instance
createCostOptimizedLLMProviders(config) Create with cost optimization, circuit breakers, and retries enabled
LLMProviders.fromEnv(env) Auto-discover providers from environment variables
llm.generateResponse(request) Generate a response with provider selection and fallback
llm.generateResponseStream(request) Streaming generation; fallback chain active before first chunk
llm.generateManagedResponseStream(request) String stream and a completion promise covering terminal accounting
llm.getRoutingInfo(request) Preflight snapshot from the client's actual planner and admission state
normalizeCanonicalRequest(request) Explicit canonical input normalization, including metadata-only identity
normalizeLegacyRequest(request) Explicit conversion of legacy input; nested metadata remains custom data
llm.generateResponseWithTools(request, executor, opts?) Managed tool-use loop with caps and abort-signal support
llm.getRecommendedModel(request, useCase?) Runtime recommendation using configured providers, health, and ledger state
getRecommendedModel(useCase, providers, context?) Pick the best active model for a use case
getRecommendedModelForWorkload(workload, providers, context?) Pick a model using gateway-friendly workload classes like summary, planning, code_draft, long_context, tool_loop
getProviderDefaultModelForWorkload(provider, workload, context?) Provider-scoped workload default with optional modelPreferences overrides
getRoutingInfo(request, providers?, context?) Pre-flight routing snapshot — use case, model, lifecycle, deprecation warning — without dispatching
runCanaryCheck(provider, golden, liveResponse) Compare live response shape against golden fixture
extractShape(obj) Extract flat path → type map from any object
retry(fn, config) One-shot retry wrapper for any async function

Security

@stackbilt/llm-providers treats supply chain security as a first-class concern:

  • Zero runtime dependencies. The published tarball contains only compiled source and the Apache-2.0 license — no transitive dependency tree to audit or compromise.
  • npm provenance attestation. Every published version is cryptographically linked to the exact GitHub commit and CI workflow that built it. Verify on the npm registry page under "Provenance."
  • CI-only OIDC publishing. Releases are published exclusively through GitHub Actions with short-lived OIDC tokens. No long-lived npm publish credentials exist.
  • SHA-pinned Actions. Every workflow step references a full commit SHA, not a mutable tag. A compromised v4 tag cannot inject code into this workflow.
  • SBOM on every commit. The supply chain workflow generates a Software Bill of Materials artifact (sbom-{sha}) on every push to main, retained for 90 days.
  • Dependency review on every PR. Pull requests are blocked if any newly introduced dependency has a known vulnerability or an incompatible license.
  • --ignore-scripts on install. CI and publish both run npm ci --ignore-scripts, preventing install-time script execution from dev dependencies.
  • npm audit on every build. Vulnerabilities in dev dependencies are caught before tests run and before publish.

See SECURITY.md for the full security policy and vulnerability reporting.

License

Apache-2.0


Built by Stackbilt.

About

Multi-LLM failover with circuit breakers, cost tracking, and intelligent retry. Cloudflare Workers native.

Resources

Contributing

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Used by

Contributors

Languages