Nirmos
Evaluations

Import evaluation cases from traces

Gateway request → public request ID → retained chat payloads → dataset case.

Trace import copies retained data into a draft dataset. It never reruns inference. Use response.metadata.requestId from SDK chat, or requestId from the Logs API. Pass it as requestLogId; the historical field name also accepts a stored log ID. logs.get() resolves the same identifiers. Trace IDs group requests and are not import identifiers. No MongoDB ID is needed.

Prerequisites

Install npm install @nirmos/sdk. Use an organization API key with gateway:execute, observability:read, evaluations:create, evaluations:read and evaluations:update permissions. The organization needs an executable chat model with configured provider credentials. This example makes one provider request and may incur charges.

An administrator must permit input/output body logging and nonzero sampling in the effective workspace/project policy before making the request. Logging defaults off with zero sampling. The legacy deployment flag does not enable capture; historical data requires the reviewed migration. TRACING_ENABLED=false disables logging. Capture stores normalized { messages } and { choices }, never raw requests, provider credentials, HTTP headers or arbitrary request metadata. Sensitive object keys are redacted; natural-language content is still application data and must follow your organization's data policy. Redacted payloads cannot be imported as complete cases.

Supported: successful non-streaming chat, including cached responses, with confirmed chat metadata and complete retained bodies. Unsupported: streaming chat (no assembled output is retained), embeddings, failed requests and legacy logs without operation metadata. Model IDs in the example are Gateway names such as openai/gpt-4o-mini, not evaluation target version IDs. Use your configured model.

Run the complete example

Save the following as evaluation-trace-import.mts, then run:

Install @nirmos/sdk and tsx. Set NIRMOS_API_KEY and NIRMOS_CHAT_MODEL for the Dashboard-configured organization/model. Hosted origins are the defaults; set the optional API/runtime URL variables only for another deployment.

NIRMOS_RUN_TRACE_EXAMPLE=1 EVALUATION_CLEANUP=1 npx tsx evaluation-trace-import.mts

The example creates JSON destination columns, makes one chat request, waits at most 30 seconds for the log, imports once, reads the created case's values, and optionally archives the dataset. Transport retries are disabled for mutations because imports do not guarantee deduplication. A lost import response requires checking dataset cases before resubmitting.

evaluation-trace-import.mts
import { APIError, Nirmos } from "@nirmos/sdk";

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

/** Destination draft needs required JSON columns named input and output. */
export async function importGatewayTrace(
  client: Nirmos,
  options: {
    datasetVersionId: string;
    model: string;
    maxWaitMs?: number;
    pollMs?: number;
  },
) {
  const response = await client.gateway.chat.create(
    {
      model: options.model,
      messages: [{ role: "user", content: "What is the capital of France?" }],
    },
    { maxRetries: 0 },
  );
  const requestId = response.metadata.requestId;
  if (!requestId) throw new Error("Gateway response omitted public request ID");
  const deadline = Date.now() + (options.maxWaitMs ?? 30_000);
  while (true) {
    const remaining = deadline - Date.now();
    if (remaining <= 0)
      throw new Error(
        `Trace ${requestId} unavailable after bounded wait; check logging and retention`,
      );
    try {
      // Logs API accepts the same public request ID. Existence confirms persistence,
      // not eligibility: import performs the authoritative payload/operation checks.
      await client.logs.get(requestId, {
        timeoutMs: Math.min(5_000, remaining),
        maxRetries: 0,
      });
      break;
    } catch (error) {
      if (!(error instanceof APIError) || error.status !== 404) throw error;
      await new Promise((resolve) =>
        setTimeout(
          resolve,
          Math.min(options.pollMs ?? 1_000, Math.max(0, deadline - Date.now())),
        ),
      );
    }
  }
  const imported = await client.evaluations.datasets.importTrace(
    {
      requestLogId: requestId,
      datasetVersionId: options.datasetVersionId,
      mapping: { input: "input", output: "output" },
      tags: ["gateway-regression"],
    },
    { maxRetries: 0 },
  );
  const datasetCase = await client.evaluations.datasets.cases.get(
    imported.case.id,
  );
  return { requestId, imported, datasetCase };
}

if (process.env.NIRMOS_RUN_TRACE_EXAMPLE === "1") {
  const apiKey = process.env.NIRMOS_API_KEY;
  const model = process.env.NIRMOS_CHAT_MODEL;
  if (!apiKey || !model)
    throw new Error("Set NIRMOS_API_KEY and NIRMOS_CHAT_MODEL");
  const client = new Nirmos({
    auth: { type: "api-key", key: apiKey },
    apiBaseUrl: process.env.NIRMOS_API_URL,
    runtimeBaseUrl: process.env.NIRMOS_RUNTIME_URL,
    maxRetries: 0,
  });
  const dataset = await client.evaluations.datasets.create({
    name: "Gateway trace demo",
  });
  try {
    for (const key of ["input", "output"]) {
      await client.evaluations.datasets.columns.create(dataset.dataset.id, {
        datasetVersionId: dataset.initialVersion.id,
        key,
        name: key,
        dataType: "json",
        role: key === "input" ? "input" : "expected",
        required: true,
      });
    }
    const result = await importGatewayTrace(client, {
      datasetVersionId: dataset.initialVersion.id,
      model,
    });
    console.log(
      result.requestId,
      result.imported.case.id,
      result.datasetCase.values,
    );
  } catch (error) {
    if (error instanceof APIError) console.error(error.code, error.message);
    throw error;
  } finally {
    if (process.env.EVALUATION_CLEANUP === "1")
      await client.evaluations.datasets.archive(dataset.dataset.id);
  }
}

Mappings and eligibility

mapping maps destination dataset column keys to input, output, model, provider, route, application, requestId or traceId. input and output copy whole normalized JSON payloads; they are not JSON paths or extracted text. Use JSON columns for them. route is the recorded routing reason, not a guaranteed route resource ID. Other unavailable metadata values remain null and cannot satisfy required columns. At least one mapping is required. expectedValues supplies explicit case data after mapping. Case metadata and tags are separate from these dataset fields.

evaluations.traceCandidates() returns the newest 100 organization logs, including requestId, importable, payloadState and truncated display previews. importable confirms operation, success and retention flags at read time; import performs final shape checks. Payload previews require observability:read; callers without it receive a permission message and cannot import. Preview strings are not dataset payloads. Import checks complete input/output retention even when mapping only metadata, preventing metadata-only rows from masquerading as useful traces.

importTraces() takes datasetId, datasetVersionId, requestLogIds (1-100) and the same mapping options. Each identifier has the same resolution semantics. Imports run sequentially and are not atomic: earlier cases may persist if a later import fails. There is no deduplication guarantee. A frozen destination requires createDraftFromFrozen: true; subsequent work must use the returned datasetVersionId.

Reuse imported payloads in a run

Freeze the returned dataset version and attach it to a suite as in the complete run tutorial. Retained payloads have declared JSON roots input and output. Map their children directly:

await nirmos.evaluations.columns.create({
  suiteId: "suite-id", key: "candidate", name: "Replay messages", category: "target",
  target: { type: "model", name: "Model", modelId: "catalog-model-id", providerId: "provider-id", inputMapping: { messages: "dataset.input.messages" } },
});
await nirmos.evaluations.columns.create({
  suiteId: "suite-id", key: "trace_exact", name: "Original output baseline", category: "evaluator",
  evaluatorVersionId: "exact-match-version-id",
  config: { inputMapping: {
    actual: { source: "target", path: "output" },
    expected: { source: "dataset", key: "output.choices.0.message.content" },
  } },
});

These are the same target/evaluator mapping formats as the main tutorial. Safe dotted children and numeric array indices are supported. Setup validates the declared root and JSON/messages column type; execution checks child presence and actual value type. Missing target paths fail explicitly, and a messages mapping must produce an array. This example uses the original text response as a regression baseline. Supply trusted expectedValues for correctness labels; tool-call-only responses require an evaluator suited to their retained structure.

Persistence, retention and errors

Logs buffer in runtime memory, flushing about every five seconds or at 100 records. Persistence is best effort; provider success does not guarantee a log. Disabled tracing, process loss, storage failure and retention can all leave logs unavailable. Retrying discovery briefly handles normal delays without repeatedly creating cases.

Positive REQUEST_LOG_RETENTION_DAYS (default 30) deletes old logs after successful flushes. There are no tombstones, so an expired request cannot be distinguished from one that never existed. Import does not report a guessed expiry or pending state. Bodies exceeding REQUEST_LOG_MAX_PAYLOAD_BYTES (default 128,000 bytes combined) are omitted entirely; they are not silently truncated. Changing settings cannot restore old bodies.

CodeMeaning and action
TRACE_NOT_FOUND (404)No accessible retained record. Includes foreign organization IDs, absent/deleted/expired logs and logs not yet persisted. Briefly poll a new request, then inspect logging.
TRACE_NOT_IMPORTABLE (422)Operation, success or streaming metadata does not identify an eligible non-streaming chat.
TRACE_PAYLOAD_UNAVAILABLE (422)Missing capture, redaction, oversized or structurally incomplete payload. Configure capture first, then make a new request.
INVALID_MAPPING / VALIDATION_ERROR (400)Check destination field names, JSON column types, required values and supplied expected data.
FROZEN_DATASET (409)Select a draft or request a draft copy.
FORBIDDEN (403)API key lacks required permission.

Organization scope is applied to every lookup, including internal-ID fallback. Errors never disclose whether another organization's trace exists. Public request IDs are server generated; caller X-Request-Id no longer chooses storage identity. Use X-Trace-Id for caller correlation.

Evaluation tutorial · Dataset methods · Logs

On this page