@drakonkat/ai-helper 1.1.1 → 1.2.2
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/ARCHITECTURE.md +14 -3
- package/CHANGELOG.md +8 -0
- package/README.md +417 -24
- package/docs/benchmark.md +273 -0
- package/package.json +17 -5
- package/scripts/bench-proxy.js +107 -0
- package/scripts/build.js +16 -0
- package/src/benchmark/fixtures.js +150 -0
- package/src/benchmark/live.js +78 -0
- package/src/benchmark/measurement.js +180 -0
- package/src/benchmark/quality.js +144 -0
- package/src/benchmark/report.js +141 -0
- package/src/benchmark/runner.js +269 -0
- package/src/codex-config.js +247 -0
- package/src/codex-routing.js +132 -0
- package/src/config.js +11 -1
- package/src/index.js +99 -22
- package/src/manager.js +126 -13
- package/src/proxy-interceptor.example.mjs +33 -0
- package/src/proxy-presets.js +226 -0
- package/src/proxy-stats.js +64 -0
- package/src/proxy-worker.js +17 -0
- package/src/proxy.js +313 -0
- package/src/tui.js +230 -75
- package/src/update.js +41 -0
- package/src/utils/metrics.js +29 -7
- package/src/utils/process.js +92 -146
- package/src/utils/versions.js +171 -0
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
// Live evaluation is opt-in. No tool requested by a model is ever executed.
|
|
2
|
+
import { performance } from "node:perf_hooks";
|
|
3
|
+
|
|
4
|
+
export function validateUpstream(value) {
|
|
5
|
+
const url = new URL(value);
|
|
6
|
+
if (!["http:", "https:"].includes(url.protocol) || url.username || url.password || url.search || url.hash) {
|
|
7
|
+
throw new Error("Live upstream must be HTTP(S), without credentials, query or fragment");
|
|
8
|
+
}
|
|
9
|
+
return url.href;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export async function readLimited(response, maxBytes) {
|
|
13
|
+
const chunks = [];
|
|
14
|
+
let size = 0;
|
|
15
|
+
for await (const chunk of response.body) {
|
|
16
|
+
size += chunk.length;
|
|
17
|
+
if (size > maxBytes) throw new Error("Response exceeds benchmark maxBodyBytes");
|
|
18
|
+
chunks.push(chunk);
|
|
19
|
+
}
|
|
20
|
+
return Buffer.concat(chunks).toString("utf8");
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export async function callProvider(body, fixture, options) {
|
|
24
|
+
const headers = { "content-type": "application/json" };
|
|
25
|
+
if (options.apiKey) {
|
|
26
|
+
if (fixture.format === "anthropic") headers["x-api-key"] = options.apiKey;
|
|
27
|
+
else headers.authorization = `Bearer ${options.apiKey}`;
|
|
28
|
+
}
|
|
29
|
+
if (fixture.format === "anthropic") headers["anthropic-version"] = "2023-06-01";
|
|
30
|
+
const url = options.upstream.replace(/\/$/, "") + fixture.path;
|
|
31
|
+
const start = performance.now();
|
|
32
|
+
const response = await fetch(url, {
|
|
33
|
+
method: "POST", headers, body: JSON.stringify(body), redirect: "error",
|
|
34
|
+
signal: options.signal ? AbortSignal.any([options.signal, AbortSignal.timeout(options.timeoutMs)]) : AbortSignal.timeout(options.timeoutMs),
|
|
35
|
+
});
|
|
36
|
+
const raw = await readLimited(response, options.maxBodyBytes);
|
|
37
|
+
const durationMs = performance.now() - start;
|
|
38
|
+
// Never put provider error bodies (which can echo credentials/prompts) in reports.
|
|
39
|
+
if (!response.ok) return { status: response.status, durationMs, error: `Provider HTTP ${response.status}` };
|
|
40
|
+
let value;
|
|
41
|
+
try { value = JSON.parse(raw); } catch { return { status: response.status, durationMs, error: "Provider did not return JSON (streaming is not supported)" }; }
|
|
42
|
+
try { return { status: response.status, durationMs, ...parseProviderResponse(value, fixture.format) }; }
|
|
43
|
+
catch { return { status: response.status, durationMs, error: "Provider returned an invalid response shape" }; }
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
const number = n => Number.isFinite(n) && n >= 0 ? n : null;
|
|
47
|
+
|
|
48
|
+
export function parseProviderResponse(value, format) {
|
|
49
|
+
const u = value?.usage || {};
|
|
50
|
+
let text = "", additionalToolCalls = 0, complete = true;
|
|
51
|
+
let inputTokens = number(u.input_tokens ?? u.prompt_tokens);
|
|
52
|
+
const outputTokens = number(u.output_tokens ?? u.completion_tokens);
|
|
53
|
+
const cachedInputTokens = number(u.input_tokens_details?.cached_tokens ?? u.prompt_tokens_details?.cached_tokens ?? u.cache_read_input_tokens);
|
|
54
|
+
const cacheWriteInputTokens = number(u.cache_creation_input_tokens);
|
|
55
|
+
if (format === "anthropic") {
|
|
56
|
+
text = (value.content || []).filter(x => x.type === "text").map(x => x.text).join("\n");
|
|
57
|
+
additionalToolCalls = (value.content || []).filter(x => x.type === "tool_use").length;
|
|
58
|
+
complete = value.stop_reason === "end_turn" || value.stop_reason === "stop_sequence";
|
|
59
|
+
// Anthropic input_tokens excludes cache reads/writes; normalize to all input.
|
|
60
|
+
if (inputTokens !== null) inputTokens += (cachedInputTokens ?? 0) + (cacheWriteInputTokens ?? 0);
|
|
61
|
+
} else if (format === "chat") {
|
|
62
|
+
const choice = value.choices?.[0];
|
|
63
|
+
const content = choice?.message?.content;
|
|
64
|
+
text = typeof content === "string" ? content : Array.isArray(content) ? content.filter(x => x.type === "text").map(x => x.text).join("\n") : "";
|
|
65
|
+
additionalToolCalls = choice?.message?.tool_calls?.length || 0;
|
|
66
|
+
complete = choice?.finish_reason === "stop";
|
|
67
|
+
} else {
|
|
68
|
+
text = typeof value.output_text === "string" ? value.output_text : (value.output || []).flatMap(x => x.content || []).filter(x => x.type === "output_text").map(x => x.text).join("\n");
|
|
69
|
+
additionalToolCalls = (value.output || []).filter(x => /(?:^|_)call$/.test(x.type || "")).length;
|
|
70
|
+
complete = value.status === "completed";
|
|
71
|
+
}
|
|
72
|
+
return {
|
|
73
|
+
text, additionalToolCalls, complete: complete && additionalToolCalls === 0,
|
|
74
|
+
usage: { inputTokens, outputTokens, cachedInputTokens, cacheWriteInputTokens,
|
|
75
|
+
totalTokens: inputTokens !== null && outputTokens !== null ? inputTokens + outputTokens : null,
|
|
76
|
+
reasoningTokens: number(u.output_tokens_details?.reasoning_tokens ?? u.completion_tokens_details?.reasoning_tokens) },
|
|
77
|
+
};
|
|
78
|
+
}
|
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
import { countTokens } from "gpt-tokenizer/encoding/o200k_base";
|
|
2
|
+
import { openAIVisionTokens, resolveVisionCost } from "pxpipe-proxy";
|
|
3
|
+
|
|
4
|
+
const PNG_SIGNATURE = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]);
|
|
5
|
+
const IMAGE_TYPES = new Set(["image", "image_url", "input_image"]);
|
|
6
|
+
const OTHER_MEDIA_TYPES = new Set(["audio", "input_audio", "output_audio", "video", "video_url", "input_video", "file", "input_file", "document"]);
|
|
7
|
+
const BINARY_KEYS = new Set(["encrypted_content", "file_data", "b64_json", "base64", "bytes", "audio_data", "image_data", "video_data"]);
|
|
8
|
+
|
|
9
|
+
function tokenize(text) {
|
|
10
|
+
// Tool output may contain special-token spellings; count them as ordinary text.
|
|
11
|
+
return countTokens(text, { disallowedSpecial: new Set() });
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
function parseBody(body) {
|
|
15
|
+
const serialized = typeof body === "string" ? body
|
|
16
|
+
: body instanceof Uint8Array ? Buffer.from(body).toString("utf8") : JSON.stringify(body);
|
|
17
|
+
const parsed = JSON.parse(serialized);
|
|
18
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
|
|
19
|
+
throw new TypeError("Benchmark measurement requires a JSON request object");
|
|
20
|
+
}
|
|
21
|
+
return { parsed, bytes: Buffer.byteLength(serialized, "utf8") };
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function pngDimensions(url) {
|
|
25
|
+
if (typeof url !== "string" || !url.startsWith("data:image/png;base64,")) return null;
|
|
26
|
+
const payload = url.slice("data:image/png;base64,".length);
|
|
27
|
+
// Decode only IHDR, never the whole image. A malformed or truncated header is
|
|
28
|
+
// not an image with zero cost. PNG dimensions are unsigned 31-bit integers.
|
|
29
|
+
if (payload.length < 44 || payload.length % 4 !== 0 || !/^[A-Za-z0-9+/]+={0,2}$/.test(payload)) return null;
|
|
30
|
+
const header = Buffer.from(payload.slice(0, 44), "base64");
|
|
31
|
+
if (header.length < 33 || !header.subarray(0, 8).equals(PNG_SIGNATURE)
|
|
32
|
+
|| header.readUInt32BE(8) !== 13 || header.toString("ascii", 12, 16) !== "IHDR") return null;
|
|
33
|
+
const width = header.readUInt32BE(16);
|
|
34
|
+
const height = header.readUInt32BE(20);
|
|
35
|
+
if (!width || !height || width > 0x7fffffff || height > 0x7fffffff) return null;
|
|
36
|
+
return { width, height };
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function recognizedOpenAIModel(value) {
|
|
40
|
+
// Do not let pxpipe's unknown-model fallback charge an Anthropic/Gemini image
|
|
41
|
+
// using OpenAI tile costs. These are model families represented by the pinned
|
|
42
|
+
// pxpipe version; future/unrecognized versions must be added deliberately.
|
|
43
|
+
const model = typeof value === "string" ? value.toLowerCase().replace(/^openai\//, "") : "";
|
|
44
|
+
const date = "(?:-\\d{4}-\\d{2}-\\d{2})?";
|
|
45
|
+
const known = ["gpt-4o", "gpt-4\\.1(?:-mini|-nano)?", "gpt-4\\.5-preview",
|
|
46
|
+
"gpt-5(?:-mini|-nano|-chat-latest)?", "gpt-5\\.[1-6](?:-mini|-nano|-sol|-terra|-luna|-chat-latest|-codex)?",
|
|
47
|
+
"o1(?:-pro)?", "o3(?:-pro)?", "o4-mini"];
|
|
48
|
+
return new RegExp(`^(?:${known.join("|")})${date}$`).test(model) ? model : null;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function imageSource(block) {
|
|
52
|
+
if (block.type === "image_url") return { url: block.image_url?.url ?? block.image_url, detail: block.image_url?.detail ?? block.detail };
|
|
53
|
+
if (block.type === "input_image") return { url: block.image_url, detail: block.detail };
|
|
54
|
+
const source = block.source ?? block.inline_data ?? block.inlineData;
|
|
55
|
+
if (source?.type === "base64" || source?.data) {
|
|
56
|
+
return { url: `data:${source.media_type ?? source.mime_type ?? source.mimeType};base64,${source.data}`, detail: block.detail };
|
|
57
|
+
}
|
|
58
|
+
return { url: source?.url ?? block.url, detail: block.detail };
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function toolStrings(body) {
|
|
62
|
+
const strings = [];
|
|
63
|
+
const add = value => {
|
|
64
|
+
if (typeof value === "string") strings.push(value);
|
|
65
|
+
else if (Array.isArray(value)) {
|
|
66
|
+
for (const block of value) {
|
|
67
|
+
if (["text", "input_text", "output_text"].includes(block?.type) && typeof block.text === "string") strings.push(block.text);
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
};
|
|
71
|
+
for (const item of Array.isArray(body.input) ? body.input : []) {
|
|
72
|
+
if (item?.type === "function_call_output") add(item.output);
|
|
73
|
+
}
|
|
74
|
+
for (const message of Array.isArray(body.messages) ? body.messages : []) {
|
|
75
|
+
if (message?.role === "tool" || message?.role === "function") add(message.content);
|
|
76
|
+
for (const block of Array.isArray(message?.content) ? message.content : []) {
|
|
77
|
+
if (block?.type === "tool_result") add(block.content);
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
return strings;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* A deterministic, cross-preset estimate, NOT provider billing/count_tokens.
|
|
85
|
+
* textTokens counts canonical JSON (including structural/request fields) after
|
|
86
|
+
* removing media payloads and opaque encrypted content. It uses o200k_base for
|
|
87
|
+
* EVERY model so comparisons do not mix compressors' incompatible counters.
|
|
88
|
+
* Image estimates use the installed pxpipe profile only for recognized OpenAI
|
|
89
|
+
* models with explicit high/original detail. Unknown detail, remote/non-PNG
|
|
90
|
+
* images, non-OpenAI media, and opaque content make totalTokens null; the known
|
|
91
|
+
* subtotal remains available in knownTokens. No remote URL is fetched.
|
|
92
|
+
*/
|
|
93
|
+
export async function measureRequest(body) {
|
|
94
|
+
const { parsed, bytes } = parseBody(body);
|
|
95
|
+
const warnings = new Set(["Local estimate: o200k_base over sanitized canonical JSON, not provider billing; JSON framing differs from model serialization."]);
|
|
96
|
+
const model = recognizedOpenAIModel(parsed.model);
|
|
97
|
+
const imageMeasurements = [];
|
|
98
|
+
let unknownMedia = 0;
|
|
99
|
+
let opaqueFields = 0;
|
|
100
|
+
let omittedPayloads = 0;
|
|
101
|
+
|
|
102
|
+
function inspectImage(block) {
|
|
103
|
+
const { url, detail } = imageSource(block);
|
|
104
|
+
const dimensions = pngDimensions(url);
|
|
105
|
+
let reason;
|
|
106
|
+
if (!model) reason = "unsupported_model";
|
|
107
|
+
else if (!dimensions) reason = "remote_non_png_or_invalid_header";
|
|
108
|
+
else if (detail !== "high" && detail !== "original") reason = "unknown_image_detail";
|
|
109
|
+
let tokens = null;
|
|
110
|
+
if (!reason) {
|
|
111
|
+
const profile = resolveVisionCost(model);
|
|
112
|
+
if (!["tile", "patch"].includes(profile?.regime)) reason = "unsupported_vision_profile";
|
|
113
|
+
// The dependency's patch-cap shortcut is not a full provider resize
|
|
114
|
+
// algorithm. Above its cap, leave the cost unknown rather than undercount.
|
|
115
|
+
else if (profile.regime === "patch" && profile.patchCap
|
|
116
|
+
&& Math.ceil(dimensions.width / 32) * Math.ceil(dimensions.height / 32) > profile.patchCap) reason = "image_resize_not_modeled";
|
|
117
|
+
else {
|
|
118
|
+
const estimate = openAIVisionTokens(model, dimensions.width, dimensions.height);
|
|
119
|
+
if (!Number.isFinite(estimate) || estimate < 0) reason = "invalid_vision_estimate";
|
|
120
|
+
else tokens = estimate;
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
if (reason) warnings.add(`Image token cost unknown (${reason}); totalTokens is null, not zero.`);
|
|
124
|
+
else warnings.add("Image tokens are an installed pxpipe profile approximation for explicit high/original detail; provider resizing/detail rules and profile overrides may differ. Validate with provider usage.");
|
|
125
|
+
imageMeasurements.push({ ...(dimensions ?? {}), detail: detail ?? null, tokens, reason: reason ?? null });
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
function stripDataUris(text) {
|
|
129
|
+
return text.replace(/data:[^\s\"'<>]*;base64,[A-Za-z0-9+/=_-]*/gi, () => {
|
|
130
|
+
omittedPayloads++;
|
|
131
|
+
return "";
|
|
132
|
+
});
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
function sanitize(value) {
|
|
136
|
+
if (typeof value === "string") return stripDataUris(value);
|
|
137
|
+
if (Array.isArray(value)) return value.map(sanitize);
|
|
138
|
+
if (!value || typeof value !== "object") return value;
|
|
139
|
+
const inline = value.inline_data ?? value.inlineData;
|
|
140
|
+
const isImage = IMAGE_TYPES.has(value.type) || /^image\//.test(inline?.mime_type ?? inline?.mimeType ?? "");
|
|
141
|
+
if (isImage) {
|
|
142
|
+
inspectImage(value);
|
|
143
|
+
// Image URLs, IDs and payloads are transport representations, NOT text.
|
|
144
|
+
return { type: value.type ?? "image", ...(value.detail ? { detail: value.detail } : {}) };
|
|
145
|
+
}
|
|
146
|
+
if (OTHER_MEDIA_TYPES.has(value.type) || inline) {
|
|
147
|
+
unknownMedia++;
|
|
148
|
+
return { type: value.type ?? "media" };
|
|
149
|
+
}
|
|
150
|
+
const result = Object.create(null);
|
|
151
|
+
for (const key of Object.keys(value).sort()) {
|
|
152
|
+
if (BINARY_KEYS.has(key) || key === "data" && value.type === "base64") {
|
|
153
|
+
if (key === "encrypted_content") opaqueFields++;
|
|
154
|
+
else omittedPayloads++;
|
|
155
|
+
continue;
|
|
156
|
+
}
|
|
157
|
+
result[key] = sanitize(value[key]);
|
|
158
|
+
}
|
|
159
|
+
return result;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
const sanitized = sanitize(parsed);
|
|
163
|
+
const textTokens = tokenize(JSON.stringify(sanitized));
|
|
164
|
+
// These are bare tool text counts, without JSON framing. Do not treat the
|
|
165
|
+
// disappearance of native tool text into images as 100% whole-request savings.
|
|
166
|
+
const toolTextTokens = toolStrings(parsed).reduce((sum, text) => sum + tokenize(stripDataUris(text)), 0);
|
|
167
|
+
const unknownImages = imageMeasurements.filter(item => item.tokens === null).length;
|
|
168
|
+
const imageTokens = imageMeasurements.reduce((sum, item) => sum + (item.tokens ?? 0), 0);
|
|
169
|
+
const knownTokens = textTokens + imageTokens;
|
|
170
|
+
if (unknownMedia) warnings.add("Audio/video/file or other media cost is unknown; its payload is excluded from text tokens.");
|
|
171
|
+
if (opaqueFields) warnings.add("Opaque encrypted_content is excluded; its token cost is unknown.");
|
|
172
|
+
if (omittedPayloads) warnings.add("Unclassified binary/base64 payloads are excluded from text tokens; their token cost is unknown.");
|
|
173
|
+
const hasUnknown = unknownImages > 0 || unknownMedia > 0 || opaqueFields > 0 || omittedPayloads > 0;
|
|
174
|
+
return {
|
|
175
|
+
method: "o200k_base:canonical-json+pxpipe:openai-vision-estimate",
|
|
176
|
+
textTokens, toolTextTokens, imageTokens, totalTokens: hasUnknown ? null : knownTokens,
|
|
177
|
+
knownTokens, images: imageMeasurements.length, unknownImages, unknownMedia, opaqueFields,
|
|
178
|
+
bytes, warnings: [...warnings], imageMeasurements,
|
|
179
|
+
};
|
|
180
|
+
}
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
// Deterministic preservation checks are a lower bound on quality, not a semantic
|
|
2
|
+
// judge. In particular, rendering text into an image does not prove it is readable.
|
|
3
|
+
const IMAGE_TYPES = new Set(["image", "input_image", "image_url"]);
|
|
4
|
+
|
|
5
|
+
function contentTexts(value) {
|
|
6
|
+
if (typeof value === "string") return [withoutDataUrls(value)];
|
|
7
|
+
if (!Array.isArray(value)) return [];
|
|
8
|
+
return value.flatMap(part => {
|
|
9
|
+
if (!part || typeof part !== "object" || IMAGE_TYPES.has(part.type)) return [];
|
|
10
|
+
if (["text", "input_text", "output_text"].includes(part.type) && typeof part.text === "string") return [withoutDataUrls(part.text)];
|
|
11
|
+
if (part.type === "tool_result") return contentTexts(part.content);
|
|
12
|
+
return [];
|
|
13
|
+
});
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
function withoutDataUrls(text) {
|
|
17
|
+
return text.replace(/data:[^\s,]*;base64,[A-Za-z0-9+/=_-]+/g, "");
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
function toolTexts(body) {
|
|
21
|
+
const result = [];
|
|
22
|
+
for (const item of Array.isArray(body?.input) ? body.input : []) {
|
|
23
|
+
if (item?.type === "function_call_output") result.push(...contentTexts(item.output));
|
|
24
|
+
}
|
|
25
|
+
for (const message of Array.isArray(body?.messages) ? body.messages : []) {
|
|
26
|
+
if (message?.role === "tool") result.push(...contentTexts(message.content));
|
|
27
|
+
for (const part of Array.isArray(message?.content) ? message.content : []) {
|
|
28
|
+
if (part?.type === "tool_result") result.push(...contentTexts(part.content));
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
return result;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function requestTexts(body) {
|
|
35
|
+
if (!body || typeof body !== "object") return [];
|
|
36
|
+
const result = [...contentTexts(body.instructions), ...contentTexts(body.system)];
|
|
37
|
+
if (typeof body.input === "string") result.push(withoutDataUrls(body.input));
|
|
38
|
+
for (const item of Array.isArray(body.input) ? body.input : []) {
|
|
39
|
+
result.push(...contentTexts(item?.content));
|
|
40
|
+
if (item?.type === "function_call_output") result.push(...contentTexts(item.output));
|
|
41
|
+
if (item?.type === "function_call" && typeof item.arguments === "string") result.push(withoutDataUrls(item.arguments));
|
|
42
|
+
}
|
|
43
|
+
for (const message of Array.isArray(body.messages) ? body.messages : []) result.push(...contentTexts(message?.content));
|
|
44
|
+
for (const tool of Array.isArray(body.tools) ? body.tools : []) {
|
|
45
|
+
const definition = tool?.function || tool;
|
|
46
|
+
if (typeof definition?.description === "string") result.push(withoutDataUrls(definition.description));
|
|
47
|
+
}
|
|
48
|
+
return result;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function hasImages(value) {
|
|
52
|
+
if (!value || typeof value !== "object") return false;
|
|
53
|
+
if (IMAGE_TYPES.has(value.type)) return true;
|
|
54
|
+
return Object.values(value).some(child => Array.isArray(child) ? child.some(hasImages) : hasImages(child));
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function toolStructure(body) {
|
|
58
|
+
const calls = new Map();
|
|
59
|
+
const outputs = new Set();
|
|
60
|
+
for (const item of Array.isArray(body?.input) ? body.input : []) {
|
|
61
|
+
if (item?.type === "function_call" && typeof item.call_id === "string") calls.set(item.call_id, item.name);
|
|
62
|
+
if (item?.type === "function_call_output" && typeof item.call_id === "string") outputs.add(item.call_id);
|
|
63
|
+
}
|
|
64
|
+
for (const message of Array.isArray(body?.messages) ? body.messages : []) {
|
|
65
|
+
for (const call of Array.isArray(message?.tool_calls) ? message.tool_calls : []) {
|
|
66
|
+
if (typeof call?.id === "string") calls.set(call.id, call.function?.name);
|
|
67
|
+
}
|
|
68
|
+
if (message?.role === "tool" && typeof message.tool_call_id === "string") outputs.add(message.tool_call_id);
|
|
69
|
+
for (const part of Array.isArray(message?.content) ? message.content : []) {
|
|
70
|
+
if (part?.type === "tool_use" && typeof part.id === "string") calls.set(part.id, part.name);
|
|
71
|
+
if (part?.type === "tool_result" && typeof part.tool_use_id === "string") outputs.add(part.tool_use_id);
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
return { calls, outputs };
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function summarize(checks) {
|
|
78
|
+
const passed = checks.filter(check => check.status === "pass").length;
|
|
79
|
+
const failed = checks.filter(check => check.status === "fail").length;
|
|
80
|
+
const unknown = checks.filter(check => check.status === "indeterminate").length;
|
|
81
|
+
return { status: failed ? "fail" : unknown ? "indeterminate" : checks.length ? "pass" : "unscored", passed, failed, unknown, total: checks.length, checks };
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function strings(value, key) {
|
|
85
|
+
if (value === undefined) return [];
|
|
86
|
+
if (!Array.isArray(value) || value.some(text => typeof text !== "string" || !text.trim())) {
|
|
87
|
+
throw new Error(`${key} must be an array of nonempty strings`);
|
|
88
|
+
}
|
|
89
|
+
return value;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** Check text and native tool invariants without decoding or OCRing images. */
|
|
93
|
+
export function evaluatePreservation(originalBody, transformedBody, checks = {}) {
|
|
94
|
+
if (!checks || typeof checks !== "object" || Array.isArray(checks)) throw new Error("checks must be an object");
|
|
95
|
+
const results = [];
|
|
96
|
+
const images = hasImages(transformedBody);
|
|
97
|
+
for (const [scope, extract] of [["toolIncludes", toolTexts], ["requestIncludes", requestTexts]]) {
|
|
98
|
+
const original = extract(originalBody);
|
|
99
|
+
const transformed = extract(transformedBody);
|
|
100
|
+
strings(checks[scope], `checks.${scope}`).forEach((expected, index) => {
|
|
101
|
+
const sourcePresent = original.some(text => text.includes(expected));
|
|
102
|
+
const present = transformed.some(text => text.includes(expected));
|
|
103
|
+
results.push({ id: `${scope}:${index}`, kind: scope, expected,
|
|
104
|
+
status: !sourcePresent ? "indeterminate" : present ? "pass" : images ? "indeterminate" : "fail",
|
|
105
|
+
reason: !sourcePresent ? "not_in_original" : present ? "preserved_text" : images ? "image_content_requires_live_evaluation" : "missing_text" });
|
|
106
|
+
});
|
|
107
|
+
}
|
|
108
|
+
if (typeof originalBody?.model === "string") {
|
|
109
|
+
const preserved = originalBody.model === transformedBody?.model;
|
|
110
|
+
results.push({ id: "structure:model", kind: "structure", status: preserved ? "pass" : "fail", reason: preserved ? "model_preserved" : "model_changed_or_missing" });
|
|
111
|
+
}
|
|
112
|
+
const original = toolStructure(originalBody);
|
|
113
|
+
const transformed = toolStructure(transformedBody);
|
|
114
|
+
for (const [id, name] of original.calls) {
|
|
115
|
+
// Only require pairs which were present in the source: some Responses inputs
|
|
116
|
+
// legitimately reference calls stored in previous_response_id server state.
|
|
117
|
+
if (!original.outputs.has(id)) continue;
|
|
118
|
+
const preserved = transformed.calls.get(id) === name && transformed.outputs.has(id);
|
|
119
|
+
results.push({ id: `structure:tool_pair:${id}`, kind: "structure", status: preserved ? "pass" : images ? "indeterminate" : "fail",
|
|
120
|
+
reason: preserved ? "tool_pair_preserved" : images ? "image_restructured_tool_history" : "tool_pair_missing_or_changed" });
|
|
121
|
+
}
|
|
122
|
+
const names = new Set((Array.isArray(transformedBody?.tools) ? transformedBody.tools : []).map(tool => tool?.function?.name || tool?.name).filter(Boolean));
|
|
123
|
+
for (const tool of Array.isArray(originalBody?.tools) ? originalBody.tools : []) {
|
|
124
|
+
const name = tool?.function?.name || tool?.name;
|
|
125
|
+
if (typeof name === "string") results.push({ id: `structure:tool_definition:${name}`, kind: "structure", status: names.has(name) ? "pass" : "fail", reason: names.has(name) ? "tool_definition_preserved" : "tool_definition_missing" });
|
|
126
|
+
}
|
|
127
|
+
return summarize(results);
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/** Exact, case-sensitive answer checks; no assertions means explicitly unscored. */
|
|
131
|
+
export function evaluateAnswer(text, answerChecks) {
|
|
132
|
+
if (answerChecks === undefined || answerChecks === null) return summarize([]);
|
|
133
|
+
if (typeof answerChecks !== "object" || Array.isArray(answerChecks)) throw new Error("answerChecks must be an object");
|
|
134
|
+
const results = [];
|
|
135
|
+
for (const kind of ["includes", "excludes"]) {
|
|
136
|
+
strings(answerChecks[kind], `answerChecks.${kind}`).forEach((expected, index) => {
|
|
137
|
+
const present = typeof text === "string" && text.includes(expected);
|
|
138
|
+
results.push({ id: `${kind}:${index}`, kind, expected,
|
|
139
|
+
status: typeof text !== "string" ? "indeterminate" : (kind === "includes" ? present : !present) ? "pass" : "fail",
|
|
140
|
+
reason: typeof text !== "string" ? "no_text_answer" : kind === "includes" ? "required_answer_text" : "forbidden_answer_text" });
|
|
141
|
+
});
|
|
142
|
+
}
|
|
143
|
+
return summarize(results);
|
|
144
|
+
}
|
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
const finite = n => Number.isFinite(n);
|
|
2
|
+
export function percentile(values, percent) {
|
|
3
|
+
const sorted = values.filter(finite).sort((a, b) => a - b);
|
|
4
|
+
return sorted.length ? sorted[Math.max(0, Math.ceil(percent / 100 * sorted.length) - 1)] : null;
|
|
5
|
+
}
|
|
6
|
+
const percent = (a, b) => b ? 100 * a / b : null;
|
|
7
|
+
const key = row => JSON.stringify([row.model, row.format, row.transport]);
|
|
8
|
+
|
|
9
|
+
function quality(rows, field) {
|
|
10
|
+
const counts = { pass: 0, fail: 0, indeterminate: 0, unscored: 0 };
|
|
11
|
+
for (const row of rows) counts[row[field]?.status || "unscored"]++;
|
|
12
|
+
return { ...counts, passRate: percent(counts.pass, rows.length) };
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
function summarize(rows) {
|
|
16
|
+
const successful = rows.filter(r => r.status === "ok");
|
|
17
|
+
const known = successful.filter(r => finite(r.before?.totalTokens) && finite(r.after?.totalTokens));
|
|
18
|
+
const before = known.reduce((n, r) => n + r.before.totalTokens, 0);
|
|
19
|
+
const after = known.reduce((n, r) => n + r.after.totalTokens, 0);
|
|
20
|
+
const tools = successful.filter(r => finite(r.before?.toolTextTokens) && finite(r.after?.toolTextTokens));
|
|
21
|
+
const toolsBefore = tools.reduce((n, r) => n + r.before.toolTextTokens, 0);
|
|
22
|
+
const toolsAfter = tools.reduce((n, r) => n + r.after.toolTextTokens, 0);
|
|
23
|
+
const usageRows = successful.filter(r => finite(r.live?.usage?.inputTokens) && finite(r.live?.usage?.outputTokens));
|
|
24
|
+
const usage = field => { const rs = successful.filter(r => finite(r.live?.usage?.[field])); return { total: rs.length ? rs.reduce((n, r) => n + r.live.usage[field], 0) : null, measured: rs.length }; };
|
|
25
|
+
const stageReasons = {};
|
|
26
|
+
for (const row of rows) for (const stage of row.stages || []) {
|
|
27
|
+
const id = `${stage.name}:${stage.reason}`;
|
|
28
|
+
stageReasons[id] = (stageReasons[id] || 0) + 1;
|
|
29
|
+
}
|
|
30
|
+
return {
|
|
31
|
+
preset: rows[0].preset, model: rows[0].model, format: rows[0].format, transport: rows[0].transport,
|
|
32
|
+
attempts: rows.length, successful: successful.length, errors: rows.length - successful.length,
|
|
33
|
+
changed: successful.filter(r => r.changed).length,
|
|
34
|
+
stageReasons,
|
|
35
|
+
tokens: { before: known.length ? before : null, after: known.length ? after : null,
|
|
36
|
+
saved: known.length ? before - after : null, savedPercent: known.length ? percent(before - after, before) : null,
|
|
37
|
+
measured: known.length, coveragePercent: percent(known.length, rows.length), partial: known.length !== rows.length },
|
|
38
|
+
toolText: { before: tools.length ? toolsBefore : null, after: tools.length ? toolsAfter : null, savedPercent: percent(toolsBefore - toolsAfter, toolsBefore), measured: tools.length,
|
|
39
|
+
note: "Text-only diagnostic: text moved into images is NOT a tool-context saving." },
|
|
40
|
+
latency: { medianMs: percentile(successful.map(r => r.durationMs), 50), p95Ms: percentile(successful.map(r => r.durationMs), 95),
|
|
41
|
+
failureP95Ms: percentile(rows.filter(r => r.status !== "ok").map(r => r.durationMs), 95),
|
|
42
|
+
firstRequestMs: rows.find(r => r.firstRequest)?.durationMs ?? null,
|
|
43
|
+
connectionMedianMs: percentile(successful.map(r => r.connectionMs), 50) },
|
|
44
|
+
preservation: quality(rows, "preservation"), answerQuality: quality(rows, "answerQuality"),
|
|
45
|
+
provider: { input: usage("inputTokens"), output: usage("outputTokens"), total: usage("totalTokens"),
|
|
46
|
+
cachedInput: usage("cachedInputTokens"), cacheWriteInput: usage("cacheWriteInputTokens"), reasoning: usage("reasoningTokens"),
|
|
47
|
+
measured: usageRows.length, complete: successful.filter(r => r.live?.complete).length,
|
|
48
|
+
additionalToolCalls: successful.reduce((n, r) => n + (r.live?.additionalToolCalls || 0), 0),
|
|
49
|
+
medianMs: percentile(successful.map(r => r.live?.durationMs), 50) },
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export function buildReport(run, { maxQualityDrop = 0, maxLatencyRegression = 25 } = {}) {
|
|
54
|
+
if (![maxQualityDrop, maxLatencyRegression].every(x => finite(x) && x >= 0)) throw new Error("Decision thresholds must be nonnegative numbers");
|
|
55
|
+
const measured = run.records.filter(r => r.phase === "measured");
|
|
56
|
+
const groups = new Map();
|
|
57
|
+
for (const row of measured) { const k = `${key(row)}:${row.preset}`; if (!groups.has(k)) groups.set(k, []); groups.get(k).push(row); }
|
|
58
|
+
const summaries = [...groups.values()].map(summarize);
|
|
59
|
+
const sampleKeys = rows => rows.map(r => JSON.stringify([r.caseId, r.round])).sort().join("\n");
|
|
60
|
+
const strata = new Map();
|
|
61
|
+
for (const s of summaries) { const k = key(s); if (!strata.has(k)) strata.set(k, []); strata.get(k).push(s); }
|
|
62
|
+
const decisions = [...strata.values()].map(group => {
|
|
63
|
+
const baseline = group.find(s => s.preset === "none");
|
|
64
|
+
const live = run.meta.mode === "live";
|
|
65
|
+
const candidates = group.map(s => {
|
|
66
|
+
const reasons = [];
|
|
67
|
+
if (!run.meta.completed) reasons.push("run_incomplete");
|
|
68
|
+
if (!baseline || baseline.errors || baseline.attempts !== s.attempts) reasons.push("baseline_missing_failed_or_incomplete");
|
|
69
|
+
const baselineRows = groups.get(`${key(s)}:none`) || [];
|
|
70
|
+
const candidateRows = groups.get(`${key(s)}:${s.preset}`) || [];
|
|
71
|
+
if (sampleKeys(baselineRows) !== sampleKeys(candidateRows)) reasons.push("baseline_samples_do_not_match");
|
|
72
|
+
if (s.errors) reasons.push("request_errors");
|
|
73
|
+
const tokens = live ? s.provider.input.total : s.tokens.after;
|
|
74
|
+
const baselineTokens = live ? baseline?.provider.input.total : baseline?.tokens.after;
|
|
75
|
+
if (live ? s.provider.measured !== s.attempts || baseline?.provider.measured !== baseline?.attempts : s.tokens.partial || baseline?.tokens.partial) reasons.push("token_coverage_incomplete");
|
|
76
|
+
if (!live) reasons.push("live_quality_not_measured");
|
|
77
|
+
if (live && (s.provider.complete !== s.attempts || baseline?.provider.complete !== baseline?.attempts)) reasons.push("answer_incomplete_or_tool_requested");
|
|
78
|
+
if (live && (s.answerQuality.unscored || s.answerQuality.indeterminate || baseline?.answerQuality.unscored || baseline?.answerQuality.indeterminate)) reasons.push("answer_quality_unscored");
|
|
79
|
+
const qualityDrop = live && baseline ? baseline.answerQuality.passRate - s.answerQuality.passRate : null;
|
|
80
|
+
if (finite(qualityDrop) && qualityDrop > maxQualityDrop) reasons.push("quality_regression");
|
|
81
|
+
// A completely failing baseline is not evidence for a useful compression flow.
|
|
82
|
+
if (live && !baseline?.answerQuality.pass) reasons.push("baseline_has_no_passing_answers");
|
|
83
|
+
const latencyRegression = baseline?.latency.p95Ms > 0 && finite(s.latency.p95Ms) ? 100 * (s.latency.p95Ms / baseline.latency.p95Ms - 1) : null;
|
|
84
|
+
if (!finite(latencyRegression)) reasons.push("latency_unmeasured");
|
|
85
|
+
else if (latencyRegression > maxLatencyRegression) reasons.push("latency_regression");
|
|
86
|
+
const comparableTokens = !reasons.some(reason => ["baseline_missing_failed_or_incomplete", "baseline_samples_do_not_match", "token_coverage_incomplete", "request_errors"].includes(reason));
|
|
87
|
+
return { preset: s.preset, eligible: reasons.length === 0, reasons,
|
|
88
|
+
inputSavedPercent: comparableTokens && finite(tokens) && finite(baselineTokens) ? percent(baselineTokens - tokens, baselineTokens) : null,
|
|
89
|
+
p95Ms: s.latency.p95Ms, latencyRegressionPercent: latencyRegression,
|
|
90
|
+
qualityPassRate: live ? s.answerQuality.passRate : null, qualityDropPercentagePoints: qualityDrop };
|
|
91
|
+
});
|
|
92
|
+
const eligible = candidates.filter(c => c.eligible);
|
|
93
|
+
const frontier = eligible.filter(c => !eligible.some(other => other !== c && other.inputSavedPercent >= c.inputSavedPercent && other.p95Ms <= c.p95Ms && other.qualityPassRate >= c.qualityPassRate &&
|
|
94
|
+
(other.inputSavedPercent > c.inputSavedPercent || other.p95Ms < c.p95Ms || other.qualityPassRate > c.qualityPassRate))).map(c => c.preset);
|
|
95
|
+
return { model: group[0].model, format: group[0].format, transport: group[0].transport,
|
|
96
|
+
status: live ? (frontier.length ? "measured_tradeoffs" : "insufficient_or_regressed") : "offline_only_no_quality_winner",
|
|
97
|
+
paretoFrontier: frontier, candidates };
|
|
98
|
+
});
|
|
99
|
+
const categories = new Map();
|
|
100
|
+
for (const row of measured) { const k = `${key(row)}:${row.preset}:${row.category}`; if (!categories.has(k)) categories.set(k, []); categories.get(k).push(row); }
|
|
101
|
+
return { ...run, thresholds: { maxQualityDropPercentagePoints: maxQualityDrop, maxLatencyRegressionPercent: maxLatencyRegression }, summaries,
|
|
102
|
+
categories: [...categories.values()].map(rows => ({ category: rows[0].category, ...summarize(rows) })), decisions,
|
|
103
|
+
warmupRecords: run.records.filter(r => r.phase === "warmup").length };
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
const cell = x => {
|
|
107
|
+
const value = x === null || x === undefined ? "" : typeof x === "object" ? JSON.stringify(x) : String(x);
|
|
108
|
+
// Also neutralize spreadsheet formula injection from imported fixture IDs/models.
|
|
109
|
+
return '"' + (typeof x === "string" && /^[=+\-@\t\r]/.test(value) ? "'" : "") + value.replaceAll('"', '""') + '"';
|
|
110
|
+
};
|
|
111
|
+
export function reportCsv(report) {
|
|
112
|
+
const columns = ["caseId", "category", "model", "format", "transport", "preset", "round", "phase", "firstRequest", "status", "before", "after", "saved", "durationMs", "connectionMs", "preservation", "answerQuality", "inputTokens", "outputTokens", "cachedInputTokens", "cacheWriteInputTokens", "complete", "error"];
|
|
113
|
+
const lines = report.records.map(r => {
|
|
114
|
+
const before = r.before?.totalTokens, after = r.after?.totalTokens;
|
|
115
|
+
const values = { ...r, before, after, saved: finite(before) && finite(after) ? before - after : null,
|
|
116
|
+
preservation: r.preservation?.status, answerQuality: r.answerQuality?.status, ...r.live?.usage, complete: r.live?.complete };
|
|
117
|
+
return columns.map(c => cell(values[c])).join(",");
|
|
118
|
+
});
|
|
119
|
+
return [columns.join(","), ...lines].join("\n") + "\n";
|
|
120
|
+
}
|
|
121
|
+
const fmt = (x, suffix = "") => finite(x) ? x.toFixed(1) + suffix : "?";
|
|
122
|
+
const md = x => String(x).replace(/[\r\n|]/g, " ");
|
|
123
|
+
export function reportMarkdown(report) {
|
|
124
|
+
const lines = ["# Proxy benchmark", "", `Mode: **${report.meta.mode}** · corpus: \`${report.meta.corpusHash}\``,
|
|
125
|
+
`Completed: ${report.meta.completed} · warmup records excluded: ${report.warmupRecords}`, "",
|
|
126
|
+
"Token estimates are not billing. Unknown multimedia costs are **unknown**, not zero. Offline preservation is not semantic quality.", "",
|
|
127
|
+
"| Model / format / transport | Flow | OK / attempts | Token saving (local estimate) | Coverage | Median / p95 ms | Preservation pass | Answer pass |",
|
|
128
|
+
"|---|---|---:|---:|---:|---:|---:|---:|"];
|
|
129
|
+
for (const s of report.summaries) lines.push(`| ${md(s.model)} / ${s.format} / ${s.transport} | ${s.preset} | ${s.successful}/${s.attempts} | ${fmt(s.tokens.savedPercent, "%")}${s.tokens.partial ? " partial" : ""} | ${fmt(s.tokens.coveragePercent, "%")} | ${fmt(s.latency.medianMs)} / ${fmt(s.latency.p95Ms)} | ${s.preservation.pass}/${s.attempts} (${s.preservation.indeterminate} unknown) | ${report.meta.mode === "live" ? `${s.answerQuality.pass}/${s.attempts}` : "not measured"} |`);
|
|
130
|
+
if (report.meta.mode === "live") {
|
|
131
|
+
lines.push("", "## Provider-reported usage (measured requests only)", "", "| Model / format / transport | Flow | Input | Output | Cache read | Cache write | Complete answers |", "|---|---|---:|---:|---:|---:|---:|");
|
|
132
|
+
for (const s of report.summaries) lines.push(`| ${md(s.model)} / ${s.format} / ${s.transport} | ${s.preset} | ${s.provider.input.total ?? "?"} | ${s.provider.output.total ?? "?"} | ${s.provider.cachedInput.total ?? "?"} | ${s.provider.cacheWriteInput.total ?? "?"} | ${s.provider.complete}/${s.attempts} |`);
|
|
133
|
+
}
|
|
134
|
+
lines.push("", "## Decision support", "", "Pareto candidates trade input-token savings against p95 latency and answer pass rate; this is not a cost or statistical-significance claim.");
|
|
135
|
+
for (const d of report.decisions) {
|
|
136
|
+
lines.push("", `### ${md(d.model)} / ${d.format} / ${d.transport}`, `Status: ${d.status}. Pareto frontier: ${d.paretoFrontier.join(", ") || "none"}.`);
|
|
137
|
+
for (const c of d.candidates) lines.push(`- ${c.preset}: input saving ${fmt(c.inputSavedPercent, "%")}, p95 change ${fmt(c.latencyRegressionPercent, "%")}; ${c.eligible ? "eligible" : c.reasons.join(", ")}.`);
|
|
138
|
+
}
|
|
139
|
+
lines.push("", "## Measurement notes", ...report.meta.notes.map(n => `- ${n}`), "");
|
|
140
|
+
return lines.join("\n");
|
|
141
|
+
}
|