@ai-changeguard/replay 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +6 -2
- package/dist/fallback.d.ts +56 -0
- package/dist/fallback.js +133 -0
- package/dist/golden.d.ts +22 -0
- package/dist/golden.js +111 -0
- package/dist/importer.d.ts +39 -0
- package/dist/importer.js +606 -0
- package/dist/index.d.ts +31 -0
- package/dist/index.js +16 -0
- package/dist/job.d.ts +30 -0
- package/dist/job.js +33 -0
- package/dist/openai-evals.d.ts +40 -0
- package/dist/openai-evals.js +182 -0
- package/dist/repair.d.ts +58 -0
- package/dist/repair.js +154 -0
- package/dist/report.d.ts +60 -0
- package/dist/report.js +165 -0
- package/dist/run.d.ts +36 -0
- package/dist/run.js +62 -0
- package/dist/savings.d.ts +85 -0
- package/dist/savings.js +220 -0
- package/dist/schema.d.ts +21 -0
- package/dist/schema.js +73 -0
- package/dist/similarity.d.ts +1 -0
- package/dist/similarity.js +23 -0
- package/dist/slim.d.ts +85 -0
- package/dist/slim.js +279 -0
- package/dist/starter.d.ts +34 -0
- package/dist/starter.js +78 -0
- package/dist/verdict.d.ts +36 -0
- package/dist/verdict.js +143 -0
- package/dist/watch.d.ts +86 -0
- package/dist/watch.js +198 -0
- package/package.json +49 -4
package/dist/job.js
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { plannedRepairCalls, repairable, runRepair } from "./repair.js";
|
|
2
|
+
import { buildReplayReport } from "./report.js";
|
|
3
|
+
import { runReplay } from "./run.js";
|
|
4
|
+
export async function runReplayJob(job) {
|
|
5
|
+
const { items, oldModel, newModel, runs, maxCalls, concurrency, client } = job;
|
|
6
|
+
const records = await runReplay({
|
|
7
|
+
items,
|
|
8
|
+
oldModel,
|
|
9
|
+
newModel,
|
|
10
|
+
runs,
|
|
11
|
+
concurrency,
|
|
12
|
+
maxCalls,
|
|
13
|
+
client,
|
|
14
|
+
...(job.signal ? { signal: job.signal } : {}),
|
|
15
|
+
...(job.onProgress ? { onProgress: job.onProgress } : {}),
|
|
16
|
+
});
|
|
17
|
+
const report = buildReplayReport(items, records, { oldModel, newModel, runs });
|
|
18
|
+
if (!job.repair || !report.items.some(repairable))
|
|
19
|
+
return { report, records };
|
|
20
|
+
const left = maxCalls - records.length;
|
|
21
|
+
const needed = plannedRepairCalls(items, report.items, newModel, runs);
|
|
22
|
+
if (needed > left) {
|
|
23
|
+
return { report, records, repairSkipped: `Prompt Repair skipped: it could need ${needed} calls, and only ${left} are left under the limit of ${maxCalls}.` };
|
|
24
|
+
}
|
|
25
|
+
try {
|
|
26
|
+
const repair = await runRepair({ items, records, results: report.items, newModel, client, runs, concurrency, maxCalls: left, ...(job.signal ? { signal: job.signal } : {}) });
|
|
27
|
+
return { report, records, repair };
|
|
28
|
+
}
|
|
29
|
+
catch (error) {
|
|
30
|
+
// A repair problem never hides the replay result.
|
|
31
|
+
return { report, records, repairSkipped: `Prompt Repair failed: ${error instanceof Error ? error.message : String(error)}` };
|
|
32
|
+
}
|
|
33
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
export interface EvalsExportOptions {
|
|
2
|
+
apiKey: string;
|
|
3
|
+
/** Folder to write into (created; one subfolder per eval). */
|
|
4
|
+
outDir: string;
|
|
5
|
+
baseUrl?: string;
|
|
6
|
+
fetch?: typeof fetch;
|
|
7
|
+
/** Told about each eval and run as it is saved. */
|
|
8
|
+
onProgress?: (message: string) => void;
|
|
9
|
+
/** Per request, body included (default 60 s). */
|
|
10
|
+
timeoutMs?: number;
|
|
11
|
+
/** Waits between retries; replaced in tests. */
|
|
12
|
+
sleep?: (ms: number) => Promise<void>;
|
|
13
|
+
}
|
|
14
|
+
export interface EvalsExportResult {
|
|
15
|
+
evals: number;
|
|
16
|
+
runs: number;
|
|
17
|
+
items: number;
|
|
18
|
+
datasetFiles: number;
|
|
19
|
+
/** Every <run>.items.jsonl written, with the run it belongs to: the input for a golden set. */
|
|
20
|
+
itemFiles: {
|
|
21
|
+
file: string;
|
|
22
|
+
run: Record<string, unknown>;
|
|
23
|
+
}[];
|
|
24
|
+
/** Things that could not be saved, with the reason (the rest is still saved). */
|
|
25
|
+
problems: string[];
|
|
26
|
+
}
|
|
27
|
+
type Obj = Record<string, unknown>;
|
|
28
|
+
/** A file-name-safe version of an OpenAI ID. */
|
|
29
|
+
export declare function safeId(id: string): string;
|
|
30
|
+
/** `fatal`: nothing more can be saved (the key is refused), so the export stops. */
|
|
31
|
+
export declare class EvalsExportError extends Error {
|
|
32
|
+
readonly fatal: boolean;
|
|
33
|
+
constructor(message: string, fatal?: boolean);
|
|
34
|
+
}
|
|
35
|
+
/** The dataset files a run read from: data_source.source of type "file_id". */
|
|
36
|
+
export declare function runFileIds(run: Obj): string[];
|
|
37
|
+
export declare function exportOpenAiEvals(options: EvalsExportOptions): Promise<EvalsExportResult>;
|
|
38
|
+
/** The settings a run sent with every call (response format, tools, limits), for the golden set. */
|
|
39
|
+
export declare function runSamplingParams(run: Record<string, unknown>): Record<string, unknown> | undefined;
|
|
40
|
+
export {};
|
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
// OpenAI Evals export. OpenAI made Evals read-only on 31 Oct 2026 and shuts it down on 30 Nov 2026, with no
|
|
2
|
+
// export button; the API still lists evals, runs and each run's output items until then. This saves all of it
|
|
3
|
+
// (graders, run settings, every recorded call and the dataset files) so nothing is lost, and the output items
|
|
4
|
+
// can then be imported as a golden set to keep testing model switches with replay.
|
|
5
|
+
import { copyFile, mkdir, open, writeFile } from "node:fs/promises";
|
|
6
|
+
import { join } from "node:path";
|
|
7
|
+
const isObj = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
|
|
8
|
+
/** A file-name-safe version of an OpenAI ID. */
|
|
9
|
+
export function safeId(id) {
|
|
10
|
+
return id.replace(/[^A-Za-z0-9_-]+/g, "_").slice(0, 100) || "unnamed";
|
|
11
|
+
}
|
|
12
|
+
/** `fatal`: nothing more can be saved (the key is refused), so the export stops. */
|
|
13
|
+
export class EvalsExportError extends Error {
|
|
14
|
+
fatal;
|
|
15
|
+
constructor(message, fatal = false) {
|
|
16
|
+
super(message);
|
|
17
|
+
this.fatal = fatal;
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
/** The dataset files a run read from: data_source.source of type "file_id". */
|
|
21
|
+
export function runFileIds(run) {
|
|
22
|
+
const ds = isObj(run.data_source) ? run.data_source : {};
|
|
23
|
+
const source = isObj(ds.source) ? ds.source : {};
|
|
24
|
+
return source.type === "file_id" && typeof source.id === "string" ? [source.id] : [];
|
|
25
|
+
}
|
|
26
|
+
const RETRY_STATUS = new Set([408, 409, 429, 500, 502, 503, 504]);
|
|
27
|
+
const ATTEMPTS = 6;
|
|
28
|
+
export async function exportOpenAiEvals(options) {
|
|
29
|
+
const base = (options.baseUrl ?? "https://api.openai.com/v1").replace(/\/$/, "");
|
|
30
|
+
const doFetch = options.fetch ?? fetch;
|
|
31
|
+
const say = options.onProgress ?? (() => undefined);
|
|
32
|
+
const sleep = options.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
|
|
33
|
+
const timeoutMs = options.timeoutMs ?? 60_000;
|
|
34
|
+
const headers = { Authorization: `Bearer ${options.apiKey}` };
|
|
35
|
+
/**
|
|
36
|
+
* One request, retried on rate limits, server errors, timeouts and dropped connections (honouring
|
|
37
|
+
* Retry-After), then read by `read` under the same timeout. A refused key is fatal everywhere.
|
|
38
|
+
*/
|
|
39
|
+
async function request(path, read) {
|
|
40
|
+
for (let attempt = 1;; attempt++) {
|
|
41
|
+
let res;
|
|
42
|
+
try {
|
|
43
|
+
res = await doFetch(`${base}${path}`, { headers, signal: AbortSignal.timeout(timeoutMs) });
|
|
44
|
+
if (res.status === 401)
|
|
45
|
+
throw new EvalsExportError("OpenAI refused the API key (401). Use a key from the organization and project that owns the evals.", true);
|
|
46
|
+
if (RETRY_STATUS.has(res.status) && attempt < ATTEMPTS) {
|
|
47
|
+
const after = Number(res.headers.get("retry-after"));
|
|
48
|
+
await sleep(Number.isFinite(after) && after > 0 ? Math.min(after, 60) * 1000 : 1000 * 2 ** (attempt - 1));
|
|
49
|
+
continue;
|
|
50
|
+
}
|
|
51
|
+
if (!res.ok)
|
|
52
|
+
throw new EvalsExportError(`OpenAI answered ${res.status} on ${path}: ${(await res.text()).slice(0, 200)}`);
|
|
53
|
+
return await read(res);
|
|
54
|
+
}
|
|
55
|
+
catch (error) {
|
|
56
|
+
if (error instanceof EvalsExportError)
|
|
57
|
+
throw error;
|
|
58
|
+
// Network error or timeout: try again, then give up on this request only.
|
|
59
|
+
if (attempt >= ATTEMPTS)
|
|
60
|
+
throw new EvalsExportError(`No answer from OpenAI on ${path} after ${ATTEMPTS} tries: ${error instanceof Error ? error.message : String(error)}`);
|
|
61
|
+
await sleep(1000 * 2 ** (attempt - 1));
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
/** Every page of a list endpoint, 100 at a time (following last_id), handed over page by page. */
|
|
66
|
+
async function eachPage(path, onPage) {
|
|
67
|
+
let after;
|
|
68
|
+
for (let page = 0; page < 100_000; page++) {
|
|
69
|
+
const sep = path.includes("?") ? "&" : "?";
|
|
70
|
+
const body = await request(`${path}${sep}limit=100${after ? `&after=${encodeURIComponent(after)}` : ""}`, (r) => r.json());
|
|
71
|
+
const data = Array.isArray(body.data) ? body.data.filter(isObj) : [];
|
|
72
|
+
await onPage(data);
|
|
73
|
+
const last = typeof body.last_id === "string" ? body.last_id : data.at(-1)?.id;
|
|
74
|
+
if (body.has_more !== true || !last || last === after)
|
|
75
|
+
return;
|
|
76
|
+
after = last;
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
const listAll = async (path) => {
|
|
80
|
+
const all = [];
|
|
81
|
+
await eachPage(path, async (data) => void all.push(...data));
|
|
82
|
+
return all;
|
|
83
|
+
};
|
|
84
|
+
const why = (error) => (error instanceof Error ? error.message : String(error));
|
|
85
|
+
const fatal = (error) => error instanceof EvalsExportError && error.fatal;
|
|
86
|
+
const result = { evals: 0, runs: 0, items: 0, datasetFiles: 0, itemFiles: [], problems: [] };
|
|
87
|
+
await mkdir(options.outDir, { recursive: true });
|
|
88
|
+
let evals;
|
|
89
|
+
try {
|
|
90
|
+
evals = await listAll("/evals");
|
|
91
|
+
}
|
|
92
|
+
catch (error) {
|
|
93
|
+
// Without the list there is nothing to save: say why plainly.
|
|
94
|
+
if (error instanceof EvalsExportError && /answered 403/.test(error.message)) {
|
|
95
|
+
throw new EvalsExportError("This API key may not read evals (403). Give it read access to Evals, or use an owner's key.", true);
|
|
96
|
+
}
|
|
97
|
+
throw error;
|
|
98
|
+
}
|
|
99
|
+
await writeFile(join(options.outDir, "evals.json"), `${JSON.stringify(evals, null, 2)}\n`);
|
|
100
|
+
/** Where each dataset file was first saved, so another eval's folder gets a copy without downloading it again. */
|
|
101
|
+
const savedFiles = new Map();
|
|
102
|
+
for (const ev of evals) {
|
|
103
|
+
const evalId = String(ev.id ?? "");
|
|
104
|
+
if (!evalId)
|
|
105
|
+
continue;
|
|
106
|
+
const dir = join(options.outDir, safeId(evalId));
|
|
107
|
+
await mkdir(dir, { recursive: true });
|
|
108
|
+
await writeFile(join(dir, "eval.json"), `${JSON.stringify(ev, null, 2)}\n`);
|
|
109
|
+
result.evals++;
|
|
110
|
+
say(`${evalId}${typeof ev.name === "string" ? ` (${ev.name})` : ""}`);
|
|
111
|
+
let runs;
|
|
112
|
+
try {
|
|
113
|
+
runs = await listAll(`/evals/${encodeURIComponent(evalId)}/runs`);
|
|
114
|
+
}
|
|
115
|
+
catch (error) {
|
|
116
|
+
if (fatal(error))
|
|
117
|
+
throw error;
|
|
118
|
+
// runs.json is left as it was, so a retry never replaces a good earlier copy with nothing.
|
|
119
|
+
result.problems.push(`${evalId}: runs not listed (${why(error)})`);
|
|
120
|
+
continue;
|
|
121
|
+
}
|
|
122
|
+
await writeFile(join(dir, "runs.json"), `${JSON.stringify(runs, null, 2)}\n`);
|
|
123
|
+
for (const run of runs) {
|
|
124
|
+
const runId = String(run.id ?? "");
|
|
125
|
+
if (!runId)
|
|
126
|
+
continue;
|
|
127
|
+
result.runs++;
|
|
128
|
+
// Pages go to disk as they arrive: a later failure keeps what was already saved.
|
|
129
|
+
const file = join(dir, `${safeId(runId)}.items.jsonl`);
|
|
130
|
+
const handle = await open(file, "w");
|
|
131
|
+
let count = 0;
|
|
132
|
+
try {
|
|
133
|
+
await eachPage(`/evals/${encodeURIComponent(evalId)}/runs/${encodeURIComponent(runId)}/output_items`, async (data) => {
|
|
134
|
+
if (data.length)
|
|
135
|
+
await handle.write(data.map((i) => `${JSON.stringify(i)}\n`).join(""));
|
|
136
|
+
count += data.length;
|
|
137
|
+
});
|
|
138
|
+
say(` ${runId}: ${count} output item${count === 1 ? "" : "s"}`);
|
|
139
|
+
}
|
|
140
|
+
catch (error) {
|
|
141
|
+
if (fatal(error))
|
|
142
|
+
throw error;
|
|
143
|
+
result.problems.push(`${evalId}/${runId}: output items ${count ? `partly saved (${count}; the rest failed: ${why(error)})` : `not saved (${why(error)})`}`);
|
|
144
|
+
}
|
|
145
|
+
finally {
|
|
146
|
+
await handle.close();
|
|
147
|
+
}
|
|
148
|
+
result.items += count;
|
|
149
|
+
if (count > 0)
|
|
150
|
+
result.itemFiles.push({ file, run });
|
|
151
|
+
// The dataset the run read, when it came from an uploaded file: the original rows and expected answers.
|
|
152
|
+
for (const fileId of runFileIds(run)) {
|
|
153
|
+
const target = join(dir, "files", `${safeId(fileId)}.jsonl`);
|
|
154
|
+
const saved = savedFiles.get(fileId);
|
|
155
|
+
if (saved === target)
|
|
156
|
+
continue;
|
|
157
|
+
try {
|
|
158
|
+
await mkdir(join(dir, "files"), { recursive: true });
|
|
159
|
+
if (saved)
|
|
160
|
+
await copyFile(saved, target);
|
|
161
|
+
else {
|
|
162
|
+
const bytes = await request(`/files/${encodeURIComponent(fileId)}/content`, async (r) => Buffer.from(await r.arrayBuffer()));
|
|
163
|
+
await writeFile(target, bytes);
|
|
164
|
+
savedFiles.set(fileId, target);
|
|
165
|
+
result.datasetFiles++;
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
catch (error) {
|
|
169
|
+
if (fatal(error))
|
|
170
|
+
throw error;
|
|
171
|
+
result.problems.push(`${evalId}: dataset file ${fileId} not saved (${why(error)})`);
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
return result;
|
|
177
|
+
}
|
|
178
|
+
/** The settings a run sent with every call (response format, tools, limits), for the golden set. */
|
|
179
|
+
export function runSamplingParams(run) {
|
|
180
|
+
const ds = isObj(run.data_source) ? run.data_source : {};
|
|
181
|
+
return isObj(ds.sampling_params) ? ds.sampling_params : undefined;
|
|
182
|
+
}
|
package/dist/repair.d.ts
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import { type LlmClient } from "@ai-changeguard/llm";
|
|
2
|
+
import type { GoldenItem } from "./golden.js";
|
|
3
|
+
import { type RunRecord } from "./run.js";
|
|
4
|
+
import { type ItemResult } from "./verdict.js";
|
|
5
|
+
/**
|
|
6
|
+
* Prompt Repair for format breaks. When the new model stops returning the JSON a prompt
|
|
7
|
+
* expects, try a short list of fixed, explainable changes on the new model only, re-test each
|
|
8
|
+
* with the same verdict rules, and report the first one that passes. Nothing is rewritten by an
|
|
9
|
+
* AI: every repair is a change a person can read and apply.
|
|
10
|
+
*/
|
|
11
|
+
export type RepairKind = "format-instruction" | "json-mode";
|
|
12
|
+
export interface RepairPatch {
|
|
13
|
+
kind: RepairKind;
|
|
14
|
+
/** Text appended to the system prompt. */
|
|
15
|
+
systemAddition: string;
|
|
16
|
+
/** Also turn on the provider's JSON output mode. */
|
|
17
|
+
jsonMode?: true;
|
|
18
|
+
}
|
|
19
|
+
export interface RepairAttempt {
|
|
20
|
+
kind: RepairKind;
|
|
21
|
+
fixed: boolean;
|
|
22
|
+
detail: string;
|
|
23
|
+
}
|
|
24
|
+
export interface RepairResult {
|
|
25
|
+
id: string;
|
|
26
|
+
fixed: boolean;
|
|
27
|
+
patch?: RepairPatch;
|
|
28
|
+
attempts: RepairAttempt[];
|
|
29
|
+
}
|
|
30
|
+
export interface RepairReport {
|
|
31
|
+
newModel: string;
|
|
32
|
+
runs: number;
|
|
33
|
+
calls: number;
|
|
34
|
+
results: RepairResult[];
|
|
35
|
+
}
|
|
36
|
+
export interface RepairOptions {
|
|
37
|
+
items: GoldenItem[];
|
|
38
|
+
/** The replay's records: the old model's answers stay the reference. */
|
|
39
|
+
records: RunRecord[];
|
|
40
|
+
results: ItemResult[];
|
|
41
|
+
newModel: string;
|
|
42
|
+
client: LlmClient;
|
|
43
|
+
runs: number;
|
|
44
|
+
concurrency?: number;
|
|
45
|
+
maxCalls?: number;
|
|
46
|
+
signal?: AbortSignal;
|
|
47
|
+
}
|
|
48
|
+
/** A prompt Repair can work on: broken, and only because the answer format broke. */
|
|
49
|
+
export declare function repairable(result: ItemResult): boolean;
|
|
50
|
+
export declare function formatInstruction(item: GoldenItem): string;
|
|
51
|
+
export declare function applyRepair(item: GoldenItem, patch: RepairPatch): GoldenItem;
|
|
52
|
+
/** The most calls a repair of these prompts can make. */
|
|
53
|
+
export declare function plannedRepairCalls(items: GoldenItem[], results: ItemResult[], newModel: string, runs: number): number;
|
|
54
|
+
export declare function runRepair(options: RepairOptions): Promise<RepairReport>;
|
|
55
|
+
export declare function formatRepairMarkdown(report: RepairReport): string;
|
|
56
|
+
export declare function formatRepairText(report: RepairReport): string;
|
|
57
|
+
/** One golden-set line in the format parseGoldenSet reads, so a repaired set can be re-run. */
|
|
58
|
+
export declare function goldenLine(item: GoldenItem): string;
|
package/dist/repair.js
ADDED
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
import { parseModelRef } from "@ai-changeguard/llm";
|
|
2
|
+
import { runReplay, SpendCapError } from "./run.js";
|
|
3
|
+
import { judgeItem } from "./verdict.js";
|
|
4
|
+
const MAX_SCHEMA_CHARS = 2000;
|
|
5
|
+
// Anthropic's API has no JSON output switch; the other providers accept one.
|
|
6
|
+
const NO_JSON_MODE = new Set(["anthropic"]);
|
|
7
|
+
/** A prompt Repair can work on: broken, and only because the answer format broke. */
|
|
8
|
+
export function repairable(result) {
|
|
9
|
+
const broken = result.reasons.filter((r) => r.severity === "broken");
|
|
10
|
+
return result.verdict === "broken" && broken.length > 0 && broken.every((r) => r.code === "format-broken");
|
|
11
|
+
}
|
|
12
|
+
export function formatInstruction(item) {
|
|
13
|
+
const base = "Answer with one JSON value only: no explanation before or after it, no Markdown, no code fences.";
|
|
14
|
+
if (!item.expect?.schema)
|
|
15
|
+
return base;
|
|
16
|
+
const schema = JSON.stringify(item.expect.schema);
|
|
17
|
+
return schema.length <= MAX_SCHEMA_CHARS ? `${base} It must match this JSON Schema: ${schema}` : base;
|
|
18
|
+
}
|
|
19
|
+
function cell(text) {
|
|
20
|
+
return text.replace(/\s+/g, " ").replace(/\|/g, "\\|");
|
|
21
|
+
}
|
|
22
|
+
function code(text) {
|
|
23
|
+
return "`" + text.replace(/\s+/g, " ").replace(/`/g, "'") + "`";
|
|
24
|
+
}
|
|
25
|
+
function candidates(item, newModel) {
|
|
26
|
+
const systemAddition = formatInstruction(item);
|
|
27
|
+
const list = [{ kind: "format-instruction", systemAddition }];
|
|
28
|
+
if (!item.jsonMode && !item.tools?.length && !NO_JSON_MODE.has(parseModelRef(newModel).provider)) {
|
|
29
|
+
list.push({ kind: "json-mode", systemAddition, jsonMode: true });
|
|
30
|
+
}
|
|
31
|
+
return list;
|
|
32
|
+
}
|
|
33
|
+
export function applyRepair(item, patch) {
|
|
34
|
+
const repaired = { ...item, system: item.system ? `${item.system}\n\n${patch.systemAddition}` : patch.systemAddition };
|
|
35
|
+
if (patch.jsonMode)
|
|
36
|
+
repaired.jsonMode = true;
|
|
37
|
+
return repaired;
|
|
38
|
+
}
|
|
39
|
+
/** The most calls a repair of these prompts can make. */
|
|
40
|
+
export function plannedRepairCalls(items, results, newModel, runs) {
|
|
41
|
+
const byId = new Map(items.map((i) => [i.id, i]));
|
|
42
|
+
return results.filter(repairable).reduce((sum, r) => sum + candidates(byId.get(r.id), newModel).length * runs, 0);
|
|
43
|
+
}
|
|
44
|
+
export async function runRepair(options) {
|
|
45
|
+
const { items, newModel, runs } = options;
|
|
46
|
+
const byId = new Map(items.map((i) => [i.id, i]));
|
|
47
|
+
const targets = options.results.filter(repairable).map((r) => ({ item: byId.get(r.id), tries: candidates(byId.get(r.id), newModel) }));
|
|
48
|
+
const maxCalls = options.maxCalls ?? 500;
|
|
49
|
+
const planned = targets.reduce((sum, t) => sum + t.tries.length * runs, 0);
|
|
50
|
+
if (planned > maxCalls) {
|
|
51
|
+
throw new SpendCapError(`Prompt Repair could need ${planned} AI calls, above the limit of ${maxCalls}. Lower the runs or raise the limit.`);
|
|
52
|
+
}
|
|
53
|
+
const results = new Map(targets.map((t) => [t.item.id, { id: t.item.id, fixed: false, attempts: [] }]));
|
|
54
|
+
const oldRecords = options.records.filter((r) => r.side === "old");
|
|
55
|
+
let calls = 0;
|
|
56
|
+
const rounds = Math.max(0, ...targets.map((t) => t.tries.length));
|
|
57
|
+
for (let round = 0; round < rounds; round++) {
|
|
58
|
+
const batch = targets.flatMap((t) => {
|
|
59
|
+
const patch = t.tries[round];
|
|
60
|
+
return patch && !results.get(t.item.id).fixed ? [{ original: t.item, patch, repaired: applyRepair(t.item, patch) }] : [];
|
|
61
|
+
});
|
|
62
|
+
if (batch.length === 0)
|
|
63
|
+
break;
|
|
64
|
+
const records = await runReplay({
|
|
65
|
+
items: batch.map((b) => b.repaired),
|
|
66
|
+
// Only the new model is called (sides); the old model's answers come from the replay.
|
|
67
|
+
oldModel: newModel,
|
|
68
|
+
newModel,
|
|
69
|
+
client: options.client,
|
|
70
|
+
runs,
|
|
71
|
+
...(options.concurrency ? { concurrency: options.concurrency } : {}),
|
|
72
|
+
maxCalls: maxCalls - calls,
|
|
73
|
+
sides: ["new"],
|
|
74
|
+
...(options.signal ? { signal: options.signal } : {}),
|
|
75
|
+
});
|
|
76
|
+
calls += records.length;
|
|
77
|
+
const reference = [...oldRecords, ...records];
|
|
78
|
+
for (const b of batch) {
|
|
79
|
+
const judged = judgeItem(b.repaired, reference);
|
|
80
|
+
const fixed = judged.verdict !== "broken";
|
|
81
|
+
const format = judged.reasons.find((r) => r.code === "format-broken");
|
|
82
|
+
const result = results.get(b.original.id);
|
|
83
|
+
result.attempts.push({
|
|
84
|
+
kind: b.patch.kind,
|
|
85
|
+
fixed,
|
|
86
|
+
detail: fixed
|
|
87
|
+
? `passes now (verdict: ${judged.verdict}, ${judged.new.runs - judged.new.errors} of ${judged.new.runs} calls answered)`
|
|
88
|
+
: (format?.detail ?? judged.reasons.find((r) => r.severity === "broken")?.detail ?? "still broken"),
|
|
89
|
+
});
|
|
90
|
+
if (fixed) {
|
|
91
|
+
result.fixed = true;
|
|
92
|
+
result.patch = b.patch;
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
return { newModel, runs, calls, results: [...results.values()] };
|
|
97
|
+
}
|
|
98
|
+
const KIND_LABEL = {
|
|
99
|
+
"format-instruction": "JSON-only instruction added to the system prompt",
|
|
100
|
+
"json-mode": "JSON-only instruction plus the provider's JSON mode",
|
|
101
|
+
};
|
|
102
|
+
export function formatRepairMarkdown(report) {
|
|
103
|
+
if (report.results.length === 0)
|
|
104
|
+
return "";
|
|
105
|
+
const fixed = report.results.filter((r) => r.fixed);
|
|
106
|
+
const lines = [
|
|
107
|
+
"### Prompt Repair",
|
|
108
|
+
"",
|
|
109
|
+
`${fixed.length} of ${report.results.length} prompt${report.results.length === 1 ? "" : "s"} with a broken answer format fixed on \`${report.newModel}\` (${report.calls} extra calls, ${report.runs} run${report.runs === 1 ? "" : "s"} per try).`,
|
|
110
|
+
"",
|
|
111
|
+
"| Prompt | Result | Tried |",
|
|
112
|
+
"| --- | --- | --- |",
|
|
113
|
+
...report.results.map((r) => `| ${cell(r.id)} | ${r.fixed ? `Fixed: ${KIND_LABEL[r.patch.kind]}` : "Not fixed"} | ${r.attempts.map((a) => cell(`${a.kind}: ${a.detail}`)).join("<br>")} |`),
|
|
114
|
+
];
|
|
115
|
+
for (const r of fixed) {
|
|
116
|
+
lines.push("", `**Change for ${code(r.id)}:** add this to the end of the system prompt${r.patch.jsonMode ? ", and turn on JSON output (`response_format: {type: \"json_object\"}` or `responseMimeType: \"application/json\"`)" : ""}:`, "", "```text", r.patch.systemAddition, "```");
|
|
117
|
+
}
|
|
118
|
+
return lines.join("\n");
|
|
119
|
+
}
|
|
120
|
+
export function formatRepairText(report) {
|
|
121
|
+
if (report.results.length === 0)
|
|
122
|
+
return "";
|
|
123
|
+
const fixed = report.results.filter((r) => r.fixed).length;
|
|
124
|
+
const lines = [`Prompt Repair: ${fixed} of ${report.results.length} format breaks fixed on ${report.newModel} (${report.calls} extra calls)`];
|
|
125
|
+
for (const r of report.results) {
|
|
126
|
+
lines.push(` ${r.fixed ? "FIXED " : "NOT FIXED"} ${r.id}${r.fixed ? `: ${KIND_LABEL[r.patch.kind]}` : ""}`);
|
|
127
|
+
for (const a of r.attempts)
|
|
128
|
+
lines.push(` tried ${a.kind}: ${a.detail}`);
|
|
129
|
+
if (r.fixed) {
|
|
130
|
+
lines.push(` add to the system prompt: ${r.patch.systemAddition}`);
|
|
131
|
+
if (r.patch.jsonMode)
|
|
132
|
+
lines.push(" and turn on the provider's JSON output mode");
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
return lines.join("\n");
|
|
136
|
+
}
|
|
137
|
+
/** One golden-set line in the format parseGoldenSet reads, so a repaired set can be re-run. */
|
|
138
|
+
export function goldenLine(item) {
|
|
139
|
+
const line = { id: item.id };
|
|
140
|
+
if (item.system)
|
|
141
|
+
line.system = item.system;
|
|
142
|
+
line.messages = item.messages;
|
|
143
|
+
if (item.tools)
|
|
144
|
+
line.tools = item.tools;
|
|
145
|
+
if (item.expect)
|
|
146
|
+
line.expect = item.expect;
|
|
147
|
+
if (item.maxTokens !== undefined)
|
|
148
|
+
line.max_tokens = item.maxTokens;
|
|
149
|
+
if (item.temperature !== undefined)
|
|
150
|
+
line.temperature = item.temperature;
|
|
151
|
+
if (item.jsonMode)
|
|
152
|
+
line.json_mode = true;
|
|
153
|
+
return JSON.stringify(line);
|
|
154
|
+
}
|
package/dist/report.d.ts
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import { type Platform } from "@ai-changeguard/catalog";
|
|
2
|
+
import type { GoldenItem } from "./golden.js";
|
|
3
|
+
import type { RunRecord, Side } from "./run.js";
|
|
4
|
+
import { type ItemResult, type JudgeOptions, type Verdict } from "./verdict.js";
|
|
5
|
+
export interface Reroute {
|
|
6
|
+
side: Side;
|
|
7
|
+
requested: string;
|
|
8
|
+
served: string;
|
|
9
|
+
}
|
|
10
|
+
interface Usage {
|
|
11
|
+
input: number;
|
|
12
|
+
output: number;
|
|
13
|
+
}
|
|
14
|
+
export interface ReplayReport {
|
|
15
|
+
oldModel: string;
|
|
16
|
+
newModel: string;
|
|
17
|
+
runs: number;
|
|
18
|
+
calls: number;
|
|
19
|
+
failedCalls: number;
|
|
20
|
+
totals: Record<Verdict, number>;
|
|
21
|
+
avgTokens: {
|
|
22
|
+
old: Usage;
|
|
23
|
+
new: Usage;
|
|
24
|
+
};
|
|
25
|
+
avgLatencyMs: {
|
|
26
|
+
old: number;
|
|
27
|
+
new: number;
|
|
28
|
+
};
|
|
29
|
+
/** US dollars per call at list price, from the average tokens; missing for a model the catalog has no price for. */
|
|
30
|
+
costPerCall?: {
|
|
31
|
+
old?: number;
|
|
32
|
+
new?: number;
|
|
33
|
+
};
|
|
34
|
+
comparedPrompts: number;
|
|
35
|
+
rateLimited: boolean;
|
|
36
|
+
reroutes: Reroute[];
|
|
37
|
+
items: ItemResult[];
|
|
38
|
+
}
|
|
39
|
+
/** The model part of a provider:model reference. */
|
|
40
|
+
export declare function modelName(ref: string): string;
|
|
41
|
+
export declare function isReroute(requested: string, served: string): boolean;
|
|
42
|
+
/**
|
|
43
|
+
* The catalog platform a provider:model reference is priced on. Undefined for gateways (groq, openrouter,
|
|
44
|
+
* ollama), which bill their own prices: the catalog only knows the providers' own APIs.
|
|
45
|
+
*/
|
|
46
|
+
export declare function platformForRef(ref: string): Platform | undefined;
|
|
47
|
+
/** List-price cost of one call for a provider:model reference, or undefined when the catalog has no price. */
|
|
48
|
+
export declare function costOfCall(ref: string, usage: Usage, today: string): number | undefined;
|
|
49
|
+
export declare function buildReplayReport(items: GoldenItem[], records: RunRecord[], options: {
|
|
50
|
+
oldModel: string;
|
|
51
|
+
newModel: string;
|
|
52
|
+
runs: number;
|
|
53
|
+
judge?: JudgeOptions;
|
|
54
|
+
today?: string;
|
|
55
|
+
}): ReplayReport;
|
|
56
|
+
/** "Cost per call at list price: $0.0012 → $0.0015 (+25%)", or "" when neither side has a price. */
|
|
57
|
+
export declare function costLine(report: ReplayReport): string;
|
|
58
|
+
export declare function formatReplayText(report: ReplayReport): string;
|
|
59
|
+
export declare function formatReplayMarkdown(report: ReplayReport): string;
|
|
60
|
+
export {};
|