@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 CHANGED
@@ -1,3 +1,7 @@
1
- # Temporary Holding Version
1
+ # @ai-changeguard/replay
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Replays real prompts on an old and a new AI model and reports what changed.
4
+
5
+ Part of [AI Change Guard](https://github.com/Navin-kumar0007/ai-change-guard-cli). To use the command-line tool, run `npx ai-change-guard`; see the [ai-change-guard](https://www.npmjs.com/package/ai-change-guard) package.
6
+
7
+ MIT licensed.
@@ -0,0 +1,56 @@
1
+ import { type LlmClient } from "@ai-changeguard/llm";
2
+ import type { GoldenItem } from "./golden.js";
3
+ import { type ReplayReport } from "./report.js";
4
+ /**
5
+ * Tested backup models. When a provider has an outage, a fallback only helps if it answers your
6
+ * prompts well enough. This replays the golden set on the primary model once and on every
7
+ * candidate, keeps the candidates with nothing broken (fewest changed answers first), and writes
8
+ * a ready LiteLLM or OpenRouter fallback config with only those.
9
+ */
10
+ export interface CandidateResult {
11
+ model: string;
12
+ report: ReplayReport;
13
+ qualifies: boolean;
14
+ /** Why a candidate was left out. */
15
+ reason?: string;
16
+ }
17
+ export interface FallbackResult {
18
+ primary: string;
19
+ runs: number;
20
+ calls: number;
21
+ candidates: CandidateResult[];
22
+ /** Qualifying candidates, best first. */
23
+ fallbacks: string[];
24
+ /** Prompts the primary never answered, so they could not be used to judge backups. */
25
+ skippedPrompts: string[];
26
+ }
27
+ export interface FallbackOptions {
28
+ items: GoldenItem[];
29
+ primary: string;
30
+ candidates: string[];
31
+ client: LlmClient;
32
+ runs?: number;
33
+ concurrency?: number;
34
+ maxCalls?: number;
35
+ signal?: AbortSignal;
36
+ /** Day the replay's cost per call is priced on (default: today). */
37
+ today?: string;
38
+ }
39
+ export declare function plannedFallbackCalls(items: number, runs: number, candidates: number): number;
40
+ /** Trimmed, de-duplicated candidates other than the primary (what the test actually runs). */
41
+ export declare function cleanCandidates(primary: string, candidates: string[]): string[];
42
+ export declare function testFallbacks(options: FallbackOptions): Promise<FallbackResult>;
43
+ /** A LiteLLM proxy config.yaml: the primary and its tested fallbacks, tried in order. Keys come from the environment. */
44
+ export declare function litellmConfig(primary: string, fallbacks: string[], note?: string): string;
45
+ /**
46
+ * The OpenRouter "models" fallback list. OpenRouter names some models differently from the
47
+ * providers (for example dots in version numbers), so ids not given as openrouter:... are listed
48
+ * for the user to check against openrouter.ai/models.
49
+ */
50
+ export declare function openrouterConfig(primary: string, fallbacks: string[]): {
51
+ body: {
52
+ models: string[];
53
+ };
54
+ unchecked: string[];
55
+ skipped: string[];
56
+ };
@@ -0,0 +1,133 @@
1
+ import { parseModelRef } from "@ai-changeguard/llm";
2
+ import { buildReplayReport } from "./report.js";
3
+ import { plannedCalls, runReplay, SpendCapError } from "./run.js";
4
+ export function plannedFallbackCalls(items, runs, candidates) {
5
+ return plannedCalls(items, runs, 1) * (1 + candidates);
6
+ }
7
+ /** Trimmed, de-duplicated candidates other than the primary (what the test actually runs). */
8
+ export function cleanCandidates(primary, candidates) {
9
+ return [...new Set(candidates.map((c) => c.trim()).filter(Boolean))].filter((c) => c !== primary);
10
+ }
11
+ /** A share this small means one broken run out of any number disqualifies a fallback. */
12
+ const ANY_RUN = 0.01;
13
+ export async function testFallbacks(options) {
14
+ const { primary, client } = options;
15
+ const runs = options.runs ?? 3;
16
+ const maxCalls = options.maxCalls ?? 500;
17
+ parseModelRef(primary);
18
+ const candidates = cleanCandidates(primary, options.candidates);
19
+ candidates.forEach((c) => parseModelRef(c));
20
+ if (candidates.length === 0)
21
+ throw new Error("Give at least one candidate model that differs from the primary.");
22
+ const planned = plannedFallbackCalls(options.items.length, runs, candidates.length);
23
+ if (planned > maxCalls) {
24
+ throw new SpendCapError(`Testing ${candidates.length} candidates needs ${planned} calls, above the limit of ${maxCalls}. Use fewer candidates or runs, or raise the limit.`);
25
+ }
26
+ const common = { client, runs, ...(options.concurrency ? { concurrency: options.concurrency } : {}), ...(options.signal ? { signal: options.signal } : {}) };
27
+ // The primary runs once; every candidate is compared against the same answers.
28
+ const primaryRecords = await runReplay({ ...common, items: options.items, oldModel: primary, newModel: primary, sides: ["old"], maxCalls });
29
+ // Without the primary's answers there is nothing to compare a backup with: stop before spending more.
30
+ const answered = new Set(primaryRecords.filter((r) => r.response).map((r) => r.itemId));
31
+ if (answered.size === 0) {
32
+ throw new Error(`${primary} did not answer any prompt (${primaryRecords[0]?.error ?? "no calls"}). Fix that first: the other models are judged against its answers.`);
33
+ }
34
+ const items = options.items.filter((i) => answered.has(i.id));
35
+ const skippedPrompts = options.items.filter((i) => !answered.has(i.id)).map((i) => i.id);
36
+ const perCandidate = plannedCalls(items.length, runs, 1);
37
+ // Candidates usually sit on different providers with their own rate limits, so they run side by side.
38
+ const results = await Promise.all(candidates.map(async (model) => {
39
+ const records = await runReplay({ ...common, items, oldModel: primary, newModel: model, sides: ["new"], maxCalls: perCandidate });
40
+ const report = buildReplayReport(items, [...primaryRecords, ...records], { oldModel: primary, newModel: model, runs, judge: { share: ANY_RUN }, ...(options.today ? { today: options.today } : {}) });
41
+ const t = report.totals;
42
+ const rerouted = report.reroutes.filter((r) => r.side === "new");
43
+ const reason = records.length > 0 && records.every((r) => r.error)
44
+ ? `every call failed: ${(records[0].error ?? "").slice(0, 120)}`
45
+ : rerouted.length > 0
46
+ ? `served as ${rerouted.map((r) => r.served).join(", ")}, not the model requested`
47
+ : t.broken > 0
48
+ ? `${t.broken} prompt${t.broken === 1 ? "" : "s"} broken in at least one run`
49
+ : t.error > 0
50
+ ? `${t.error} prompt${t.error === 1 ? "" : "s"} could not be compared`
51
+ : undefined;
52
+ return { model, report, qualifies: !reason, ...(reason ? { reason } : {}), calls: records.length };
53
+ }));
54
+ const fallbacks = results
55
+ .filter((r) => r.qualifies)
56
+ .sort((a, b) => a.report.totals.changed - b.report.totals.changed || a.report.avgLatencyMs.new - b.report.avgLatencyMs.new)
57
+ .map((r) => r.model);
58
+ return {
59
+ primary,
60
+ runs,
61
+ calls: primaryRecords.length + results.reduce((n, r) => n + r.calls, 0),
62
+ candidates: results.map(({ calls: _calls, ...r }) => r),
63
+ fallbacks,
64
+ skippedPrompts,
65
+ };
66
+ }
67
+ // ---------- LiteLLM ----------
68
+ const LITELLM = {
69
+ openai: { prefix: "openai", key: "OPENAI_API_KEY" },
70
+ anthropic: { prefix: "anthropic", key: "ANTHROPIC_API_KEY" },
71
+ google: { prefix: "gemini", key: "GEMINI_API_KEY" },
72
+ mistral: { prefix: "mistral", key: "MISTRAL_API_KEY" },
73
+ groq: { prefix: "groq", key: "GROQ_API_KEY" },
74
+ openrouter: { prefix: "openrouter", key: "OPENROUTER_API_KEY" },
75
+ ollama: { prefix: "ollama", base: "http://localhost:11434" },
76
+ };
77
+ const yamlString = (s) => JSON.stringify(s);
78
+ /** A LiteLLM proxy config.yaml: the primary and its tested fallbacks, tried in order. Keys come from the environment. */
79
+ export function litellmConfig(primary, fallbacks, note) {
80
+ const names = new Map();
81
+ const used = new Set();
82
+ for (const ref of [primary, ...fallbacks]) {
83
+ const base = parseModelRef(ref).model.split("/").pop().replace(/[^\w.-]+/g, "-");
84
+ let name = base;
85
+ for (let n = 2; used.has(name); n++)
86
+ name = `${base}-${n}`;
87
+ used.add(name);
88
+ names.set(ref, name);
89
+ }
90
+ const lines = [`# AI Change Guard: fallbacks that passed your golden set${note ? ` (${note})` : ""}`, "model_list:"];
91
+ for (const ref of [primary, ...fallbacks]) {
92
+ const { provider, model } = parseModelRef(ref);
93
+ const p = LITELLM[provider];
94
+ lines.push(` - model_name: ${yamlString(names.get(ref))}`, " litellm_params:", ` model: ${yamlString(`${p.prefix}/${model}`)}`);
95
+ if (p.key)
96
+ lines.push(` api_key: ${yamlString(`os.environ/${p.key}`)}`);
97
+ if (p.base)
98
+ lines.push(` api_base: ${yamlString(p.base)}`);
99
+ }
100
+ lines.push("", "router_settings:", ` fallbacks: [{${yamlString(names.get(primary))}: [${fallbacks.map((f) => yamlString(names.get(f))).join(", ")}]}]`, "");
101
+ return lines.join("\n");
102
+ }
103
+ // ---------- OpenRouter ----------
104
+ const OPENROUTER_PREFIX = { openai: "openai", anthropic: "anthropic", google: "google", mistral: "mistralai" };
105
+ /**
106
+ * The OpenRouter "models" fallback list. OpenRouter names some models differently from the
107
+ * providers (for example dots in version numbers), so ids not given as openrouter:... are listed
108
+ * for the user to check against openrouter.ai/models.
109
+ */
110
+ export function openrouterConfig(primary, fallbacks) {
111
+ // The first id is the model OpenRouter tries first; dropping the primary would quietly promote a backup.
112
+ if (parseModelRef(primary).provider !== "openrouter" && !OPENROUTER_PREFIX[parseModelRef(primary).provider]) {
113
+ throw new Error(`OpenRouter does not serve ${primary}, so it cannot head an OpenRouter fallback list. Use --format litellm instead.`);
114
+ }
115
+ const models = [];
116
+ const unchecked = [];
117
+ const skipped = [];
118
+ for (const ref of [primary, ...fallbacks]) {
119
+ const { provider, model } = parseModelRef(ref);
120
+ if (provider === "openrouter")
121
+ models.push(model);
122
+ else if (OPENROUTER_PREFIX[provider]) {
123
+ const id = `${OPENROUTER_PREFIX[provider]}/${model}`;
124
+ models.push(id);
125
+ unchecked.push(id);
126
+ }
127
+ else
128
+ skipped.push(ref);
129
+ }
130
+ if (models.length < 2)
131
+ throw new Error("None of the tested backups is available on OpenRouter. Use --format litellm instead.");
132
+ return { body: { models }, unchecked, skipped };
133
+ }
@@ -0,0 +1,22 @@
1
+ import type { ChatMessage, ToolDef } from "@ai-changeguard/llm";
2
+ import type { JsonSchema } from "./schema.js";
3
+ export interface GoldenExpect {
4
+ json?: boolean;
5
+ schema?: JsonSchema;
6
+ tool?: string;
7
+ contains?: string[];
8
+ }
9
+ export interface GoldenItem {
10
+ id: string;
11
+ system?: string;
12
+ messages: ChatMessage[];
13
+ tools?: ToolDef[];
14
+ expect?: GoldenExpect;
15
+ maxTokens?: number;
16
+ temperature?: number;
17
+ jsonMode?: boolean;
18
+ }
19
+ export declare class GoldenSetError extends Error {
20
+ }
21
+ export declare function parseGoldenSet(text: string): GoldenItem[];
22
+ export declare function loadGoldenSet(path: string): Promise<GoldenItem[]>;
package/dist/golden.js ADDED
@@ -0,0 +1,111 @@
1
+ import { readFile } from "node:fs/promises";
2
+ export class GoldenSetError extends Error {
3
+ }
4
+ function isObject(value) {
5
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
6
+ }
7
+ function parseMessages(raw, where) {
8
+ if (typeof raw.input === "string" && raw.input.trim())
9
+ return [{ role: "user", content: raw.input }];
10
+ const list = raw.messages;
11
+ if (Array.isArray(list) && list.length > 0) {
12
+ const messages = list.map((m, i) => {
13
+ if (!isObject(m) || (m.role !== "user" && m.role !== "assistant") || typeof m.content !== "string") {
14
+ throw new GoldenSetError(`${where}: messages[${i}] needs a role of "user" or "assistant" and text content`);
15
+ }
16
+ return { role: m.role, content: m.content };
17
+ });
18
+ if (messages.at(-1)?.role !== "user")
19
+ throw new GoldenSetError(`${where}: the last message must be from the user`);
20
+ return messages;
21
+ }
22
+ throw new GoldenSetError(`${where}: needs "input" (text) or "messages" (a list of {role, content})`);
23
+ }
24
+ function parseTools(raw, where) {
25
+ if (raw === undefined)
26
+ return undefined;
27
+ if (!Array.isArray(raw))
28
+ throw new GoldenSetError(`${where}: "tools" must be a list`);
29
+ return raw.map((t, i) => {
30
+ if (!isObject(t) || typeof t.name !== "string" || !isObject(t.parameters)) {
31
+ throw new GoldenSetError(`${where}: tools[${i}] needs a "name" and a "parameters" JSON schema`);
32
+ }
33
+ const tool = { name: t.name, parameters: t.parameters };
34
+ if (typeof t.description === "string")
35
+ tool.description = t.description;
36
+ return tool;
37
+ });
38
+ }
39
+ function parseExpect(raw, where) {
40
+ if (raw === undefined)
41
+ return undefined;
42
+ if (!isObject(raw))
43
+ throw new GoldenSetError(`${where}: "expect" must be an object`);
44
+ const expect = {};
45
+ if (raw.json !== undefined)
46
+ expect.json = Boolean(raw.json);
47
+ if (raw.schema !== undefined) {
48
+ if (!isObject(raw.schema))
49
+ throw new GoldenSetError(`${where}: "expect.schema" must be a JSON schema object`);
50
+ expect.schema = raw.schema;
51
+ }
52
+ if (raw.tool !== undefined) {
53
+ if (typeof raw.tool !== "string")
54
+ throw new GoldenSetError(`${where}: "expect.tool" must be a tool name`);
55
+ expect.tool = raw.tool;
56
+ }
57
+ if (raw.contains !== undefined) {
58
+ if (!Array.isArray(raw.contains) || !raw.contains.every((s) => typeof s === "string")) {
59
+ throw new GoldenSetError(`${where}: "expect.contains" must be a list of text`);
60
+ }
61
+ expect.contains = raw.contains;
62
+ }
63
+ return expect;
64
+ }
65
+ export function parseGoldenSet(text) {
66
+ const items = [];
67
+ const ids = new Set();
68
+ text.split(/\r?\n/).forEach((rawLine, index) => {
69
+ const line = rawLine.trim();
70
+ if (!line || line.startsWith("//"))
71
+ return;
72
+ const where = `Line ${index + 1}`;
73
+ let raw;
74
+ try {
75
+ raw = JSON.parse(line);
76
+ }
77
+ catch {
78
+ throw new GoldenSetError(`${where}: not valid JSON`);
79
+ }
80
+ if (!isObject(raw))
81
+ throw new GoldenSetError(`${where}: each line must be a JSON object`);
82
+ const id = raw.id === undefined ? `line-${index + 1}` : String(raw.id);
83
+ if (ids.has(id))
84
+ throw new GoldenSetError(`${where}: duplicate id "${id}"`);
85
+ ids.add(id);
86
+ if (raw.system !== undefined && typeof raw.system !== "string")
87
+ throw new GoldenSetError(`${where}: "system" must be text`);
88
+ const item = { id, messages: parseMessages(raw, where) };
89
+ if (typeof raw.system === "string")
90
+ item.system = raw.system;
91
+ const tools = parseTools(raw.tools, where);
92
+ if (tools)
93
+ item.tools = tools;
94
+ const expect = parseExpect(raw.expect, where);
95
+ if (expect)
96
+ item.expect = expect;
97
+ if (typeof raw.max_tokens === "number")
98
+ item.maxTokens = raw.max_tokens;
99
+ if (typeof raw.temperature === "number")
100
+ item.temperature = raw.temperature;
101
+ if (raw.json_mode === true)
102
+ item.jsonMode = true;
103
+ items.push(item);
104
+ });
105
+ if (items.length === 0)
106
+ throw new GoldenSetError("The golden set is empty.");
107
+ return items;
108
+ }
109
+ export async function loadGoldenSet(path) {
110
+ return parseGoldenSet(await readFile(path, "utf8"));
111
+ }
@@ -0,0 +1,39 @@
1
+ import type { GoldenItem } from "./golden.js";
2
+ /**
3
+ * Builds a golden set from logs people already have, so nobody has to write test prompts.
4
+ *
5
+ * Tools export logs in different wrappers (Langfuse traces and observations, Helicone request
6
+ * records, OpenTelemetry spans, plain JSONL of API requests), but the prompt inside is almost
7
+ * always one of a few request shapes. So the importer walks every record, finds a request body
8
+ * wherever it sits, and reads it by shape: OpenAI Chat Completions, OpenAI Responses,
9
+ * Anthropic Messages, Gemini generateContent, or OpenTelemetry GenAI attributes.
10
+ *
11
+ * When the recorded answer is present it also derives checks: an answer that was JSON becomes
12
+ * expect.json, and an answer that called a tool becomes expect.tool.
13
+ */
14
+ export interface ImportOptions {
15
+ /** Keep at most this many prompts, spread evenly over the log (default 50). */
16
+ limit?: number;
17
+ /** Keep only calls to this model (matched on the last path segment, case-insensitive). */
18
+ model?: string;
19
+ }
20
+ export interface ImportResult {
21
+ items: GoldenItem[];
22
+ /** Records looked at (objects that could hold a call). */
23
+ records: number;
24
+ /** Distinct prompts found before the limit was applied. */
25
+ found: number;
26
+ /** Why records were left out, with counts. */
27
+ skipped: Record<string, number>;
28
+ /** Calls per model among the prompts found. */
29
+ models: Record<string, number>;
30
+ /** Prompts kept by a --model filter although the log did not name their model (raw Gemini bodies, say). */
31
+ unknownModel: number;
32
+ }
33
+ type Json = unknown;
34
+ /** gpt-4o matches gpt-4o and its dated snapshots (gpt-4o-2024-08-06), never gpt-4o-mini. */
35
+ export declare function sameModel(logged: string, wanted: string): boolean;
36
+ export declare function importPrompts(text: string, options?: ImportOptions): ImportResult;
37
+ /** Like importPrompts, for records already parsed (several files at once, or records given extra fields). */
38
+ export declare function importValues(values: Json[], options?: ImportOptions, badLines?: number): ImportResult;
39
+ export {};