Nirmos
Examples and recipes

Configure Gateway automatic fallback

Provision explicit fallback triggers, then invoke the route from application code.

Create a nondefault chat route with a primary target and one backup. Provisioning is a one-time administrative operation; application requests use its returned route ID.

Prerequisites and Dashboard setup

Configure working credentials for both target providers in the same organization. Choose active, compatible chat models. Generate a setup key with route:create; inference needs gateway:execute. Cleanup needs route:delete, and inspecting logs needs observability:read. A production application key can have only execution access after setup.

Set NIRMOS_API_KEY. For provisioning, set NIRMOS_PRIMARY_PROVIDER_ID, NIRMOS_PRIMARY_MODEL_ID, NIRMOS_BACKUP_PROVIDER_ID and NIRMOS_BACKUP_MODEL_ID to catalog IDs. Use different primary and backup targets.

Install the published package and a TypeScript runner in a new project:

npm install @nirmos/sdk
npm install --save-dev tsx typescript @types/node

Use a trusted Node.js process with Fetch and Web Crypto. Read secrets from its environment or secret store. Optional NIRMOS_API_URL and NIRMOS_RUNTIME_URL select another deployment; leave them unset for hosted defaults. The SDK does not load .env files automatically.

Complete code

Save as fallback.ts.

fallback.ts
import { Nirmos, NirmosError } from "@nirmos/sdk";

function requiredEnv(name: string): string {
  const value = process.env[name];
  if (!value) throw new Error(`Set ${name} before running this recipe`);
  return value;
}
function configuredClient(): Nirmos {
  return new Nirmos({
    auth: { type: "api-key", key: requiredEnv("NIRMOS_API_KEY") },
    apiBaseUrl: process.env.NIRMOS_API_URL,
    runtimeBaseUrl: process.env.NIRMOS_RUNTIME_URL,
    maxRetries: 0,
  });
}
function report(error: unknown): never {
  if (error instanceof NirmosError) {
    console.error({ code: error.code, status: error.status, requestId: error.requestId });
  }
  throw error;
}

export async function provisionFallback(
  client: Nirmos,
  targets: { primaryProviderId: string; primaryModelId: string; backupProviderId: string; backupModelId: string },
) {
  const route = await client.routes.create({
    name: `Recipe fallback ${Date.now()}`, status: "active", isDefault: false, strategy: "weighted",
    // Required by nondefault route validation. Runtime does not evaluate this condition.
    matchExpression: {
      id: "recipe-group", type: "group", combinator: "and",
      children: [{ id: "recipe-condition", type: "condition", field: "request.application", operator: "equals", value: "sdk-fallback-demo" }],
    },
    targets: [{ providerId: targets.primaryProviderId, modelId: targets.primaryModelId, enabled: true, weight: 1 }],
    fallback: {
      enabled: true, triggerErrors: ["timeout", "rate_limited", "provider_unavailable", "provider_error", "connection_error"],
      maxAttempts: 1, timeoutMs: 30_000,
      targets: [{ providerId: targets.backupProviderId, modelId: targets.backupModelId, enabled: true }],
    },
  });
  if (!route.id) throw new Error("Route creation returned no ID; inspect before retrying creation");
  console.log({ routeId: route.id });
  return route.id;
}

export async function invokeFallback(client: Nirmos, routeId: string) {
  const completion = await client.gateway.chat.create({
    route: routeId, messages: [{ role: "user", content: "Explain an AI gateway in one sentence." }],
    maxOutputTokens: 200,
  }, { timeoutMs: 90_000, signal: AbortSignal.timeout(95_000), maxRetries: 0 });
  console.log(completion.outputText);
  console.log({ requestId: completion.metadata.requestId, model: completion.model, provider: completion.metadata.provider });
  return completion;
}

if (process.env.NIRMOS_RUN_RECIPE === "1") {
  try {
    const client = configuredClient();
    if (process.env.NIRMOS_PROVISION_ROUTE === "1") {
      await provisionFallback(client, {
        primaryProviderId: requiredEnv("NIRMOS_PRIMARY_PROVIDER_ID"), primaryModelId: requiredEnv("NIRMOS_PRIMARY_MODEL_ID"),
        backupProviderId: requiredEnv("NIRMOS_BACKUP_PROVIDER_ID"), backupModelId: requiredEnv("NIRMOS_BACKUP_MODEL_ID"),
      });
    } else await invokeFallback(client, requiredEnv("NIRMOS_ROUTE_ID"));
  } catch (error) { report(error); }
}

Provision once, then execute

NIRMOS_RUN_RECIPE=1 NIRMOS_PROVISION_ROUTE=1 npx tsx fallback.ts

Save the printed route ID as NIRMOS_ROUTE_ID. Provisioning changes shared configuration and makes no inference request. It does not change the organization's default route.

NIRMOS_RUN_RECIPE=1 npx tsx fallback.ts

A healthy primary produces a normal response. When a selected upstream failure category occurs, runtime can try the configured backup. Inspect returned model/provider metadata and the request's stored logs to identify the executing target. This recipe does not intentionally break production credentials or guarantee a fallback on every execution.

Trigger boundaries

The chosen list includes timeout, rate limiting, provider unavailable/error and connection failures. It excludes authentication errors, invalid requests, context-length failures and content blocking. Nirmos authentication/permission failures and unresolved routes happen outside eligible provider fallback. Caller cancellation stops execution.

The stored match condition is required by nondefault configuration validation but does not execute conditional routing. Invoke this route explicitly; the condition is not access control. SDK HTTP retries remain disabled in this example. Runtime same-target retries are a separate layer, and streaming cannot continue on another model after any chunk has been emitted.

Delete only this demo route with routes.delete(routeId) after confirming no callers use it. Route configuration · Routing behavior · Route methods

On this page