swooshexamples

Examples

13 runnable scripts that exercise swoosh end to end. They run offline with simulated providers — no API keys — so you can read, run, and tweak them immediately. From the repo root: bun packages/model-router/examples/<file>.

01 Quickstart

Route a support ticket to the best available model and get structured output.

bun packages/model-router/examples/01-quickstart.ts · View source ↗

// Route a support ticket to the best available model and get structured output.
// Run from the repo root: bun packages/model-router/examples/01-quickstart.ts
import {
  createCallbackProviderAdapter,
  createStaticCapabilityCatalog,
  ModelRouter,
} from "@swoosh-dev/router";
import { exampleCatalog } from "./shared/catalog";
import { printAttempts, printPlan } from "./shared/print";

interface Triage {
  category: "billing" | "bug" | "how-to";
  urgency: "low" | "high";
}

// Simulated providers. Swap these for createAiSdkProviderAdapter in a real app.
const providers = [
  createCallbackProviderAdapter({
    providerId: "google",
    generateObject: () => ({ category: "billing", urgency: "high" }) satisfies Triage,
  }),
  createCallbackProviderAdapter({
    providerId: "anthropic",
    generateObject: () => ({ category: "billing", urgency: "high" }) satisfies Triage,
  }),
];

const router = new ModelRouter({
  catalog: createStaticCapabilityCatalog(exampleCatalog),
  providers,
  defaultPreference: "balanced",
});

const ticket = "I was charged twice for my subscription this month. Please fix this today.";

const result = await router.run<string, Triage>({
  task: "support.triage",
  input: ticket,
  prompt: `Classify this support ticket: ${ticket}`,
  inputModalities: ["text"],
  requiresFeatures: ["structured_output"],
});

printPlan(result.plan);
printAttempts(result.attempts);
console.log("output     ", result.output);

02 Cost guardrails

Summarize a long document with a hard budget. Models whose estimated cost exceeds maxCostUsd are rejected at planning time, before any tokens are spent.

bun packages/model-router/examples/02-cost-guardrails.ts · View source ↗

// Summarize a long document with a hard budget. Models whose estimated cost
// exceeds maxCostUsd are rejected at planning time, before any tokens are spent.
// Run from the repo root: bun packages/model-router/examples/02-cost-guardrails.ts
import {
  createCallbackProviderAdapter,
  createStaticCapabilityCatalog,
  ModelRouter,
} from "@swoosh-dev/router";
import { exampleCatalog } from "./shared/catalog";
import { printPlan } from "./shared/print";

const router = new ModelRouter({
  catalog: createStaticCapabilityCatalog(exampleCatalog),
  providers: ["google", "anthropic", "openai", "mistral", "local"].map((providerId) =>
    createCallbackProviderAdapter({ providerId }),
  ),
});

const plan = await router.plan({
  task: "report.summarize",
  input: "(a 400-page incident report)",
  inputModalities: ["text"],
  requiresFeatures: ["structured_output"],
  estimatedInputTokens: 150_000,
  estimatedOutputTokens: 4_000,
  preference: "cheapest",
  constraints: { maxCostUsd: 0.1 },
});

// claude-opus-4-8 is rejected: 150k input tokens at $15/M already costs $2.25.
// gpt-4o and mistral-large are rejected on context window, not cost.
printPlan(plan);

03 Multimodal routing

Extract line items from a photographed receipt. Declaring image input automatically filters out text-only models — no manual model lists.

bun packages/model-router/examples/03-multimodal-routing.ts · View source ↗

// Extract line items from a photographed receipt. Declaring image input
// automatically filters out text-only models — no manual model lists.
// Run from the repo root: bun packages/model-router/examples/03-multimodal-routing.ts
import {
  createCallbackProviderAdapter,
  createStaticCapabilityCatalog,
  ModelRouter,
} from "@swoosh-dev/router";
import { exampleCatalog } from "./shared/catalog";
import { printPlan } from "./shared/print";

interface Receipt {
  merchant: string;
  totalCents: number;
  lineItems: { label: string; cents: number }[];
}

const router = new ModelRouter({
  catalog: createStaticCapabilityCatalog(exampleCatalog),
  providers: ["google", "anthropic", "openai", "mistral", "local"].map((providerId) =>
    createCallbackProviderAdapter({
      providerId,
      // images arrive as a first-class field — no metadata smuggling.
      generateObject: (request) => {
        console.log(`  ${providerId} received ${request.images?.length ?? 0} image(s)`);
        return {
          merchant: "Blue Bottle Coffee",
          totalCents: 1250,
          lineItems: [
            { label: "Latte", cents: 650 },
            { label: "Croissant", cents: 600 },
          ],
        } satisfies Receipt;
      },
    }),
  ),
});

const result = await router.generate<string, Receipt>({
  task: "receipt.extract",
  input: "",
  prompt: "Extract the merchant, total, and line items from this receipt.",
  schema: { type: "object" },
  images: [{ data: "data:image/png;base64,(receipt photo)", mediaType: "image/png" }],
  inputModalities: ["text", "image"],
  requiresFeatures: ["structured_output"],
  preference: "cheapest",
});

// mistral-large and llama-3.3-70b are rejected: text-only input.
printPlan(result.plan);
console.log("output     ", result.output);

04 Custom policy

Routing policies are plain functions. This one keeps traffic inside EU-hosted providers for data-residency reasons, then picks the cheapest.

bun packages/model-router/examples/04-custom-policy.ts · View source ↗

// Routing policies are plain functions. This one keeps traffic inside
// EU-hosted providers for data-residency reasons, then picks the cheapest.
// Run from the repo root: bun packages/model-router/examples/04-custom-policy.ts
import {
  createCallbackProviderAdapter,
  createStaticCapabilityCatalog,
  ModelRouter,
  type RoutingPolicy,
} from "@swoosh-dev/router";
import { exampleCatalog } from "./shared/catalog";
import { printPlan } from "./shared/print";

const EU_HOSTED = new Set(["mistral", "local"]);

const euResidencyThenCheapest: RoutingPolicy = ({ candidates }) =>
  candidates
    .filter((candidate) => EU_HOSTED.has(candidate.capability.providerId))
    .sort(
      (left, right) =>
        (left.estimatedCostUsd ?? Number.POSITIVE_INFINITY) -
        (right.estimatedCostUsd ?? Number.POSITIVE_INFINITY),
    );

const router = new ModelRouter({
  catalog: createStaticCapabilityCatalog(exampleCatalog),
  providers: ["google", "anthropic", "openai", "mistral", "local"].map((providerId) =>
    createCallbackProviderAdapter({ providerId }),
  ),
});

const plan = await router.plan({
  task: "contract.redline",
  input: "(an employment contract)",
  inputModalities: ["text"],
  preference: euResidencyThenCheapest,
});

// llama-3.3-70b wins on price; mistral-large is the fallback.
// US-hosted candidates never make it into the route list.
printPlan(plan);

05 Outage fallback

When the selected provider fails, execution moves down the ranked route list automatically. The result includes the full attempt history.

bun packages/model-router/examples/05-outage-fallback.ts · View source ↗

// When the selected provider fails, execution moves down the ranked route
// list automatically. The result includes the full attempt history.
// Run from the repo root: bun packages/model-router/examples/05-outage-fallback.ts
import {
  createCallbackProviderAdapter,
  createStaticCapabilityCatalog,
  ModelRouter,
} from "@swoosh-dev/router";
import { exampleCatalog } from "./shared/catalog";
import { printAttempts, printPlan } from "./shared/print";

const router = new ModelRouter({
  catalog: createStaticCapabilityCatalog(exampleCatalog),
  providers: [
    createCallbackProviderAdapter({
      providerId: "google",
      generateObject: () => {
        throw new Error("503 service unavailable");
      },
    }),
    createCallbackProviderAdapter({
      providerId: "anthropic",
      generateObject: () => {
        throw new Error("429 rate limited");
      },
    }),
    createCallbackProviderAdapter({
      providerId: "openai",
      generateObject: () => ({ summary: "Q3 revenue grew 14% quarter over quarter." }),
    }),
  ],
});

const result = await router.run<string, { summary: string }>({
  task: "earnings.summarize",
  input: "(earnings call transcript)",
  prompt: "Summarize the key results in one sentence.",
  inputModalities: ["text"],
  requiresFeatures: ["structured_output"],
  preference: "cheapest",
});

printPlan(result.plan);
printAttempts(result.attempts);
console.log("output     ", result.output);

06 Bring your own catalog

Opt out of models.dev: source the catalog from your own database (or any async loader) while still producing the canonical ModelCapability shape.

bun packages/model-router/examples/06-bring-your-own-catalog.ts · View source ↗

// Opt out of models.dev: source the catalog from your own database (or any
// async loader) while still producing the canonical ModelCapability shape.
// Run from the repo root: bun packages/model-router/examples/06-bring-your-own-catalog.ts
import {
  createCallbackProviderAdapter,
  createCapabilityCatalog,
  type ModelCapability,
  ModelRouter,
} from "@swoosh-dev/router";
import { printPlan } from "./shared/print";

// Pretend this is a table in your database. The "columns" are exactly the
// ModelCapability fields — your row maps straight onto the interface.
interface ModelRow {
  provider: string;
  model: string;
  vision: boolean;
  ctx: number;
  inUsdPerM: number;
  outUsdPerM: number;
}

const rows: ModelRow[] = [
  { provider: "internal", model: "house-small", vision: false, ctx: 32_000, inUsdPerM: 0, outUsdPerM: 0 },
  { provider: "internal", model: "house-large", vision: true, ctx: 200_000, inUsdPerM: 0.5, outUsdPerM: 1.5 },
];

const rowToCapability = (row: ModelRow): ModelCapability => ({
  providerId: row.provider,
  providerName: "Internal",
  modelId: row.model,
  modelName: row.model,
  inputModalities: row.vision ? ["text", "image"] : ["text"],
  outputModalities: ["text"],
  features: row.vision
    ? ["structured_output", "tools", "attachments"]
    : ["structured_output", "tools"],
  limits: { contextTokens: row.ctx },
  pricing: { inputPerMillionTokens: row.inUsdPerM, outputPerMillionTokens: row.outUsdPerM },
  latencyClass: "fast",
});

const router = new ModelRouter({
  // No models.dev — load and map your own rows. Could be a DB query, an API, a file.
  catalog: createCapabilityCatalog(async () => {
    const fetched = await Promise.resolve(rows); // e.g. await db.select().from(models)
    return fetched.map(rowToCapability);
  }),
  providers: ["internal"].map((providerId) => createCallbackProviderAdapter({ providerId })),
});

const plan = await router.plan({
  task: "doc.summarize",
  input: "(an internal document)",
  inputModalities: ["text"],
  preference: "cheapest",
});

// Routes purely against your own catalog — house-small wins on price.
printPlan(plan);

07 Model access

Tell the router which models you actually have access to — declared once, not per request. A broad catalog (here the fixture; in production, models.dev) supplies the configs; you intersect it down to your accessible set.

bun packages/model-router/examples/07-model-access.ts · View source ↗

// Tell the router which models you actually have access to — declared once,
// not per request. A broad catalog (here the fixture; in production, models.dev)
// supplies the configs; you intersect it down to your accessible set.
// Run from the repo root: bun packages/model-router/examples/07-model-access.ts
import {
  createCallbackProviderAdapter,
  createStaticCapabilityCatalog,
  filterCapabilityCatalog,
  hasApiKey,
  ModelRouter,
} from "@swoosh-dev/router";
import { exampleCatalog } from "./shared/catalog";
import { printPlan } from "./shared/print";

// The full catalog lists models across google, anthropic, openai, mistral, local.
const universe = createStaticCapabilityCatalog(exampleCatalog);

// Option A — allowlist the exact models your account/contract permits.
// Configs (pricing, limits, features) still come from the catalog; you only name ids.
const accessible = filterCapabilityCatalog(universe, [
  "google/gemini-2.5-flash",
  "anthropic/claude-haiku-4-5",
  "openai/gpt-4o",
]);

// Option B — gate whole providers by whether their API key is present.
// hasApiKey looks up the conventional env var(s) per provider (GEMINI_API_KEY,
// OPENAI_API_KEY, …). It reads process.env by default; here we inject a fake
// env so the example is deterministic offline.
const env = { GEMINI_API_KEY: "demo", OPENAI_API_KEY: "demo" }; // no ANTHROPIC_API_KEY
const providers = ["google", "anthropic", "openai", "mistral", "local"].map((providerId) =>
  createCallbackProviderAdapter({ providerId, isAvailable: () => hasApiKey(providerId, { env }) }),
);

const router = new ModelRouter({ catalog: accessible, providers });

const plan = await router.plan({
  task: "doc.classify",
  input: "(a document)",
  inputModalities: ["text"],
  requiresFeatures: ["structured_output"],
  preference: "cheapest",
});

// Only the three allowlisted models are even considered; claude-haiku is then
// rejected because its key is missing — leaving gemini (selected) and gpt-4o.
printPlan(plan);

09 Load balancing

LiteLLM-style rotation, two ways: • loadBalance — spread requests across the N cheapest providers, not just #1. • roundRobin — rotate API keys within one provider to spread rate limits.

bun packages/model-router/examples/09-load-balancing.ts · View source ↗

// LiteLLM-style rotation, two ways:
//   • loadBalance — spread requests across the N cheapest providers, not just #1.
//   • roundRobin  — rotate API keys within one provider to spread rate limits.
// Run from the repo root: bun packages/model-router/examples/09-load-balancing.ts
import {
  createCallbackProviderAdapter,
  createStaticCapabilityCatalog,
  loadBalance,
  ModelRouter,
  roundRobin,
} from "@swoosh-dev/router";

// Three image-generation models; replicate and openai are the two cheapest.
const imageCatalog = createStaticCapabilityCatalog([
  {
    providerId: "replicate", providerName: "Replicate", modelId: "flux-schnell", modelName: "FLUX schnell",
    inputModalities: ["text"], outputModalities: ["image"], features: [],
    limits: {}, pricing: { outputPerMillionTokens: 3 }, latencyClass: "fast",
  },
  {
    providerId: "openai", providerName: "OpenAI", modelId: "gpt-image-1", modelName: "GPT Image 1",
    inputModalities: ["text"], outputModalities: ["image"], features: [],
    limits: {}, pricing: { outputPerMillionTokens: 4 }, latencyClass: "standard",
  },
  {
    providerId: "google", providerName: "Google", modelId: "imagen-4", modelName: "Imagen 4",
    inputModalities: ["text"], outputModalities: ["image"], features: [],
    limits: {}, pricing: { outputPerMillionTokens: 12 }, latencyClass: "standard",
  },
]);

// openai rotates between two keys; we log which one each call used.
const nextOpenAiKey = roundRobin(["openai-key-A", "openai-key-B"]);

const router = new ModelRouter({
  catalog: imageCatalog,
  providers: ["replicate", "openai", "google"].map((providerId) =>
    createCallbackProviderAdapter({
      providerId,
      generateObject: () => {
        const key = providerId === "openai" ? ` (key ${nextOpenAiKey()})` : "";
        return { url: `https://cdn.example/${providerId}.png`, via: providerId + key };
      },
    }),
  ),
});

// Cheapest image gen — but cycle through the two cheapest providers.
const balanced = loadBalance("cheapest", { across: 2 });

for (let i = 1; i <= 4; i++) {
  const result = await router.run<string, { url: string; via: string }>({
    task: "image.generate",
    input: "a watercolor fox",
    prompt: "a watercolor fox",
    inputModalities: ["text"],
    outputModalities: ["image"],
    preference: balanced,
  });
  console.log(`request ${i} → ${result.output.via}`);
}
// → replicate, openai (key A), replicate, openai (key B): providers alternate,
//   and openai's two keys rotate across the calls that land on it.

10 Benchmark routing

Route by benchmark performance, not just price. byBenchmark ranks on a named benchmark — or a function that blends several, so you decide what "best" means.

bun packages/model-router/examples/10-benchmark-routing.ts · View source ↗

// Route by benchmark performance, not just price. byBenchmark ranks on a named
// benchmark — or a function that blends several, so you decide what "best" means.
// Run from the repo root: bun packages/model-router/examples/10-benchmark-routing.ts
import {
  byBenchmark,
  createCallbackProviderAdapter,
  createStaticCapabilityCatalog,
  type ModelCapability,
  ModelRouter,
} from "@swoosh-dev/router";
import { printPlan } from "./shared/print";

const model = (
  providerId: string,
  modelId: string,
  benchmarks: Record<string, number>,
): ModelCapability => ({
  providerId, providerName: providerId, modelId, modelName: modelId,
  inputModalities: ["text"], outputModalities: ["text"],
  features: ["structured_output"], limits: { contextTokens: 200_000 },
  pricing: { inputPerMillionTokens: 1, outputPerMillionTokens: 3 }, latencyClass: "standard",
  benchmarks,
});

const catalog = createStaticCapabilityCatalog([
  model("openai", "gpt-5", { swe_bench: 0.72, gpqa: 0.85 }),
  model("anthropic", "claude-opus", { swe_bench: 0.78, gpqa: 0.84 }),
  model("google", "gemini-pro", { swe_bench: 0.64, gpqa: 0.84 }),
]);

const router = new ModelRouter({
  catalog,
  providers: ["openai", "anthropic", "google"].map((p) => createCallbackProviderAdapter({ providerId: p })),
});

const base = {
  task: "code.fix",
  input: "patch this failing test",
  inputModalities: ["text"] as const,
  requiresFeatures: ["structured_output"] as const,
};

// 1) Single benchmark: best at SWE-bench → claude-opus.
const sweBest = await router.plan({ ...base, preference: byBenchmark("swe_bench") });
console.log("best @ swe_bench:");
printPlan(sweBest);

// 2) Composite: weight coding 70% / reasoning 30% → your own definition of "best".
const blended = byBenchmark((c) => 0.7 * (c.benchmarks?.swe_bench ?? 0) + 0.3 * (c.benchmarks?.gpqa ?? 0));
const blendedPlan = await router.plan({ ...base, preference: blended });
console.log("\nbest @ 0.7·swe_bench + 0.3·gpqa:");
printPlan(blendedPlan);

11 LLM judge

Dynamic routing: an LLM judge classifies each prompt, then the policy routes by the verdict — cheap models for chat, top models for coding, search models for research. The classifier returns structured output (the category).

bun packages/model-router/examples/11-llm-judge.ts · View source ↗

// Dynamic routing: an LLM judge classifies each prompt, then the policy routes
// by the verdict — cheap models for chat, top models for coding, search models
// for research. The classifier returns structured output (the category).
// Run from the repo root: bun packages/model-router/examples/11-llm-judge.ts
import {
  byBenchmark,
  createCallbackProviderAdapter,
  createStaticCapabilityCatalog,
  type ModelCapability,
  ModelRouter,
} from "@swoosh-dev/router";
import { llmJudgePolicy } from "@swoosh-dev/judge";
import { printPlan } from "./shared/print";

const model = (providerId: string, modelId: string, extra: Partial<ModelCapability>): ModelCapability => ({
  providerId, providerName: providerId, modelId, modelName: modelId,
  inputModalities: ["text"], outputModalities: ["text"], features: ["structured_output"],
  limits: { contextTokens: 200_000 }, pricing: { inputPerMillionTokens: 1, outputPerMillionTokens: 3 },
  latencyClass: "standard", ...extra,
});

const router = new ModelRouter({
  catalog: createStaticCapabilityCatalog([
    model("local", "tiny", { pricing: { inputPerMillionTokens: 0, outputPerMillionTokens: 0 } }),
    model("anthropic", "opus", { qualityScore: 10, benchmarks: { swe_bench: 0.78 } }),
    model("perplexity", "sonar", { features: ["structured_output", "web_search"] }),
  ]),
  providers: ["local", "anthropic", "perplexity"].map((p) => createCallbackProviderAdapter({ providerId: p })),
});

type Kind = "chat" | "coding" | "research";

// Stand-in for a structured-output LLM call. In production this is e.g.
// judge.generateObject({ schema: KindSchema, prompt }) routed through swoosh itself.
let judgeCalls = 0;
const classify = ({ prompt }: { prompt: string }): Kind => {
  judgeCalls++;
  if (/\b(code|bug|patch|function|test)\b/i.test(prompt)) return "coding";
  if (/\b(latest|today|news|current|who won)\b/i.test(prompt)) return "research";
  return "chat";
};

const smart = llmJudgePolicy<Kind>({
  classify,
  route: {
    chat: "cheapest",
    coding: byBenchmark("swe_bench"),
    research: ({ candidates }) => candidates.filter((c) => c.capability.features.includes("web_search")),
  },
});

for (const prompt of [
  "just say hi back to me",
  "patch this failing unit test",
  "who won the game last night?",
  "just say hi back to me", // repeat → served from the judge cache
]) {
  const plan = await router.plan({ task: "assist", input: prompt, inputModalities: ["text"], preference: smart });
  console.log(`"${prompt.slice(0, 28)}…" → ${plan.selected.capability.providerId}/${plan.selected.capability.modelId}`);
}
console.log(`\njudge invoked ${judgeCalls}× for 4 requests (1 was cached)`);

12 Unified generate

One method, three kinds of output — the request decides, not the method name.

bun packages/model-router/examples/12-unified-generate.ts · View source ↗

// One method, three kinds of output — the request decides, not the method name.
// Run from the repo root: bun packages/model-router/examples/12-unified-generate.ts
import {
  createCallbackProviderAdapter,
  createStaticCapabilityCatalog,
  type GeneratedImage,
  type ModelCapability,
  ModelRouter,
} from "@swoosh-dev/router";

const textModel: ModelCapability = {
  providerId: "anthropic",
  providerName: "Anthropic",
  modelId: "claude-haiku-4-5",
  modelName: "Claude Haiku 4.5",
  inputModalities: ["text"],
  outputModalities: ["text"],
  features: ["structured_output"],
  limits: { contextTokens: 200_000 },
  pricing: { inputPerMillionTokens: 1, outputPerMillionTokens: 5 },
};

const imageModel: ModelCapability = {
  providerId: "imagegen",
  providerName: "ImageGen",
  modelId: "image-1",
  modelName: "Image One",
  inputModalities: ["text"],
  outputModalities: ["image"],
  features: [],
  limits: {},
  pricing: {},
};

const router = new ModelRouter({
  catalog: createStaticCapabilityCatalog([textModel, imageModel]),
  providers: [
    createCallbackProviderAdapter({
      providerId: "anthropic",
      generateText: () => "Crisp, calm, and a little playful.",
      generateObject: () => ({ tone: "warm", energy: "high" }),
    }),
    createCallbackProviderAdapter({
      providerId: "imagegen",
      generateImage: () => ({ base64: "iVBORw0KGgo=", mediaType: "image/png" }),
    }),
  ],
  defaultPreference: "cheapest",
});

// 1) text — no schema and no image modality
const text = await router.generate<string, string>({
  task: "brand.tagline",
  input: "an artisan bakery",
  inputModalities: ["text"],
  prompt: "Write a one-line tagline.",
});
console.log("text   ", text.output, `(via ${text.attempts.at(-1)?.providerId})`);

// 2) structured — a `schema` is present
const object = await router.generate<string, { tone: string; energy: string }>({
  task: "brand.voice",
  input: "an artisan bakery",
  inputModalities: ["text"],
  schema: { type: "object" },
});
console.log("object ", object.output, `(via ${object.attempts.at(-1)?.providerId})`);

// 3) image — outputModalities includes "image"
const image = await router.generate<string, GeneratedImage>({
  task: "brand.hero",
  input: "an artisan bakery",
  inputModalities: ["text"],
  outputModalities: ["image"],
  prompt: "A warm overhead shot of fresh sourdough.",
});
console.log(
  "image  ",
  `${image.output.mediaType}, ${image.output.base64.length} b64 chars`,
  `(via ${image.attempts.at(-1)?.providerId})`,
);

13 Reranking

Rerank search candidates by relevance to a query. Reranking is a task, not a modality: route on "rerank" and the adapter decides whether a dedicated cross-encoder (Cohere/Voyage — cheap, scores only) or an LLM reranker (pricier, returns per-result rationales) does the work. "explanations" is an intent: require it to route to a reason-capable reranker. Unlike embeddings, rerankers are stateless, so cross-model fallback is safe.

bun packages/model-router/examples/13-reranking.ts · View source ↗

// Rerank search candidates by relevance to a query. Reranking is a task, not a
// modality: route on "rerank" and the adapter decides whether a dedicated
// cross-encoder (Cohere/Voyage — cheap, scores only) or an LLM reranker (pricier,
// returns per-result rationales) does the work. "explanations" is an intent:
// require it to route to a reason-capable reranker. Unlike embeddings, rerankers
// are stateless, so cross-model fallback is safe.
// Run from the repo root: bun packages/model-router/examples/13-reranking.ts
import {
  createCallbackProviderAdapter,
  createStaticCapabilityCatalog,
  llmReranker,
  ModelRouter,
  type ModelCapability,
} from "@swoosh-dev/router";
import { printAttempts, printPlan } from "./shared/print";

const reranker = (
  id: string,
  extra: Pick<ModelCapability, "rerank" | "features" | "pricing" | "qualityScore">,
): ModelCapability => {
  const [providerId, modelId] = id.split("/") as [string, string];
  return {
    providerId,
    providerName: providerId,
    modelId,
    modelName: modelId,
    inputModalities: ["text"],
    outputModalities: ["text"],
    features: extra.features ?? [],
    limits: {},
    pricing: extra.pricing,
    qualityScore: extra.qualityScore,
    rerank: extra.rerank,
  };
};

const catalog = createStaticCapabilityCatalog([
  reranker("cohere/rerank-3.5", { rerank: { maxDocuments: 1000 }, features: [], pricing: { inputPerMillionTokens: 0.1 }, qualityScore: 0.62 }),
  reranker("voyage/rerank-2", { rerank: { maxDocuments: 1000 }, features: [], pricing: { inputPerMillionTokens: 0.05 }, qualityScore: 0.6 }),
  reranker("openai/gpt-5", { rerank: { maxDocuments: 100 }, features: ["explanations"], pricing: { inputPerMillionTokens: 2.5 }, qualityScore: 0.9 }),
]);

// Offline "relevance": query-term overlap (a real cross-encoder is far better).
const relevance = (query: string, doc: string) => {
  const terms = new Set(query.toLowerCase().split(/\W+/).filter(Boolean));
  const words = doc.toLowerCase().split(/\W+/);
  return words.filter((w) => terms.has(w)).length;
};

// Dedicated cross-encoders: scores only, no rationale.
const crossEncoder = (providerId: string) =>
  createCallbackProviderAdapter({
    providerId,
    rerank: ({ query, documents }) =>
      documents.map((doc, index) => ({ index, score: relevance(query, doc) })),
  });

// LLM reranker: the llmReranker() helper turns a structured-output call into a
// rerank callback (ordering + reasons). Here the "LLM" is faked offline by
// reading the query/documents back out of the prompt the helper builds.
const fakeStructuredLlm = ({ prompt }: { prompt: string }) => {
  const query = (prompt.match(/Query: (.*)/)?.[1] ?? "").toLowerCase();
  const terms = new Set(query.split(/\W+/).filter(Boolean));
  const docs = [...prompt.matchAll(/^\[(\d+)\] (.*)$/gm)].map((m) => ({ index: Number(m[1]), text: m[2]! }));
  const ranking = docs
    .map((d) => ({ index: d.index, hits: d.text.toLowerCase().split(/\W+/).filter((w) => terms.has(w)).length }))
    .filter((d) => d.hits > 0)
    .sort((a, b) => b.hits - a.hits)
    .map((d) => ({ index: d.index, reason: `matches ${d.hits} query term(s)` }));
  return { ranking };
};

const llmRerankAdapter = createCallbackProviderAdapter({
  providerId: "openai",
  rerank: llmReranker({ generateObject: fakeStructuredLlm }),
});

const router = new ModelRouter({
  catalog,
  providers: [crossEncoder("cohere"), crossEncoder("voyage"), llmRerankAdapter],
});

const query = "quick chocolate dessert";
const documents = [
  "No-bake chocolate fridge cake, ready fast",
  "Slow-braised beef short ribs, three hours",
  "Five-minute chocolate mug cake, quick dessert",
  "Grilled salmon with lemon",
  "Dark chocolate truffles, quick and easy",
];

const show = (label: string, results: readonly { index: number; score: number; document: string; reason?: string }[]) => {
  console.log(`\n${label}`);
  for (const r of results) {
    console.log(`  [${r.score}] ${r.document}${r.reason ? `  — ${r.reason}` : ""}`);
  }
};

// 1. Cheapest: routes to a dedicated cross-encoder (Voyage, cheapest). No reasons.
const plain = await router.rerank({ task: "search.rerank", query, documents, topK: 3, preference: "cheapest" });
printPlan(plain.plan);
show(`cheapest -> ${plain.model.providerId}/${plain.model.modelId} (top 3)`, plain.results);

// 2. Need rationales: require "explanations" -> routes to the LLM reranker.
const explained = await router.rerank({
  task: "search.rerank",
  query,
  documents,
  topK: 3,
  requiresFeatures: ["explanations"],
});
show(`requiresFeatures: ["explanations"] -> ${explained.model.providerId}/${explained.model.modelId}`, explained.results);

// 3. Fallback is safe (stateless): if the chosen reranker is down, another takes over.
const flaky = new ModelRouter({
  catalog,
  providers: [
    createCallbackProviderAdapter({ providerId: "voyage", rerank: () => { throw new Error("voyage 503"); } }),
    crossEncoder("cohere"),
    llmRerankAdapter,
  ],
});
const recovered = await flaky.rerank({ task: "search.rerank", query, documents, topK: 3, preference: "cheapest" });
console.log(`\nfallback: served by ${recovered.model.providerId}/${recovered.model.modelId}`);
printAttempts(recovered.attempts);