@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
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
function termVector(text) {
|
|
2
|
+
const vector = new Map();
|
|
3
|
+
for (const word of text.toLowerCase().match(/[\p{L}\p{N}]+/gu) ?? [])
|
|
4
|
+
vector.set(word, (vector.get(word) ?? 0) + 1);
|
|
5
|
+
return vector;
|
|
6
|
+
}
|
|
7
|
+
function norm(vector) {
|
|
8
|
+
let sum = 0;
|
|
9
|
+
for (const count of vector.values())
|
|
10
|
+
sum += count * count;
|
|
11
|
+
return Math.sqrt(sum);
|
|
12
|
+
}
|
|
13
|
+
export function similarity(a, b) {
|
|
14
|
+
if (!a.trim() && !b.trim())
|
|
15
|
+
return 1;
|
|
16
|
+
const va = termVector(a);
|
|
17
|
+
const vb = termVector(b);
|
|
18
|
+
let dot = 0;
|
|
19
|
+
for (const [word, count] of va)
|
|
20
|
+
dot += count * (vb.get(word) ?? 0);
|
|
21
|
+
const denominator = norm(va) * norm(vb);
|
|
22
|
+
return denominator === 0 ? 0 : dot / denominator;
|
|
23
|
+
}
|
package/dist/slim.d.ts
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import { type LlmClient } from "@ai-changeguard/llm";
|
|
2
|
+
import type { GoldenItem } from "./golden.js";
|
|
3
|
+
import { type ReplayReport } from "./report.js";
|
|
4
|
+
/** Prompts that must use one system prompt before a shorter one can be proved on them. */
|
|
5
|
+
export declare const MIN_SLIM_ITEMS = 3;
|
|
6
|
+
export type SlimStyle = "concise" | "minimal";
|
|
7
|
+
export declare const SLIM_STYLES: SlimStyle[];
|
|
8
|
+
/** Template placeholders ({name}, {{name}}, ${name}), sorted, so two prompts can be compared. */
|
|
9
|
+
export declare function placeholders(text: string): string[];
|
|
10
|
+
export declare function slimRequest(system: string, style: SlimStyle): string;
|
|
11
|
+
/** The rewritten prompt in a writer answer ({"prompt": "..."}), or undefined. */
|
|
12
|
+
export declare function parseSlimAnswer(text: string): string | undefined;
|
|
13
|
+
/** Why a rewrite can't be tested, or undefined when it can: too little shorter, or placeholders changed. */
|
|
14
|
+
export declare function rewriteProblem(original: string, rewrite: string): string | undefined;
|
|
15
|
+
export interface SlimVariant {
|
|
16
|
+
style: SlimStyle;
|
|
17
|
+
/** The rewritten system prompt (empty when the writer gave none). */
|
|
18
|
+
prompt: string;
|
|
19
|
+
qualifies: boolean;
|
|
20
|
+
reason?: string;
|
|
21
|
+
report?: ReplayReport;
|
|
22
|
+
changedShare?: number;
|
|
23
|
+
/** Average input tokens per call, measured in the replay. */
|
|
24
|
+
inputTokens?: {
|
|
25
|
+
old: number;
|
|
26
|
+
new: number;
|
|
27
|
+
};
|
|
28
|
+
/** US dollars per call at list price (the higher of today's and the price two months out), measured tokens. */
|
|
29
|
+
costPerCall?: {
|
|
30
|
+
current: number;
|
|
31
|
+
candidate: number;
|
|
32
|
+
};
|
|
33
|
+
/** Share of the cost per call saved, or of the input tokens when the model has no list price. */
|
|
34
|
+
savingShare?: number;
|
|
35
|
+
/** Dollars a month saved, from the calls per month given and this prompt's share of the golden set. */
|
|
36
|
+
monthlySaving?: number;
|
|
37
|
+
}
|
|
38
|
+
export interface SlimPrompt {
|
|
39
|
+
/** The system prompt as the golden set has it. */
|
|
40
|
+
system: string;
|
|
41
|
+
/** Prompts in the golden set that use it. */
|
|
42
|
+
items: number;
|
|
43
|
+
variants: SlimVariant[];
|
|
44
|
+
/** Why it was not tested (too few prompts, over the call limit, the model never answered). */
|
|
45
|
+
reason?: string;
|
|
46
|
+
/** Prompts your model did not answer with the original, so they were not compared. */
|
|
47
|
+
skippedPrompts: string[];
|
|
48
|
+
/** The qualifying rewrite that saves the most. */
|
|
49
|
+
best?: SlimVariant;
|
|
50
|
+
}
|
|
51
|
+
export interface SlimResult {
|
|
52
|
+
model: string;
|
|
53
|
+
writer: string;
|
|
54
|
+
runs: number;
|
|
55
|
+
calls: number;
|
|
56
|
+
callsPerMonth?: number;
|
|
57
|
+
prompts: SlimPrompt[];
|
|
58
|
+
/** Golden-set prompts with no system prompt, which have nothing to slim. */
|
|
59
|
+
withoutSystem: number;
|
|
60
|
+
}
|
|
61
|
+
export interface SlimOptions {
|
|
62
|
+
items: GoldenItem[];
|
|
63
|
+
/** The model the app uses (provider:model): both sides of every replay run on it. */
|
|
64
|
+
model: string;
|
|
65
|
+
/** The model that writes the shorter prompts (default: `model`). */
|
|
66
|
+
writer?: string;
|
|
67
|
+
client: LlmClient;
|
|
68
|
+
styles?: SlimStyle[];
|
|
69
|
+
/** Most system prompts to slim, the most-used first (default 3). */
|
|
70
|
+
maxPrompts?: number;
|
|
71
|
+
callsPerMonth?: number;
|
|
72
|
+
runs?: number;
|
|
73
|
+
concurrency?: number;
|
|
74
|
+
maxCalls?: number;
|
|
75
|
+
today?: string;
|
|
76
|
+
signal?: AbortSignal;
|
|
77
|
+
}
|
|
78
|
+
/** Calls a slimming run spends at most: one writer call and one replay per style, plus your model once per prompt. */
|
|
79
|
+
export declare function plannedSlimCalls(itemsPerPrompt: number[], runs: number, styles: number): number;
|
|
80
|
+
/** The prompt counts of the system prompts a run will slim: the most-used first, each with enough prompts. */
|
|
81
|
+
export declare function slimTargets(items: GoldenItem[], maxPrompts?: number): number[];
|
|
82
|
+
export declare function slimPrompts(options: SlimOptions): Promise<SlimResult>;
|
|
83
|
+
export declare function formatSlimText(result: SlimResult): string;
|
|
84
|
+
/** The slimming card: Markdown for a pull request or the Action's Summary. */
|
|
85
|
+
export declare function formatSlimMarkdown(result: SlimResult): string;
|
package/dist/slim.js
ADDED
|
@@ -0,0 +1,279 @@
|
|
|
1
|
+
// Verified Prompt Slimming (plan 8.14, the paid half of Token Saver): a shorter system prompt that answers your
|
|
2
|
+
// real prompts the same way. A model you choose rewrites each system prompt shorter; the golden set is replayed
|
|
3
|
+
// on your model with the old and the new prompt, and the shorter one is proposed only when nothing broke and at
|
|
4
|
+
// most 2% of answers changed: savings with proof, like Money-Finder.
|
|
5
|
+
import { formatUsd, localToday } from "@ai-changeguard/catalog";
|
|
6
|
+
import { parseModelRef } from "@ai-changeguard/llm";
|
|
7
|
+
import { buildReplayReport } from "./report.js";
|
|
8
|
+
import { plannedCalls, runReplay, SpendCapError } from "./run.js";
|
|
9
|
+
import { MAX_CHANGED_SHARE, steadyCost } from "./savings.js";
|
|
10
|
+
import { extractJson } from "./schema.js";
|
|
11
|
+
/** Prompts that must use one system prompt before a shorter one can be proved on them. */
|
|
12
|
+
export const MIN_SLIM_ITEMS = 3;
|
|
13
|
+
/** A rewrite must be at least this much shorter (in characters) to be worth testing. */
|
|
14
|
+
const MIN_SHRINK = 0.1;
|
|
15
|
+
/** And must save at least this share of the cost (or input tokens) per call, measured. */
|
|
16
|
+
const MIN_SAVING = 0.03;
|
|
17
|
+
/** One broken run out of any number disqualifies a rewrite. */
|
|
18
|
+
const ANY_RUN = 0.01;
|
|
19
|
+
export const SLIM_STYLES = ["concise", "minimal"];
|
|
20
|
+
const TARGET = {
|
|
21
|
+
concise: "about 30% shorter",
|
|
22
|
+
minimal: "as short as it can be, about half its length or less",
|
|
23
|
+
};
|
|
24
|
+
const PLACEHOLDER_RE = /\$\{[^}]*\}|\{\{[^{}]*\}\}|\{[A-Za-z_][\w.]*\}/g;
|
|
25
|
+
/** Template placeholders ({name}, {{name}}, ${name}), sorted, so two prompts can be compared. */
|
|
26
|
+
export function placeholders(text) {
|
|
27
|
+
return [...text.matchAll(PLACEHOLDER_RE)].map((m) => m[0]).sort();
|
|
28
|
+
}
|
|
29
|
+
export function slimRequest(system, style) {
|
|
30
|
+
return [
|
|
31
|
+
"Below is the system prompt of one feature in an app. It is sent with every call, so every word costs money.",
|
|
32
|
+
"",
|
|
33
|
+
"<system_prompt>",
|
|
34
|
+
system,
|
|
35
|
+
"</system_prompt>",
|
|
36
|
+
"",
|
|
37
|
+
`Rewrite it ${TARGET[style]}, without changing what the model does or how it answers.`,
|
|
38
|
+
"Keep: every rule, limit and refusal; the output format, JSON keys and field names; the structure of any examples;",
|
|
39
|
+
"every template placeholder exactly as written ({name}, {{name}}, ${name}); names, numbers and links; the language it is written in.",
|
|
40
|
+
"Remove: repetition, filler, politeness, explanations meant for people, and words that do not change the answer.",
|
|
41
|
+
'Reply with only JSON: {"prompt": "..."}',
|
|
42
|
+
].join("\n");
|
|
43
|
+
}
|
|
44
|
+
/** The rewritten prompt in a writer answer ({"prompt": "..."}), or undefined. */
|
|
45
|
+
export function parseSlimAnswer(text) {
|
|
46
|
+
const pick = (value) => {
|
|
47
|
+
const p = value && typeof value === "object" ? value.prompt : undefined;
|
|
48
|
+
return typeof p === "string" && p.trim() ? p.trim() : undefined;
|
|
49
|
+
};
|
|
50
|
+
const parsed = extractJson(text);
|
|
51
|
+
if (parsed.ok)
|
|
52
|
+
return pick(parsed.value);
|
|
53
|
+
const m = /\{[\s\S]*\}/.exec(text);
|
|
54
|
+
const retry = m ? extractJson(m[0]) : parsed;
|
|
55
|
+
return retry.ok ? pick(retry.value) : undefined;
|
|
56
|
+
}
|
|
57
|
+
/** Why a rewrite can't be tested, or undefined when it can: too little shorter, or placeholders changed. */
|
|
58
|
+
export function rewriteProblem(original, rewrite) {
|
|
59
|
+
if (!rewrite.trim())
|
|
60
|
+
return "the rewrite is empty";
|
|
61
|
+
if (rewrite.length > original.length * (1 - MIN_SHRINK))
|
|
62
|
+
return `only ${Math.max(0, Math.round((1 - rewrite.length / original.length) * 100))}% shorter`;
|
|
63
|
+
const a = placeholders(original).join("\n");
|
|
64
|
+
const b = placeholders(rewrite).join("\n");
|
|
65
|
+
if (a !== b)
|
|
66
|
+
return "the rewrite changed the template placeholders";
|
|
67
|
+
return undefined;
|
|
68
|
+
}
|
|
69
|
+
/** Calls a slimming run spends at most: one writer call and one replay per style, plus your model once per prompt. */
|
|
70
|
+
export function plannedSlimCalls(itemsPerPrompt, runs, styles) {
|
|
71
|
+
return itemsPerPrompt.reduce((n, items) => n + styles + plannedCalls(items, runs, 1) * (1 + styles), 0);
|
|
72
|
+
}
|
|
73
|
+
function groupBySystem(items) {
|
|
74
|
+
const groups = new Map();
|
|
75
|
+
for (const item of items) {
|
|
76
|
+
if (!item.system?.trim())
|
|
77
|
+
continue;
|
|
78
|
+
const list = groups.get(item.system);
|
|
79
|
+
if (list)
|
|
80
|
+
list.push(item);
|
|
81
|
+
else
|
|
82
|
+
groups.set(item.system, [item]);
|
|
83
|
+
}
|
|
84
|
+
return [...groups].map(([system, list]) => ({ system, items: list })).sort((a, b) => b.items.length - a.items.length);
|
|
85
|
+
}
|
|
86
|
+
/** The prompt counts of the system prompts a run will slim: the most-used first, each with enough prompts. */
|
|
87
|
+
export function slimTargets(items, maxPrompts = 3) {
|
|
88
|
+
return groupBySystem(items)
|
|
89
|
+
.filter((g) => g.items.length >= MIN_SLIM_ITEMS)
|
|
90
|
+
.slice(0, maxPrompts)
|
|
91
|
+
.map((g) => g.items.length);
|
|
92
|
+
}
|
|
93
|
+
export async function slimPrompts(options) {
|
|
94
|
+
const { model, client } = options;
|
|
95
|
+
const writer = options.writer ?? model;
|
|
96
|
+
parseModelRef(model);
|
|
97
|
+
parseModelRef(writer);
|
|
98
|
+
const today = options.today ?? localToday();
|
|
99
|
+
const runs = options.runs ?? 3;
|
|
100
|
+
const styles = [...new Set(options.styles ?? SLIM_STYLES)];
|
|
101
|
+
const maxCalls = options.maxCalls ?? 500;
|
|
102
|
+
const groups = groupBySystem(options.items);
|
|
103
|
+
const withSystem = groups.reduce((n, g) => n + g.items.length, 0);
|
|
104
|
+
const common = { client, runs, ...(options.concurrency ? { concurrency: options.concurrency } : {}), ...(options.signal ? { signal: options.signal } : {}) };
|
|
105
|
+
// Which prompts are tested is decided before any call, so the limit is checked on the real plan.
|
|
106
|
+
const prompts = [];
|
|
107
|
+
const testable = [];
|
|
108
|
+
for (const group of groups) {
|
|
109
|
+
const out = { system: group.system, items: group.items.length, variants: [], skippedPrompts: [] };
|
|
110
|
+
prompts.push(out);
|
|
111
|
+
if (group.items.length < MIN_SLIM_ITEMS)
|
|
112
|
+
out.reason = `only ${group.items.length} prompt${group.items.length === 1 ? "" : "s"} use${group.items.length === 1 ? "s" : ""} it; at least ${MIN_SLIM_ITEMS} are needed to prove a shorter one`;
|
|
113
|
+
else if (testable.length >= (options.maxPrompts ?? 3))
|
|
114
|
+
out.reason = "not tested this time (more system prompts than --max-prompts)";
|
|
115
|
+
else
|
|
116
|
+
testable.push({ group, out });
|
|
117
|
+
}
|
|
118
|
+
const planned = plannedSlimCalls(testable.map((t) => t.group.items.length), runs, styles.length);
|
|
119
|
+
if (planned > maxCalls) {
|
|
120
|
+
throw new SpendCapError(`Slimming ${testable.length} system prompt${testable.length === 1 ? "" : "s"} needs up to ${planned} calls, above the limit of ${maxCalls}. Use fewer runs or prompts, or raise the limit.`);
|
|
121
|
+
}
|
|
122
|
+
let calls = 0;
|
|
123
|
+
for (const { group, out } of testable) {
|
|
124
|
+
const oldRecords = await runReplay({ ...common, items: group.items, oldModel: model, newModel: model, sides: ["old"], maxCalls });
|
|
125
|
+
calls += oldRecords.length;
|
|
126
|
+
const answered = new Set(oldRecords.filter((r) => r.response).map((r) => r.itemId));
|
|
127
|
+
if (answered.size === 0) {
|
|
128
|
+
out.reason = `${model} did not answer any of its prompts (${(oldRecords[0]?.error ?? "no calls").slice(0, 120)})`;
|
|
129
|
+
continue;
|
|
130
|
+
}
|
|
131
|
+
const items = group.items.filter((i) => answered.has(i.id));
|
|
132
|
+
out.skippedPrompts = group.items.filter((i) => !answered.has(i.id)).map((i) => i.id);
|
|
133
|
+
const tried = new Set();
|
|
134
|
+
for (const style of styles) {
|
|
135
|
+
let prompt = "";
|
|
136
|
+
try {
|
|
137
|
+
calls++;
|
|
138
|
+
const res = await client({
|
|
139
|
+
model: writer,
|
|
140
|
+
system: "You shorten the system prompts of AI apps without changing what they make the model do.",
|
|
141
|
+
messages: [{ role: "user", content: slimRequest(group.system, style) }],
|
|
142
|
+
maxTokens: Math.min(8000, Math.max(1000, Math.ceil(group.system.length / 2))),
|
|
143
|
+
jsonMode: true,
|
|
144
|
+
});
|
|
145
|
+
prompt = parseSlimAnswer(res.text) ?? "";
|
|
146
|
+
}
|
|
147
|
+
catch (error) {
|
|
148
|
+
out.variants.push({ style, prompt: "", qualifies: false, reason: `the writer failed: ${(error instanceof Error ? error.message : String(error)).slice(0, 120)}` });
|
|
149
|
+
continue;
|
|
150
|
+
}
|
|
151
|
+
const problem = !prompt ? "the writer did not return a prompt" : tried.has(prompt) ? "same rewrite as the one before" : rewriteProblem(group.system, prompt);
|
|
152
|
+
if (problem) {
|
|
153
|
+
out.variants.push({ style, prompt, qualifies: false, reason: problem });
|
|
154
|
+
continue;
|
|
155
|
+
}
|
|
156
|
+
tried.add(prompt);
|
|
157
|
+
const newItems = items.map((i) => ({ ...i, system: prompt }));
|
|
158
|
+
const records = await runReplay({ ...common, items, newItems, oldModel: model, newModel: model, sides: ["new"], maxCalls: plannedCalls(items.length, runs, 1) });
|
|
159
|
+
calls += records.length;
|
|
160
|
+
const report = buildReplayReport(items, [...oldRecords, ...records], { oldModel: model, newModel: model, runs, judge: { share: ANY_RUN }, today });
|
|
161
|
+
const t = report.totals;
|
|
162
|
+
const compared = report.items.length || 1;
|
|
163
|
+
const changedShare = t.changed / compared;
|
|
164
|
+
const inputTokens = { old: report.avgTokens.old.input, new: report.avgTokens.new.input };
|
|
165
|
+
const current = steadyCost(model, report.avgTokens.old, today);
|
|
166
|
+
const candidate = steadyCost(model, report.avgTokens.new, today);
|
|
167
|
+
const priced = current !== undefined && candidate !== undefined && report.comparedPrompts > 0 ? { current, candidate } : undefined;
|
|
168
|
+
const savingShare = priced ? (priced.current > 0 ? 1 - priced.candidate / priced.current : undefined) : inputTokens.old > 0 && report.comparedPrompts > 0 ? 1 - inputTokens.new / inputTokens.old : undefined;
|
|
169
|
+
const firstBroken = report.items.find((i) => i.verdict === "broken");
|
|
170
|
+
const reason = records.length > 0 && records.every((r) => r.error)
|
|
171
|
+
? `every call failed: ${(records[0].error ?? "").slice(0, 120)}`
|
|
172
|
+
: t.broken > 0
|
|
173
|
+
? `${t.broken} prompt${t.broken === 1 ? "" : "s"} broken in at least one run (first: ${firstBroken.id}, ${(firstBroken.reasons[0]?.detail ?? firstBroken.error ?? "").slice(0, 120)})`
|
|
174
|
+
: t.error > 0
|
|
175
|
+
? `${t.error} prompt${t.error === 1 ? "" : "s"} could not be compared`
|
|
176
|
+
: changedShare > MAX_CHANGED_SHARE
|
|
177
|
+
? `${t.changed} of ${compared} prompts answered differently (more than ${Math.round(MAX_CHANGED_SHARE * 100)}%)`
|
|
178
|
+
: savingShare === undefined
|
|
179
|
+
? "no token counts came back, so the saving could not be measured"
|
|
180
|
+
: savingShare < MIN_SAVING
|
|
181
|
+
? savingShare < 0
|
|
182
|
+
? `costs more per call on your prompts (+${Math.round(-savingShare * 100)}%): longer answers outweigh the shorter prompt`
|
|
183
|
+
: `only ${Math.round(savingShare * 100)}% cheaper per call on your prompts`
|
|
184
|
+
: undefined;
|
|
185
|
+
const share = withSystem > 0 ? group.items.length / withSystem : 0;
|
|
186
|
+
out.variants.push({
|
|
187
|
+
style,
|
|
188
|
+
prompt,
|
|
189
|
+
qualifies: !reason,
|
|
190
|
+
...(reason ? { reason } : {}),
|
|
191
|
+
report,
|
|
192
|
+
changedShare,
|
|
193
|
+
inputTokens,
|
|
194
|
+
...(priced ? { costPerCall: priced } : {}),
|
|
195
|
+
...(savingShare !== undefined ? { savingShare } : {}),
|
|
196
|
+
...(priced && options.callsPerMonth !== undefined ? { monthlySaving: (priced.current - priced.candidate) * options.callsPerMonth * share } : {}),
|
|
197
|
+
});
|
|
198
|
+
}
|
|
199
|
+
const best = out.variants.filter((v) => v.qualifies).sort((a, b) => (b.savingShare ?? 0) - (a.savingShare ?? 0))[0];
|
|
200
|
+
if (best)
|
|
201
|
+
out.best = best;
|
|
202
|
+
}
|
|
203
|
+
return { model, writer, runs, calls, prompts, withoutSystem: options.items.length - withSystem, ...(options.callsPerMonth !== undefined ? { callsPerMonth: options.callsPerMonth } : {}) };
|
|
204
|
+
}
|
|
205
|
+
// ---------- Reports ----------
|
|
206
|
+
function usd(amount) {
|
|
207
|
+
return amount >= 100 ? `$${Math.round(amount).toLocaleString("en-US")}` : formatUsd(amount);
|
|
208
|
+
}
|
|
209
|
+
function preview(text, max = 70) {
|
|
210
|
+
const one = text.replace(/\s+/g, " ").trim();
|
|
211
|
+
return one.length > max ? `${one.slice(0, max - 1)}…` : one;
|
|
212
|
+
}
|
|
213
|
+
function savingText(v) {
|
|
214
|
+
const pct = Math.round((v.savingShare ?? 0) * 100);
|
|
215
|
+
const tokens = v.inputTokens ? `${Math.round(v.inputTokens.old)} → ${Math.round(v.inputTokens.new)} input tokens per call` : "";
|
|
216
|
+
const cost = v.costPerCall ? `, ${usd(v.costPerCall.current)} → ${usd(v.costPerCall.candidate)} per call` : "";
|
|
217
|
+
const month = v.monthlySaving !== undefined ? `, about ${usd(v.monthlySaving)} a month` : "";
|
|
218
|
+
return `${pct}% ${v.costPerCall ? "cheaper per call" : "fewer input tokens"} (${tokens}${cost}${month})`;
|
|
219
|
+
}
|
|
220
|
+
function verdictLine(v) {
|
|
221
|
+
const t = v.report.totals;
|
|
222
|
+
return `${t.same} same · ${t.changed} changed · ${t.broken} broken on ${v.report.items.length} prompts`;
|
|
223
|
+
}
|
|
224
|
+
export function formatSlimText(result) {
|
|
225
|
+
const out = [`Prompt slimming on ${result.model} (rewrites by ${result.writer}, ${result.runs} run${result.runs === 1 ? "" : "s"} per prompt)`];
|
|
226
|
+
if (result.prompts.length === 0)
|
|
227
|
+
out.push("No prompt in the golden set has a system prompt, so there is nothing to slim.");
|
|
228
|
+
for (const p of result.prompts) {
|
|
229
|
+
out.push("", `System prompt "${preview(p.system)}" (${p.system.length} characters, ${p.items} prompt${p.items === 1 ? "" : "s"})`);
|
|
230
|
+
if (p.reason) {
|
|
231
|
+
out.push(` NOT TESTED: ${p.reason}`);
|
|
232
|
+
continue;
|
|
233
|
+
}
|
|
234
|
+
if (p.best) {
|
|
235
|
+
out.push(` SAVE ${p.best.style} rewrite, ${p.best.prompt.length} characters: ${savingText(p.best)}`, ` ${verdictLine(p.best)}`, " New prompt:");
|
|
236
|
+
out.push(...p.best.prompt.split("\n").map((l) => ` ${l}`));
|
|
237
|
+
}
|
|
238
|
+
else
|
|
239
|
+
out.push(" No shorter prompt answered your prompts the same way. Keep the prompt you have.");
|
|
240
|
+
for (const v of p.variants)
|
|
241
|
+
if (v !== p.best)
|
|
242
|
+
out.push(` ${v.qualifies ? "ALSO" : "SKIP"} ${v.style}: ${v.qualifies ? savingText(v) : v.reason}`);
|
|
243
|
+
if (p.skippedPrompts.length)
|
|
244
|
+
out.push(` WARNING: ${result.model} did not answer ${p.skippedPrompts.length} prompt(s) (${p.skippedPrompts.slice(0, 5).join(", ")}), so they were not compared.`);
|
|
245
|
+
}
|
|
246
|
+
if (result.withoutSystem > 0)
|
|
247
|
+
out.push("", `${result.withoutSystem} prompt(s) have no system prompt and were left out.`);
|
|
248
|
+
if (result.callsPerMonth === undefined && result.prompts.some((p) => p.best?.costPerCall))
|
|
249
|
+
out.push("Add --calls-per-month or --log ai-calls.jsonl to see the monthly saving.");
|
|
250
|
+
out.push(`${result.calls} calls used. Costs use list prices, at the higher of today's and the price two months out (no batch, cache or volume discounts).`);
|
|
251
|
+
return out.join("\n");
|
|
252
|
+
}
|
|
253
|
+
/** The slimming card: Markdown for a pull request or the Action's Summary. */
|
|
254
|
+
export function formatSlimMarkdown(result) {
|
|
255
|
+
const out = [`## Prompt slimming: \`${result.model}\``, ""];
|
|
256
|
+
if (result.prompts.length === 0)
|
|
257
|
+
return [...out, "No prompt in the golden set has a system prompt, so there is nothing to slim."].join("\n");
|
|
258
|
+
for (const p of result.prompts) {
|
|
259
|
+
out.push(`### "${preview(p.system, 60).replace(/[`|]/g, "'")}" (${p.system.length} characters, ${p.items} prompt${p.items === 1 ? "" : "s"})`, "");
|
|
260
|
+
if (p.reason) {
|
|
261
|
+
out.push(`Not tested: ${p.reason}.`, "");
|
|
262
|
+
continue;
|
|
263
|
+
}
|
|
264
|
+
if (p.best) {
|
|
265
|
+
out.push(`**Use the ${p.best.style} rewrite (${p.best.prompt.length} characters): ${savingText(p.best)}.**`, "", `On your real prompts, with your model: ${verdictLine(p.best)}, ${result.runs} runs each.`, "");
|
|
266
|
+
out.push("<details><summary>The shorter prompt</summary>", "", "```text", p.best.prompt.replace(/```/g, "'''"), "```", "", "</details>", "");
|
|
267
|
+
}
|
|
268
|
+
else
|
|
269
|
+
out.push("**No shorter prompt answered your prompts the same way.** Keep the prompt you have.", "");
|
|
270
|
+
out.push("| Rewrite | Result |", "| --- | --- |");
|
|
271
|
+
for (const v of p.variants)
|
|
272
|
+
out.push(`| ${v.style} (${v.prompt.length} chars) | ${v.qualifies ? `Passes: ${verdictLine(v)}, ${savingText(v)}` : `Skipped: ${(v.reason ?? "").replace(/\|/g, "/")}`} |`);
|
|
273
|
+
if (p.skippedPrompts.length)
|
|
274
|
+
out.push("", `> **Warning:** ${result.model} did not answer ${p.skippedPrompts.length} prompt(s), so they were not compared.`);
|
|
275
|
+
out.push("");
|
|
276
|
+
}
|
|
277
|
+
out.push(`Rewrites by \`${result.writer}\`. List prices at the higher of today's and the price two months out; no batch, cache or volume discounts.`);
|
|
278
|
+
return out.join("\n");
|
|
279
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import type { LlmClient } from "@ai-changeguard/llm";
|
|
2
|
+
import type { GoldenItem } from "./golden.js";
|
|
3
|
+
/**
|
|
4
|
+
* A starter golden set for apps with no logs yet: for each system prompt found in the code,
|
|
5
|
+
* one call to a model of the user's choice writes realistic user messages for that feature.
|
|
6
|
+
* The system prompt stays exactly as written in the code; only the user messages are made up,
|
|
7
|
+
* so the set is clearly marked as generated and real logs (import, recorder) replace it later.
|
|
8
|
+
*/
|
|
9
|
+
export interface StarterSource {
|
|
10
|
+
/** Base for the item ids, e.g. "bot.py-4". */
|
|
11
|
+
id: string;
|
|
12
|
+
system: string;
|
|
13
|
+
/** The code expects JSON answers, so every item gets a JSON check. */
|
|
14
|
+
json: boolean;
|
|
15
|
+
}
|
|
16
|
+
export interface StarterOptions {
|
|
17
|
+
sources: StarterSource[];
|
|
18
|
+
model: string;
|
|
19
|
+
client: LlmClient;
|
|
20
|
+
/** User messages per system prompt (default 8). */
|
|
21
|
+
count?: number;
|
|
22
|
+
}
|
|
23
|
+
export interface StarterResult {
|
|
24
|
+
items: GoldenItem[];
|
|
25
|
+
calls: number;
|
|
26
|
+
failures: {
|
|
27
|
+
id: string;
|
|
28
|
+
error: string;
|
|
29
|
+
}[];
|
|
30
|
+
}
|
|
31
|
+
export declare function starterRequest(system: string, count: number): string;
|
|
32
|
+
/** The messages in a generator answer: {"messages": [...]} or a bare list, strings only. */
|
|
33
|
+
export declare function parseStarterAnswer(text: string, count: number): string[];
|
|
34
|
+
export declare function generateStarterSet(options: StarterOptions): Promise<StarterResult>;
|
package/dist/starter.js
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import { extractJson } from "./schema.js";
|
|
2
|
+
const MAX_MESSAGE_CHARS = 2000;
|
|
3
|
+
export function starterRequest(system, count) {
|
|
4
|
+
return [
|
|
5
|
+
"Below is the system prompt of one feature in an app.",
|
|
6
|
+
"",
|
|
7
|
+
"<system_prompt>",
|
|
8
|
+
system,
|
|
9
|
+
"</system_prompt>",
|
|
10
|
+
"",
|
|
11
|
+
`Write ${count} messages that real users would send to this feature, to test it before a model change.`,
|
|
12
|
+
"Mix everyday cases, harder edge cases, and one or two messages that are unclear or off-topic.",
|
|
13
|
+
"Write each message the way a user would type it. Fill any template placeholders with realistic values.",
|
|
14
|
+
`Reply with only JSON: {"messages": ["...", "..."]}`,
|
|
15
|
+
].join("\n");
|
|
16
|
+
}
|
|
17
|
+
function parseValue(value, count) {
|
|
18
|
+
const list = Array.isArray(value) ? value : value && typeof value === "object" ? value.messages : undefined;
|
|
19
|
+
if (!Array.isArray(list))
|
|
20
|
+
return [];
|
|
21
|
+
const seen = new Set();
|
|
22
|
+
const out = [];
|
|
23
|
+
for (const v of list) {
|
|
24
|
+
if (typeof v !== "string")
|
|
25
|
+
continue;
|
|
26
|
+
const t = v.trim();
|
|
27
|
+
if (!t || t.length > MAX_MESSAGE_CHARS || seen.has(t))
|
|
28
|
+
continue;
|
|
29
|
+
seen.add(t);
|
|
30
|
+
out.push(t);
|
|
31
|
+
if (out.length === count)
|
|
32
|
+
break;
|
|
33
|
+
}
|
|
34
|
+
return out;
|
|
35
|
+
}
|
|
36
|
+
/** The messages in a generator answer: {"messages": [...]} or a bare list, strings only. */
|
|
37
|
+
export function parseStarterAnswer(text, count) {
|
|
38
|
+
const parsed = extractJson(text);
|
|
39
|
+
if (parsed.ok)
|
|
40
|
+
return parseValue(parsed.value, count);
|
|
41
|
+
// Some models add a sentence around the JSON; take the outermost object or list.
|
|
42
|
+
const m = /[[{][\s\S]*[\]}]/.exec(text);
|
|
43
|
+
const retry = m ? extractJson(m[0]) : parsed;
|
|
44
|
+
return retry.ok ? parseValue(retry.value, count) : [];
|
|
45
|
+
}
|
|
46
|
+
export async function generateStarterSet(options) {
|
|
47
|
+
const count = options.count ?? 8;
|
|
48
|
+
const items = [];
|
|
49
|
+
const failures = [];
|
|
50
|
+
let calls = 0;
|
|
51
|
+
for (const source of options.sources) {
|
|
52
|
+
calls++;
|
|
53
|
+
try {
|
|
54
|
+
const res = await options.client({
|
|
55
|
+
model: options.model,
|
|
56
|
+
system: "You write realistic test inputs for AI-powered apps.",
|
|
57
|
+
messages: [{ role: "user", content: starterRequest(source.system, count) }],
|
|
58
|
+
maxTokens: 2000,
|
|
59
|
+
jsonMode: true,
|
|
60
|
+
});
|
|
61
|
+
const messages = parseStarterAnswer(res.text, count);
|
|
62
|
+
if (messages.length === 0) {
|
|
63
|
+
failures.push({ id: source.id, error: "the model did not return a list of messages" });
|
|
64
|
+
continue;
|
|
65
|
+
}
|
|
66
|
+
messages.forEach((content, i) => {
|
|
67
|
+
const item = { id: `${source.id}-${i + 1}`, system: source.system, messages: [{ role: "user", content }] };
|
|
68
|
+
if (source.json)
|
|
69
|
+
item.expect = { json: true };
|
|
70
|
+
items.push(item);
|
|
71
|
+
});
|
|
72
|
+
}
|
|
73
|
+
catch (error) {
|
|
74
|
+
failures.push({ id: source.id, error: error instanceof Error ? error.message : String(error) });
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
return { items, calls, failures };
|
|
78
|
+
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import type { GoldenItem } from "./golden.js";
|
|
2
|
+
import type { RunRecord } from "./run.js";
|
|
3
|
+
export type Verdict = "same" | "changed" | "broken" | "error";
|
|
4
|
+
export type ReasonCode = "calls-failing" | "format-broken" | "tool-change" | "tool-args-missing" | "missing-text" | "new-refusal" | "answer-drift";
|
|
5
|
+
export interface Reason {
|
|
6
|
+
code: ReasonCode;
|
|
7
|
+
severity: "broken" | "changed";
|
|
8
|
+
detail: string;
|
|
9
|
+
}
|
|
10
|
+
export interface SideStats {
|
|
11
|
+
runs: number;
|
|
12
|
+
errors: number;
|
|
13
|
+
avgInputTokens: number;
|
|
14
|
+
avgOutputTokens: number;
|
|
15
|
+
avgLatencyMs: number;
|
|
16
|
+
avgChars: number;
|
|
17
|
+
servedModels: string[];
|
|
18
|
+
}
|
|
19
|
+
export interface ItemResult {
|
|
20
|
+
id: string;
|
|
21
|
+
verdict: Verdict;
|
|
22
|
+
reasons: Reason[];
|
|
23
|
+
old: SideStats;
|
|
24
|
+
new: SideStats;
|
|
25
|
+
sampleOld?: string;
|
|
26
|
+
sampleNew?: string;
|
|
27
|
+
error?: string;
|
|
28
|
+
}
|
|
29
|
+
export interface JudgeOptions {
|
|
30
|
+
/**
|
|
31
|
+
* Share of the new answers that must show a problem before it counts (default 0.4: 2 of 5).
|
|
32
|
+
* The nightly watch uses 0.6 (3 of 5) so a single odd answer never raises an alarm.
|
|
33
|
+
*/
|
|
34
|
+
share?: number;
|
|
35
|
+
}
|
|
36
|
+
export declare function judgeItem(item: GoldenItem, records: RunRecord[], options?: JudgeOptions): ItemResult;
|