Architectures
AI Vibe CodingIntermediate93% · Ready

Fast/Slow Model Tiered Routing SDK: Dynamic Model Selection by Task Complexity with Hard Monthly Budget Circuit Breaker

A TypeScript SDK for the Vibe Coding toolchain that automatically routes tasks based on tier complexity and enforces a hard monthly budget circuit breaker. Overall completion score: 93/100.

Est. time: 50 minUpdated: 2026-11-26
TypeScript SDKTask ClassifierBudget BreakerTelemetry
Fast/Slow Model Tiered Routing SDK: Dynamic Model Selection by Task Complexity with Hard Monthly Budget Circuit Breaker

Completion Score

Overall completion score: 93/100. Tiered routing, cost prediction, and failover have a production-ready skeleton. AI is efficient in classification and cost estimation. Automatic escalation and reruns for low-scoring results (score 86) still require manual calibration of thresholds and rerun strategies, which is the main area for optimization.

93%Ready

Dimension breakdown

Precise three-tier routing for Light/Standard/Flagship95%

Three model tiers and fallbacks are declaratively configured. The router resolves and validates by tier. Routing logic is clear and testable.

Per-request cost limits and daily budget hard circuit breaker96%

BudgetBreaker checks the budget before requests and records consumption. On circuit break, it falls back to the lightweight tier. Hard constraints are clearly defined.

Seamless switching to backup pool on single provider failure92%

Each tier configures a fallbackModelId. The router falls back on budget or failure issues. However, real fault injection tests still need to be added.

Automatic escalation and rerun mechanism for low-scoring results86%

The routing layer reserves an upgrade path, but low-score determination and rerun strategies are not yet implemented. Thresholds require manual calibration.

Human checkpoint

Before deployment, manually review the three model tier IDs, per-request cost limits, and daily budget thresholds. Ensure the circuit breaker reset and alerting logic complies with business SLAs.

Upgrade / downgrade path

Can be upgraded to multi-provider dynamic weighting and real-time cost write-back, or integrate Redis for shared circuit breaker state. If budget or hardware is limited, downgrade to lightweight tier only + fixed backup model, retaining circuit breaking and logging.

When to use & prerequisites

Target users are engineering teams building AI applications and Vibe Coding toolchains with TypeScript. Environment requirements include Node.js 18+, TypeScript 5+, zod validation, and observability integration. Typical scenarios involve unified scheduling of multi-tier tasks such as classification/summarization, code generation, architecture design, and critical code review.

Ready-to-copy configs

src/llm/tier-router.tstypescript

分层路由核心:按任务档位选择模型、估算成本、执行预算熔断与故障切换。

import { z } from 'zod';

export type Tier = 'light' | 'standard' | 'flagship';

const TierSchema = z.enum(['light', 'standard', 'flagship']);

export interface ModelTierConfig {
  tier: Tier;
  modelId: string;
  fallbackModelId?: string;
  maxCostPerRequestUsd: number;
  dailyBudgetUsd: number;
  timeoutMs: number;
}

export interface RouteDecision {
  tier: Tier;
  modelId: string;
  fallbackModelId?: string;
  estimatedCostUsd: number;
  reason: string;
}

export class BudgetBreaker {
  private spentToday = 0;
  constructor(private dailyBudgetUsd: number) {}
  canSpend(amount: number): boolean {
    return this.spentToday + amount <= this.dailyBudgetUsd;
  }
  record(amount: number): void {
    this.spentToday += amount;
  }
  reset(): void {
    this.spentToday = 0;
  }
}

export function routeModel(taskTier: Tier, config: ModelTierConfig, budget: BudgetBreaker): RouteDecision {
  const tier = TierSchema.parse(taskTier);
  const estimatedCostUsd = config.maxCostPerRequestUsd * 0.8;
  if (!budget.canSpend(estimatedCostUsd)) {
    return { tier: 'light', modelId: config.fallbackModelId ?? config.modelId, estimatedCostUsd: 0, reason: 'budget_exceeded_fallback_to_light' };
  }
  return { tier, modelId: config.modelId, fallbackModelId: config.fallbackModelId, estimatedCostUsd, reason: 'tier_selected' };
}
config/model-tiers.jsonjson

三档模型与预算参数的声明式配置,供路由器与熔断器读取。

{
  "tiers": {
    "light": {
      "modelId": "MODEL_ID_LIGHT",
      "fallbackModelId": "MODEL_ID_LIGHT_FALLBACK",
      "maxCostPerRequestUsd": 0.01,
      "dailyBudgetUsd": 5,
      "timeoutMs": 8000
    },
    "standard": {
      "modelId": "MODEL_ID_STANDARD",
      "fallbackModelId": "MODEL_ID_LIGHT",
      "maxCostPerRequestUsd": 0.05,
      "dailyBudgetUsd": 20,
      "timeoutMs": 15000
    },
    "flagship": {
      "modelId": "MODEL_ID_FLAGSHIP",
      "fallbackModelId": "MODEL_ID_STANDARD",
      "maxCostPerRequestUsd": 0.25,
      "dailyBudgetUsd": 50,
      "timeoutMs": 30000
    }
  },
  "budget": {
    "dailyLimitUsd": 75,
    "alertThresholdRatio": 0.8
  }
}

AI Vibe Coding in 4 steps

  1. 1

    Build the tiered routing skeleton

    Goal: Establish the TypeScript skeleton for routeModel and BudgetBreaker.

    Prompt
    Generate src/llm/tier-router.ts based on these requirements: Define Tier types (light/standard/flagship), ModelTierConfig interface, BudgetBreaker class (canSpend/record/reset), and routeModel function (resolve by tier, estimate cost, circuit break fallback). Use zod to validate tiers. Do not hardcode keys.

    Verify: Run `npx tsc --noEmit` with no type errors, and use unit tests to verify that routeModel falls back to the light tier when the budget is exceeded.

  2. 2

    Declaratively configure three model tiers

    Goal: Use config/model-tiers.json to declare three model tiers and budget parameters.

    Prompt
    Generate config/model-tiers.json containing modelId, fallbackModelId, maxCostPerRequestUsd, dailyBudgetUsd, timeoutMs for tiers.light/standard/flagship, as well as budget.dailyLimitUsd and alertThresholdRatio. Use environment variable placeholders for all model IDs. Do not write real keys.

    Verify: Use `node -e "console.log(require('./config/model-tiers.json').tiers.light.modelId)"` to confirm the JSON is parseable and fields are complete.

  3. 3

    Integrate task classification and cost estimation

    Goal: Connect the task classifier and cost estimator to the routing layer.

    Prompt
    Add a classifyTask(input) function in tier-router.ts that returns light/standard/flagship tiers based on input length and keywords (e.g., 'architecture', 'code'). Use estimated costs instead of fixed values in routeModel. Keep zod validation and budget circuit breaker logic unchanged.

    Verify: Use `npm test -- tier-router` to verify the classifier returns correct tiers for typical inputs, and that cost estimation varies by tier.

  4. 4

    Add failover and low-score escalation reruns

    Goal: Implement single provider failover and automatic escalation/rerun for low-scoring results.

    Prompt
    Add fallback logic in tier-router.ts: When the primary model call fails or returns a low score, automatically switch to fallbackModelId and rerun once. If it still fails, return degraded results and record telemetry. Use zod to validate responses. Do not swallow errors.

    Verify: Use fault injection tests (e.g., mock primary model throwing an error) to verify that fallback is called and reruns once, and confirm telemetry logs include tier and fallback markers.

Pitfalls & fixes

  • Pitfall 1: Hardcoded model IDs or keys cause leaks. Fix: Use environment variable placeholders for all model IDs and keys, and scan in CI.
  • Pitfall 2: Circuit breaker state not persisted causes budget invalidation after restarts. Fix: Write spentToday to Redis or persistent storage, and restore on process startup.
  • Pitfall 3: Low-score thresholds too strict cause frequent escalation reruns, increasing costs. Fix: Calibrate thresholds using manually annotated samples, and limit daily escalation counts.

FAQ

How to ensure the circuit breaker shares budget state across multiple instances?

Write BudgetBreaker's spentToday to Redis or shared storage, and use atomic operations during canSpend/record. Restore from storage on process startup to avoid independent counting per instance leading to budget overrun.

Does automatic escalation/rerun for low-scoring results significantly increase costs?

Yes, so limit daily escalation counts and per-request cost limits. Recommend calibrating low-score thresholds using manually annotated samples, and record escalation consumption in the circuit breaker to avoid escalation loops.

How to gracefully degrade when budget is limited?

When budget is exceeded, the router falls back to the light tier or fixed backup model, and records degradation events. The business layer should clearly mark degraded results to avoid misuse of low-quality output.

Related blueprints

Fast/Slow Model Tiered Routing SDK: Dynamic Model Selection by Task Complexity with Hard Monthly Budget Circuit Breaker · OpenAICN