swooshdocs

swoosh documentation

Intent-driven, policy-driven model routing for TypeScript. Declare what a task needs and how to choose; get an inspectable plan and automatic fallback. Plain Promises, zero runtime dependencies.

01 Installation

Just want it to work? npm i @swoosh-dev/sdk ai @ai-sdk/openai, then const router = await createRouter() — the enriched catalog and your key-detected providers, wired for you. The granular packages below are for when you want control over each piece.

The core router has zero runtime dependencies:

# the router engine, catalogs, policies, callback adapter
npm install @swoosh-dev/router

Add the AI SDK adapter only if you route through the Vercel AI SDK:

npm install @swoosh-dev/ai-sdk ai
Requirements. TypeScript 5+, ES2022 target, an environment with fetch (Node 18+, Bun, Deno, or the browser) if you use ModelsDevCapabilityCatalog.

02 Packages

swoosh is split so the core stays dependency-light. Provider integrations that pull in third-party SDKs live in their own packages.

PackageInstallContents
@swoosh-dev/sdknpm i @swoosh-dev/sdk ai @ai-sdk/openaiBatteries-included drop-in — createRouter() with the enriched catalog and providers auto-wired from your API keys. Re-exports everything.
@swoosh-dev/routernpm i @swoosh-dev/routerRouter engine, capability catalogs, built-in policies, callback adapter. Zero runtime dependencies.
@swoosh-dev/ai-sdknpm i @swoosh-dev/ai-sdk aiVercel AI SDK provider adapter. ai is a peer dependency.
@swoosh-dev/capabilitiesnpm i @swoosh-dev/capabilitiesCurated, enriched model dataset + defaultCatalog() — models.dev plus the features it omits (web_search, latency, quality, benchmarks).
@swoosh-dev/judgenpm i @swoosh-dev/judgeDynamic policies — classify the prompt with an LLM judge (structured output) and route by the verdict.

The extension points are types, not packages: a policy is a plain function, and catalogs/providers are interfaces — so you can extend swoosh in your own code without any extra package.

03 Quick start

Construct a router with a catalog and one or more provider adapters, then route a task. Every method returns a Promise — just await it.

import { ModelRouter, ModelsDevCapabilityCatalog } from "@swoosh-dev/router";
import { createAiSdkProviderAdapter } from "@swoosh-dev/ai-sdk";
import { google } from "@ai-sdk/google";
import { generateObject } from "ai";

const router = new ModelRouter({
  catalog: new ModelsDevCapabilityCatalog(),  // live pricing + limits
  providers: [
    createAiSdkProviderAdapter({
      providerId: "google",
      models: { "gemini-2.5-flash": google("gemini-2.5-flash") },
      generateObject: (request) => generateObject(request as never),
    }),
  ],
  defaultPreference: "balanced",
});

const recipe = await router.generateObject({
  task: "recipe.extract",
  input: pageText,
  prompt: "Extract the recipe from this page.",
  inputModalities: ["text"],
  requiresFeatures: ["structured_output"],
  preference: "cheapest",
  constraints: { maxCostUsd: 0.01 },
});
Offline examples. The examples directory has eleven runnable scripts using simulated providers — no API keys required.

04 Core concepts

Two ideas drive everything: intent (what the task needs) and policy (how to choose among models that qualify).

Intent — what a task needs

A request declares requirements rather than a model id: input/output modalities, required features (structured output, tools, reasoning, web search…), and rough token estimates. The router keeps only the models in the catalog that satisfy every requirement.

Policy — how to choose

Among qualifying candidates, a preference ranks them: a built-in ("cheapest", "fastest", "best_quality", "balanced") or a custom function. Constraints (maxCostUsd, maxLatencyClass, provider allow/deny lists) are hard filters applied before ranking — each rejection carries a reason.

Plan, then execute

plan() returns an inspectable RoutePlan — selected model, ranked fallbacks, every rejection, and a cost estimate — without calling any provider. run() / runText() execute the plan, walking the ranked routes until one succeeds and recording each attempt.

05 ModelRouter

The engine. Construct once with options, then call the planning and execution methods. Every method returns a Promise and rejects with ModelRouterError.

Constructor

new ModelRouter(options: ModelRouterOptions)
OptionTypeNotes
catalog requiredCapabilityCatalogSource of the model list — static or from models.dev.
providers requiredProviderAdapter[]Adapters keyed by providerId. A catalog model with no available adapter is rejected.
defaultPreference optionalRoutingPreferenceUsed when a request omits preference. Falls back to "balanced".

plan(request)

plan<Input>(request: TaskRequest<Input>): Promise<RoutePlan>

Filters and ranks candidates and returns the RoutePlan without executing. Rejects with ModelRouterError if no model satisfies the request.

run(request)

run<Input, Output>(request: GenerateObjectRequest<Input>): Promise<RouterRunResult<Output>>

Plans, then executes generateObject down the ranked routes until one succeeds. Returns the output plus the plan and the attempts log.

runText(request)

runText<Input>(request: GenerateTextRequest<Input>): Promise<RouterRunResult<string>>

Same as run but executes the adapter's generateText. The prompt field is required on a text request.

generateObject(request) / generateText(request)

generateObject<Input, Output>(request): Promise<Output>
generateText<Input>(request): Promise<string>

Convenience wrappers that return only the output, discarding the plan and attempts. Use run/runText when you want to inspect routing.

06 Request & constraints

Every method takes a TaskRequest. Object/text variants add a prompt, optional schema, and metadata.

FieldTypeDefault / notes
task requiredstringLabel for logs and errors, e.g. "recipe.extract".
input requiredInputYour payload; passed to the adapter untouched.
inputModalities requiredModelModality[]Model must support all of these.
outputModalitiesModelModality[]Defaults to ["text"].
estimatedInputTokensnumberDefaults to 8000. Drives cost estimate and context-window filtering.
estimatedOutputTokensnumberDefaults to 2000.
requiresFeaturesModelFeature[]Rejects models missing any of these features (e.g. "structured_output", "tools", "reasoning", "web_search").
preferenceRoutingPreference | RoutingPolicyA built-in name or a custom function. Falls back to defaultPreference.
constraintsTaskConstraintsHard filters, below.

TaskConstraints

FieldTypeBehavior
maxCostUsdnumberRejects models whose estimated cost exceeds this.
maxLatencyClassLatencyClassRejects models slower than this class.
allowedProviderIdsstring[]Allowlist — everything else is rejected.
deniedProviderIdsstring[]Denylist.
preferredProviderIdsstring[]Sorted ahead of others by the built-in policies.
allowFallbacksbooleanWhen false, the plan keeps only the selected model.

07 RoutePlan

What plan() returns and what run() reports back inside its result.

interface RoutePlan {
  task: string;
  preference: RoutingPreference | "custom";
  selected: RankedModel;              // { capability, score, reason, estimatedCostUsd? }
  fallbacks: RankedModel[];           // ranked alternates, tried in order
  rejected: RejectedModel[];          // { providerId, modelId, reason }
  estimate: { inputTokens: number; outputTokens: number; costUsd?: number };
}

run() / runText() resolve to a RouterRunResult:

interface RouterRunResult<Output> {
  output: Output;
  plan: RoutePlan;
  attempts: RouterAttempt[];  // { providerId, modelId, ok, error? } per route tried
}

08 Rejection reasons

Every excluded model appears in plan.rejected with one of these exact strings — log or surface them to debug routing.

ReasonTriggered when
No available provider adapter.No adapter registered for the model's providerId, or its isAvailable() returned false.
Provider is not allowed by policy.allowedProviderIds is set and excludes this provider.
Provider is denied by policy.Provider is in deniedProviderIds.
Model does not support the required input modalities.Request inputModalities not all supported.
Model does not support the required output modalities.Request outputModalities not all supported.
Missing required feature: <name>.A feature in requiresFeatures is absent from the model's features (the reason names the missing feature).
Estimated input exceeds context window.Input tokens > model's context limit.
Estimated output exceeds output limit.Output tokens > model's output limit.
Model is slower than the latency policy allows.Model's latencyClass slower than maxLatencyClass.
Estimated cost exceeds policy.Estimated cost > maxCostUsd.

09 Capability catalogs

A catalog supplies the list of ModelCapability the router chooses from. ModelCapability is the canonical schema — the "columns" your source populates. models.dev is one built-in source; you can ignore it entirely and bring your own.

Bring your own source. CapabilityCatalog is just { listCapabilities(): Promise<ModelCapability[]> }. Use createCapabilityCatalog for a DB or API, createStaticCapabilityCatalog for a fixed list, or ModelsDevCapabilityCatalog for live metadata — they all yield the same shape.

createCapabilityCatalog(load) — bring your own DB

Wraps any sync or async loader (a database query, an internal API, a cached file) into a catalog. The router never assumes models.dev — point it at your own table. Loader failures become a ModelRouterError.

import { createCapabilityCatalog, normalizeModelsDevCatalog } from "@swoosh-dev/router";

// Map your own rows onto the ModelCapability "columns".
const catalog = createCapabilityCatalog(async () => {
  const rows = await db.select().from(models);
  return rows.map((r) => ({
    providerId: r.provider, providerName: r.providerName,
    modelId: r.model, modelName: r.label,
    inputModalities: r.vision ? ["text", "image"] : ["text"],
    outputModalities: ["text"],
    features: r.structured ? ["structured_output", "tools"] : ["tools"],
    limits: { contextTokens: r.ctx }, pricing: { inputPerMillionTokens: r.inUsd },
  }));
});

// Already storing rows in models.dev's JSON shape? Reuse the normalizer:
const fromCache = createCapabilityCatalog(() => normalizeModelsDevCatalog(cachedJson));
Augmenting features. models.dev flags structured_output, tools, reasoning, and attachments. For a feature it doesn't expose yet — e.g. web_search — add it in your loader's .map(): features: WEB_SEARCH_MODELS.has(m.modelId) ? [...m.features, "web_search"] : m.features. mergeCapabilities(base, overrides) does this for you, keyed by providerId/modelId (features unioned; limits/pricing shallow-merged; other fields replaced).

Prebuilt dataset — @swoosh-dev/capabilities

Don't want to wire models.dev yourself? @swoosh-dev/capabilities ships a curated, bundled snapshot — models.dev narrowed to major providers and enriched with web_search, latency classes, and quality scores (which models.dev omits) — behind a one-call catalog. Offline, no keys, refreshed by CI.

import { defaultCatalog } from "@swoosh-dev/capabilities";

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

ModelsDevCapabilityCatalog

Optional built-in. Fetches live provider/model metadata (pricing, context limits, modality support) from models.dev and normalizes it.

new ModelsDevCapabilityCatalog(
  url? = "https://models.dev/api.json",
  fetcher? = fetch,
);

createStaticCapabilityCatalog(capabilities)

Pins a fixed array of capabilities — best for reproducible routing and tests.

const catalog = createStaticCapabilityCatalog([
  {
    providerId: "anthropic", providerName: "Anthropic",
    modelId: "claude-haiku-4-5", modelName: "Claude Haiku 4.5",
    inputModalities: ["text", "image"], outputModalities: ["text"],
    features: ["structured_output", "tools", "attachments"],
    limits: { contextTokens: 200_000, outputTokens: 64_000 },
    pricing: { inputPerMillionTokens: 1, outputPerMillionTokens: 5 },
    latencyClass: "fast", qualityScore: 7.5,
  },
]);

normalizeModelsDevCatalog(json)

The pure transform from a raw models.dev payload to ModelCapability[] — useful if you fetch and cache the JSON yourself.

10 Model access

A catalog lists the universe of models; you rarely have access to all of them. Tell swoosh what you can actually use once, at construction — never per request. The model's full config still comes from the catalog; you only declare which ones you have. Options, simplest first — and they compose.

1 · Gate providers by API key provider granularity

An adapter's isAvailable() decides whether a whole provider is usable. A catalog model whose provider has no available adapter is rejected with No available provider adapter. The hasApiKey helper checks the conventional environment variable(s) for a provider — OPENAI_API_KEY, ANTHROPIC_API_KEY, GEMINI_API_KEY, and so on — so a provider is only used when its key is actually present.

import { createCallbackProviderAdapter, hasApiKey } from "@swoosh-dev/router";

createCallbackProviderAdapter({
  providerId: "openai",
  isAvailable: () => hasApiKey("openai"),  // looks up OPENAI_API_KEY in process.env
  generateObject: callOpenAI,
});

hasApiKey reads process.env by default (guarded for non-Node runtimes); pass { env } to use another source or { vars } to override the names. The provider → env-var conventions live in the exported apiKeyEnvVars map, and unmapped providers fall back to a derived <PROVIDER>_API_KEY (so "gemini" → GEMINI_API_KEY).

2 · Allowlist specific models recommended

Wrap a broad catalog with filterCapabilityCatalog and an allowlist of "providerId/modelId" keys (a bare "modelId" matches across providers). models.dev supplies pricing, limits, and features; you only name the ids you have.

import { ModelsDevCapabilityCatalog, filterCapabilityCatalog } from "@swoosh-dev/router";

const catalog = filterCapabilityCatalog(new ModelsDevCapabilityCatalog(), [
  "openai/gpt-4o",
  "anthropic/claude-haiku-4-5",
  "google/gemini-2.5-flash",
]);

3 · Filter with a predicate dynamic

Pass a function instead of a list — it runs on every listCapabilities() call, so it can read live state (a feature flag, a per-tenant entitlement set, remaining credits).

const catalog = filterCapabilityCatalog(
  new ModelsDevCapabilityCatalog(),
  (model) => tenant.enabledModels.has(`${model.providerId}/${model.modelId}`),
);

4 · Bring your own catalog

If your database already stores only the models you have, createCapabilityCatalog is the access list — no filtering needed. Your table is the source of truth.

5 · Discover from the provider pattern

Most providers expose a "models I can access" endpoint (OpenAI GET /v1/models, OpenRouter /models, Ollama /api/tags). Fetch it at startup and use the result as the filter — swoosh makes no live calls of its own, so wire this in your loader:

const available = new Set(
  (await openai.models.list()).data.map((m) => `openai/${m.id}`),
);
const catalog = filterCapabilityCatalog(new ModelsDevCapabilityCatalog(), [...available]);
They compose. Filter the catalog to your licensed models and gate providers by key — a model must survive both to be routed. Anything excluded shows up in plan.rejected with a reason, so access decisions are auditable.

Bring-your-own-keys apps

Because providers are chosen from the keys that are present, BYO-keys apps need no provider-specific branching. With @swoosh-dev/sdk, pass each user's keys as env and the router wires whatever they brought — the same call for everyone:

const router = await createRouter({
  env: { OPENAI_API_KEY: user.keys.openai, OPENROUTER_API_KEY: user.keys.openrouter },
});

Users never configure models — the catalog supplies them, so new models become routable as the dataset updates, with no code change. A user who brings only an OpenRouter key is routed across the OpenRouter catalog; one with raw provider keys across those. "Bring your keys, the router handles the rest."

11 Routing policies

A policy ranks the qualifying candidates. Pass a built-in name or a function as preference.

PreferenceRanks by
"cheapest"Lowest estimated cost.
"fastest"Fastest latency class, then cost.
"best_quality"Highest quality score.
"balanced"Combined quality + latency − cost score (the default).

Preferred providers (via preferredProviderIds) sort ahead within any built-in.

Custom policies

A RoutingPolicy is just a function from ranked candidates to ranked candidates. Filter, reorder, or both:

import type { RoutingPolicy } from "@swoosh-dev/router";

const euOnlyThenCheapest: RoutingPolicy = ({ candidates }) =>
  candidates
    .filter((c) => EU_PROVIDERS.has(c.capability.providerId))
    .sort((a, b) => (a.estimatedCostUsd ?? Infinity) - (b.estimatedCostUsd ?? Infinity));

router.plan({ task: "redline", input, inputModalities: ["text"], preference: euOnlyThenCheapest });

When a function is used, plan.preference is reported as "custom". Helpers estimatedCostUsd, qualityScore, and namedPolicy are exported if you want to compose the built-ins.

Composable helpers a-la-carte

Each is a one-import policy you drop into preference — combine only the ones you need.

HelperWhat it does
pin(ids)Pin a model — or a fallback band — to the front; the rest follow.
qualityCap(max)Best model under a quality ceiling — "good enough, don't overpay."
byCoverage(tags)Soft tag match — rank by overlap. Routes connectors/subagents, not just models.
sticky(currentId, base)Keep the warm model (prefix cache) unless a challenger wins by a margin.
byBenchmark(src)Rank by a benchmark — a name, a blend fn, or a live { resolve } source.
loadBalance · roundRobinSpread across the top-N · rotate API keys.

Load balancing & key rotation rotation

loadBalance spreads requests across the top-N candidates instead of always picking #1 — "cheapest, but cycle through the two cheapest providers." It wraps a base preference or policy, ranks, then round-robins which of the top across is selected each call; the rest stay as ordered fallbacks, so failover still works. It's stateful (holds a cursor) — build it once and reuse it.

import { loadBalance } from "@swoosh-dev/router";

const balanced = loadBalance("cheapest", { across: 2 });  // or strategy: "random"
await router.run({ ...request, preference: balanced });  // 1st of the two cheapest
await router.run({ ...request, preference: balanced });  // 2nd of the two cheapest

To rotate API keys within a provider (spread rate limits across keys), use roundRobin inside the adapter — it returns the next item each call:

import { roundRobin, createCallbackProviderAdapter } from "@swoosh-dev/router";

const nextKey = roundRobin([process.env.OPENAI_KEY_A!, process.env.OPENAI_KEY_B!]);
createCallbackProviderAdapter({
  providerId: "openai",
  generateObject: ({ prompt, model }) => callOpenAI(prompt, model.modelId, nextKey()),
});

Route by benchmark byBenchmark

Rank on benchmark scores (see the benchmarks field on ModelCapability, populated by @swoosh-dev/capabilities). Pass a benchmark name, or a function that blends several so you decide what "best" means. Candidates with no score sort last, and minimum drops them.

import { byBenchmark } from "@swoosh-dev/router";

preference: byBenchmark("swe_bench", { minimum: 0.5 }),
preference: byBenchmark((m) => 0.7 * (m.benchmarks?.swe_bench ?? 0) + 0.3 * (m.benchmarks?.gpqa ?? 0)),

Dynamic policies & LLM judges async

Policies are async-capable, so a policy can await an LLM call before choosing. @swoosh-dev/judge classifies each prompt with your structured-output judge and routes by the verdict — cheap models for chat, top models for coding, search models for research. The verdict comes from your LLM; the result is still an ordinary ranked list, so failover and everything else work unchanged. Verdicts are cached by prompt so identical requests aren't re-judged.

import { llmJudgePolicy } from "@swoosh-dev/judge";
import { byBenchmark } from "@swoosh-dev/router";

const smart = llmJudgePolicy({
  classify: ({ prompt }) => judge.generateObject({ schema: TaskKind, prompt }), // your LLM
  route: {
    chat: "cheapest",
    coding: byBenchmark("swe_bench"),
    research: ({ candidates }) => candidates.filter((c) => c.capability.features.includes("web_search")),
  },
});
await router.run({ ...request, preference: smart });

12 Provider adapters

An adapter implements generateObject and/or generateText for one providerId. The router resolves the chosen ModelCapability to an adapter by id.

createCallbackProviderAdapter(options) @swoosh-dev/router

Wraps plain async/sync callbacks. Provide either method; an optional isAvailable() gates the provider.

import { createCallbackProviderAdapter } from "@swoosh-dev/router";

const anthropic = createCallbackProviderAdapter({
  providerId: "anthropic",
  isAvailable: () => Boolean(process.env.ANTHROPIC_API_KEY),
  generateText: async ({ model, prompt }) => callClaude(model.modelId, prompt),
});

createAiSdkProviderAdapter(options) @swoosh-dev/ai-sdk

Bridges the Vercel AI SDK. models maps each catalog modelId to its AI SDK model instance; the adapter resolves and calls it, unwrapping the SDK's { object } result.

import { createAiSdkProviderAdapter } from "@swoosh-dev/ai-sdk";
import { openai } from "@ai-sdk/openai";
import { generateObject } from "ai";

createAiSdkProviderAdapter({
  providerId: "openai",
  models: { "gpt-4o": openai("gpt-4o") },
  generateObject: (request) => generateObject(request as never),
});
Writing your own. A ProviderAdapter is { providerId, name?, isAvailable?, generateObject?, generateText?, rerank? } where the methods return Promises. The callback adapter is the easy path; implement the interface directly only if you need finer control.

13 Reranking

Reorder retrieved documents by relevance to a query. Reranking is a task, not a modality — you route on it, and the adapter decides whether a dedicated cross-encoder or an LLM does the work. Unlike embeddings, rerankers are stateless, so cross-model fallback is safe.

const { results } = await router.rerank({
  task: "search.rerank",
  query,
  documents,                          // string[]
  topK: 8,
  requiresFeatures: ["explanations"],   // route to a reason-capable reranker
  preference: "cheapest",
});
// results: { index, document, score, reason? }[] — sorted desc, capped at topK

Dedicated vs. LLM rerankers

Dedicated cross-encoders (Cohere, Voyage, Jina) are cheap and fast but return scores only. An LLM reranker is pricier but can return a per-result reason. That difference is an intent: the "explanations" feature. Require it to route to a reason-capable reranker; omit it to get the cheapest dedicated one. reason is populated only when the chosen reranker supports it.

llmReranker(options) @swoosh-dev/router

Turns a structured-output call into a rerank callback — it asks the model to order the documents (with reasons) and maps that to scores. Declare features: ["explanations"] on the model's catalog entry so requests can route to it.

import { createCallbackProviderAdapter, llmReranker } from "@swoosh-dev/router";

const reranker = createCallbackProviderAdapter({
  providerId: "openai",
  rerank: llmReranker({
    generateObject: ({ prompt, schema }) => generateObject({ model, prompt, schema }),
  }),
});
Batteries included. @swoosh-dev/capabilities ships dedicated rerankers (Cohere, Voyage, Jina, mixedbread) in its dataset. Pricing differs by provider — Cohere bills per search (rerank.pricePerSearchUsd), Voyage/Jina per token — and cost-based routing handles both. Plan a rerank without executing via router.planRerank(request).

14 Resilience

Routing has two seams: which model to pick (policies, above) and how the plan runs — fallback, retry, timeout, cooldown. Every piece is opt-in; the defaults stay "fail fast, fall over."

Automatic fallback

Each run / generate walks the ranked routes: if the selected model's adapter throws, it tries the next, recording every attempt. On by default — set constraints.allowFallbacks: false to disable.

Retry & timeout per request

retry re-tries the same route with exponential backoff before falling through — for transient 429/5xx where waiting helps. timeout fails a slow route so the router moves on. Both are request fields:

await router.generate({
  task, input, prompt, inputModalities: ["text"],
  retry: { attempts: 3, backoffMs: 200, retryOn: (e) => isTransient(e) },
  timeout: 10_000,  // ms per attempt
});

Cooldown-aware routing healthAware

The lean half of LiteLLM-style health routing — no server, no DB. A HealthTracker consumes the attempts each run returns: a failure benches that deployment for a cooldown, a success clears it. healthAware routes around cooling-down routes (kept as last resort, never dropped), composing with any base policy.

import { createHealthTracker, healthAware } from "@swoosh-dev/router";

const health = createHealthTracker({ cooldownMs: 60_000 });
const policy = healthAware("cheapest", health);

const res = await router.run({ ...request, preference: policy });
health.record(res.attempts);  // a 429 benches that route for 60s

Sessions stateful glue

Health, sticky, and budget are stateful — they need memory across calls. A Session is the thin container that holds that state and wires the feedback loop for you, instead of threading it by hand. It reads only the generic plan + attempts, so it composes with any routing (models, connectors, subagents) — not a model-only feature.

import { createSession, createHealthTracker } from "@swoosh-dev/router";

const session = createSession({
  health: createHealthTracker(),
  budgetUsd: 5,        // downgrades to cheapest when spent (or "throw")
  sticky: true,        // prefer the warm model
});

const res = await router.run({ ...request, preference: session.preference("balanced") });
session.record(res);     // updates health, spend, warm model
session.remaining;       // budget left

Usage & cost metering no DB

Adapters report token usage through a router-injected reportUsage — the @swoosh-dev/ai-sdk adapter wires it automatically for generateObject — so usage surfaces on result.usage and each attempt. createUsageMeter() tallies tokens and actual cost across runs (Session budgets use it too): the lean alternative to a spend database — snapshot the totals yourself if you need durability.

import { createUsageMeter } from "@swoosh-dev/router";

const meter = createUsageMeter();
const res = await router.run(request);
meter.record(res);
meter.inputTokens;  meter.outputTokens;  meter.costUsd;  meter.calls;
Lean by design. These are the LiteLLM pieces worth having — fallback, retry, cooldown, key rotation — as composable functions, not a proxy. No gateway, virtual keys, or spend DB; swoosh stays an embeddable library.

15 Types

All types are re-exported from the package root. Key unions:

TypeValues / shape
ModelModality"text" | "image" | "audio" | "video" | "pdf" | "file"
ModelFeature"structured_output" | "tools" | "reasoning" | "attachments" | "web_search" | (string & {}) — open set; surface your own.
RoutingPreference"cheapest" | "fastest" | "best_quality" | "balanced"
LatencyClass"fast" | "standard" | "slow"
ModelCapabilityprovider/model ids + names, modalities, features, limits, pricing, optional latencyClass / qualityScore / benchmarks (open Record<string, number>).
RankedModel{ capability, score, reason, estimatedCostUsd? }
CapabilityCatalog{ listCapabilities(): Promise<ModelCapability[]> }
ProviderAdapter{ providerId, name?, isAvailable?, generateObject?, generateText? }
RoutingPolicy(ctx: { request, candidates }) => RankedModel[] | Promise<RankedModel[]> — async-capable.

16 Errors

Failures reject the returned Promise with a ModelRouterError. Handle them with try/catch (or .catch()).

import { ModelRouterError } from "@swoosh-dev/router";

try {
  const result = await router.run(request);
} catch (err) {
  if (err instanceof ModelRouterError) {
    // no model satisfied the request, or every route failed
  }
}

Two cases produce a ModelRouterError: no model satisfies the request (plan), and every ranked route failed at execution (run / runText). The message names the task.