vectorbench 0.0.0-stage → 3.0.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/.env.example +10 -0
- package/LICENSE +201 -0
- package/NOTICE +49 -0
- package/README.md +164 -2
- package/bench.config.mjs +255 -0
- package/bin/vectorbench.mjs +68 -0
- package/harness/Dockerfile +104 -0
- package/harness/adapters/chat.mjs +192 -0
- package/harness/adapters/index.mjs +77 -0
- package/harness/adapters/interactions.mjs +212 -0
- package/harness/adapters/messages.mjs +190 -0
- package/harness/adapters/responses.mjs +179 -0
- package/harness/box/README.md +46 -0
- package/harness/box/check.mjs +18 -0
- package/harness/box/tools.py +638 -0
- package/harness/box/vb3d.py +556 -0
- package/harness/claude-code.mjs +629 -0
- package/harness/codex-account.mjs +122 -0
- package/harness/codex.mjs +933 -0
- package/harness/grok-build.mjs +233 -0
- package/harness/loop.mjs +114 -0
- package/harness/prices.mjs +30 -0
- package/harness/request.mjs +155 -0
- package/harness/sandbox.mjs +77 -0
- package/package.json +76 -4
- package/scripts/doctor.mjs +113 -0
- package/scripts/harness.mjs +547 -0
- package/scripts/partner.mjs +140 -0
- package/scripts/zip.mjs +77 -0
- package/src/model-apis.js +516 -0
- package/worker/svg.js +350 -0
|
@@ -0,0 +1,516 @@
|
|
|
1
|
+
// How to ask a model for a drawing over each kind of API, and how to read
|
|
2
|
+
// the answer. One user message at a given reasoning effort and nothing else
|
|
3
|
+
// (no system prompt, no temperature, no tools), answered in one shape:
|
|
4
|
+
//
|
|
5
|
+
// { text, ended: 'complete' | 'refused' | 'truncated', id, servedModel, usage }
|
|
6
|
+
//
|
|
7
|
+
// Used by `npm run generate` (scripts/providers.mjs, with our keys) and by
|
|
8
|
+
// the tool-using harness (harness/adapters/). Nothing here knows where the
|
|
9
|
+
// key came from.
|
|
10
|
+
//
|
|
11
|
+
// A thrown ProviderError means the request itself failed (network, rate
|
|
12
|
+
// limit, bad key): no answer was given, so it can be asked again.
|
|
13
|
+
|
|
14
|
+
export class ProviderError extends Error {
|
|
15
|
+
/**
|
|
16
|
+
* `fatal`: nothing sent to this provider will work until something is fixed (key, credit).
|
|
17
|
+
* `cancelled`: the person asking gave up; nothing went wrong.
|
|
18
|
+
*/
|
|
19
|
+
constructor(message, { fatal = false, cancelled = false } = {}) {
|
|
20
|
+
super(message);
|
|
21
|
+
this.fatal = fatal;
|
|
22
|
+
this.cancelled = cancelled;
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export const RETRIES = 4;
|
|
27
|
+
|
|
28
|
+
// At maximum effort one drawing can take half an hour, longer than any HTTP
|
|
29
|
+
// request should stay open. Background requests are asked how they're
|
|
30
|
+
// getting on every `timing.pollMs`.
|
|
31
|
+
export const timing = { pollMs: 10_000, giveUpMs: 90 * 60 * 1000, requestMs: 5 * 60 * 1000 };
|
|
32
|
+
|
|
33
|
+
const cancelled = () => new ProviderError('Cancelled.', { cancelled: true });
|
|
34
|
+
|
|
35
|
+
function sleep(ms, signal) {
|
|
36
|
+
return new Promise((resolve, reject) => {
|
|
37
|
+
if (signal?.aborted) return reject(cancelled());
|
|
38
|
+
const stop = () => {
|
|
39
|
+
clearTimeout(timer);
|
|
40
|
+
reject(cancelled());
|
|
41
|
+
};
|
|
42
|
+
const timer = setTimeout(() => {
|
|
43
|
+
signal?.removeEventListener('abort', stop);
|
|
44
|
+
resolve();
|
|
45
|
+
}, ms);
|
|
46
|
+
signal?.addEventListener('abort', stop, { once: true });
|
|
47
|
+
});
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** Polls `get()` until `running(data)` is false; returns the last answer. */
|
|
51
|
+
async function waitFor(get, running, what, { signal, onStatus } = {}) {
|
|
52
|
+
const started = Date.now();
|
|
53
|
+
for (;;) {
|
|
54
|
+
const data = await get();
|
|
55
|
+
if (!running(data)) return data;
|
|
56
|
+
onStatus?.(String(data.status ?? 'in_progress'));
|
|
57
|
+
if (Date.now() - started > timing.giveUpMs) throw new ProviderError(`${what} was still running after ${timing.giveUpMs / 60000} minutes`);
|
|
58
|
+
await sleep(timing.pollMs, signal);
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* Sends JSON, waiting out rate limits and server errors, and returns the
|
|
64
|
+
* successful Response. `declined(status, body)` lets a caller say that an
|
|
65
|
+
* error response is the model's answer (a safety block) rather than a failed
|
|
66
|
+
* request; that comes back as `{ declined }`.
|
|
67
|
+
*
|
|
68
|
+
* `timeoutMs: 0` is for streamed answers, which stay open as long as the
|
|
69
|
+
* model is writing.
|
|
70
|
+
*/
|
|
71
|
+
async function request(method, url, headers, body, { declined = () => false, signal, retries = RETRIES, timeoutMs = timing.requestMs } = {}) {
|
|
72
|
+
for (let attempt = 0; ; attempt++) {
|
|
73
|
+
let response;
|
|
74
|
+
try {
|
|
75
|
+
const limits = [signal, timeoutMs ? AbortSignal.timeout(timeoutMs) : null].filter(Boolean);
|
|
76
|
+
response = await fetch(url, {
|
|
77
|
+
method,
|
|
78
|
+
headers: { 'Content-Type': 'application/json', ...headers },
|
|
79
|
+
body: body === undefined ? undefined : JSON.stringify(body),
|
|
80
|
+
signal: limits.length > 1 ? AbortSignal.any(limits) : limits[0],
|
|
81
|
+
});
|
|
82
|
+
} catch (error) {
|
|
83
|
+
if (signal?.aborted) throw cancelled();
|
|
84
|
+
if (attempt < retries) {
|
|
85
|
+
await sleep(2000 * 2 ** attempt, signal);
|
|
86
|
+
continue;
|
|
87
|
+
}
|
|
88
|
+
throw new ProviderError(`couldn't reach ${new URL(url).host} (${error.cause?.code ?? error.name})`);
|
|
89
|
+
}
|
|
90
|
+
if (response.ok) return { response };
|
|
91
|
+
|
|
92
|
+
const raw = await response.text();
|
|
93
|
+
let parsed = null;
|
|
94
|
+
try {
|
|
95
|
+
parsed = JSON.parse(raw);
|
|
96
|
+
} catch {}
|
|
97
|
+
// Providers disagree on the envelope: {error: {...}}, [{error: {...}}],
|
|
98
|
+
// or {code, error: "message"}.
|
|
99
|
+
const envelope = Array.isArray(parsed) ? parsed[0] : parsed;
|
|
100
|
+
const problem = typeof envelope?.error === 'object' ? envelope.error : envelope;
|
|
101
|
+
if (declined(response.status, problem)) return { declined: problem };
|
|
102
|
+
|
|
103
|
+
const detail = raw.slice(0, 300).replace(/\s+/g, ' ');
|
|
104
|
+
// Out of credit or over a hard quota is a 429 that waiting won't fix.
|
|
105
|
+
const code = String(problem?.code);
|
|
106
|
+
const exhausted = code !== 'rate_limit_exceeded' && /credit_balance_exhausted|insufficient_quota|quota_exceeded|_limit_exceeded$/.test(code);
|
|
107
|
+
// Some providers answer a bad key with a 400 rather than a 401.
|
|
108
|
+
const badKey = response.status < 500 && /api key|authentication/i.test(detail);
|
|
109
|
+
const retryable = !exhausted && !badKey && (response.status === 408 || response.status === 429 || response.status >= 500);
|
|
110
|
+
if (retryable && attempt < retries) {
|
|
111
|
+
const wait = Number(response.headers.get('retry-after')) * 1000 || 2000 * 2 ** attempt;
|
|
112
|
+
await sleep(Math.min(wait, 60_000), signal);
|
|
113
|
+
continue;
|
|
114
|
+
}
|
|
115
|
+
const fatal = exhausted || badKey || [401, 402, 403].includes(response.status);
|
|
116
|
+
throw new ProviderError(`${new URL(url).host} answered ${response.status}: ${detail}`, { fatal });
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
async function sendJson(method, url, headers, body, options) {
|
|
121
|
+
const result = await request(method, url, headers, body, options);
|
|
122
|
+
return result.declined ? { declined: result.declined } : result.response.json();
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/** The JSON objects of a server-sent event stream, in order. */
|
|
126
|
+
async function* events(response) {
|
|
127
|
+
const reader = response.body.getReader();
|
|
128
|
+
const decoder = new TextDecoder();
|
|
129
|
+
let buffer = '';
|
|
130
|
+
for (;;) {
|
|
131
|
+
const { done, value } = await reader.read();
|
|
132
|
+
buffer += decoder.decode(value ?? new Uint8Array(), { stream: !done });
|
|
133
|
+
const blocks = buffer.split(/\r?\n\r?\n/);
|
|
134
|
+
buffer = done ? '' : blocks.pop();
|
|
135
|
+
for (const block of blocks) {
|
|
136
|
+
const data = block
|
|
137
|
+
.split(/\r?\n/)
|
|
138
|
+
.filter((line) => line.startsWith('data:'))
|
|
139
|
+
.map((line) => line.slice(5).trimStart())
|
|
140
|
+
.join('\n');
|
|
141
|
+
if (!data || data === '[DONE]') continue;
|
|
142
|
+
try {
|
|
143
|
+
yield JSON.parse(data);
|
|
144
|
+
} catch {}
|
|
145
|
+
}
|
|
146
|
+
if (done) return;
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/** Reads a stream to its end, turning a dropped connection into a ProviderError. */
|
|
151
|
+
async function eachEvent(response, url, signal, handle) {
|
|
152
|
+
try {
|
|
153
|
+
for await (const event of events(response)) handle(event);
|
|
154
|
+
} catch (error) {
|
|
155
|
+
if (error instanceof ProviderError) throw error;
|
|
156
|
+
if (signal?.aborted) throw cancelled();
|
|
157
|
+
throw new ProviderError(`the connection to ${new URL(url).host} dropped before the answer finished (${error.name})`);
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
const isObject = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
162
|
+
|
|
163
|
+
/** `extra` laid over `body`; objects are merged, anything else replaces. */
|
|
164
|
+
function merge(body, extra) {
|
|
165
|
+
if (!isObject(extra)) return body;
|
|
166
|
+
const out = { ...body };
|
|
167
|
+
for (const [key, value] of Object.entries(extra)) {
|
|
168
|
+
out[key] = isObject(value) && isObject(out[key]) ? merge(out[key], value) : value;
|
|
169
|
+
}
|
|
170
|
+
return out;
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/** Where a background request is asked about: `{id}` in the template, or the id appended. */
|
|
174
|
+
function statusAt(template, id) {
|
|
175
|
+
return template.includes('{id}') ? template.replace('{id}', encodeURIComponent(id)) : `${template.replace(/\/+$/, '')}/${id}`;
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/**
|
|
179
|
+
* Waits for a background request, then deletes the provider's stored copy.
|
|
180
|
+
* If the person asking gives up, the provider is told to stop too.
|
|
181
|
+
*/
|
|
182
|
+
async function background(first, { at, headers, running, what, signal, onStatus, retries, declined }) {
|
|
183
|
+
let data = first;
|
|
184
|
+
try {
|
|
185
|
+
if (running(data)) data = await waitFor(() => sendJson('GET', at, headers, undefined, { signal, retries, declined }), running, what, { signal, onStatus });
|
|
186
|
+
} catch (error) {
|
|
187
|
+
if (error.cancelled) sendJson('POST', `${at}/cancel`, headers, undefined, { retries: 0 }).catch(() => {});
|
|
188
|
+
throw error;
|
|
189
|
+
}
|
|
190
|
+
await sendJson('DELETE', at, headers, undefined, { retries, declined }).catch(() => {});
|
|
191
|
+
return data;
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
// The plumbing above, for the tool-using harness (harness/adapters/), whose
|
|
195
|
+
// requests have more than one turn but fail, stream and wait the same way.
|
|
196
|
+
export { request, sendJson, eachEvent, background, merge, statusAt };
|
|
197
|
+
|
|
198
|
+
/* Request bodies ------------------------------------------------------------ */
|
|
199
|
+
|
|
200
|
+
// Kept apart from the calls so the exact request can be shown before it is
|
|
201
|
+
// sent. A missing effort or token limit is left out, and the API's own
|
|
202
|
+
// default applies.
|
|
203
|
+
const bodies = {
|
|
204
|
+
responses: ({ model, text, maxOutputTokens, effort, asMessages = false, background: inBackground = false, stream = false, extraBody }) =>
|
|
205
|
+
merge(
|
|
206
|
+
{
|
|
207
|
+
model,
|
|
208
|
+
input: asMessages ? [{ role: 'user', content: text }] : text,
|
|
209
|
+
...(maxOutputTokens && { max_output_tokens: maxOutputTokens }),
|
|
210
|
+
...(effort && { reasoning: { effort } }),
|
|
211
|
+
// A background response has to be stored while it runs; it's
|
|
212
|
+
// deleted once we have it.
|
|
213
|
+
...(inBackground ? { background: true, store: true } : { store: false }),
|
|
214
|
+
// Streamed where the API has no background mode, so a long think
|
|
215
|
+
// can't outlast the connection.
|
|
216
|
+
...(stream && !inBackground && { stream: true }),
|
|
217
|
+
},
|
|
218
|
+
extraBody,
|
|
219
|
+
),
|
|
220
|
+
|
|
221
|
+
interactions: ({ model, text, maxOutputTokens, effort, extraBody }) =>
|
|
222
|
+
merge(
|
|
223
|
+
{
|
|
224
|
+
model,
|
|
225
|
+
input: text,
|
|
226
|
+
// Run in the background (which needs the interaction stored while it
|
|
227
|
+
// runs; it's deleted once we have it).
|
|
228
|
+
background: true,
|
|
229
|
+
generation_config: { ...(maxOutputTokens && { max_output_tokens: maxOutputTokens }), ...(effort && { thinking_level: effort }) },
|
|
230
|
+
},
|
|
231
|
+
extraBody,
|
|
232
|
+
),
|
|
233
|
+
|
|
234
|
+
// OpenRouter takes `reasoning: { effort }`; OpenAI's own chat API and most
|
|
235
|
+
// servers that copy it take `reasoning_effort`.
|
|
236
|
+
chat: ({ model, text, maxOutputTokens, effort, effortField = 'reasoning', stream = false, extraBody }) =>
|
|
237
|
+
merge(
|
|
238
|
+
{
|
|
239
|
+
model,
|
|
240
|
+
messages: [{ role: 'user', content: text }],
|
|
241
|
+
...(maxOutputTokens && { max_tokens: maxOutputTokens }),
|
|
242
|
+
...(effort && (effortField === 'reasoning' ? { reasoning: { effort } } : { reasoning_effort: effort })),
|
|
243
|
+
...(stream && { stream: true }),
|
|
244
|
+
},
|
|
245
|
+
extraBody,
|
|
246
|
+
),
|
|
247
|
+
|
|
248
|
+
messages: ({ model, text, maxOutputTokens, effort, extraBody }) =>
|
|
249
|
+
merge(
|
|
250
|
+
{
|
|
251
|
+
model,
|
|
252
|
+
...(maxOutputTokens && { max_tokens: maxOutputTokens }),
|
|
253
|
+
...(effort && { output_config: { effort } }),
|
|
254
|
+
messages: [{ role: 'user', content: text }],
|
|
255
|
+
// Streamed so a long answer can't hit an HTTP timeout.
|
|
256
|
+
stream: true,
|
|
257
|
+
},
|
|
258
|
+
extraBody,
|
|
259
|
+
),
|
|
260
|
+
};
|
|
261
|
+
|
|
262
|
+
/** The body `styles[style]` would send for these options. */
|
|
263
|
+
export const requestBody = (style, options) => bodies[style](options);
|
|
264
|
+
|
|
265
|
+
/* Responses API (OpenAI, xAI) ----------------------------------------------- */
|
|
266
|
+
|
|
267
|
+
const FINISHED = new Set(['completed', 'incomplete', 'failed', 'cancelled']);
|
|
268
|
+
|
|
269
|
+
/** A streamed Responses answer: the finished response from its last event. */
|
|
270
|
+
async function streamedResponse(options) {
|
|
271
|
+
const { url, headers, signal, retries } = options;
|
|
272
|
+
const { response } = await request('POST', url, headers, bodies.responses(options), { signal, retries, timeoutMs: 0 });
|
|
273
|
+
// A server that ignores `stream` answers with one JSON body after all.
|
|
274
|
+
if (!(response.headers.get('content-type') ?? '').includes('event-stream')) return response.json();
|
|
275
|
+
let data = null;
|
|
276
|
+
await eachEvent(response, url, signal, (event) => {
|
|
277
|
+
if (event.type === 'error') throw new ProviderError(`${new URL(url).host} sent an error mid-answer: ${String(event.message ?? event.error?.message ?? '').slice(0, 200)}`);
|
|
278
|
+
if (event.response && FINISHED.has(event.response.status)) data = event.response;
|
|
279
|
+
});
|
|
280
|
+
if (!data) throw new ProviderError(`${new URL(url).host} closed the stream without an answer`);
|
|
281
|
+
return data;
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
async function responses(options) {
|
|
285
|
+
const { url, headers, model, statusUrl, signal, onStatus, retries } = options;
|
|
286
|
+
const streamed = options.stream && !options.background;
|
|
287
|
+
let data = streamed ? await streamedResponse(options) : await sendJson('POST', url, headers, bodies.responses(options), { signal, retries });
|
|
288
|
+
if (streamed && (data.status === 'failed' || data.status === 'cancelled')) {
|
|
289
|
+
throw new ProviderError(`${new URL(url).host} ${data.status} the response: ${JSON.stringify(data.error ?? {}).slice(0, 200)}`);
|
|
290
|
+
}
|
|
291
|
+
if (options.background && data.id) {
|
|
292
|
+
data = await background(data, {
|
|
293
|
+
at: statusAt(statusUrl || url, data.id),
|
|
294
|
+
headers,
|
|
295
|
+
running: (d) => d.status === 'queued' || d.status === 'in_progress',
|
|
296
|
+
what: `${model} response ${data.id}`,
|
|
297
|
+
signal,
|
|
298
|
+
onStatus,
|
|
299
|
+
retries,
|
|
300
|
+
});
|
|
301
|
+
if (data.status === 'failed' || data.status === 'cancelled') {
|
|
302
|
+
throw new ProviderError(`${new URL(url).host} ${data.status} the response: ${JSON.stringify(data.error ?? {}).slice(0, 200)}`);
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
// The answer is the text parts of the message items; reasoning items are skipped.
|
|
306
|
+
const parts = (data.output ?? []).filter((item) => item.type === 'message').flatMap((item) => item.content ?? []);
|
|
307
|
+
const refused = parts.some((part) => part.type === 'refusal') || data.incomplete_details?.reason === 'content_filter';
|
|
308
|
+
return {
|
|
309
|
+
text: parts.filter((part) => part.type === 'output_text').map((part) => part.text).join(''),
|
|
310
|
+
ended: refused ? 'refused' : data.status === 'completed' ? 'complete' : 'truncated',
|
|
311
|
+
id: data.id ?? null,
|
|
312
|
+
servedModel: data.model ?? model,
|
|
313
|
+
usage: { input: data.usage?.input_tokens ?? null, output: data.usage?.output_tokens ?? null },
|
|
314
|
+
};
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
/* Google Gemini (Interactions API) ----------------------------------------- */
|
|
318
|
+
|
|
319
|
+
const SAFETY_CODES = new Set(['safety', 'jailbreak', 'prohibited_content', 'blocklist']);
|
|
320
|
+
|
|
321
|
+
async function interactions(options) {
|
|
322
|
+
const { url, headers, model, statusUrl, signal, onStatus, retries } = options;
|
|
323
|
+
// Gemini reports a safety block as a 400, not as an empty answer.
|
|
324
|
+
const declined = (status, problem) => status === 400 && [problem?.code, problem?.status].some((value) => SAFETY_CODES.has(String(value).toLowerCase()));
|
|
325
|
+
let data = await sendJson('POST', url, headers, bodies.interactions(options), { declined, signal, retries });
|
|
326
|
+
if (!data.declined && data.id) {
|
|
327
|
+
data = await background(data, {
|
|
328
|
+
at: statusAt(statusUrl || url, data.id),
|
|
329
|
+
headers,
|
|
330
|
+
running: (d) => !d.declined && d.status === 'in_progress',
|
|
331
|
+
what: `${model} interaction ${data.id}`,
|
|
332
|
+
signal,
|
|
333
|
+
onStatus,
|
|
334
|
+
retries,
|
|
335
|
+
declined,
|
|
336
|
+
});
|
|
337
|
+
}
|
|
338
|
+
if (data.declined) {
|
|
339
|
+
return { text: '', ended: 'refused', id: null, servedModel: model, usage: { input: null, output: null } };
|
|
340
|
+
}
|
|
341
|
+
// Model output steps hold the answer; thought steps are skipped.
|
|
342
|
+
const answer = (data.steps ?? [])
|
|
343
|
+
.filter((step) => step.type === 'model_output')
|
|
344
|
+
.flatMap((step) => step.content ?? [])
|
|
345
|
+
.filter((part) => part.type === 'text')
|
|
346
|
+
.map((part) => part.text)
|
|
347
|
+
.join('');
|
|
348
|
+
if (data.status !== 'completed' && data.status !== 'incomplete') {
|
|
349
|
+
throw new ProviderError(`Gemini ended with status "${data.status}"`);
|
|
350
|
+
}
|
|
351
|
+
return {
|
|
352
|
+
text: answer,
|
|
353
|
+
ended: data.status === 'completed' ? 'complete' : 'truncated',
|
|
354
|
+
id: data.id ?? null,
|
|
355
|
+
servedModel: data.model ?? model,
|
|
356
|
+
usage: { input: data.usage?.total_input_tokens ?? null, output: data.usage?.total_output_tokens ?? null },
|
|
357
|
+
};
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
/* Chat completions (OpenRouter, and anything that copies OpenAI's chat API) -- */
|
|
361
|
+
|
|
362
|
+
const chatText = (content) => (Array.isArray(content) ? content.map((part) => part.text ?? '').join('') : (content ?? ''));
|
|
363
|
+
const chatEnded = (reason) => (reason === 'stop' ? 'complete' : reason === 'content_filter' ? 'refused' : 'truncated');
|
|
364
|
+
|
|
365
|
+
async function chat(options) {
|
|
366
|
+
const { url, headers, model, stream = false, signal, onStatus, retries } = options;
|
|
367
|
+
const { response } = await request('POST', url, headers, bodies.chat(options), { signal, retries, timeoutMs: stream ? 0 : timing.requestMs });
|
|
368
|
+
const host = new URL(url).host;
|
|
369
|
+
|
|
370
|
+
// A server that ignores `stream` answers with one JSON body after all.
|
|
371
|
+
if (!stream || !(response.headers.get('content-type') ?? '').includes('event-stream')) {
|
|
372
|
+
const data = await response.json();
|
|
373
|
+
const choice = data.choices?.[0];
|
|
374
|
+
const reason = choice?.finish_reason;
|
|
375
|
+
// OpenRouter can report a failure inside a 200.
|
|
376
|
+
if (!choice || data.error || reason === 'error') {
|
|
377
|
+
throw new ProviderError(`${host} gave no answer: ${JSON.stringify(data.error ?? choice?.error ?? data).slice(0, 200)}`);
|
|
378
|
+
}
|
|
379
|
+
return {
|
|
380
|
+
text: chatText(choice.message?.content),
|
|
381
|
+
ended: chatEnded(reason),
|
|
382
|
+
id: data.id ?? null,
|
|
383
|
+
servedModel: data.model ?? model,
|
|
384
|
+
usage: { input: data.usage?.prompt_tokens ?? null, output: data.usage?.completion_tokens ?? null },
|
|
385
|
+
};
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
const answer = { text: '', reason: null, id: null, servedModel: model, usage: { input: null, output: null } };
|
|
389
|
+
await eachEvent(response, url, signal, (chunk) => {
|
|
390
|
+
const choice = chunk.choices?.[0];
|
|
391
|
+
if (chunk.error || choice?.finish_reason === 'error') {
|
|
392
|
+
throw new ProviderError(`${host} gave no answer: ${JSON.stringify(chunk.error ?? choice?.error ?? chunk).slice(0, 200)}`);
|
|
393
|
+
}
|
|
394
|
+
answer.id ??= chunk.id ?? null;
|
|
395
|
+
if (chunk.model) answer.servedModel = chunk.model;
|
|
396
|
+
if (chunk.usage) answer.usage = { input: chunk.usage.prompt_tokens ?? null, output: chunk.usage.completion_tokens ?? null };
|
|
397
|
+
if (choice?.finish_reason) answer.reason = choice.finish_reason;
|
|
398
|
+
const piece = chatText(choice?.delta?.content);
|
|
399
|
+
if (piece) {
|
|
400
|
+
answer.text += piece;
|
|
401
|
+
onStatus?.('writing', answer.text.length);
|
|
402
|
+
} else if (choice?.delta && !choice.finish_reason) {
|
|
403
|
+
onStatus?.('thinking');
|
|
404
|
+
}
|
|
405
|
+
});
|
|
406
|
+
if (!answer.reason && !answer.text) throw new ProviderError(`${host} closed the stream without an answer`);
|
|
407
|
+
// No finish reason means the stream stopped mid-answer.
|
|
408
|
+
return { text: answer.text, ended: answer.reason ? chatEnded(answer.reason) : 'truncated', id: answer.id, servedModel: answer.servedModel, usage: answer.usage };
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
/* Messages API (Anthropic, over fetch) -------------------------------------- */
|
|
412
|
+
|
|
413
|
+
export const ANTHROPIC_VERSION = '2026-10-21';
|
|
414
|
+
|
|
415
|
+
async function messages(options) {
|
|
416
|
+
const { url, headers, model, signal, onStatus, retries } = options;
|
|
417
|
+
const { response } = await request('POST', url, headers, bodies.messages(options), { signal, retries, timeoutMs: 0 });
|
|
418
|
+
const host = new URL(url).host;
|
|
419
|
+
|
|
420
|
+
const answer = { text: '', reason: null, id: null, servedModel: model, usage: { input: null, output: null } };
|
|
421
|
+
await eachEvent(response, url, signal, (event) => {
|
|
422
|
+
if (event.type === 'error') {
|
|
423
|
+
throw new ProviderError(`${host} stopped the answer: ${event.error?.type ?? 'error'}: ${event.error?.message ?? ''}`.trim());
|
|
424
|
+
}
|
|
425
|
+
if (event.type === 'message_start') {
|
|
426
|
+
answer.id = event.message?.id ?? null;
|
|
427
|
+
answer.servedModel = event.message?.model ?? model;
|
|
428
|
+
answer.usage.input = event.message?.usage?.input_tokens ?? null;
|
|
429
|
+
} else if (event.type === 'content_block_delta') {
|
|
430
|
+
if (event.delta?.type === 'text_delta') {
|
|
431
|
+
answer.text += event.delta.text;
|
|
432
|
+
onStatus?.('writing', answer.text.length);
|
|
433
|
+
} else {
|
|
434
|
+
onStatus?.('thinking');
|
|
435
|
+
}
|
|
436
|
+
} else if (event.type === 'message_delta') {
|
|
437
|
+
if (event.delta?.stop_reason) answer.reason = event.delta.stop_reason;
|
|
438
|
+
if (event.usage?.output_tokens != null) answer.usage.output = event.usage.output_tokens;
|
|
439
|
+
}
|
|
440
|
+
});
|
|
441
|
+
if (!answer.reason && !answer.text) throw new ProviderError(`${host} closed the stream without an answer`);
|
|
442
|
+
return {
|
|
443
|
+
text: answer.text,
|
|
444
|
+
ended: answer.reason === 'end_turn' ? 'complete' : answer.reason === 'refusal' ? 'refused' : 'truncated',
|
|
445
|
+
id: answer.id,
|
|
446
|
+
servedModel: answer.servedModel,
|
|
447
|
+
usage: answer.usage,
|
|
448
|
+
};
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
/**
|
|
452
|
+
* One function per kind of API. Each takes
|
|
453
|
+
* { url, headers, model, text, maxOutputTokens, effort, extraBody, statusUrl, signal, onStatus, retries }
|
|
454
|
+
* plus the options of its style (`background`, `asMessages`, `stream`, `effortField`).
|
|
455
|
+
*/
|
|
456
|
+
export const styles = { responses, interactions, chat, messages };
|
|
457
|
+
|
|
458
|
+
/* Presets ------------------------------------------------------------------- */
|
|
459
|
+
|
|
460
|
+
// Each API we can ask, with its address and how it takes the key. `via` ties
|
|
461
|
+
// a preset to the adapter of the same name in scripts/providers.mjs, which
|
|
462
|
+
// asks a model from bench.config.mjs with it.
|
|
463
|
+
export const presets = [
|
|
464
|
+
{ id: 'anthropic', via: 'anthropic', label: 'Anthropic (Messages API)', style: 'messages', url: 'https://api.anthropic.com/v1/messages', auth: 'x-api-key' },
|
|
465
|
+
{ id: 'openai', via: 'openai', label: 'OpenAI (Responses API)', style: 'responses', url: 'https://api.openai.com/v1/responses', auth: 'bearer', background: true },
|
|
466
|
+
{ id: 'gemini', via: 'gemini', label: 'Google Gemini (Interactions API)', style: 'interactions', url: 'https://generativelanguage.googleapis.com/v1beta/interactions', auth: 'x-goog-api-key' },
|
|
467
|
+
// xAI has no background mode and closes a long plain request, so it streams.
|
|
468
|
+
{ id: 'xai', via: 'xai', label: 'xAI (Responses API)', style: 'responses', url: 'https://api.x.ai/v1/responses', auth: 'bearer', asMessages: true, stream: true },
|
|
469
|
+
{ id: 'openrouter', via: 'openrouter', label: 'OpenRouter (Chat Completions)', style: 'chat', url: 'https://openrouter.ai/api/v1/chat/completions', auth: 'bearer', stream: true },
|
|
470
|
+
// OpenRouter held to the model's maker. Kimi's weights are open and
|
|
471
|
+
// OpenRouter lists two dozen hosts for them, most at a lower precision;
|
|
472
|
+
// Qwen4 Max gained a second host (Novita) the day it launched.
|
|
473
|
+
// `provider.only` keeps the request on the maker's own endpoint, so the
|
|
474
|
+
// model that answers is the one its maker serves. A preset's `extraBody`
|
|
475
|
+
// is part of the request wherever the preset is used.
|
|
476
|
+
{
|
|
477
|
+
id: 'openrouter-moonshot',
|
|
478
|
+
via: 'openrouter-moonshot',
|
|
479
|
+
label: 'OpenRouter, served by Moonshot AI (Chat Completions)',
|
|
480
|
+
style: 'chat',
|
|
481
|
+
url: 'https://openrouter.ai/api/v1/chat/completions',
|
|
482
|
+
auth: 'bearer',
|
|
483
|
+
stream: true,
|
|
484
|
+
extraBody: { provider: { only: ['moonshotai/mxfp4'], allow_fallbacks: false } },
|
|
485
|
+
},
|
|
486
|
+
{
|
|
487
|
+
id: 'openrouter-alibaba',
|
|
488
|
+
via: 'openrouter-alibaba',
|
|
489
|
+
label: 'OpenRouter, served by Alibaba (Chat Completions)',
|
|
490
|
+
style: 'chat',
|
|
491
|
+
url: 'https://openrouter.ai/api/v1/chat/completions',
|
|
492
|
+
auth: 'bearer',
|
|
493
|
+
stream: true,
|
|
494
|
+
extraBody: { provider: { only: ['alibaba'], allow_fallbacks: false } },
|
|
495
|
+
},
|
|
496
|
+
{ id: 'custom-chat', label: 'Custom: OpenAI-compatible chat completions', style: 'chat', url: '', auth: 'bearer', stream: true, effortField: 'reasoning_effort' },
|
|
497
|
+
{ id: 'custom-responses', label: 'Custom: Responses-compatible', style: 'responses', url: '', auth: 'bearer' },
|
|
498
|
+
{ id: 'custom-messages', label: 'Custom: Anthropic-compatible', style: 'messages', url: '', auth: 'x-api-key' },
|
|
499
|
+
];
|
|
500
|
+
|
|
501
|
+
/**
|
|
502
|
+
* The headers that carry the key. `auth` is 'bearer', the name of a header
|
|
503
|
+
* that takes the bare key ('x-api-key', 'x-goog-api-key', or the caller's
|
|
504
|
+
* own), or 'none'.
|
|
505
|
+
*/
|
|
506
|
+
export function authHeaders(auth, apiKey, style) {
|
|
507
|
+
const headers = {};
|
|
508
|
+
if (auth === 'bearer') headers.Authorization = `Bearer ${apiKey}`;
|
|
509
|
+
else if (auth && auth !== 'none') headers[auth] = apiKey;
|
|
510
|
+
if (style === 'messages') {
|
|
511
|
+
headers['anthropic-version'] = ANTHROPIC_VERSION;
|
|
512
|
+
// Anthropic only answers a browser that says it means to call directly.
|
|
513
|
+
if (typeof window !== 'undefined') headers['anthropic-dangerous-direct-browser-access'] = 'true';
|
|
514
|
+
}
|
|
515
|
+
return headers;
|
|
516
|
+
}
|