Nirmos
Examples and recipes

Evaluate a model against two cases

Configure a frozen dataset, exact-match evaluator, and bounded model run.

This supplemental recipe measures a model directly. For a saved prompt candidate, use evaluate a prompt before release.

Prerequisites

Create a Dashboard key with evaluation:create, evaluation:read, evaluation:update, evaluation:run and evaluation:cancel, plus provider:read and model:read for discovery. Optional archival needs evaluation:update. Configure a working provider credential and select a chat model in the same organization.

This example creates only disposable evaluation resources. The exact-match scorer is deterministic and makes no judge calls. The model target still makes two provider requests; its answers and scores are not guaranteed. Offline documentation tests inject Fetch responses and do not consume provider quota. Live execution has not been verified against your deployment.

Save as evaluation-quickstart.mts. Install with npm install @nirmos/sdk. Run with Node.js 24+:

NIRMOS_RUN_EVALUATION_EXAMPLE=1 node --env-file=.env evaluation-quickstart.mts

Set NIRMOS_API_KEY, NIRMOS_API_URL, NIRMOS_RUNTIME_URL, NIRMOS_PROVIDER_ID and NIRMOS_MODEL_ID. URLs are origins without /v1. Provider/model values are catalog IDs from providers.list() and models.list({ providerId }), not display names. The model must belong to that provider and have working credentials/quota. EVALUATION_CLEANUP=1 archives resources after a terminal run; otherwise keep the logged IDs for inspection.

evaluation-quickstart.mts
import { Nirmos } from "@nirmos/sdk";

declare const process: { env: Record<string, string | undefined> };

function requireId(value: unknown, label: string): string {
  if (typeof value !== "string" || !value) throw new Error(`Missing ${label}`);
  return value;
}

export async function evaluationQuickstart(
  client: Nirmos,
  options: {
    providerId: string;
    modelId: string;
    cleanup?: boolean;
    pollMs?: number;
    maxPolls?: number;
  },
) {
  let datasetId: string | undefined;
  let suiteId: string | undefined;
  let evaluatorId: string | undefined;
  let runId: string | undefined;
  let terminal = false;
  let submissionStarted = false;
  try {
    const dataset = await client.evaluations.datasets.create({
      name: "SDK two-case demo",
    });
    datasetId = requireId(dataset.dataset.id, "dataset ID");
    const datasetVersionId = requireId(
      dataset.initialVersion?.id,
      "dataset version ID",
    );
    console.log({ datasetId, datasetVersionId });
    for (const column of [
      { key: "question", name: "Question", role: "input" as const },
      { key: "expected", name: "Expected", role: "expected" as const },
      { key: "topic", name: "Topic", role: "metadata" as const },
    ]) {
      await client.evaluations.datasets.columns.create(datasetId, {
        datasetVersionId,
        ...column,
        dataType: "text",
        required: true,
      });
    }
    for (const data of [
      {
        question: "Reply with exactly Paris and nothing else.",
        expected: "Paris",
        topic: "cities",
      },
      {
        question: "Reply with exactly Tokyo and nothing else.",
        expected: "Tokyo",
        topic: "cities",
      },
    ]) {
      await client.evaluations.datasets.cases.create(datasetId, {
        datasetVersionId,
        data,
        tags: ["sdk-demo"],
      });
    }
    await client.evaluations.datasets.versions.freeze(
      datasetId,
      datasetVersionId,
    );
    const suite = await client.evaluations.suites.create({
      name: "SDK exact-match demo",
      datasetVersionId,
    });
    suiteId = requireId(suite.id, "suite ID");
    console.log({ suiteId });
    const target = await client.evaluations.columns.create({
      suiteId,
      key: "candidate",
      name: "Candidate",
      category: "target",
      enabled: true,
      config: { role: "candidate", dataType: "output" },
      target: {
        type: "model",
        name: "Demo model",
        providerId: options.providerId,
        modelId: options.modelId,
        inputMapping: { user_message: "dataset.question" },
      },
    });
    // The target's logical ID is distinct from the immutable version used in runs.
    const targetId = requireId(target.target?.id, "target ID");
    const targetVersionId = requireId(
      target.targetVersion?.id,
      "target version ID",
    );
    const evaluator = await client.evaluations.evaluators.create({
      name: "SDK exact match",
      version: {
        type: "exact_match",
        category: "deterministic",
        scope: "output",
        inputSchema: [
          { key: "actual", type: "any", required: true },
          { key: "expected", type: "any", required: true },
        ],
        config: {
          caseSensitive: true,
          trimWhitespace: true,
          normalizeWhitespace: false,
        },
        outputType: "boolean",
        scoreDirection: "none",
      },
    });
    evaluatorId = requireId(evaluator.evaluator.id, "evaluator ID");
    const evaluatorVersionId = requireId(
      evaluator.version?.id,
      "evaluator version ID",
    );
    console.log({ evaluatorId, targetVersionId, evaluatorVersionId });
    await client.evaluations.columns.create({
      suiteId,
      key: "exact_match",
      name: "Exact match",
      category: "evaluator",
      enabled: true,
      evaluatorVersionId,
      config: {
        inputMapping: {
          actual: { source: "target", path: "output" },
          expected: { source: "dataset", key: "expected" },
        },
      },
    });
    const experiment = await client.evaluations.experiments.prepare({
      suiteId,
      datasetVersionId,
      targetVersionIds: [targetVersionId],
      evaluatorVersionIds: [evaluatorVersionId],
      trialCount: 1,
    });
    const experimentId = requireId(experiment.id, "experiment ID");
    // Persist this input and submissionId if implementing replay across process restarts.
    const submissionId = crypto.randomUUID();
    console.log({ experimentId, submissionId });
    submissionStarted = true;
    const created = await client.evaluations.runs.create(
      {
        experimentId,
        cases: "all",
        targetIds: [targetVersionId],
        evaluatorIds: [evaluatorVersionId],
        trialCount: 1,
      },
      { idempotencyKey: submissionId, maxRetries: 0 },
    );
    runId = created.id;
    console.log({ runId });
    for (let attempt = 0; attempt < (options.maxPolls ?? 60); attempt++) {
      const run = await client.evaluations.runs.get(runId, {
        timeoutMs: 10_000,
        maxRetries: 0,
      });
      if (["COMPLETED", "FAILED", "CANCELLED"].includes(run.status)) {
        terminal = true;
        const results = await client.evaluations.runs.results(runId, {
          page: 1,
          pageSize: 25,
        });
        for (const trial of results.data) {
          console.log({
            caseId: trial.caseId,
            trialStatus: trial.status,
            error: trial.error,
          });
          for (const score of trial.scores) {
            console.log({
              evaluatorVersionId: score.evaluatorVersionId,
              status: score.status,
              value: score.value,
              passed: score.passed,
              error: score.error,
            });
          }
        }
        // Two cases × one target × one trial fit on one page.
        if (run.status !== "COMPLETED")
          throw new Error(`Run ${runId}: ${run.status}`);
        if (
          results.data.length !== 2 ||
          results.data.some(
            (trial) =>
              trial.status !== "COMPLETED" ||
              trial.scores.length !== 1 ||
              trial.scores.some(
                (score) => score.status !== "COMPLETED" || score.error,
              ),
          )
        ) {
          throw new Error(
            "Run ended with missing or failed trials/scores; inspect results",
          );
        }
        // Runtime GET returns persisted aggregates after terminal processing.
        const summary = run.summary;
        if (!summary || typeof summary.overallPassRate !== "number")
          throw new Error("Missing aggregate scores; inspect the terminal run");
        console.log({ overallPassRate: summary.overallPassRate, byEvaluator: summary.byEvaluator });
        return { runId, results, summary }; // passed:false is a valid evaluation outcome.
      }
      await new Promise((resolve) =>
        setTimeout(resolve, options.pollMs ?? 2000),
      );
    }
    await client.evaluations.runs.cancel(runId);
    throw new Error(
      `Polling limit reached; cancellation requested for ${runId}. Confirm terminal state before cleanup.`,
    );
  } finally {
    // Never archive inputs while background execution might still use them.
    if (options.cleanup && (!submissionStarted || terminal)) {
      const cleanup = await Promise.allSettled([
        ...(suiteId ? [client.evaluations.suites.archive(suiteId)] : []),
        ...(evaluatorId
          ? [client.evaluations.evaluators.archive(evaluatorId)]
          : []),
        ...(datasetId ? [client.evaluations.datasets.archive(datasetId)] : []),
      ]);
      for (const result of cleanup)
        if (result.status === "rejected")
          console.error("Archive failed:", result.reason);
    }
  }
}

if (process.env.NIRMOS_RUN_EVALUATION_EXAMPLE === "1") {
  const key = requireId(process.env.NIRMOS_API_KEY, "NIRMOS_API_KEY");
  await evaluationQuickstart(
    new Nirmos({
      auth: { type: "api-key", key },
      apiBaseUrl: process.env.NIRMOS_API_URL,
      runtimeBaseUrl: process.env.NIRMOS_RUNTIME_URL,
      maxRetries: 0,
    }),
    {
      providerId: requireId(
        process.env.NIRMOS_PROVIDER_ID,
        "NIRMOS_PROVIDER_ID",
      ),
      modelId: requireId(process.env.NIRMOS_MODEL_ID, "NIRMOS_MODEL_ID"),
      cleanup: process.env.EVALUATION_CLEANUP === "1",
    },
  );
}

Offline execution

The installed package includes a no-network transport fixture:

node node_modules/@nirmos/sdk/examples/evaluation-offline.mjs

It demonstrates one passing and one failing score with simulated responses. It does not establish live persistence or provider availability.

Cleanup

Archive only disposable resources after a terminal run. If submission or cancellation is uncertain, preserve the logged IDs and inspect execution before cleanup. Archival retains run history. Result interpretation explains why completed execution can still contain failures.

On this page