> ## Documentation Index
> Fetch the complete documentation index at: https://openrouter.ai/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Test a New Model on Your Production Prompts

> Fetch the prompts your app already sent, rerun them on a candidate model, and compare answers, time, and cost

Use this guide when you want to test a candidate model on the prompts your app already sends, comparing answer quality, generation time, and cost before you switch.

## What you're building

![Terminal output of replay.ts comparing 6 generation IDs: each row prints generation time before and after, candidate cost as a multiple of production, and a blind judge verdict with a one-sentence reason, ending with candidate 3, production 2, tie 1, and total cost 0.12x production](https://mintcdn.com/openrouter-d02e98a0/5H7VPBma0FSDKDGB/assets/cookbook/evaluate-and-optimize/replay-production-prompts/replay-report.png?fit=max\&auto=format\&n=5H7VPBma0FSDKDGB\&q=85\&s=cf224c9c75e2f4a3704325bd1fd620a7)

Six prompts from an app log, rerun on a candidate model. Each entry shows generation time, cost relative to production, and which answer a judge model preferred.

With [Input & Output Logging](https://openrouter.ai/docs/guides/features/input-output-logging.md) turned on, OpenRouter privately stores the full prompt and completion for each request. You can fetch them later by generation ID through `GET /api/v1/generation/content` without storing prompt bodies in your own logs.

By the end, you will have a `replay.ts` script that:

1. Reads generation IDs from your app's log file.
2. Fetches the stored prompt and production answer for each ID.
3. Reruns the same prompt on a candidate model.
4. Compares generation time and cost as a multiple of production.
5. Asks a judge model from a third lab to pick the better answer blind.

> [!TIP]
>
> Building with a coding agent? Paste this page's URL into Claude Code, Codex, or Cursor and ask it to find the generation IDs in your app logs and run this script against them.

## Before you start

You need:

* A user-owned OpenRouter API key in `OPENROUTER_API_KEY` (org-level keys without a creator cannot read stored content).
* [Input & Output Logging](https://openrouter.ai/docs/guides/features/input-output-logging.md) turned on under **Observability** settings before your app sends the requests you want to replay.
* An app that writes each OpenRouter response `id` to its logs.
* Bun, or Node.js 20 or later with a TypeScript runner.

> [!NOTE]
>
> **Input & Output Logging limits:**
>
> * Only requests sent while the setting is on have stored content.
> * Requests sent to `eu.openrouter.ai` or `us.openrouter.ai` are not stored.
> * In an organization, org admins can read stored content for all requests. Other members can read only requests made with API keys they created.
> * Multimodal attachments (images, audio, video, and files) are redacted before storage. This script skips multimodal prompts; to replay them, supply the original media from your app.
> * Stored records do not carry over per-request `provider` routing or retention settings (such as `zdr` or `data_collection: "deny"`), or inference parameters like `response_format` and `tools`.

The example app summarizes support tickets in one sentence and assigns a severity from P1 to P4:

* **Production:** [`google/gemini-4-hydrogen`](https://openrouter.ai/google/gemini-4-hydrogen)
* **Candidate:** [`openai/gpt-6.2-sol`](https://openrouter.ai/openai/gpt-6.2-sol)
* **Judge:** [`anthropic/claude-sonnet-5.5`](https://openrouter.ai/anthropic/claude-sonnet-5.5)

See each model's page on OpenRouter for pricing.

## Step 1: Log generation IDs in your app

Every OpenRouter response includes an `id` that starts with `gen-`. OpenRouter has no endpoint that lists your generations, so write each response `id` to your app logs.

You do not need to log full prompts yourself. A plain text log with one `gen-` ID per request is enough:

```text title="logs/app.log" lines theme={null}
16:48:48 INFO  ticket=48213 received
16:48:48 INFO  ticket=48213 summarized model=google/gemini-4-hydrogen generation_id=gen-1795452528-viqLLGkunEbJZMXNLeoZ
16:48:54 INFO  ticket=48219 received
16:48:54 INFO  ticket=48219 summarized model=google/gemini-4-hydrogen generation_id=gen-1795452534-Fmtj7avyoayukSQpLtaP
```

## Step 2: Set up the script and API helpers

Create `replay.ts` and add the API helpers along with `readGenerationIds()`, which pulls every unique `gen-` ID from your log file.

Metadata for a request that just finished can take a few seconds to appear on `/generation?id=...`, so `get()` retries `404` responses on `/generation?` before throwing an error. `get()` throws an `ApiError` with the HTTP status so the caller can skip `404` rows for unstored prompts while still failing fast on auth or server errors.

If production enforces per-request retention or routing rules (such as `provider.zdr` or `provider.data_collection: "deny"`), set them in `PROVIDER_PREFERENCES` or enforce them at the workspace level with [Guardrails](https://openrouter.ai/docs/guides/features/guardrails.md) before running the script so neither the candidate nor the judge sends production data to providers you excluded.

```ts title="replay.ts" lines theme={null}
import { readFileSync } from "node:fs";

const API = "https://openrouter.ai/api/v1";
const headers = {
  Authorization: `Bearer ${process.env.OPENROUTER_API_KEY}`,
  "Content-Type": "application/json",
};

const CANDIDATE = "openai/gpt-6.2-sol";
const JUDGE = "anthropic/claude-sonnet-5.5";

// Match your production routing and retention policy on both candidate and judge calls.
// For example: { zdr: true, data_collection: "deny" }
const PROVIDER_PREFERENCES: Record<string, unknown> | undefined = undefined;

class ApiError extends Error {
  constructor(
    readonly status: number,
    body: string,
  ) {
    super(`${status} ${body}`);
  }
}

async function get(path: string) {
  for (let attempt = 0; attempt < 15; attempt++) {
    const res = await fetch(`${API}${path}`, { headers });
    if (res.ok) return (await res.json()).data;

    // Metadata for a request that just finished can take a few seconds to appear.
    const shouldRetry = res.status === 404 && path.startsWith("/generation?");
    if (!shouldRetry) throw new ApiError(res.status, await res.text());

    await new Promise((resolve) => setTimeout(resolve, 2000));
  }
  throw new Error(`No metadata for ${path}`);
}

async function chat(body: object) {
  const payload = PROVIDER_PREFERENCES
    ? { ...body, provider: PROVIDER_PREFERENCES }
    : body;

  const res = await fetch(`${API}/chat/completions`, {
    method: "POST",
    headers,
    body: JSON.stringify(payload),
  });
  if (!res.ok) throw new ApiError(res.status, await res.text());
  return res.json();
}

function readGenerationIds(logPath: string) {
  const log = readFileSync(logPath, "utf8");
  return [...new Set(log.match(/gen-[A-Za-z0-9-]+/g) ?? [])];
}
```

## Step 3: Fetch stored prompts and rerun on the candidate

Call [Get stored content for a generation](https://openrouter.ai/docs/api/api-reference/generations/get-stored-prompt-completion-and-error-content-for-a-generation.md) (`GET /api/v1/generation/content?id=<generation id>`) to fetch what production sent and returned. The response looks like this:

```json lines theme={null}
{
  "data": {
    "input": {
      "messages": [
        {
          "role": "system",
          "content": "You summarize support tickets for an on-call engineer."
        },
        {
          "role": "user",
          "content": "Summarize this ticket in one sentence, then give a severity from P1 to P4. ..."
        }
      ]
    },
    "output": {
      "reasoning": null,
      "completion": "..."
    },
    "error": null
  }
}
```

Add `fetchStoredRun()` to read the stored chat `messages` and production completion, skipping requests that cannot be replayed fairly through `/chat/completions`:

* `404` responses (prompts sent before logging was turned on or excluded from logging).
* Failed generations or records without a string `output.completion`.
* Non-chat `/completions` records (no `input.messages` array).
* Multimodal prompts whose image, audio, video, or file inputs were redacted before storage.

Then add `rerunPrompt()` to send the plain-text messages to `CANDIDATE`. This example assumes plain-text prompts; if production relies on settings like `response_format`, `tools`, or `temperature`, pass those same parameters in `rerunPrompt()` so the candidate is judged under the same constraints.

```ts title="replay.ts" lines theme={null}
const MEDIA_KEYS = ["image_url", "input_audio", "video_url", "input_video", "file"];

function hasRedactedMedia(messages: unknown[]) {
  return messages.some((msg) => {
    if (!msg || typeof msg !== "object") return false;
    const record = msg as Record<string, unknown>;
    if (Array.isArray(record.images) || record.audio != null) return true;
    if (!Array.isArray(record.content)) return false;
    return record.content.some(
      (part) =>
        part &&
        typeof part === "object" &&
        MEDIA_KEYS.some((key) => (part as Record<string, unknown>)[key] != null),
    );
  });
}

async function fetchStoredRun(id: string) {
  let stored;
  try {
    stored = await get(`/generation/content?id=${id}`);
  } catch (err) {
    if (err instanceof ApiError && err.status === 404) {
      return { skip: "no stored content" as const };
    }
    throw err;
  }

  if (stored.error || typeof stored.output?.completion !== "string") {
    return { skip: "failed or empty production run" as const };
  }

  if (!Array.isArray(stored.input?.messages)) {
    return { skip: "not a chat completion" as const };
  }

  const messages = stored.input.messages;
  if (hasRedactedMedia(messages)) {
    return { skip: "multimodal inputs are redacted in stored logs" as const };
  }

  return { messages, answer: stored.output.completion as string };
}

async function rerunPrompt(messages: unknown[]) {
  const rerun = await chat({ model: CANDIDATE, messages });
  return {
    id: rerun.id as string,
    answer: rerun.choices[0].message.content as string,
  };
}
```

## Step 4: Compare generation time and cost

Call [Get generation](https://openrouter.ai/docs/api/api-reference/generations/get-generation.md) (`GET /api/v1/generation?id=<generation id>`) for both the production ID and the candidate ID to read `generation_time` (in milliseconds) and `total_cost`. For BYOK requests (`is_byok: true`), the provider bills inference separately from OpenRouter's charge, so `fetchMetrics()` adds `upstream_inference_cost` (or treats cost as unknown when that estimate is missing) and flags those rows so the report labels them as estimates.

```ts title="replay.ts" lines theme={null}
async function fetchMetrics(id: string) {
  const meta = await get(`/generation?id=${id}`);
  const timeMs = typeof meta.generation_time === "number" ? meta.generation_time : null;
  const openRouterCost = typeof meta.total_cost === "number" ? meta.total_cost : null;
  const isByok = meta.is_byok === true;

  if (openRouterCost == null) {
    return { timeMs, cost: null, isByok };
  }

  if (isByok) {
    const upstreamCost =
      typeof meta.upstream_inference_cost === "number" ? meta.upstream_inference_cost : null;
    return {
      timeMs,
      cost: upstreamCost == null ? null : openRouterCost + upstreamCost,
      isByok: true,
    };
  }

  return { timeMs, cost: openRouterCost, isByok: false };
}
```

## Step 5: Judge both answers blind

Send the original prompt and both answers to `JUDGE` using [structured outputs](https://openrouter.ai/docs/guides/features/structured-outputs.md).

`judgeAnswers()` uses the same `chat()` helper as `rerunPrompt()`, so any `PROVIDER_PREFERENCES` you configure apply to the judge call as well. Before replaying sensitive production rows, make sure those preferences or your workspace guardrails cover both models, or exclude those IDs from the log.

LLM judges can favor whichever answer appears first when two answers are close. Passing `candidateIsA` and flipping it on each prompt alternates the A/B order, then maps `"A"` or `"B"` back to `"candidate"` or `"production"`.

```ts title="replay.ts" expandable lines theme={null}
async function judgeAnswers(
  messages: unknown[],
  productionAnswer: string,
  candidateAnswer: string,
  candidateIsA: boolean,
) {
  const answerA = candidateIsA ? candidateAnswer : productionAnswer;
  const answerB = candidateIsA ? productionAnswer : candidateAnswer;

  const response = await chat({
    model: JUDGE,
    messages: [
      {
        role: "user",
        content:
          "Two models answered the same request. Pick the answer that follows the instructions " +
          "more closely and is more accurate, or call it a tie. In the reason, say what the better " +
          "answer does that the other does not, in under 20 words, without naming A or B.\n\n" +
          `REQUEST:\n${JSON.stringify(messages)}\n\n` +
          `ANSWER A:\n${answerA}\n\n` +
          `ANSWER B:\n${answerB}`,
      },
    ],
    response_format: {
      type: "json_schema",
      json_schema: {
        name: "verdict",
        strict: true,
        schema: {
          type: "object",
          properties: {
            winner: { type: "string", enum: ["A", "B", "tie"] },
            reason: { type: "string" },
          },
          required: ["winner", "reason"],
          additionalProperties: false,
        },
      },
    },
  });

  const { winner, reason } = JSON.parse(response.choices[0].message.content);
  if (winner === "tie") return { winner: "tie" as const, reason };

  const pickedCandidate = (winner === "A") === candidateIsA;
  return {
    winner: pickedCandidate ? ("candidate" as const) : ("production" as const),
    reason: reason as string,
  };
}
```

## Step 6: Run the replay and read the report

Add `main()` to loop through the generation IDs, print one block per prompt, and print a summary at the end:

```ts title="replay.ts" expandable lines theme={null}
const seconds = (ms: number | null) =>
  ms == null ? "n/a" : `${(ms / 1000).toFixed(1)}s`;

const costRatio = (candidate: number | null, production: number | null) => {
  if (candidate == null || production == null) return "n/a";
  if (production === 0) return candidate === 0 ? "1.00x production" : "n/a (zero baseline)";
  return `${(candidate / production).toFixed(2)}x production`;
};

async function main() {
  const logPath = process.argv[2] ?? "logs/app.log";
  const ids = readGenerationIds(logPath);
  console.log(`Found ${ids.length} generation IDs`);

  let compared = 0;
  let skipped = 0;
  let wins = 0;
  let losses = 0;
  let ties = 0;
  let productionCost = 0;
  let candidateCost = 0;
  let hasMissingCost = false;
  let hasByokCost = false;

  for (const id of ids) {
    const production = await fetchStoredRun(id);
    if ("skip" in production) {
      skipped++;
      console.log(`\n${id}\n  skipped (${production.skip})`);
      continue;
    }

    const candidate = await rerunPrompt(production.messages);

    const before = await fetchMetrics(id);
    const after = await fetchMetrics(candidate.id);
    const rowHasByok = before.isByok || after.isByok;
    if (rowHasByok) hasByokCost = true;
    if (before.cost != null && after.cost != null) {
      productionCost += before.cost;
      candidateCost += after.cost;
    } else {
      hasMissingCost = true;
    }

    // Alternate A/B order so the judge does not favor whichever answer comes first.
    const verdict = await judgeAnswers(
      production.messages,
      production.answer,
      candidate.answer,
      compared % 2 === 0,
    );
    compared++;

    if (verdict.winner === "candidate") wins++;
    else if (verdict.winner === "production") losses++;
    else ties++;

    const rowCostNote =
      rowHasByok && before.cost != null && after.cost != null ? " (includes BYOK estimate)" : "";

    console.log(
      `\n${id}\n` +
        `  time    ${seconds(before.timeMs)} -> ${seconds(after.timeMs)}\n` +
        `  cost    ${costRatio(after.cost, before.cost)}${rowCostNote}\n` +
        `  better  ${verdict.winner}: ${verdict.reason}`,
    );
  }

  const totalCostLine =
    compared === 0
      ? "n/a (no compared prompts)"
      : hasMissingCost
        ? "n/a (missing cost data)"
        : `${costRatio(candidateCost, productionCost)}${hasByokCost ? " (includes BYOK estimates)" : ""}`;
  const skippedNote = skipped > 0 ? ` (${skipped} skipped)` : "";

  console.log(
    `\n${CANDIDATE} on ${compared} production prompts${skippedNote}\n` +
      `  better answer: candidate ${wins}, production ${losses}, tie ${ties}\n` +
      `  total cost: ${totalCostLine}`,
  );
}

await main();
```

Run the script against your log file:

```bash theme={null}
bun replay.ts logs/app.log
```

```text expandable lines theme={null}
Found 6 generation IDs

gen-1795452528-viqLLGkunEbJZMXNLeoZ
  time    4.9s -> 2.1s
  cost    0.18x production
  better  candidate: Gives an accurate one-sentence summary, including the depot code re-entry and the 140 drivers; the other overstates by claiming 140 scanners are confirmed affected.

gen-1795452534-Fmtj7avyoayukSQpLtaP
  time    3.7s -> 0.8s
  cost    0.14x production
  better  production: Includes the customer's request to prevent recurrence in the one-sentence summary, while the other omits this action item.

gen-1795452539-i0KXRh16JlZsi9hRpCm9
  time    7.4s -> 0.8s
  cost    0.08x production
  better  candidate: Follows the format exactly: one-sentence summary plus a severity, without extra justification the user did not request.

gen-1795452547-PZTHgaZAxEYaP5bxSc5A
  time    2.8s -> 1.9s
  cost    0.14x production
  better  candidate: Gives a one-sentence summary and P4 severity without adding unsupported claims; the other asserts core functionality is unaffected, which the ticket never states.

gen-1795452551-mCZvSoMhqg0GPo8uWAyp
  time    4.1s -> 1.9s
  cost    0.18x production
  better  tie: Both give an accurate one-sentence summary and P1 severity; neither adds anything meaningfully better or violates instructions.

gen-1795452556-9t8U36khX8IgfaW3449x
  time    7.1s -> 1.9s
  cost    0.08x production
  better  production: Gives a one-sentence summary plus a severity with justification; P2 fits incorrect customer-facing tax documentation affecting multiple clients better than P3.

openai/gpt-6.2-sol on 6 production prompts
  better answer: candidate 3, production 2, tie 1
  total cost: 0.12x production
```

Six prompts show that the script works, not whether to switch models. Judge verdicts also vary between runs: two runs over these six prompts gave the candidate 3 wins, 2 losses, and 1 tie, then 5 wins, 1 loss, and 0 ties. Replay a few hundred IDs and read the prompts where `production` wins before changing your production model.

## Troubleshooting

| Error | Cause | Fix |
| - | - | - |
| `403 Org-level API keys cannot access generation content` | `OPENROUTER_API_KEY` is an org-level key without a creator | Use a personal API key (or an org admin's creator-owned key) |
| `404 Content not available for this generation` | Input & Output Logging was off when the request ran, or its API key is excluded from logging | Turn the setting on. Only requests made after that have stored content |
| `skipped (multimodal inputs are redacted in stored logs)` | Private logging strips image, audio, video, and file payloads before storage | Supply the original media from your app when replaying multimodal requests |
| `404 Generation gen-... not found` | The ID does not exist, or the request belongs to an account your key cannot read | Use a key from the workspace that made the request |
| `400 id: Invalid generation ID` | The regular expression matched text that is not a generation ID | Tighten the pattern in `readGenerationIds()` to match your log format |
| `401 No cookie auth credentials found` | The request has no `Authorization` header | Set `OPENROUTER_API_KEY` |
| `401 User not found.` | The API key is wrong or deleted | Check the key |

## Check your work

Run `bun replay.ts logs/app.log` and confirm it prints one entry per generation ID with `time`, `cost`, and `better` lines, followed by a summary. Inspect a few prompts where `production` wins to see where the candidate falls short before you switch models.
