Open SourceApache-2.0 License

ai-prod-guard

Production guard for AI workloads — hard spend caps, intelligent retries, automatic provider failover, and health tracking, for deployed services.

How it works

ai-prod-guard wraps your existing provider calls with a single createRuntimeGuard() instance that enforces limits before each request goes out — for AI businesses that need runtime protection across multiple services.

1

Cost caps checked first

Per-request and per-session spend limits are enforced before the network call is made, so a runaway retry loop can't spiral into a surprise bill.

2

Retry with backoff

429, 408, and 5xx errors are retried automatically with Retry-After and exponential backoff, up to maxRetries.

3

Fallback and health tracking

On exhausted retries or a non-retryable error (401, 403), the guard switches to the next fallback provider and marks the failed one unhealthy until it auto-recovers.

1

Install

Terminal
npm install ai-prod-guard

Requires Node.js 18+. TypeScript library, no CLI.

2

Usage

Configure a primary and fallback providers, then call guard.call() instead of calling the provider SDK directly.

index.ts
import { createRuntimeGuard } from "ai-prod-guard";

const guard = createRuntimeGuard({
  maxCostPerRequest: 1.0,
  maxCostPerSession: 50.0,
  maxRetries: 3,
  primaryProvider: {
    name: "openai",
    call: (req, signal) => openai.chat.completions.create(req, { signal }),
    estimateCost: () => 0.03,
  },
  fallbackProviders: [
    {
      name: "anthropic",
      call: (req, signal) => anthropic.messages.create({ ...req, signal }),
      estimateCost: () => 0.02,
    },
  ],
});

const response = await guard.call((provider, signal) =>
  provider.call(
    { model: "gpt-4o", messages: [{ role: "user", content: "Generate report" }] },
    signal
  )
);

Example output

guard.getSpendSummary()
const { confirmedUsd, potentialUsd, totalExposureUsd } = guard.getSpendSummary();
// confirmedUsd: successfully completed calls (definitely billed)
// potentialUsd: timed out or disconnected calls (may have billed)
// totalExposureUsd: confirmed + potential + in-flight

console.log(`Confirmed: $${confirmedUsd}, Potential: $${potentialUsd}`);

What's included

Per-request and per-session hard spend caps, checked before network calls
Automatic retries for 429/408/5xx with Retry-After and exponential backoff
Automatic fallback to backup providers in order
Per-instance provider health tracking with auto-recovery interval
Timeout enforcement via Promise.race + AbortSignal
Confirmed vs potential spend accounting, never merged
Event hooks: onRetry, onFallback, onLimitHit
Concurrent-safe spend caps via atomic reservation
View on GitHub →

Ready to try ai-prod-guard?

npm install ai-prod-guard — no account needed to get started.