Evaluate a prompt before release
Run cases against a pinned draft, inspect scores, and publish deliberately.
Build an application-controlled release check. This recipe creates an unpublished prompt version, a frozen two-case dataset and an exact-match evaluator, then runs the pinned candidate. Publication requires both passing results and an explicit application flag.
Prerequisites and Dashboard setup
Configure a provider credential and choose an accessible chat model. Set NIRMOS_MODEL_ID to its catalog ID, not its provider-qualified inference name. The configured evaluation runtime must support background execution.
Generate a key with prompt:create, evaluation:create, evaluation:update, evaluation:read, evaluation:run and evaluation:cancel. Optional publication needs prompt:publish; optional cleanup needs prompt:delete. Select those grants in the Dashboard. Runtime execution of the evaluation uses the authorized evaluation operation; it does not require giving this key arbitrary Gateway execution access.
Set NIRMOS_API_KEY and NIRMOS_MODEL_ID. This recipe creates disposable resources and invokes the model twice; the exact-match scorer makes no judge calls.
Install the published package and a TypeScript runner in a new project:
npm install @nirmos/sdk
npm install --save-dev tsx typescript @types/nodeUse 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 prompt-evaluation.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;
}
function id(value: unknown, label: string): string {
if (typeof value !== "string" || !value) throw new Error(`Missing ${label}`);
return value;
}
export async function evaluatePrompt(
client: Nirmos,
options: { modelId: string; publish?: boolean; cleanup?: boolean; maxPolls?: number; pollMs?: number },
) {
let promptId: string | undefined;
let datasetId: string | undefined;
let suiteId: string | undefined;
let evaluatorId: string | undefined;
let runId: string | undefined;
let submitted = false;
let terminal = false;
let published = false;
try {
const prompt = await client.prompts.create({
name: "Recipe capital names", slug: `evaluation-${crypto.randomUUID()}`,
});
promptId = prompt.promptId;
const saved = await client.prompts.versions.create(promptId, {
branchId: prompt.branchId, commitMessage: "Candidate for evaluation",
temperature: 0, maxTokens: 100, topP: 1,
messages: [
{ order: 0, role: "system", contentBlocks: [{ order: 0, type: "text", text: "Answer with only the capital city name. Do not add punctuation or explanation." }] },
{ order: 1, role: "user", contentBlocks: [{ order: 0, type: "text", text: "{{question}}" }] },
],
});
const promptVersionId = id(saved.versionId, "prompt version ID");
console.log({ promptId, promptVersionId });
const dataset = await client.evaluations.datasets.create({ name: "Recipe capital cases" });
datasetId = id(dataset.dataset.id, "dataset ID");
const datasetVersionId = id(dataset.initialVersion?.id, "dataset version ID");
for (const column of [
{ key: "question", name: "Question", role: "input" as const },
{ key: "expected", name: "Expected", role: "expected" as const },
]) {
await client.evaluations.datasets.columns.create(datasetId, {
datasetVersionId, ...column, dataType: "text", required: true,
});
}
for (const data of [
{ question: "What is the capital of France?", expected: "Paris" },
{ question: "What is the capital of Japan?", expected: "Tokyo" },
]) await client.evaluations.datasets.cases.create(datasetId, { datasetVersionId, data });
await client.evaluations.datasets.versions.freeze(datasetId, datasetVersionId);
const suite = await client.evaluations.suites.create({ name: "Recipe prompt candidate", datasetVersionId });
suiteId = id(suite.id, "suite ID");
const target = await client.evaluations.columns.create({
suiteId, key: "candidate", name: "Unpublished candidate", category: "target", enabled: true,
config: { role: "candidate", dataType: "output" },
target: {
type: "prompt", name: "Pinned draft", promptId, promptVersionId,
executionType: "model", modelId: options.modelId,
inputMapping: { question: "dataset.question" },
},
});
const targetVersionId = id(target.targetVersion?.id, "target version ID");
const evaluator = await client.evaluations.evaluators.create({
name: "Recipe exact city",
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 = id(evaluator.evaluator.id, "evaluator ID");
const evaluatorVersionId = id(evaluator.version?.id, "evaluator version ID");
await client.evaluations.columns.create({
suiteId, key: "exact_city", name: "Exact city", 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 submissionKey = crypto.randomUUID();
const input = {
experimentId: id(experiment.id, "experiment ID"), cases: "all" as const,
targetIds: [targetVersionId], evaluatorIds: [evaluatorVersionId], trialCount: 1,
};
// Persist input and submissionKey before submitting in a production application.
console.log({ datasetId, suiteId, evaluatorId, experimentId: input.experimentId, submissionKey });
submitted = true;
const created = await client.evaluations.runs.create(input, { idempotencyKey: submissionKey, 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, status: trial.status, error: trial.error, scores: trial.scores });
// This recipe has exactly two cases, one target and one trial each.
const acceptable = run.status === "COMPLETED" && results.data.length === 2 && results.data.every(trial =>
trial.status === "COMPLETED" && !trial.error && trial.scores.length === 1 && trial.scores.every(score =>
score.status === "COMPLETED" && !score.error && score.passed === true,
),
);
console.log({ overallPassRate: run.summary?.overallPassRate, acceptable });
if (!acceptable) throw new Error("Candidate not released: inspect failed trials or scores");
if (options.publish) {
await client.prompts.versions.publish(promptId, promptVersionId);
published = true;
console.log({ publishedPromptId: promptId, promptVersionId });
} else console.log("Candidate passed; review results before rerunning with explicit publication enabled.");
return { promptId, promptVersionId, runId, published, results };
}
await new Promise(resolve => setTimeout(resolve, options.pollMs ?? 2000));
}
await client.evaluations.runs.cancel(runId);
throw new Error(`Polling budget exhausted for ${runId}; confirm terminal cancellation before cleanup`);
} finally {
if (options.cleanup && (!submitted || terminal)) {
const actions = [
...(suiteId ? [client.evaluations.suites.archive(suiteId)] : []),
...(evaluatorId ? [client.evaluations.evaluators.archive(evaluatorId)] : []),
...(datasetId ? [client.evaluations.datasets.archive(datasetId)] : []),
...(promptId && !published ? [client.prompts.delete(promptId)] : []),
];
const cleaned = await Promise.allSettled(actions);
for (const result of cleaned) if (result.status === "rejected") console.error("Cleanup failed; inspect retained IDs");
}
}
}
if (process.env.NIRMOS_RUN_RECIPE === "1") {
try {
await evaluatePrompt(configuredClient(), {
modelId: requiredEnv("NIRMOS_MODEL_ID"),
publish: process.env.NIRMOS_PUBLISH_PROMPT === "1",
cleanup: process.env.NIRMOS_RECIPE_CLEANUP === "1",
});
} catch (error) { report(error); }
}Run and inspect
NIRMOS_RUN_RECIPE=1 npx tsx prompt-evaluation.tsThe script prints resource/run IDs, trial scores and an acceptable decision. A passing candidate remains unpublished by default. Model answers can vary; failed comparisons or failed trials prevent publication.
NIRMOS_PUBLISH_PROMPT=1 enables the explicit publish call only after every trial and score passes. This is application logic, not an automatic Nirmos production gate. Rerunning creates a new disposable candidate; to release the previously reviewed version instead, use its logged prompt/version IDs with publication.
Cleanup and recovery
Set NIRMOS_RECIPE_CLEANUP=1 to archive disposable evaluation resources after terminal execution and delete an unpublished demo prompt. A published prompt is retained. After uncertain submission or cancellation, the script leaves resources intact; inspect run state before cleanup. Retain the submission key and identical input when recovering an uncertain submission.
Two cases are an orchestration example, not sufficient production coverage. Expand representative cases and thresholds for your release needs. Result interpretation explains pending reviews, false comparisons and failed scores. Evaluation methods · Binding reference