This quickstart is as of modelrig v0.19.0 (the published npm package).
ModelRig quickstart — See. Grade. Improve.
The question this page answers: how do I get from nothing to my first run on /runs, with its steps and artifacts, in about ten minutes?
ModelRig is the operating layer for your AI workstream. Each LLM task becomes a versioned route file (prompt template + JSON schema + candidate models + policy) that you call with one line — rig.run("task.name", {input, tags}) — and three things happen at once:
- See — the run lands in an inspectable artifact store (runs → steps → artifacts, lineaged and integrity-hashed; see the instrumentation guide), with cost/tokens/tier and a grade recorded against your tags.
- Grade — you get schema-validated output, served only by a model you authorized, you attach grades from signals you already have, and you can replay that traffic against cheaper candidates in a bake-off before you change anything.
- Improve — a winning candidate is a proposal you review. Never a silent swap: automated changes (opt-in) are proven before they apply, and a change you promote in ModelRig (console or MCP) is versioned and reversible — or merge it as a PR if you keep routes in git.
The path is the same whoever does the work: mint a key → install → confirm the org → wrap one pipeline execution in a run (raw lane, no route) → see it on Runs (/runs) → graduate a call site to a route when you want one. Creating the org and key is yours (two minutes, once, "Before you start"); after that, point your coding agent at this page or follow the steps by hand. An OpenAI-compatible client can also use the optional gateway (below the steps), once a provider key is stored in Vault. Want to watch calls first? Choosing a lane shows the observe path, which skips the route.
Before you start — create your org and key (two minutes, human-only)
Account setup stays human: your coding agent never creates accounts, signs in, or holds credentials. Once, up front, sign up and create your organization at app.modelrig.ai (email and an org name is the whole form). Then:
Mint a key in the org you want the data in. Sign in at https://app.modelrig.ai, check the organization name in the header badge, and create a key on the API keys page. The rig_sk_ secret is shown once. One key = one org: every row the key exports lands in the organization it was minted in, whichever organization you happen to be viewing in the console. Set it on every service, worker and cron that creates a rig; your provider keys stay where they are.
# Wherever your app reads configuration: .env.local, your platform's env vars, a secret manager. Never in code.
MODELRIG_API_KEY=rig_sk_…
That key is the only ModelRig credential your app ever holds — never a database URL, never a service-role key. Provider keys never leave your process. Which org a key belongs to, and how the console chooses the org it shows you, is Orgs and keys.
What the key is needed for: everything you see on app.modelrig.ai — Runs, Calls, grades, the gateway and modelrig doctor's org check. Without one, the SDK still serves your calls and records telemetry to ./.modelrig/telemetry.db on your machine (npx modelrig status reads it), but nothing reaches the console. You can add it later.
There are two ways your calls are keyed and billed, and you pick per route:
- Bring your own keys (BYOK). Your provider keys stay in your environment; ModelRig routes to the provider directly. The first 1,000,000 requests each month are free, then a flat 2% of list price. On the raw lane (
rig.runRaw) thetimeoutMsdefault is tier-aware — flex ⇒ settimeoutMsin minutes (default 900 s since 0.5.0); see the raw-lane defaults table. - Managed keys. ModelRig fronts the provider's inference cost, so managed calls are provider cost + 2% from the first request — no key for you to hold.
Same flat 2% margin either way; your negotiated provider discounts stay yours.
Point your coding agent at it
The fastest migration is the one your agent performs. Paste the migration prompt from modelrig.ai/get-started (the console's /setup page carries the same prompt) into Claude Code, Codex, or Cursor from inside your project. It is the maintained version: it starts the agent at the bottom of the autonomy ladder, has it confirm the org your key exports to, wrap each pipeline execution in a run, and stop for your approval at every checkpoint.
Your agent reads the docs, finds your LLM call sites, and wires them in. It won't create accounts, sign in, or touch your API keys (those stay in the environment you set before you start), and when it replaces a call site with rig.run() it keeps prompt and schema semantics unchanged — same model, human-reviewed.
Or set it up by hand
1. Install
pnpm add modelrig # or npm i modelrig — Node >= 20
It installs a native module (better-sqlite3) from a prebuilt binary on macOS and Linux (x64/arm64); any other platform compiles it at install time and needs a C++ toolchain.
Deploying: modelrig needs a Node runtime (not Edge/Workers), and if your deploy bundles server code you must mark it external — Next.js serverExternalPackages: ['modelrig'], esbuild --external:better-sqlite3, webpack externals. Set MODELRIG_API_KEY on every service, worker, and cron that runs a rig; hosted-platform specifics are in Deploying.
import { createRig, loadConfigFromEnv } from "modelrig";
Environment (read once, in ModelRig's config layer only):
# Provider keys: only the providers you configure get adapters. Set the ones
# your routes (or runRaw calls) use; these are the names the SDK reads.
GEMINI_API_KEY=…
OPENAI_API_KEY=…
DEEPSEEK_API_KEY=…
ANTHROPIC_API_KEY=…
XAI_API_KEY=… # grok
ZAI_API_KEY=… # Z.ai / Zhipu
MODELRIG_DEEPINFRA_API_KEY=…
MODELRIG_FIREWORKS_API_KEY=…
OPENROUTER_API_KEY=… # OpenRouter (your own key)
ASSEMBLYAI_API_KEY=… # AssemblyAI LLM Gateway (your own key; no console vault slot)
# Bedrock / Azure OpenAI / Vertex take structured credentials, a set each:
# MODELRIG_BEDROCK_ACCESS_KEY_ID (+ _SECRET_ACCESS_KEY, _REGION),
# MODELRIG_AZURE_OPENAI_ENDPOINT (+ the rest of its set),
# MODELRIG_VERTEX_SERVICE_ACCOUNT_JSON (+ the rest of its set) — see route-bundles.md.
# Where your telemetry goes — pick ONE lane:
MODELRIG_API_KEY=rig_sk_… # hosted: rows go to ModelRig,
# scoped to the org that key names
# SET IT ON EVERY service/worker/cron
# (omit it and everything below still works, locally)
MODELRIG_ROUTES_DIR=./modelrig/routes # default
MODELRIG_TELEMETRY_DB=./.modelrig/telemetry.db # default
MODELRIG_ENVELOPE_BUDGET_USD=25 # default envelope budget
2. Confirm the org
Confirm the org before you trust an empty console. Run modelrig doctor from the same environment your app runs in, once your app has started with the key. It asks GET /v1/whoami which organization the key belongs to and prints the org's name and, in parentheses, its slug; the name must match the org badge in the console header. If it names a different organization, your data is landing there: switch the console to that organization, or mint a key in the one you meant (https://modelrig.dev/orgs-and-keys.html).
npx modelrig doctor
# [modelrig] key rig_sk_…AbCd → org «Your Org» (your-org) ✓ (ingest https://api.modelrig.ai, …)
# No CLI in that environment? Ask the API directly (same host the SDK uses):
curl -H "Authorization: Bearer $MODELRIG_API_KEY" "${MODELRIG_INGEST_URL:-https://api.modelrig.ai}/v1/whoami"
3. Wrap one execution in a run — raw lane, no route yet
Every pipeline execution is a run. A run is the standard way ModelRig records what your workstream did — not an appendix. The console's Runs tab then shows the run → step → artifact chain you can click through, and Group by (/projects) groups it by tag.
No route yet, because you are observing first or calling providers through a rig.runRaw seam? You don't need one:
No routes yet? Build the rig raw-only. Observing a pipeline, or recording calls your code makes itself, needs no route files. Construct the rig with routesDir: null: rig.runRaw, rig.runRawStream and rig.recordCall work at once, and rig.run / rig.runBundle refuse with a teaching error until you add routes. Without it, createRig loads ./modelrig/routes: a directory you configured that is missing throws, and a missing default directory falls back to raw-only with a one-line warning.
import { createRig, loadConfigFromEnv } from "modelrig";
// Raw-only on purpose: no route files needed. rig.runRaw, rig.runRawStream and
// rig.recordCall work; rig.run needs routes (add them later, drop routesDir: null).
const rig = createRig({ ...loadConfigFromEnv(), routesDir: null });
The same run, with rig.runRaw doing the call:
No routes yet? The same run on the raw lane. A run does not need a route. Build the rig with routesDir: null and call rig.runRaw inside run.scope: each call records a step named by stepKey, and artifact.save attaches the work products, exactly as on a route. Your code passes its own provider key from its environment, and nothing about the request changes. Graduate a call site to a route later, when you want schema validation, fallbacks or a bake-off.
import { createRig, loadConfigFromEnv } from "modelrig";
// No route files: the raw lane. Each rig.runRaw inside the scope records a step.
const rig = createRig({ ...loadConfigFromEnv(), routesDir: null });
await rig.artifacts.run.scope(
{ pipeline: "support", episodeKey: ticketId, environment: process.env.NODE_ENV ?? "development" },
async () => {
const result = await rig.runRaw({
provider: "openai",
model: "gpt-5.4-mini",
apiKey: process.env.OPENAI_API_KEY ?? "", // your provider key, from your own environment
systemPrompt: "Summarize this support ticket in two sentences.",
userPrompt: ticket,
tags: { subject: customer, feature: "summarize" },
stepKey: "summarize", // names this step on /runs
});
rig.artifacts.artifact.save(result.output, { name: "summary", type: "step_output", stepKey: "summarize" });
},
);
await rig.close(); // flushes the exporter — call once at shutdown
Change a step's model (no redeploy)
The stepKey you just passed is also the handle ModelRig pins a model to (needs modelrig 0.14.0 or newer). Keep passing the model you use today: it is the step's default. To change it later, open Routes & steps in the console, pick the step, choose a model, tier or Flex window and Save. The step's next run uses it, and Rollback restores any earlier version. Semantics (run-scoped, fail-open, fail-closed, cache) are in Routing & reliability.
Choose the model per step without a deploy. Name each rig.runRaw call's step with stepKey, and the model your code passes becomes that step's default. Pin a different model, tier or Flex window for the step on Routes & steps in the console (https://app.modelrig.ai/routes), or with set_call_config from the MCP oracle: no redeploy. A pin applies to runs that start after ModelRig's settings cache refreshes (at most about a minute after you save); a run never changes model mid-run. With no pin, the call is exactly what your code asked for. If ModelRig can't be reached, the step keeps the last pin it read, or uses your code's model if it never read one; the call never fails because of it. Keys never move: the call still goes out from your process on your own provider key, and a pin to another provider uses that provider's key from your environment, failing closed with an error naming the variable (for example OPENAI_API_KEY) when it is missing. A pin the call can't use (grounding or a responseSchema the pinned model can't honor) fails closed before dispatch, and a cache handle made for your code's model is dropped, so the pinned call runs uncached. Every change is a version you can roll back in one click, and each call records model_source (code or step-config). It needs MODELRIG_API_KEY; createRig({ ...loadConfigFromEnv(), stepConfig: false }) turns it off.
const overview = await rig.runRaw({
stepKey: "business_overview", // the step's name: the handle a pin attaches to
provider: "gemini",
model: "gemini-3.1-pro-preview", // your code's default; a step pin replaces it for new runs
apiKey: process.env.GEMINI_API_KEY ?? "",
systemPrompt: "You are an equity analyst.",
userPrompt: "Summarize the business in five bullets.",
});
- Raw lane: a
rig.runRawcall inside a run context records a ground-truth step (since 0.5.0), so grounded/cached pipelines fill the same graph as routed ones. - A call your code makes itself (a direct provider client, a stream, an embedding) is invisible until you record it:
Record a call your code makes itself. A provider call your code makes directly (a client ModelRig has no lane for, a stream you read yourself, an embedding, a fallback) is invisible until you report it. Call rig.recordCall right after it returns, inside the run, with the tokens the provider reported: the call shows on /inferences as "Reported by your code", joins its run and step, and counts toward cost. It is synchronous and never throws; invalid input warns once and records nothing (inferenceId: null). Spread optional fields only when the provider reported them, so the call type-checks under exactOptionalPropertyTypes.
const started = Date.now();
const resp = await genai.models.generateContent({ model: "gemini-3.1-pro-preview", contents });
const u = resp.usageMetadata;
const finishReason = resp.candidates?.[0]?.finishReason;
const rec = rig.recordCall({
provider: "gemini",
model: "gemini-3.1-pro-preview",
usage: {
tokensIn: u?.promptTokenCount ?? 0, // total input, cached included
tokensOut: (u?.candidatesTokenCount ?? 0) + (u?.thoughtsTokenCount ?? 0),
tokensCached: u?.cachedContentTokenCount ?? 0,
// optional fields: spread only when the provider reported them
...(u?.thoughtsTokenCount !== undefined ? { reasoningTokens: u.thoughtsTokenCount } : {}),
},
servedTier: "standard", // the tier that SERVED the call: pass what the provider reports (flex, priority); it is priced at that tier
latencyMs: Date.now() - started,
stepKey: "summarize", // the step on /runs (inside run.scope / run.start)
...(finishReason !== undefined ? { finishReason } : {}),
});
if (rec.inferenceId !== null) rig.grade({ kind: "inference", id: rec.inferenceId }, { score: 1, kind: "deterministic" });
- Reserved tags:
run_idandstepare stamped by the SDK; the full list of reserved keys is in the instrumentation guide.
The full artifact API — lineage (link), grades, the reusable per-step seam, and run.scope vs run.start — is the instrumentation guide.
4. Define a route bundle (when you want one)
One YAML file per route under modelrig/routes/:
# modelrig/routes/example.support_summarize.yaml
route: example.support_summarize # the task handle you pass to rig.run
version: 1 # bump on ANY change
schema: ./schemas/support_summarize.schema.json # null for unstructured routes
candidates: # THE candidate set — the invariant boundary.
- provider: openai # Nothing outside this list can ever serve
model: gpt-5.4-mini # the route: enforced by a branded type at
- provider: gemini # compile time and a runtime guard.
model: gemini-3.1-flash-lite
require: [schema_conformant] # hard constraints on candidate eligibility
prefer: [cost] # advisory ordering (cheapest first)
prompt:
system: ./prompts/support_summarize.system.md
variables: [ticket, product, priorContext]
policy:
retries: { content_invalid: 2, network: 4, capacity_shed: 3 }
timeout_ms: 60000
tier: flex # requested tier; served tier is recorded
json: native # native strict schema | json_mode (rung 2)
sampling: { temperature: 0.1, max_output_tokens: 8192 }
# ^ preserve the original call's sampling;
# absent = the adapter's own defaults
Prompt templates support {{variable}} substitution and capability-conditional blocks resolved against the serving candidate's flags:
Summarise this ticket for the next agent: {{ticket}}
{{#if capability.grounded_native}}
Use web search to verify recent events.
{{/if}}
{{#unless capability.structured_native}}
CRITICAL: respond with a single JSON object, no markdown fences.
{{/unless}}
Variables must be declared in prompt.variables; referencing an undeclared variable fails at load time, not at run time.
The route references two files next to it, and both must exist or the route fails to load (schema file not found / prompt.system file not found). npx modelrig init writes this starter route's two files, modelrig/routes/schemas/support_summarize.schema.json and modelrig/routes/prompts/support_summarize.system.md, without overwriting files you already have. Then npx modelrig validate checks the bundle with no provider key.
The schema file is a JSON Schema. ModelRig validates output under JSON Schema 2020-12 as the primary dialect and also accepts draft-07 (a schema declaring either $schema compiles). Validation runs non-strict with union types allowed, and format is annotation-only — it is not asserted (an email/date-time format is documentation, not a constraint). Author 2020-12 unless you have a draft-07 schema already; both work.
5. Call the route inside the run
With the route above in place:
const rig = createRig(loadConfigFromEnv());
const result = await rig.run("example.support_summarize", {
input: { ticket: rawTicket, product: "Acme Cloud", priorContext: history },
tags: { subject: "acme", feature: "summarize" },
budget: { envelope: "ticket-123" }, // hard-stop cost envelope for the run
});
result.output; // JSON, already validated against your schema
result.meta.provider; // which candidate actually served
result.meta.costEstimateUsd; // priced from the pinned LiteLLM snapshot
result.meta.servedTier; // vs meta.requestedTier — downgrades visible
result.meta.attemptsByClass; // retries consumed, per failure class
await rig.close(); // flushes telemetry; await it once at shutdown (R6)
Inside the run from step 3, the routed call replaces rig.runRaw:
Wrap one pipeline execution in a run. Every pipeline execution is a run. Wrap each execution in run.scope (or run.start / run.end), name one step per model call with stepKey, artifact.save the work products, and pass environment so the Env column on /runs is filled. Inside the run the SDK stamps run_id and step on every call. run_id is reserved: don't set it yourself.
import { createRig, loadConfigFromEnv } from "modelrig";
const rig = createRig(loadConfigFromEnv());
// Every pipeline execution is a run. Inside the scope the SDK records each
// rig.run / rig.runRaw call as a step and stamps run_id and step on every row.
// run_id is reserved: don't set it yourself (put your own attempt id in a tag of
// your own, such as pipeline_attempt_id).
await rig.artifacts.run.scope(
{ pipeline: "support", episodeKey: ticketId, environment: process.env.NODE_ENV ?? "development" },
async () => {
const result = await rig.run("example.support_summarize", {
input: { ticket, product, priorContext },
tags: { subject: customer, feature: "summarize" },
stepKey: "summarize", // names this step on /runs
});
rig.artifacts.artifact.save(result.output, { name: "summary", type: "step_output", stepKey: "summarize" });
},
);
await rig.close(); // flushes the exporter — call once at shutdown
6. See it on Runs (/runs)
Open /runs in the console, with the org badge showing the org doctor named: the run, its steps in order, and the artifacts you saved. modelrig status prints runs recorded: N (last: …) as the local mirror, and modelrig validate warns if a rig records calls but never starts a run. If the page is empty:
The console is empty: five checks, in order. If /runs (or /inferences) is empty for the org in the header badge, work these checks in order. The full tree is https://modelrig.dev/troubleshooting.html.
1. npx modelrig doctor, from the environment your app runs in.
no export sink configured → this process does not see MODELRIG_API_KEY: set it, redeploy, open a new shell.
malformed key → the value is truncated, quoted or padded: paste the whole rig_sk_… secret again.
AUTH FAILED (401 / 403) → the key is mistyped, revoked or not accepted: mint a key, set it, redeploy, open a new shell.
whoami unreachable → no network path to the ingest host (firewall, proxy, wrong MODELRIG_INGEST_URL): fix the route out, retry.
2. The org doctor prints is not the org in the badge → wrong org: switch the console, or mint a key in the org you meant.
3. /inferences has rows but /runs is empty → the calls are not inside run.scope / run.start.
4. A run is missing a step or a cost → that call is not on a ModelRig lane (see not-captured).
5. A doc describes something your install lacks → compare `npm ls modelrig` with the version stamp in modelrig.dev/llms.txt.
7. Grade it, then prove a cheaper model
Attach a grade to a call or a whole run. A grade is your judgment: a 0–1 score with an optional comment, from a validator, a downstream accept/reject, a human or a model. Grade one call by its inference id (result.meta.inferenceId, or the inferenceId rig.recordCall returns). Grade a whole run by its run id, run.runId on the handle run.start returns: that grade shows on the run page and on /projects. A run grade whose id is the run's episodeKey also shows, on the run page only. run_id is a reserved tag the SDK stamps, not a variable your code has. A grade whose id matches no call or run attaches to nothing. The write is synchronous and local and never throws into your pipeline.
const run = rig.artifacts.run.start({ pipeline: "support", episodeKey: ticketId, environment: "production" });
const result = await rig.runRaw({
provider: "openai",
model: "gpt-5.4-mini",
apiKey: process.env.OPENAI_API_KEY ?? "",
systemPrompt: "Summarize this support ticket in two sentences.",
userPrompt: ticket,
tags: { subject: customer },
stepKey: "summarize",
});
run.end("succeeded");
// one call: the inference id rides on every result (rig.runRaw and rig.run alike)
rig.grade({ kind: "inference", id: result.meta.inferenceId }, { score: 1, kind: "deterministic", grader: "schema-check" });
// the whole run: its id is run.runId from run.start (shows on the run page and on /projects)
rig.grade({ kind: "run", id: run.runId }, { score: 0, kind: "human", comment: "missed the refund request" });
Have an AI grader judge outputs against your rubric. Code grades cover what your code can already check. To have an AI grader judge outputs against your rubric, create one on Graders (https://app.modelrig.ai/graders), which gives you a copy-paste prompt for your coding agent; the same prompt is at https://modelrig.dev/set-up-a-grader.html.
Prove a cheaper model on your own traffic. A bake-off replays your own inputs through the variants a route declares and reports the effective cost of conformance for each. --variants names entries in the route's variants: block (default is the route as declared), never model ids, and a variant can only narrow the route's candidates. Set capture: true first: replay works on traffic captured after that, not before. With no captured traffic (a run-based pipeline), promote a real /runs output to a golden (the console's make golden, or promoteToEval) and use --from-eval-cases <task>; its variants come from the route bundle named after the task. A bake-off measures and never switches anything.
# 1. in modelrig/routes/example.support_summarize.yaml: capture traffic, and declare
# a cheaper variant (narrowing only: its candidates must be in the route's list)
capture: true
variants:
- name: cheap
candidates:
- provider: gemini
model: gemini-3.1-flash-lite
# 2. after traffic accumulates, compare the route as declared (default) with cheap
npx modelrig bakeoff --route example.support_summarize --variants default,cheap --replay-last 50
# no captured route traffic? promote a real /runs output to a golden, then
npx modelrig bakeoff --from-eval-cases example.support_summarize --variants default,cheap
Optional — keep prompts and outputs (call capture)
(call capture needs modelrig 0.14.0 or newer) ModelRig records every call's metadata and cost from the first run. Prompt and output text is kept only when you save it or turn on call capture (captureCalls):
Keep prompts and outputs: turn on call capture. By default ModelRig records every call's metadata and cost (model, tokens, tier, latency, failure, and hashes and sizes of the request and output), not the prompt or output text. You keep text two ways: save it yourself with artifact.save, or turn on call capture in code with artifacts.captureCalls: true. It is off by default and is not an env var, and it needs api mode (MODELRIG_API_KEY): direct and local-only rigs never capture. With it on, each attempt ModelRig sends to a provider through rig.run, rig.runBundle, rig.runStream, rig.runRaw and rig.runRawStream saves the request as rendered before provider-side additions as a prompt artifact and the response text as a raw_response artifact; retried attempts each get their own pair, a failed attempt keeps its prompt plus the model's response when the provider returned one (for example a content_invalid or quality-rejected attempt), and the call page labels them captured (opt-in). It applies only when your organization's content posture is managed, and never under metadata or off, while the SDK has not read (or cannot re-read) the posture, or on a zero-retention route or run. On the current modelrig release, a call in mask mode: mask is captured exactly as it was dispatched, already tokenized; a detect call is never captured, and older SDKs skip every route or call with a mask policy. Captured text takes the same path as any artifact you save: your scrub setting runs first (a pii or phi route is scrubbed at redact or stronger), the upload size limit applies, and stored content follows your organization's retention setting on /account. rig.recordCall never captures text; save artifacts for those calls yourself. Details: https://modelrig.dev/not-captured.html.
import { createRig, loadConfigFromEnv } from "modelrig";
// Opt in, in code (not an env var): keep each call's prompt and response text.
const rig = createRig(loadConfigFromEnv({ artifacts: { captureCalls: true } }));
Optional — the gateway (OpenAI-compatible base URL)
Setup starts at step 3 (a run on the raw lane), not here. The gateway is an optional path for an OpenAI-compatible client, and it needs a provider key stored in Vault first:
Optional — the gateway (OpenAI-compatible base URL). Optional, and not where setup starts: an OpenAI-compatible client can point its base URL at https://api.modelrig.ai/v1 with your rig_sk_ key (MODELRIG_API_KEY) as its API key, naming the model as <provider>/<model> (such as openai/gpt-5.4-mini) for a BYOK passthrough on your own provider key. A human must first store that provider key on the Vault page (https://app.modelrig.ai/vault), and a coding agent never handles the value; without a stored key the call returns 402, and it never falls back to a ModelRig key. Serving a route over the gateway needs managed serving (ask us). Gateway calls show on Calls (/inferences) but carry no run context, so they never fill Runs (/runs): runs come from the SDK path, rig.runRaw or rig.recordCall inside run.scope.
# Optional: point an OpenAI-compatible client at ModelRig (needs a provider key stored in Vault).
base_url = https://api.modelrig.ai/v1
api_key = $MODELRIG_API_KEY # your rig_sk_ key, sent as the bearer
model = "openai/gpt-5.4-mini" # <provider>/<model>: BYOK passthrough on the key stored in Vault (402 without one)
Change your route's model live (no redeploy)
A route's call-config — which model/provider serves it, and its sampling — can be changed while your app runs, without editing YAML or redeploying. You set it in the console (the route's call-config card), or your coding agent sets it for you over MCP (set_call_config, below); the SDK reads the current config just-before-call and merges it over your bundle. Two modes:
pin— one model serves the route right now.experiment— a weighted live A/B across arms, with the chosen arm recorded on every row so the console can score it.
See what a route serves — before its first call. Your YAML stays the deploy-time default and the fail-open safety net; ModelRig is where you see and change it. A rig created with a routesDir and a control-plane key registers each route the moment createRig() runs — its metadata (route, version, candidates) and its declared bundle (the prompt template with its {{placeholders}}, schema, policy, plus a content hash): fire-and-forget, fail-open, through the same /v1/ingest call telemetry uses (the ingest scope is enough). The bundle is stored as route configuration, not captured content — it holds the authored template, never per-call values — so it is stored even when your org's capture posture is off (telemetry rows are still dropped then). Registering the bundle is what lets the control plane validate and accept a pin for the route: a pin is checked against the route's require before it is written, so a route with no registered bundle refuses pins with a teaching 422. If you promote a prompt version in ModelRig (Prompt System of Record), the promoted template wins over the one in your YAML on every later registration; everything else (candidates, schema, policy) follows your deploy. So every route shows up in the console and over MCP right away, and one read answers "what will this route serve, and why?":
curl -H "authorization: Bearer $MODELRIG_API_KEY" \
"${MODELRIG_INGEST_URL:-https://api.modelrig.ai}/v1/routes/example.support_summarize/call-config?include=effective"
{
"version": 0, "mode": null, "config": null, // no override yet
"effective": {
"source": "deployed_default", // pin | experiment | deployed_default | unknown
"provider": "openai", "model": "gpt-5.4-mini", // your YAML's first candidate
"version": 1, // the YAML route version
"since": "2026-10-10T12:00:00Z" // when the deployment last declared it
},
"drift": null
}
source: "pin" means a call-config pin is serving (its version is the call-config version); unknown means no deployment has registered the route in your org yet. When a pin is set but recent calls on the route served a different model, drift says so — { servedProvider, servedModel, calls, lastSeen, pinnedCalls, windowStart } (last 24h, starting 5 minutes after the pin, ≤500 calls sampled). Drift means your app is not honoring the pin: its resolver is failing open (an older SDK, a wrong MODELRIG_API_KEY, or a call path that never resolves call-config — see below). The console's call-config card shows the same thing as Serving: \<model\> — \<pin vN | YAML default\> plus a drift warning; get_call_config over MCP returns it too. Without ?include=effective the response is unchanged (that is what the SDK's serve-time poll reads).
Read call-config just-before-call. Build a resolver once (it caches with a short TTL and revalidates by ETag — no per-call network cost when fresh), then overlay the current config onto a bundle and serve it through rig.runBundle():
import {
createRig, loadConfigFromEnv,
createApiCallConfigFetcher, createCallConfigResolver,
getCallConfig, // pin-only convenience: route + bundle → runnable bundle
} from "modelrig";
const rig = createRig(loadConfigFromEnv());
// Build once, reuse across calls. TTL is the cache-freshness window (~30–60s).
const resolver = createCallConfigResolver({
fetcher: createApiCallConfigFetcher({
ingestUrl: process.env.MODELRIG_INGEST_URL ?? "https://api.modelrig.ai",
apiKey: process.env.MODELRIG_API_KEY!, // a read needs no special scope
}),
ttlMs: 30_000,
});
// `bundle` is the route's deploy-time bundle you already hold (see runBundle below).
// getCallConfig merges the live PIN over it; with no override it returns the SAME
// bundle reference — byte-identical to today.
const runnable = await getCallConfig("example.support_summarize", { resolver, bundle });
const result = await rig.runBundle(runnable, { input, tags });
Fail-open, always. The read never throws: on any error it serves the last-known-good config, and a route with no override resolves byte-identical to the deploy-time bundle (the same bundle reference, unchanged). Turning this on adds no failure mode to the hot path.
Where it applies. Call-config is overlaid onto a bundle you serve through rig.run() / rig.runBundle() — not rig.runRaw. The raw lane is BYOK and has no route or bundle to overlay, so a routeless raw-lane caller that wants live routing must first own a route/bundle (build one with bundleFromResolved, or resolve one from disk) and serve it through runBundle.
A/B — draw an arm locally, record it. For mode='experiment', resolve the config and draw the arm for this one call with resolveCallConfigForRun, then thread the arm name onto rig.runBundle(..., { arm }) so it lands on inferences.meta.arm:
const resolved = await resolver.getCallConfig("example.support_summarize");
const { bundle: runnable, arm } = resolveCallConfigForRun(bundle, resolved, {
input, // stickyKey (if set) reads its unit from here…
// unitKey: userId, // …or pass the unit key explicitly (sticky assignment)
});
// arm is string | null and RunOptions.arm is optional: pass it only when one was
// drawn (a bare `arm` fails to compile under exactOptionalPropertyTypes).
const result = await rig.runBundle(runnable, { input, tags, ...(arm !== null ? { arm } : {}) });
// arm is null for a pin / no-override / non-experiment call ⇒ no meta.arm (byte-identical).
Sticky assignment means the same unit always draws the same arm, so the A/B is measured honestly. The console reads per-arm outcomes at GET /v1/console/ab-readout?route=<route>. How meta.arm is populated and overlaid is in the instrumentation guide.
Set it from your coding agent (MCP). The modelrig-oracle MCP server exposes get_call_config, set_call_config (pin or experiment), and rollback_call_config, so the agent in your editor can pin a model or start an A/B on your behalf — a real, versioned, reversible control-plane change (not a draft). Writes need a rig_sk_ key with the route-config scope; reads need none. The full flow, the eligibility gate, and the rollback contract are in The MCP oracle → Setting a route's live config.
When it fails, it fails typed
import { RigFailureError } from "modelrig";
try {
await rig.run("example.support_summarize", opts);
} catch (err) {
if (err instanceof RigFailureError) {
err.failure.class; // content_invalid | capacity_shed | network | refusal
// | cache_invalid | timeout | config_auth
// | budget_exhausted | invariant_violation
// | quality_rejected
err.failure.fixHint; // machine-readable remediation when available
}
}
Retry budgets are per class and non-fungible — exhausting network retries never consumes the content_invalid budget. Terminal classes (budget_exhausted, invariant_violation) are never retried. config_auth (bad or missing credentials) is non-retryable by contract: it cannot appear in a bundle's retry budgets, is never retried on the same candidate, and the run loop advances straight to the next candidate — a dead key never burns backoff time. Failures that still billed tokens (refusals, truncations) carry their token usage, so envelopes and telemetry account the real spend.
Each class — what it means, whether it retries, and how it backs off — is on Routing & reliability; that page also covers how the whole candidate ladder runs: the ordering, the validate → repair → fall-through sequence, and the parts that are not built yet.
Where the telemetry goes
Every attempt (not just every run) writes one row to package-owned SQLite, tagged with your tags — always, with no key. Setting MODELRIG_API_KEY turns on api export mode: a background exporter ships batches to the ingest API (api.modelrig.ai, override with MODELRIG_INGEST_URL), which the console reads — fire-and-forget: a transient failure (network, 5xx) is retried, a rejected key (401/403) drops the rows and logs AUTH FAILED; the inference path never blocks on it. Inspect live rows in your local SQLite file, or in the console once the key is set — never a database URL of your own.
MODELRIG_API_KEY gates the exporter per process. Set it on EVERY service, worker, and cron that constructs a rig — a process without it buffers to its own local SQLite and ships nothing. A multi-service deployment that sets the key on only the web tier silently loses every row a worker or cron produced.
Turning Optimization on for a route (capture: true) is the recommended default — your traffic is what makes the routing smarter and the bill smaller, and everything it keeps you can see and export in the console. Keeping the prompts, outputs and evidence too is content custody, which is on by default — every new org is created managed, having accepted the published terms at signup — and captures into your managed store, scrubbed for the PII/PHI you classify. Either way the opt-out is one account setting (the console or the set_org_settings MCP tool): set posture off to capture nothing or metadata to keep hashes only, or use a zero_retention route. Pure router (capture off) stays real and selectable, at the same flat 2%.
Telemetry says what happened; a grade says whether it was good. Attach a 0–1 score (up = 1, down = 0) to a call or a whole run with rig.grade(...) — from the SDK or over HTTP for a non-SDK surface (see the grade protocol) — and every run gets an automatic run-outcome@v1 grade, with an explicit, bounded model judge available when you want one (see the grade protocol).
Serve without holding the provider key (optional)
Everything above runs on your provider key — destination: direct, the default, and nothing here changes it. If you would rather ModelRig serve a route's model on its own credentials and bill it from a prepaid balance, declare destination: modelrig-served on the route, set managedServing: true in the rig config, have an org owner or admin mint a key with the serve scope, and turn managed serving on in Account settings. The walk-through, including what each refusal teaches, is Managed serving.
Runtime requirements
ModelRig assumes a long-lived Node process with a writable disk, and a few things follow from that. Check them before you deploy:
- Node ≥ 20. The local telemetry buffer is
better-sqlite3(a C/C++ addon): it installs from a prebuilt binary on macOS and Linux (x64/arm64), and compiles at install time anywhere else — on such a platform, or a slim container without the prebuilt, add the build essentials (python3,make, a C++ compiler). - A writable disk. Telemetry and captures go to a local SQLite file (
MODELRIG_TELEMETRY_DB, default./.modelrig/telemetry.db); the background exporter batches from it. A read-only filesystem breaks this. - Serverless (Vercel functions, AWS Lambda, Google Cloud Functions): supported, with two required adjustments. (1) Point the telemetry DB at the only writable location —
MODELRIG_TELEMETRY_DB=/tmp/modelrig/telemetry.db. (2)await rig.close()once per invocation before the handler returns: the function may freeze or be killed the moment you respond, andclose()is what drains the final rows (H1) — skip it and you silently lose the last attempts of every invocation. Expect a native-module cold-start cost on the first call after a scale-up. - Edge runtimes (Vercel Edge, Cloudflare Workers) are unsupported. They have no native-addon support and no filesystem, so
better-sqlite3cannot load at all. Run ModelRig in a Node runtime; if an edge function must call a route, put ModelRig behind a Node service it calls over HTTP.
When it doesn't work
The first three failures below stop the bundle loading; the fourth lets it load and then misbehave, so it is the one to watch for. The full list, in the loader's own words, is in route-bundles.md.
- The bundle won't load, naming a schema or prompt path. The file isn't at the path the bundle names — paths resolve relative to the bundle. Create it there, or set
schema: nullfor a free-form task. - The bundle won't load, naming an undeclared variable. A
{{name}}in the template isn't inprompt.variables. Add it (or fix the typo). - The first call succeeds locally but nothing appears in the console. Usually
MODELRIG_API_KEYisn't set in that environment, or it belongs to a different org than the one the console is showing. Runnpx modelrig doctorthere and work through Troubleshooting an empty console. - The call runs but the output isn't what the old code produced. Usually a wrong
json: native— a claim about the model, valid only for one whose registry entry shows probedstructured_native. Check the probed registry, not memory.
Still stuck? See the Troubleshooting guide.