@abhishek944/pi-classifier 0.4.0 → 0.5.1
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/CHANGELOG.md +33 -0
- package/README.md +269 -31
- package/dist/auth.d.ts +4 -2
- package/dist/auth.js +18 -2
- package/dist/box-tool.d.ts +2 -24
- package/dist/box-tool.js +5 -35
- package/dist/choices.js +35 -1
- package/dist/classify.d.ts +3 -0
- package/dist/classify.js +3 -3
- package/dist/config.d.ts +140 -3
- package/dist/config.js +401 -20
- package/dist/cost.js +42 -4
- package/dist/durable.d.ts +34 -0
- package/dist/durable.js +237 -0
- package/dist/extension.d.ts +2 -275
- package/dist/extension.js +49 -211
- package/dist/extract.d.ts +11 -0
- package/dist/extract.js +191 -0
- package/dist/http.d.ts +6 -1
- package/dist/http.js +64 -28
- package/dist/index.d.ts +3 -1
- package/dist/index.js +1 -0
- package/dist/inputs.d.ts +16 -1
- package/dist/inputs.js +421 -14
- package/dist/mcp-cli.d.ts +2 -0
- package/dist/mcp-cli.js +39 -0
- package/dist/mcp-server.d.ts +28 -0
- package/dist/mcp-server.js +121 -0
- package/dist/mcp-tool-definitions.d.ts +19 -0
- package/dist/mcp-tool-definitions.js +64 -0
- package/dist/providers.d.ts +1 -0
- package/dist/providers.js +1144 -53
- package/dist/tool-contracts.d.ts +785 -0
- package/dist/tool-contracts.js +530 -0
- package/dist/tree.js +1 -1
- package/dist/types.d.ts +284 -8
- package/dist/validation.js +122 -10
- package/package.json +34 -6
- package/src/auth.ts +26 -2
- package/src/box-tool.ts +12 -47
- package/src/choices.ts +42 -1
- package/src/classify.ts +6 -4
- package/src/config.ts +450 -23
- package/src/cost.ts +42 -4
- package/src/durable.ts +298 -0
- package/src/extension.ts +75 -288
- package/src/extract.ts +228 -0
- package/src/http.ts +63 -32
- package/src/index.ts +15 -0
- package/src/inputs.ts +454 -13
- package/src/mcp-cli.ts +44 -0
- package/src/mcp-server.ts +179 -0
- package/src/mcp-tool-definitions.ts +104 -0
- package/src/providers.ts +1323 -56
- package/src/tool-contracts.ts +785 -0
- package/src/tree.ts +1 -1
- package/src/types.ts +231 -5
- package/src/validation.ts +114 -9
package/dist/providers.js
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import { randomUUID } from "node:crypto";
|
|
2
|
-
import { imageContentParts, imageReferences, imageUrl, mapImageReferences, namedImage, questionImageReferences } from "./image-content.js";
|
|
2
|
+
import { imageContentParts, imageReferences, imageUrl, isImageReference, mapImageReferences, namedImage, questionImageReferences } from "./image-content.js";
|
|
3
3
|
import { postJson } from "./http.js";
|
|
4
4
|
import { estimateCost, tokenCount } from "./cost.js";
|
|
5
|
+
import { openRouterDecisionCapabilities } from "./config.js";
|
|
5
6
|
import { ClassifierError, isRecord, } from "./types.js";
|
|
6
7
|
/**
|
|
7
8
|
* Provider protocol adapters. Every request goes through the shared `postJson` boundary, which
|
|
@@ -11,6 +12,7 @@ import { ClassifierError, isRecord, } from "./types.js";
|
|
|
11
12
|
*/
|
|
12
13
|
const OPENAI_LABEL = "OpenAI Decisions";
|
|
13
14
|
const PERPLEXITY_LABEL = "Perplexity Decisions";
|
|
15
|
+
const SARVAM_LABEL = "Sarvam Prism";
|
|
14
16
|
const TYPESAFE_LABEL = "TypeSafe System One";
|
|
15
17
|
const CLOUDFLARE_LABEL = "Cloudflare Workers AI";
|
|
16
18
|
const EPSILON = 1e-6;
|
|
@@ -19,10 +21,24 @@ export async function classifyWithProvider(route, input, apiKey, signal) {
|
|
|
19
21
|
switch (route.api) {
|
|
20
22
|
case "openai-decisions":
|
|
21
23
|
return classifyOpenAi(route, input, apiKey, signal);
|
|
24
|
+
case "openrouter-decisions":
|
|
25
|
+
return classifyOpenRouter(route, input, apiKey, signal);
|
|
26
|
+
case "gemini-decisions":
|
|
27
|
+
return classifyGemini(route, input, apiKey, signal);
|
|
28
|
+
case "inception-decisions":
|
|
29
|
+
return classifyInception(route, input, apiKey, signal);
|
|
30
|
+
case "parallel-decisions":
|
|
31
|
+
return classifyParallel(route, input, apiKey, signal);
|
|
32
|
+
case "local-system-one":
|
|
33
|
+
return classifyLocalSystemOne(route, input, apiKey, signal);
|
|
22
34
|
case "perplexity-decisions":
|
|
23
35
|
return classifyPerplexity(route, input, apiKey, signal);
|
|
36
|
+
case "sarvam-system-one":
|
|
37
|
+
return classifySarvam(route, input, apiKey, signal);
|
|
24
38
|
case "system-one":
|
|
25
39
|
return classifySystemOne(route, input, apiKey, signal);
|
|
40
|
+
case "liquid-system-one":
|
|
41
|
+
return classifyLiquid(route, input, apiKey, signal);
|
|
26
42
|
case "microsoft-system-one":
|
|
27
43
|
return classifyMicrosoft(route, input, apiKey, signal);
|
|
28
44
|
case "cloudflare-system-one":
|
|
@@ -80,7 +96,20 @@ function normalizedUsage(value) {
|
|
|
80
96
|
}
|
|
81
97
|
return usage;
|
|
82
98
|
}
|
|
83
|
-
function
|
|
99
|
+
function reportedCost(value, source) {
|
|
100
|
+
if (!isRecord(value))
|
|
101
|
+
return undefined;
|
|
102
|
+
const raw = value.cost;
|
|
103
|
+
const total = typeof raw === "number" && Number.isFinite(raw) && raw >= 0
|
|
104
|
+
? raw
|
|
105
|
+
: typeof raw === "string" && /^\d+(?:\.\d+)?$/.test(raw)
|
|
106
|
+
? Number(raw)
|
|
107
|
+
: undefined;
|
|
108
|
+
if (total === undefined)
|
|
109
|
+
return undefined;
|
|
110
|
+
return { currency: "USD", total, source };
|
|
111
|
+
}
|
|
112
|
+
function finish(route, answers, rawUsage, requestId, providerCost) {
|
|
84
113
|
const result = {
|
|
85
114
|
provider: route.route,
|
|
86
115
|
model: route.model,
|
|
@@ -92,6 +121,8 @@ function finish(route, answers, rawUsage, requestId) {
|
|
|
92
121
|
result.usage = usage;
|
|
93
122
|
if (requestId !== undefined)
|
|
94
123
|
result.requestId = requestId;
|
|
124
|
+
if (providerCost !== undefined)
|
|
125
|
+
result.providerCost = providerCost;
|
|
95
126
|
return result;
|
|
96
127
|
}
|
|
97
128
|
function textContent(value) {
|
|
@@ -101,10 +132,36 @@ function textContent(value) {
|
|
|
101
132
|
throw new ClassifierError("capability", "This content placement does not support images on the selected route.");
|
|
102
133
|
return value.join("");
|
|
103
134
|
}
|
|
135
|
+
function openAiImagePart(image, detail) {
|
|
136
|
+
return {
|
|
137
|
+
type: "input_image",
|
|
138
|
+
image_url: imageUrl(image),
|
|
139
|
+
...(detail !== undefined ? { detail } : {}),
|
|
140
|
+
};
|
|
141
|
+
}
|
|
104
142
|
function openAiContent(value, input) {
|
|
105
|
-
return imageContentParts(value, (id) => (
|
|
143
|
+
return imageContentParts(value, (id) => openAiImagePart(namedImage(input.images, id), input.imageDetail))
|
|
106
144
|
.map((part) => typeof part === "string" ? { type: "input_text", text: part } : part);
|
|
107
145
|
}
|
|
146
|
+
function jsonValueCount(value) {
|
|
147
|
+
let total = 1;
|
|
148
|
+
if (Array.isArray(value))
|
|
149
|
+
for (const entry of value)
|
|
150
|
+
total += jsonValueCount(entry);
|
|
151
|
+
else if (isRecord(value))
|
|
152
|
+
for (const entry of Object.values(value))
|
|
153
|
+
total += jsonValueCount(entry);
|
|
154
|
+
return total;
|
|
155
|
+
}
|
|
156
|
+
function openAiJsonPart(value) {
|
|
157
|
+
if (isRecord(value) || (Array.isArray(value) && value.every((entry) => isRecord(entry)))) {
|
|
158
|
+
const bytes = Buffer.byteLength(JSON.stringify(value));
|
|
159
|
+
if (bytes > 256 * 1024 || jsonValueCount(value) > 10_000)
|
|
160
|
+
fail(OPENAI_LABEL + " input_json exceeds the documented 256 KiB / 10,000-value limit. Supply a smaller JSON state.");
|
|
161
|
+
return { type: "input_json", data: value };
|
|
162
|
+
}
|
|
163
|
+
return undefined;
|
|
164
|
+
}
|
|
108
165
|
/* Answer parsing for map-shaped answers (Perplexity, System One, Clef) --- */
|
|
109
166
|
function labelProbabilities(label, id, value, labels) {
|
|
110
167
|
if (!isRecord(value))
|
|
@@ -125,6 +182,25 @@ function labelProbabilities(label, id, value, labels) {
|
|
|
125
182
|
return checkDistribution(label, id, result);
|
|
126
183
|
}
|
|
127
184
|
/** Probability mass must be close to 1; it is never renormalized on the caller's behalf. */
|
|
185
|
+
function independentLabelProbabilities(label, id, value, labels) {
|
|
186
|
+
if (!isRecord(value))
|
|
187
|
+
fail(label + " returned invalid probabilities for " + id + ".");
|
|
188
|
+
const result = Object.create(null);
|
|
189
|
+
for (const [key, entry] of Object.entries(value)) {
|
|
190
|
+
if (!labels.includes(key))
|
|
191
|
+
fail(label +
|
|
192
|
+
" returned an unknown option in the probabilities for " +
|
|
193
|
+
id +
|
|
194
|
+
".");
|
|
195
|
+
result[key] = probability(label, entry, "probability for " + id + "." + key);
|
|
196
|
+
}
|
|
197
|
+
for (const key of labels) {
|
|
198
|
+
if (!Object.hasOwn(result, key))
|
|
199
|
+
fail(label + " did not return a probability for " + id + "." + key + ".");
|
|
200
|
+
}
|
|
201
|
+
// Liquid multi-select questions treat each label as its own yes/no decision.
|
|
202
|
+
return result;
|
|
203
|
+
}
|
|
128
204
|
function checkDistribution(label, id, probabilities) {
|
|
129
205
|
let total = 0;
|
|
130
206
|
for (const value of Object.values(probabilities))
|
|
@@ -167,6 +243,47 @@ function scoreValue(label, id, value, levels) {
|
|
|
167
243
|
fail(label + " returned a score outside the rubric for " + id + ".");
|
|
168
244
|
return Math.min(maximum, Math.max(0, value));
|
|
169
245
|
}
|
|
246
|
+
function nonNegativeInteger(label, value, field) {
|
|
247
|
+
if (!Number.isSafeInteger(value) || value < 0)
|
|
248
|
+
fail(label + " returned an invalid " + field + ".");
|
|
249
|
+
return value;
|
|
250
|
+
}
|
|
251
|
+
function codePointSlice(source, start, end) {
|
|
252
|
+
const characters = Array.from(source);
|
|
253
|
+
if (start > end || end > characters.length)
|
|
254
|
+
return "";
|
|
255
|
+
return characters.slice(start, end).join("");
|
|
256
|
+
}
|
|
257
|
+
function parseTextSpans(label, id, value, sources) {
|
|
258
|
+
if (!Array.isArray(value))
|
|
259
|
+
fail(label + " returned invalid spans for " + id + ".");
|
|
260
|
+
return value.map((entry, index) => {
|
|
261
|
+
if (!isRecord(entry))
|
|
262
|
+
fail(label + " returned an invalid span for " + id + ".");
|
|
263
|
+
const start = nonNegativeInteger(label, entry.start, "span offset for " + id);
|
|
264
|
+
const end = nonNegativeInteger(label, entry.end, "span offset for " + id);
|
|
265
|
+
if (typeof entry.text !== "string" || end < start)
|
|
266
|
+
fail(label + " returned an invalid span for " + id + ".");
|
|
267
|
+
let searchResult;
|
|
268
|
+
if (entry.search_result !== undefined) {
|
|
269
|
+
searchResult = nonNegativeInteger(label, entry.search_result, "search result index for " + id);
|
|
270
|
+
if (sources.snippets === undefined || searchResult >= sources.snippets.length)
|
|
271
|
+
fail(label + " returned an unknown search result for " + id + ".");
|
|
272
|
+
}
|
|
273
|
+
const source = searchResult === undefined ? sources.state : sources.snippets[searchResult];
|
|
274
|
+
if (source === undefined || codePointSlice(source, start, end) !== entry.text)
|
|
275
|
+
fail(label + " returned a span that does not match its source for " + id + ".");
|
|
276
|
+
const span = {
|
|
277
|
+
start,
|
|
278
|
+
end,
|
|
279
|
+
text: entry.text,
|
|
280
|
+
score: probability(label, entry.score, "span score for " + id + "." + index),
|
|
281
|
+
};
|
|
282
|
+
if (searchResult !== undefined)
|
|
283
|
+
span.searchResult = searchResult;
|
|
284
|
+
return span;
|
|
285
|
+
});
|
|
286
|
+
}
|
|
170
287
|
function parseBox(label, id, value, confidence) {
|
|
171
288
|
if (!isRecord(value))
|
|
172
289
|
fail(label + " returned an invalid box for " + id + ".");
|
|
@@ -190,7 +307,7 @@ function parseBox(label, id, value, confidence) {
|
|
|
190
307
|
confidence: probability(label, confidence, "confidence for " + id),
|
|
191
308
|
};
|
|
192
309
|
}
|
|
193
|
-
function parseTypedAnswer(label, id, question, answer) {
|
|
310
|
+
function parseTypedAnswer(label, id, question, answer, sources = {}) {
|
|
194
311
|
if (!isRecord(answer))
|
|
195
312
|
fail(label + " returned an invalid answer for " + id + ".");
|
|
196
313
|
if (answer.type === "refusal")
|
|
@@ -231,6 +348,11 @@ function parseTypedAnswer(label, id, question, answer) {
|
|
|
231
348
|
probabilities: levelProbabilities(label, id, answer.probabilities, question.criteria.length),
|
|
232
349
|
};
|
|
233
350
|
}
|
|
351
|
+
if (question.type === "locate") {
|
|
352
|
+
if (answer.type !== "locate")
|
|
353
|
+
fail(label + " did not return a locate answer for " + id + ".");
|
|
354
|
+
return { type: "locate", spans: parseTextSpans(label, id, answer.spans, sources) };
|
|
355
|
+
}
|
|
234
356
|
if (answer.type !== "box")
|
|
235
357
|
fail(label + " did not return a box answer for " + id + ".");
|
|
236
358
|
return parseBox(label, id, answer.box, answer.confidence);
|
|
@@ -256,7 +378,7 @@ function validateDecision(label, id, answer) {
|
|
|
256
378
|
}
|
|
257
379
|
return answer;
|
|
258
380
|
}
|
|
259
|
-
function parseTypedAnswers(label, value, questions) {
|
|
381
|
+
function parseTypedAnswers(label, value, questions, sources = {}) {
|
|
260
382
|
if (!isRecord(value))
|
|
261
383
|
fail(label + " returned an unexpected response.");
|
|
262
384
|
// Question IDs may be "__proto__", so answers are collected without a prototype.
|
|
@@ -264,7 +386,7 @@ function parseTypedAnswers(label, value, questions) {
|
|
|
264
386
|
for (const [id, question] of Object.entries(questions)) {
|
|
265
387
|
if (!Object.hasOwn(value, id))
|
|
266
388
|
fail(label + " did not return an answer for " + id + ".");
|
|
267
|
-
answers[id] = validateDecision(label, id, parseTypedAnswer(label, id, question, value[id]));
|
|
389
|
+
answers[id] = validateDecision(label, id, parseTypedAnswer(label, id, question, value[id], sources));
|
|
268
390
|
}
|
|
269
391
|
return answers;
|
|
270
392
|
}
|
|
@@ -288,45 +410,103 @@ function openAiQuestion(id, question, input) {
|
|
|
288
410
|
if (question.type === "choice")
|
|
289
411
|
return {
|
|
290
412
|
type: "choice", name: id, instructions: wireInstructions,
|
|
291
|
-
choices: Object.entries(question.criteria).map(([value, description]) => ({
|
|
413
|
+
choices: Object.entries(question.criteria).map(([value, description]) => ({
|
|
414
|
+
// Only caller-supplied boolean labels map to booleans. The internal NONE sentinel
|
|
415
|
+
// remains a distinct string so boolean questions can still reject all options.
|
|
416
|
+
value: question.booleanValues && (value === "true" || value === "false") ? value === "true" : value,
|
|
417
|
+
description: textContent(description),
|
|
418
|
+
})),
|
|
292
419
|
};
|
|
293
420
|
if (question.type === "score")
|
|
294
421
|
return {
|
|
295
422
|
type: "score", name: id, instructions: wireInstructions,
|
|
296
|
-
levels: question.criteria.map((label) => ({
|
|
423
|
+
levels: question.criteria.map((label, index) => ({
|
|
424
|
+
label: textContent(label),
|
|
425
|
+
...(question.descriptions?.[index] !== undefined ? { description: question.descriptions[index] } : {}),
|
|
426
|
+
})),
|
|
297
427
|
};
|
|
298
428
|
throw unsupportedBox();
|
|
299
429
|
}
|
|
300
|
-
function
|
|
430
|
+
function openAiCachePayload(input) {
|
|
431
|
+
const payload = {};
|
|
432
|
+
if (input.promptCache?.key !== undefined)
|
|
433
|
+
payload.prompt_cache_key = input.promptCache.key;
|
|
434
|
+
if (input.promptCache?.mode !== undefined || input.promptCache?.ttl !== undefined)
|
|
435
|
+
payload.prompt_cache_options = {
|
|
436
|
+
...(input.promptCache?.mode !== undefined ? { mode: input.promptCache.mode } : {}),
|
|
437
|
+
...(input.promptCache?.ttl !== undefined ? { ttl: input.promptCache.ttl } : {}),
|
|
438
|
+
};
|
|
439
|
+
return payload;
|
|
440
|
+
}
|
|
441
|
+
function openAiSetBreakpoint(parts) {
|
|
442
|
+
const first = parts.find((part) => isRecord(part) && (part.type === "input_text" || part.type === "input_image"));
|
|
443
|
+
if (isRecord(first)) {
|
|
444
|
+
first.prompt_cache_breakpoint = { mode: "explicit" };
|
|
445
|
+
return true;
|
|
446
|
+
}
|
|
447
|
+
return false;
|
|
448
|
+
}
|
|
449
|
+
function openAiStateParts(input) {
|
|
301
450
|
const text = typeof input.state === "string" ? input.state : JSON.stringify(input.state);
|
|
302
|
-
const shared = input.images.filter((image) => image.id === undefined);
|
|
303
451
|
const references = imageReferences(input.state);
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
]
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
452
|
+
const parts = references.length > 0
|
|
453
|
+
? openAiContent(input.state, input)
|
|
454
|
+
: text
|
|
455
|
+
? (() => {
|
|
456
|
+
const jsonPart = typeof input.state === "string" ? undefined : openAiJsonPart(input.state);
|
|
457
|
+
return jsonPart ? [{ type: "input_text", text: "Structured state:" }, jsonPart] : [{ type: "input_text", text }];
|
|
458
|
+
})()
|
|
459
|
+
: [];
|
|
460
|
+
for (const image of input.images.filter((entry) => entry.id === undefined))
|
|
461
|
+
parts.push(openAiImagePart(image, input.imageDetail));
|
|
462
|
+
return parts;
|
|
463
|
+
}
|
|
464
|
+
function openAiInput(input) {
|
|
465
|
+
const payload = openAiCachePayload(input);
|
|
466
|
+
if (input.conversation !== undefined) {
|
|
467
|
+
const items = input.conversation.map((item) => ({ ...(isRecord(item) ? item : {}) }));
|
|
468
|
+
const stateParts = openAiStateParts(input);
|
|
469
|
+
if (stateParts.length > 0)
|
|
470
|
+
items.unshift({ type: "message", role: "user", content: stateParts });
|
|
471
|
+
if (input.promptCache?.breakpoints) {
|
|
472
|
+
const userItem = items.find((item) => isRecord(item) && item.type === "message" && item.role === "user" && Array.isArray(item.content));
|
|
473
|
+
if (!isRecord(userItem) || !openAiSetBreakpoint(userItem.content)) {
|
|
474
|
+
const parts = [{ type: "input_text", text: "", prompt_cache_breakpoint: { mode: "explicit" } }];
|
|
475
|
+
items.unshift({ type: "message", role: "user", content: parts });
|
|
476
|
+
}
|
|
477
|
+
}
|
|
478
|
+
return { input: items, payload };
|
|
479
|
+
}
|
|
480
|
+
const content = openAiStateParts(input);
|
|
481
|
+
const breakpointSet = input.promptCache?.breakpoints === true && openAiSetBreakpoint(content);
|
|
482
|
+
if (!breakpointSet && input.promptCache?.breakpoints)
|
|
483
|
+
content.unshift({ type: "input_text", text: "", prompt_cache_breakpoint: { mode: "explicit" } });
|
|
484
|
+
const text = typeof input.state === "string" ? input.state : JSON.stringify(input.state);
|
|
485
|
+
if (!breakpointSet &&
|
|
486
|
+
input.promptCache?.breakpoints !== true &&
|
|
487
|
+
content.length === 1 &&
|
|
488
|
+
isRecord(content[0]) &&
|
|
489
|
+
content[0].type === "input_text" &&
|
|
490
|
+
content[0].text === text &&
|
|
491
|
+
Object.keys(payload).length === 0)
|
|
492
|
+
return { input: text, payload };
|
|
493
|
+
return { input: [{ type: "message", role: "user", content }], payload };
|
|
494
|
+
}
|
|
495
|
+
function openAiChoiceProbabilities(label, id, value, labels, booleanValues) {
|
|
315
496
|
if (!Array.isArray(value))
|
|
316
497
|
fail(label + " returned invalid probabilities for " + id + ".");
|
|
317
498
|
const mapped = Object.create(null);
|
|
318
499
|
for (const entry of value) {
|
|
319
|
-
if (!isRecord(entry)
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
if (Object.hasOwn(mapped, entry.value))
|
|
500
|
+
if (!isRecord(entry))
|
|
501
|
+
fail(label + " returned an unknown option in the probabilities for " + id + ".");
|
|
502
|
+
const key = booleanValues && typeof entry.value === "boolean"
|
|
503
|
+
? (entry.value ? "true" : "false")
|
|
504
|
+
: typeof entry.value === "string" ? entry.value : undefined;
|
|
505
|
+
if (key === undefined || !labels.includes(key))
|
|
506
|
+
fail(label + " returned an unknown option in the probabilities for " + id + ".");
|
|
507
|
+
if (Object.hasOwn(mapped, key))
|
|
328
508
|
fail(label + " returned duplicate probabilities for " + id + ".");
|
|
329
|
-
mapped[
|
|
509
|
+
mapped[key] = entry.probability;
|
|
330
510
|
}
|
|
331
511
|
return labelProbabilities(label, id, mapped, labels);
|
|
332
512
|
}
|
|
@@ -365,14 +545,17 @@ function parseOpenAiAnswer(label, id, question, answer) {
|
|
|
365
545
|
};
|
|
366
546
|
}
|
|
367
547
|
if (question.type === "choice") {
|
|
368
|
-
if (answer.type !== "choice"
|
|
548
|
+
if (answer.type !== "choice")
|
|
369
549
|
fail(label + " did not return a choice answer for " + id + ".");
|
|
370
|
-
|
|
550
|
+
const choice = question.booleanValues && typeof answer.choice === "boolean"
|
|
551
|
+
? (answer.choice ? "true" : "false")
|
|
552
|
+
: typeof answer.choice === "string" ? answer.choice : undefined;
|
|
553
|
+
if (choice === undefined || !Object.hasOwn(question.criteria, choice))
|
|
371
554
|
fail(label + " returned an unknown choice for " + id + ".");
|
|
372
555
|
return {
|
|
373
556
|
type: "choice",
|
|
374
|
-
choice
|
|
375
|
-
probabilities: openAiChoiceProbabilities(label, id, answer.probabilities, Object.keys(question.criteria)),
|
|
557
|
+
choice,
|
|
558
|
+
probabilities: openAiChoiceProbabilities(label, id, answer.probabilities, Object.keys(question.criteria), question.booleanValues === true),
|
|
376
559
|
confidence: probability(label, answer.confidence, "confidence for " + id),
|
|
377
560
|
};
|
|
378
561
|
}
|
|
@@ -416,14 +599,411 @@ function parseOpenAiAnswers(label, value, questions) {
|
|
|
416
599
|
}
|
|
417
600
|
async function classifyOpenAi(route, input, apiKey, signal) {
|
|
418
601
|
const questions = Object.entries(input.questions).map(([id, question]) => openAiQuestion(id, question, input));
|
|
419
|
-
const
|
|
602
|
+
const preparedInput = openAiInput(input);
|
|
603
|
+
const { body, requestId, costHeader } = await postJson(route, "decisions", {
|
|
420
604
|
model: route.model,
|
|
421
|
-
input:
|
|
605
|
+
input: preparedInput.input,
|
|
422
606
|
questions,
|
|
607
|
+
...preparedInput.payload,
|
|
423
608
|
}, apiKey, signal);
|
|
424
609
|
if (!isRecord(body))
|
|
425
610
|
fail(OPENAI_LABEL + " returned an unexpected response.");
|
|
426
|
-
|
|
611
|
+
const metadata = isRecord(body.provider_metadata) ? body.provider_metadata.gateway : undefined;
|
|
612
|
+
const gatewayCost = reportedCost(metadata, "gateway") ??
|
|
613
|
+
(costHeader ? { currency: "USD", total: Number(costHeader), source: "gateway" } : undefined);
|
|
614
|
+
return finish(route, parseOpenAiAnswers(OPENAI_LABEL, body.answers, input.questions), body.usage, requestId, gatewayCost);
|
|
615
|
+
}
|
|
616
|
+
/* OpenRouter alpha Decisions ---------------------------------------------- */
|
|
617
|
+
const OPENROUTER_LABEL = "OpenRouter Decisions";
|
|
618
|
+
const OPENROUTER_ID = /^[A-Za-z0-9_.:-]{1,128}$/;
|
|
619
|
+
function openRouterImagePart(image, detail) {
|
|
620
|
+
return {
|
|
621
|
+
type: "image_url",
|
|
622
|
+
image_url: {
|
|
623
|
+
url: imageUrl(image),
|
|
624
|
+
...(detail !== undefined ? { detail } : {}),
|
|
625
|
+
},
|
|
626
|
+
};
|
|
627
|
+
}
|
|
628
|
+
function openRouterState(input, flexible) {
|
|
629
|
+
const shared = input.images.filter((image) => image.id === undefined);
|
|
630
|
+
if (!flexible) {
|
|
631
|
+
let parts;
|
|
632
|
+
if (isImageReference(input.state))
|
|
633
|
+
parts = [openRouterImagePart(namedImage(input.images, input.state.$image), input.imageDetail)];
|
|
634
|
+
else if (Array.isArray(input.state)) {
|
|
635
|
+
parts = input.state.map((entry) => isImageReference(entry)
|
|
636
|
+
? openRouterImagePart(namedImage(input.images, entry.$image), input.imageDetail)
|
|
637
|
+
: typeof entry === "string" ? entry : JSON.stringify(entry));
|
|
638
|
+
}
|
|
639
|
+
else
|
|
640
|
+
parts = [typeof input.state === "string" ? input.state : JSON.stringify(input.state)];
|
|
641
|
+
for (const image of shared)
|
|
642
|
+
parts.push(openRouterImagePart(image, input.imageDetail));
|
|
643
|
+
return parts.length === 1 && typeof parts[0] === "string" ? parts[0] : parts;
|
|
644
|
+
}
|
|
645
|
+
if (input.images.length === 0)
|
|
646
|
+
return input.state;
|
|
647
|
+
const parts = imageContentParts(input.state, (id) => openRouterImagePart(namedImage(input.images, id), input.imageDetail));
|
|
648
|
+
for (const image of shared)
|
|
649
|
+
parts.push(openRouterImagePart(image, input.imageDetail));
|
|
650
|
+
if (parts.length === 0)
|
|
651
|
+
return input.state;
|
|
652
|
+
return parts;
|
|
653
|
+
}
|
|
654
|
+
function openRouterMedia(media) {
|
|
655
|
+
return media.map((entry) => entry.type === "audio"
|
|
656
|
+
? {
|
|
657
|
+
type: "input_audio",
|
|
658
|
+
input_audio: {
|
|
659
|
+
data: entry.data,
|
|
660
|
+
format: entry.mimeType.slice(entry.mimeType.indexOf("/") + 1),
|
|
661
|
+
},
|
|
662
|
+
}
|
|
663
|
+
: { type: "video_url", video_url: { url: "data:" + entry.mimeType + ";base64," + entry.data } });
|
|
664
|
+
}
|
|
665
|
+
function openRouterQuestion(id, question, input, flexible) {
|
|
666
|
+
if (question.type === "extract")
|
|
667
|
+
throw new ClassifierError("capability", "OpenRouter Decisions does not support extract questions.");
|
|
668
|
+
const content = flexible
|
|
669
|
+
? (value) => mapImageReferences(value, (imageId) => openRouterImagePart(namedImage(input.images, imageId), input.imageDetail))
|
|
670
|
+
: textContent;
|
|
671
|
+
const wire = {
|
|
672
|
+
type: question.type === "bool" ? "noul" : question.type,
|
|
673
|
+
instructions: content(question.instructions),
|
|
674
|
+
};
|
|
675
|
+
if (question.type === "bool") {
|
|
676
|
+
if (question.criteria)
|
|
677
|
+
wire.criteria = Object.fromEntries(Object.entries(question.criteria).map(([key, value]) => [key, content(value)]));
|
|
678
|
+
return wire;
|
|
679
|
+
}
|
|
680
|
+
if (question.type === "choice") {
|
|
681
|
+
wire.criteria = Object.fromEntries(Object.entries(question.criteria).map(([key, value]) => [key, content(value)]));
|
|
682
|
+
return wire;
|
|
683
|
+
}
|
|
684
|
+
if (question.type === "score") {
|
|
685
|
+
wire.criteria = question.criteria.map(content);
|
|
686
|
+
return wire;
|
|
687
|
+
}
|
|
688
|
+
if (question.type === "box")
|
|
689
|
+
return wire;
|
|
690
|
+
throw new ClassifierError("capability", "OpenRouter Decisions does not support " + question.type + " questions.");
|
|
691
|
+
}
|
|
692
|
+
function openRouterAnswers(value, questions) {
|
|
693
|
+
if (!isRecord(value))
|
|
694
|
+
fail(OPENROUTER_LABEL + " returned an unexpected response.");
|
|
695
|
+
const answers = Object.create(null);
|
|
696
|
+
for (const [id, question] of Object.entries(questions)) {
|
|
697
|
+
if (!Object.hasOwn(value, id))
|
|
698
|
+
fail(OPENROUTER_LABEL + " did not return an answer for " + id + ".");
|
|
699
|
+
const raw = value[id];
|
|
700
|
+
if (isRecord(raw) &&
|
|
701
|
+
raw.type !== "refusal" &&
|
|
702
|
+
raw.confidence === undefined &&
|
|
703
|
+
isRecord(raw.probabilities) &&
|
|
704
|
+
(question.type === "choice" || question.type === "score")) {
|
|
705
|
+
const probabilities = Object.values(raw.probabilities).filter((entry) => typeof entry === "number" && Number.isFinite(entry));
|
|
706
|
+
if (probabilities.length > 0)
|
|
707
|
+
answers[id] = { ...raw, confidence: Math.max(...probabilities) };
|
|
708
|
+
else
|
|
709
|
+
answers[id] = raw;
|
|
710
|
+
}
|
|
711
|
+
else
|
|
712
|
+
answers[id] = raw;
|
|
713
|
+
}
|
|
714
|
+
return parseTypedAnswers(OPENROUTER_LABEL, answers, questions);
|
|
715
|
+
}
|
|
716
|
+
async function classifyOpenRouter(route, input, apiKey, signal) {
|
|
717
|
+
const caps = openRouterDecisionCapabilities(route.model);
|
|
718
|
+
if (!caps.box && Object.values(input.questions).some((question) => question.type === "box"))
|
|
719
|
+
throw new ClassifierError("capability", "OpenRouter box questions require a TypeSafe Jev 1.14 endpoint.");
|
|
720
|
+
const stateParts = openRouterState(input, caps.flexibleImagePlacement);
|
|
721
|
+
const state = Array.isArray(stateParts) || typeof stateParts === "string" || isRecord(stateParts)
|
|
722
|
+
? stateParts
|
|
723
|
+
: JSON.stringify(stateParts);
|
|
724
|
+
const payload = {
|
|
725
|
+
model: route.model,
|
|
726
|
+
state,
|
|
727
|
+
questions: Object.fromEntries(Object.entries(input.questions).map(([id, question]) => [id, openRouterQuestion(id, question, input, caps.flexibleImagePlacement)])),
|
|
728
|
+
};
|
|
729
|
+
if (input.media.length > 0) {
|
|
730
|
+
const withParts = Array.isArray(state) ? state : [state];
|
|
731
|
+
payload.state = [...withParts, ...openRouterMedia(input.media)];
|
|
732
|
+
}
|
|
733
|
+
const { body, requestId } = await postJson(route, "alpha/decisions", payload, apiKey, signal);
|
|
734
|
+
if (!isRecord(body))
|
|
735
|
+
fail(OPENROUTER_LABEL + " returned an unexpected response.");
|
|
736
|
+
const bodyId = typeof body.id === "string" && OPENROUTER_ID.test(body.id) ? body.id : undefined;
|
|
737
|
+
return finish(route, openRouterAnswers(body.answers, input.questions), body.usage, requestId ?? bodyId, reportedCost(body.usage, "provider"));
|
|
738
|
+
}
|
|
739
|
+
/* Shared derived-confidence parsing for newer System One-like adapters ---- */
|
|
740
|
+
function deriveConfidenceAnswers(label, rawAnswers, questions) {
|
|
741
|
+
if (!isRecord(rawAnswers))
|
|
742
|
+
fail(label + " returned an unexpected response.");
|
|
743
|
+
const answers = Object.create(null);
|
|
744
|
+
for (const [id, question] of Object.entries(questions)) {
|
|
745
|
+
if (!Object.hasOwn(rawAnswers, id))
|
|
746
|
+
fail(label + " did not return an answer for " + id + ".");
|
|
747
|
+
const raw = rawAnswers[id];
|
|
748
|
+
if (isRecord(raw) &&
|
|
749
|
+
raw.type !== "refusal" &&
|
|
750
|
+
raw.confidence === undefined &&
|
|
751
|
+
isRecord(raw.probabilities) &&
|
|
752
|
+
(question.type === "choice" || question.type === "score")) {
|
|
753
|
+
const values = Object.values(raw.probabilities).filter((entry) => typeof entry === "number" && Number.isFinite(entry));
|
|
754
|
+
answers[id] = values.length > 0 ? { ...raw, confidence: Math.max(...values) } : raw;
|
|
755
|
+
}
|
|
756
|
+
else
|
|
757
|
+
answers[id] = raw;
|
|
758
|
+
}
|
|
759
|
+
return parseTypedAnswers(label, answers, questions);
|
|
760
|
+
}
|
|
761
|
+
function mediaDataUrl(entry) {
|
|
762
|
+
return "data:" + entry.mimeType + ";base64," + entry.data;
|
|
763
|
+
}
|
|
764
|
+
/* Google Gemini Decisions -------------------------------------------------- */
|
|
765
|
+
const GEMINI_LABEL = "Gemini Decisions";
|
|
766
|
+
function geminiInput(input) {
|
|
767
|
+
const text = typeof input.state === "string" ? input.state : JSON.stringify(input.state);
|
|
768
|
+
const blocks = text ? [{ type: "text", text }] : [];
|
|
769
|
+
for (const image of input.images) {
|
|
770
|
+
if ("url" in image)
|
|
771
|
+
blocks.push({ type: "image", uri: image.url });
|
|
772
|
+
else
|
|
773
|
+
blocks.push({ type: "image", data: image.data, mime_type: image.mimeType });
|
|
774
|
+
}
|
|
775
|
+
for (const media of input.media)
|
|
776
|
+
blocks.push({ type: media.type, data: media.data, mime_type: media.mimeType });
|
|
777
|
+
if (blocks.length === 0)
|
|
778
|
+
return text;
|
|
779
|
+
return blocks.length === 1 && isRecord(blocks[0]) && blocks[0].type === "text" ? text : blocks;
|
|
780
|
+
}
|
|
781
|
+
function geminiQuestion(id, question) {
|
|
782
|
+
if (question.type === "extract")
|
|
783
|
+
throw new ClassifierError("capability", "Gemini Decisions does not support extract questions.");
|
|
784
|
+
const wire = {
|
|
785
|
+
type: question.type === "bool" ? "noul" : question.type,
|
|
786
|
+
instructions: textContent(question.instructions),
|
|
787
|
+
};
|
|
788
|
+
if (question.type === "bool" && question.criteria) {
|
|
789
|
+
const criteria = {};
|
|
790
|
+
if (question.criteria.true !== undefined)
|
|
791
|
+
criteria.true_description = textContent(question.criteria.true);
|
|
792
|
+
if (question.criteria.false !== undefined)
|
|
793
|
+
criteria.false_description = textContent(question.criteria.false);
|
|
794
|
+
if (Object.keys(criteria).length > 0)
|
|
795
|
+
wire.criteria = criteria;
|
|
796
|
+
}
|
|
797
|
+
else if (question.type === "choice") {
|
|
798
|
+
wire.criteria = Object.fromEntries(Object.entries(question.criteria).map(([key, value]) => [key, textContent(value)]));
|
|
799
|
+
}
|
|
800
|
+
else if (question.type === "score") {
|
|
801
|
+
wire.criteria = question.criteria.map(textContent);
|
|
802
|
+
}
|
|
803
|
+
return wire;
|
|
804
|
+
}
|
|
805
|
+
async function classifyGemini(route, input, apiKey, signal) {
|
|
806
|
+
const payload = {
|
|
807
|
+
model: route.model,
|
|
808
|
+
input: geminiInput(input),
|
|
809
|
+
questions: Object.fromEntries(Object.entries(input.questions).map(([id, question]) => [id, geminiQuestion(id, question)])),
|
|
810
|
+
};
|
|
811
|
+
const { body, requestId } = await postJson(route, "decisions", payload, apiKey, signal);
|
|
812
|
+
if (!isRecord(body))
|
|
813
|
+
fail(GEMINI_LABEL + " returned an unexpected response.");
|
|
814
|
+
const rawUsage = isRecord(body.usage)
|
|
815
|
+
? {
|
|
816
|
+
input_tokens: body.usage.total_input_tokens,
|
|
817
|
+
output_tokens: body.usage.total_output_tokens,
|
|
818
|
+
total_tokens: body.usage.total_tokens,
|
|
819
|
+
}
|
|
820
|
+
: undefined;
|
|
821
|
+
return finish(route, deriveConfidenceAnswers(GEMINI_LABEL, body.answers, input.questions), rawUsage, requestId);
|
|
822
|
+
}
|
|
823
|
+
/* Inception Mercury Decide ------------------------------------------------- */
|
|
824
|
+
const INCEPTION_LABEL = "Inception Mercury Decide";
|
|
825
|
+
function inceptionImagePart(image) {
|
|
826
|
+
return { type: "image_url", image_url: { url: imageUrl(image) } };
|
|
827
|
+
}
|
|
828
|
+
function inceptionState(input) {
|
|
829
|
+
if (input.images.length === 0 && input.media.length === 0)
|
|
830
|
+
return input.state;
|
|
831
|
+
const parts = imageContentParts(input.state, (id) => inceptionImagePart(namedImage(input.images, id)));
|
|
832
|
+
for (const image of input.images.filter((entry) => entry.id === undefined))
|
|
833
|
+
parts.push(inceptionImagePart(image));
|
|
834
|
+
return parts.length === 1 && typeof parts[0] === "string" ? parts[0] : parts;
|
|
835
|
+
}
|
|
836
|
+
function inceptionQuestion(id, question, input) {
|
|
837
|
+
const content = (value) => mapImageReferences(value, (imageId) => inceptionImagePart(namedImage(input.images, imageId)));
|
|
838
|
+
const wire = {
|
|
839
|
+
type: question.type === "bool" ? "noul" : question.type,
|
|
840
|
+
instructions: question.instructions === undefined ? undefined : content(question.instructions),
|
|
841
|
+
};
|
|
842
|
+
if (question.type === "choice") {
|
|
843
|
+
wire.criteria = Object.fromEntries(Object.entries(question.criteria).map(([key, value]) => [key, content(value)]));
|
|
844
|
+
}
|
|
845
|
+
else if (question.type === "score") {
|
|
846
|
+
wire.criteria = question.criteria.map(content);
|
|
847
|
+
}
|
|
848
|
+
else if (question.type === "extract") {
|
|
849
|
+
wire.criteria = Object.fromEntries(Object.entries(question.criteria).map(([key, value]) => [key, textContent(value)]));
|
|
850
|
+
if (question.source !== undefined)
|
|
851
|
+
wire.source = question.source;
|
|
852
|
+
if (question.threshold !== undefined)
|
|
853
|
+
wire.threshold = question.threshold;
|
|
854
|
+
if (question.snapToWords !== undefined)
|
|
855
|
+
wire.snap_to_words = question.snapToWords;
|
|
856
|
+
if (question.debug !== undefined)
|
|
857
|
+
wire.debug = question.debug;
|
|
858
|
+
}
|
|
859
|
+
else if (question.type === "bool" && question.criteria) {
|
|
860
|
+
wire.criteria = Object.fromEntries(Object.entries(question.criteria).map(([key, value]) => [key, content(value)]));
|
|
861
|
+
}
|
|
862
|
+
return wire;
|
|
863
|
+
}
|
|
864
|
+
function inceptionAnswers(rawAnswers, questions, input) {
|
|
865
|
+
if (!isRecord(rawAnswers))
|
|
866
|
+
fail(INCEPTION_LABEL + " returned an unexpected response.");
|
|
867
|
+
const answers = Object.create(null);
|
|
868
|
+
for (const [id, question] of Object.entries(questions)) {
|
|
869
|
+
const raw = rawAnswers[id];
|
|
870
|
+
if (raw === undefined)
|
|
871
|
+
fail(INCEPTION_LABEL + " did not return an answer for " + id + ".");
|
|
872
|
+
if (question.type !== "extract")
|
|
873
|
+
continue;
|
|
874
|
+
if (!isRecord(raw) || !isRecord(raw.spans) || !isRecord(raw.not_stated))
|
|
875
|
+
fail(INCEPTION_LABEL + " returned an invalid extract answer for " + id + ".");
|
|
876
|
+
const sourceField = question.source;
|
|
877
|
+
const sourceValue = typeof input.state === "string"
|
|
878
|
+
? input.state
|
|
879
|
+
: sourceField !== undefined && isRecord(input.state)
|
|
880
|
+
? input.state[sourceField]
|
|
881
|
+
: undefined;
|
|
882
|
+
if (typeof sourceValue !== "string")
|
|
883
|
+
fail(INCEPTION_LABEL + " cannot locate extract spans without a source string.");
|
|
884
|
+
const source = sourceValue;
|
|
885
|
+
const spans = Object.create(null);
|
|
886
|
+
const notStated = Object.create(null);
|
|
887
|
+
for (const field of Object.keys(question.criteria)) {
|
|
888
|
+
const entries = raw.spans[field] ?? [];
|
|
889
|
+
if (!Array.isArray(entries))
|
|
890
|
+
fail(INCEPTION_LABEL + " returned invalid extract spans for " + id + ".");
|
|
891
|
+
spans[field] = entries.map((entry) => {
|
|
892
|
+
if (!isRecord(entry) || typeof entry.text !== "string")
|
|
893
|
+
fail(INCEPTION_LABEL + " returned an invalid extract span for " + id + ".");
|
|
894
|
+
const start = nonNegativeInteger(INCEPTION_LABEL, entry.start, "extract span offset for " + id);
|
|
895
|
+
const end = nonNegativeInteger(INCEPTION_LABEL, entry.end, "extract span offset for " + id);
|
|
896
|
+
if (end < start || codePointSlice(source, start, end) !== entry.text)
|
|
897
|
+
fail(INCEPTION_LABEL + " returned an extract span that does not match its source for " + id + ".");
|
|
898
|
+
return {
|
|
899
|
+
start,
|
|
900
|
+
end,
|
|
901
|
+
text: entry.text,
|
|
902
|
+
score: probability(INCEPTION_LABEL, entry.confidence, "extract confidence for " + id),
|
|
903
|
+
};
|
|
904
|
+
});
|
|
905
|
+
notStated[field] = probability(INCEPTION_LABEL, raw.not_stated[field], "not_stated for " + id);
|
|
906
|
+
}
|
|
907
|
+
answers[id] = { type: "extract", spans, notStated };
|
|
908
|
+
}
|
|
909
|
+
const coreQuestions = Object.fromEntries(Object.entries(questions).filter(([, question]) => question.type !== "extract"));
|
|
910
|
+
if (Object.keys(coreQuestions).length > 0) {
|
|
911
|
+
const core = deriveConfidenceAnswers(INCEPTION_LABEL, rawAnswers, coreQuestions);
|
|
912
|
+
for (const [id, answer] of Object.entries(core))
|
|
913
|
+
answers[id] = answer;
|
|
914
|
+
}
|
|
915
|
+
return answers;
|
|
916
|
+
}
|
|
917
|
+
async function classifyInception(route, input, apiKey, signal) {
|
|
918
|
+
const payload = {
|
|
919
|
+
model: route.model,
|
|
920
|
+
state: inceptionState(input),
|
|
921
|
+
questions: Object.fromEntries(Object.entries(input.questions).map(([id, question]) => [id, inceptionQuestion(id, question, input)])),
|
|
922
|
+
};
|
|
923
|
+
const { body, requestId } = await postJson(route, "decisions", payload, apiKey, signal);
|
|
924
|
+
if (!isRecord(body))
|
|
925
|
+
fail(INCEPTION_LABEL + " returned an unexpected response.");
|
|
926
|
+
return finish(route, inceptionAnswers(body.answers, input.questions, input), body.usage, requestId);
|
|
927
|
+
}
|
|
928
|
+
/* Parallel Decisions ------------------------------------------------------- */
|
|
929
|
+
const PARALLEL_LABEL = "Parallel Decisions";
|
|
930
|
+
function parallelCitations(value) {
|
|
931
|
+
if (value === undefined)
|
|
932
|
+
return [];
|
|
933
|
+
if (!Array.isArray(value))
|
|
934
|
+
fail(PARALLEL_LABEL + " returned invalid citations.");
|
|
935
|
+
return value.map((entry) => {
|
|
936
|
+
if (!isRecord(entry) || typeof entry.url !== "string")
|
|
937
|
+
fail(PARALLEL_LABEL + " returned an invalid citation.");
|
|
938
|
+
try {
|
|
939
|
+
const url = new URL(entry.url);
|
|
940
|
+
if (!["http:", "https:"].includes(url.protocol))
|
|
941
|
+
throw new Error();
|
|
942
|
+
}
|
|
943
|
+
catch {
|
|
944
|
+
fail(PARALLEL_LABEL + " returned an invalid citation URL.");
|
|
945
|
+
}
|
|
946
|
+
const citation = { url: entry.url };
|
|
947
|
+
if (typeof entry.title === "string")
|
|
948
|
+
citation.title = entry.title;
|
|
949
|
+
if (entry.excerpts !== undefined) {
|
|
950
|
+
if (!Array.isArray(entry.excerpts) || !entry.excerpts.every((text) => typeof text === "string"))
|
|
951
|
+
fail(PARALLEL_LABEL + " returned invalid citation excerpts.");
|
|
952
|
+
citation.excerpts = entry.excerpts;
|
|
953
|
+
}
|
|
954
|
+
return citation;
|
|
955
|
+
});
|
|
956
|
+
}
|
|
957
|
+
async function classifyParallel(route, input, apiKey, signal) {
|
|
958
|
+
if (input.images.length > 0 || input.media.length > 0 || input.mode !== undefined)
|
|
959
|
+
throw new ClassifierError("capability", "Parallel Decisions accepts text/JSON state only.");
|
|
960
|
+
const payload = {
|
|
961
|
+
state: input.state,
|
|
962
|
+
questions: systemOneQuestions(input.questions, false),
|
|
963
|
+
mode: "fast",
|
|
964
|
+
};
|
|
965
|
+
const { body, requestId } = await postJson(route, "decisions", payload, apiKey, signal);
|
|
966
|
+
if (!isRecord(body))
|
|
967
|
+
fail(PARALLEL_LABEL + " returned an unexpected response.");
|
|
968
|
+
const result = finish(route, deriveConfidenceAnswers(PARALLEL_LABEL, body.answers, input.questions), body.usage, requestId);
|
|
969
|
+
const citations = parallelCitations(body.citations);
|
|
970
|
+
if (citations.length > 0)
|
|
971
|
+
result.citations = citations;
|
|
972
|
+
if (typeof body.decision_id === "string" && /^[A-Za-z0-9_.:-]{1,128}$/.test(body.decision_id))
|
|
973
|
+
result.requestId = result.requestId ?? body.decision_id;
|
|
974
|
+
return result;
|
|
975
|
+
}
|
|
976
|
+
/* Self-hosted System One runtimes ------------------------------------------ */
|
|
977
|
+
const LOCAL_LABEL = "Local System One";
|
|
978
|
+
async function classifyLocalSystemOne(route, input, apiKey, signal) {
|
|
979
|
+
const payload = {
|
|
980
|
+
...(route.provider !== "llamacpp" ? { model: route.model } : {}),
|
|
981
|
+
state: input.state,
|
|
982
|
+
questions: systemOneQuestions(input.questions, false),
|
|
983
|
+
};
|
|
984
|
+
if (input.images.length > 0)
|
|
985
|
+
payload.images = input.images.map((image) => {
|
|
986
|
+
if ("url" in image)
|
|
987
|
+
throw new ClassifierError("capability", "Local System One routes require local image data.");
|
|
988
|
+
return imageUrl(image);
|
|
989
|
+
});
|
|
990
|
+
const audio = input.media.filter((entry) => entry.type === "audio");
|
|
991
|
+
const video = input.media.filter((entry) => entry.type === "video");
|
|
992
|
+
if (route.provider === "llamacpp") {
|
|
993
|
+
const files = [...input.images, ...input.media];
|
|
994
|
+
if (files.length > 0)
|
|
995
|
+
payload.files = files.map((entry) => ("type" in entry ? mediaDataUrl(entry) : imageUrl(entry)));
|
|
996
|
+
}
|
|
997
|
+
else {
|
|
998
|
+
if (audio.length > 0)
|
|
999
|
+
payload.audio = audio.map(mediaDataUrl);
|
|
1000
|
+
if (video.length > 0)
|
|
1001
|
+
payload.videos = video.map(mediaDataUrl);
|
|
1002
|
+
}
|
|
1003
|
+
const { body, requestId } = await postJson(route, "v1/systemone", payload, apiKey, signal);
|
|
1004
|
+
if (!isRecord(body))
|
|
1005
|
+
fail(LOCAL_LABEL + " returned an unexpected response.");
|
|
1006
|
+
return finish(route, deriveConfidenceAnswers(LOCAL_LABEL, body.answers, input.questions), body.usage, requestId);
|
|
427
1007
|
}
|
|
428
1008
|
/* Perplexity Decisions ---------------------------------------------------- */
|
|
429
1009
|
function systemOneQuestions(questions, allowBox, content = textContent) {
|
|
@@ -435,6 +1015,12 @@ function systemOneQuestions(questions, allowBox, content = textContent) {
|
|
|
435
1015
|
result[id] = { type: "box", instructions: content(question.instructions) };
|
|
436
1016
|
continue;
|
|
437
1017
|
}
|
|
1018
|
+
if (question.type === "locate") {
|
|
1019
|
+
result[id] = { type: "locate", instructions: content(question.instructions) };
|
|
1020
|
+
continue;
|
|
1021
|
+
}
|
|
1022
|
+
if (question.type !== "bool" && question.type !== "choice" && question.type !== "score")
|
|
1023
|
+
throw new ClassifierError("capability", "The selected route does not support " + question.type + " questions.");
|
|
438
1024
|
const wire = {
|
|
439
1025
|
type: question.type === "bool" ? "noul" : question.type,
|
|
440
1026
|
instructions: content(question.instructions),
|
|
@@ -463,25 +1049,261 @@ function perplexityState(input) {
|
|
|
463
1049
|
...shared.map((image) => ({ type: "image_url", image_url: { url: imageUrl(image) } })),
|
|
464
1050
|
];
|
|
465
1051
|
}
|
|
1052
|
+
function webEntry(entry, field) {
|
|
1053
|
+
if (!isRecord(entry) ||
|
|
1054
|
+
typeof entry.title !== "string" ||
|
|
1055
|
+
typeof entry.url !== "string" ||
|
|
1056
|
+
typeof entry.snippet !== "string")
|
|
1057
|
+
fail(PERPLEXITY_LABEL + " returned an invalid " + field + " entry.");
|
|
1058
|
+
try {
|
|
1059
|
+
const url = new URL(entry.url);
|
|
1060
|
+
if (!["http:", "https:"].includes(url.protocol))
|
|
1061
|
+
throw new Error();
|
|
1062
|
+
}
|
|
1063
|
+
catch {
|
|
1064
|
+
fail(PERPLEXITY_LABEL + " returned an invalid URL in " + field + ".");
|
|
1065
|
+
}
|
|
1066
|
+
return { title: entry.title, url: entry.url, snippet: entry.snippet };
|
|
1067
|
+
}
|
|
1068
|
+
function providerDate(value, field) {
|
|
1069
|
+
if (typeof value !== "string" || !/^\d{4}-\d{2}-\d{2}$/.test(value))
|
|
1070
|
+
fail(PERPLEXITY_LABEL + " returned an invalid date in " + field + ".");
|
|
1071
|
+
return value;
|
|
1072
|
+
}
|
|
1073
|
+
function parseSearchResults(value) {
|
|
1074
|
+
if (value === undefined)
|
|
1075
|
+
return [];
|
|
1076
|
+
if (!Array.isArray(value) || value.length > 100)
|
|
1077
|
+
fail(PERPLEXITY_LABEL + " returned invalid search_results.");
|
|
1078
|
+
return value.map((entry) => {
|
|
1079
|
+
const base = webEntry(entry, "search_results");
|
|
1080
|
+
const result = { ...base };
|
|
1081
|
+
if (isRecord(entry) && entry.date !== undefined)
|
|
1082
|
+
result.date = providerDate(entry.date, "search_results");
|
|
1083
|
+
if (isRecord(entry) && entry.last_updated !== undefined)
|
|
1084
|
+
result.lastUpdated = providerDate(entry.last_updated, "search_results");
|
|
1085
|
+
return result;
|
|
1086
|
+
});
|
|
1087
|
+
}
|
|
1088
|
+
function parseFetchedResults(value) {
|
|
1089
|
+
if (value === undefined)
|
|
1090
|
+
return [];
|
|
1091
|
+
if (!Array.isArray(value) || value.length > 1)
|
|
1092
|
+
fail(PERPLEXITY_LABEL + " returned invalid fetched_results.");
|
|
1093
|
+
return value.map((entry) => webEntry(entry, "fetched_results"));
|
|
1094
|
+
}
|
|
1095
|
+
function withWebGroundingCost(cost, questionCount, fetched) {
|
|
1096
|
+
if (cost.status !== "estimated")
|
|
1097
|
+
return cost;
|
|
1098
|
+
const searchFeeMaximum = questionCount * 0.001;
|
|
1099
|
+
const fetchFee = fetched * 0.0005;
|
|
1100
|
+
return {
|
|
1101
|
+
...cost,
|
|
1102
|
+
nonToken: {
|
|
1103
|
+
currency: "USD",
|
|
1104
|
+
webGrounding: {
|
|
1105
|
+
status: "estimated_maximum",
|
|
1106
|
+
searchesRequested: questionCount,
|
|
1107
|
+
searchFeeMaximum,
|
|
1108
|
+
successfulFetches: fetched,
|
|
1109
|
+
fetchFee,
|
|
1110
|
+
totalMaximum: searchFeeMaximum + fetchFee,
|
|
1111
|
+
note: "Perplexity bills one Fast Search per question before duplicate-query sharing and failed-search exclusions are known; exact billed searches are not returned. The token estimate already includes fetched page text and search evidence.",
|
|
1112
|
+
},
|
|
1113
|
+
},
|
|
1114
|
+
};
|
|
1115
|
+
}
|
|
466
1116
|
async function classifyPerplexity(route, input, apiKey, signal) {
|
|
467
1117
|
const state = perplexityState(input);
|
|
468
|
-
const
|
|
1118
|
+
const payload = {
|
|
469
1119
|
model: route.model,
|
|
470
1120
|
state,
|
|
471
1121
|
questions: systemOneQuestions(input.questions, false),
|
|
472
|
-
}
|
|
1122
|
+
};
|
|
1123
|
+
if (input.mode !== undefined)
|
|
1124
|
+
payload.mode = input.mode;
|
|
1125
|
+
const { body, requestId } = await postJson(route, "decisions", payload, apiKey, signal);
|
|
473
1126
|
if (!isRecord(body))
|
|
474
1127
|
fail(PERPLEXITY_LABEL + " returned an unexpected response.");
|
|
475
|
-
|
|
1128
|
+
const searches = parseSearchResults(body.search_results);
|
|
1129
|
+
const fetched = parseFetchedResults(body.fetched_results);
|
|
1130
|
+
const snippets = searches.map((result) => result.snippet);
|
|
1131
|
+
const sources = { snippets };
|
|
1132
|
+
if (typeof input.state === "string")
|
|
1133
|
+
sources.state = input.state;
|
|
1134
|
+
const result = finish(route, parseTypedAnswers(PERPLEXITY_LABEL, body.answers, input.questions, sources), body.usage, requestId);
|
|
1135
|
+
if (input.mode === "web_grounding") {
|
|
1136
|
+
result.webGrounding = { searchResults: searches };
|
|
1137
|
+
if (fetched.length > 0)
|
|
1138
|
+
result.webGrounding.fetchedResults = fetched;
|
|
1139
|
+
result.cost = withWebGroundingCost(result.cost, Object.keys(input.questions).length, fetched.length);
|
|
1140
|
+
}
|
|
1141
|
+
return result;
|
|
1142
|
+
}
|
|
1143
|
+
/* Sarvam Prism Decisions API ---------------------------------------------- */
|
|
1144
|
+
const SARVAM_REQUEST_ID_PATTERN = /^[A-Za-z0-9_.:-]{1,128}$/;
|
|
1145
|
+
function sarvamSafeDetail(value, apiKey, pattern) {
|
|
1146
|
+
if (typeof value !== "string" || !pattern.test(value))
|
|
1147
|
+
return undefined;
|
|
1148
|
+
return apiKey.length > 0 && value.includes(apiKey) ? undefined : value;
|
|
1149
|
+
}
|
|
1150
|
+
const sarvamHeaderRequestId = (value, apiKey) => sarvamSafeDetail(value, apiKey, SARVAM_REQUEST_ID_PATTERN);
|
|
1151
|
+
const sarvamErrorDetail = (status, body, apiKey) => {
|
|
1152
|
+
if (!isRecord(body) || !isRecord(body.error))
|
|
1153
|
+
return undefined;
|
|
1154
|
+
const error = body.error;
|
|
1155
|
+
const code = typeof error.code === "string" &&
|
|
1156
|
+
[
|
|
1157
|
+
"invalid_request_error",
|
|
1158
|
+
"insufficient_quota_error",
|
|
1159
|
+
"invalid_api_key_error",
|
|
1160
|
+
"not_found_error",
|
|
1161
|
+
"unprocessable_entity_error",
|
|
1162
|
+
"rate_limit_exceeded_error",
|
|
1163
|
+
"internal_server_error",
|
|
1164
|
+
"model_call_failed",
|
|
1165
|
+
"model_overloaded",
|
|
1166
|
+
].includes(error.code)
|
|
1167
|
+
? error.code
|
|
1168
|
+
: undefined;
|
|
1169
|
+
const param = sarvamSafeDetail(error.param, apiKey, /^[A-Za-z0-9_.:-]{1,256}$/);
|
|
1170
|
+
const requestId = sarvamSafeDetail(error.request_id, apiKey, SARVAM_REQUEST_ID_PATTERN);
|
|
1171
|
+
if (!code && !param && !requestId)
|
|
1172
|
+
return undefined;
|
|
1173
|
+
const summaries = {
|
|
1174
|
+
402: "Sarvam reported insufficient quota.",
|
|
1175
|
+
403: "Sarvam rejected the API key.",
|
|
1176
|
+
404: "Sarvam does not recognize the selected model.",
|
|
1177
|
+
422: "Sarvam rejected the request shape.",
|
|
1178
|
+
429: "Sarvam rate-limited the request.",
|
|
1179
|
+
500: "Sarvam reported an internal error.",
|
|
1180
|
+
502: "Sarvam could not reach the decision model.",
|
|
1181
|
+
503: "Sarvam reported that the model is overloaded.",
|
|
1182
|
+
};
|
|
1183
|
+
let detail = summaries[status] ?? "Sarvam rejected the request.";
|
|
1184
|
+
if (code)
|
|
1185
|
+
detail += " Code: " + code + ".";
|
|
1186
|
+
if (param)
|
|
1187
|
+
detail += " Field: " + param + ".";
|
|
1188
|
+
if (requestId)
|
|
1189
|
+
detail += " Request ID: " + requestId + ".";
|
|
1190
|
+
return detail;
|
|
1191
|
+
};
|
|
1192
|
+
function sarvamRequestId(body, apiKey) {
|
|
1193
|
+
return sarvamSafeDetail(body.request_id, apiKey, SARVAM_REQUEST_ID_PATTERN);
|
|
1194
|
+
}
|
|
1195
|
+
function sarvamQuestion(id, question, minimumChoices) {
|
|
1196
|
+
if (question.type !== "bool" && question.type !== "choice" && question.type !== "score")
|
|
1197
|
+
throw new ClassifierError("capability", "The selected route does not support " + question.type + " questions.");
|
|
1198
|
+
const wire = {
|
|
1199
|
+
type: question.type === "bool" ? "noul" : question.type,
|
|
1200
|
+
instructions: textContent(question.instructions),
|
|
1201
|
+
};
|
|
1202
|
+
if (question.type === "bool") {
|
|
1203
|
+
if (question.criteria !== undefined)
|
|
1204
|
+
wire.criteria = Object.fromEntries(Object.entries(question.criteria).map(([key, value]) => [key, textContent(value)]));
|
|
1205
|
+
return wire;
|
|
1206
|
+
}
|
|
1207
|
+
if (question.type === "choice") {
|
|
1208
|
+
const entries = Object.entries(question.criteria);
|
|
1209
|
+
if (entries.length < minimumChoices || entries.length > 255)
|
|
1210
|
+
throw new ClassifierError("input", "Sarvam requires " + minimumChoices + " to 255 options for choice question " + id + ".");
|
|
1211
|
+
wire.criteria = Object.fromEntries(entries.map(([key, value]) => [key, textContent(value)]));
|
|
1212
|
+
return wire;
|
|
1213
|
+
}
|
|
1214
|
+
if (question.criteria.length < 2 || question.criteria.length > 10)
|
|
1215
|
+
throw new ClassifierError("input", "Sarvam Prism requires 2 to 10 levels for score question " + id + ".");
|
|
1216
|
+
wire.criteria = question.criteria.map(textContent);
|
|
1217
|
+
return wire;
|
|
1218
|
+
}
|
|
1219
|
+
function sarvamAnswers(value, questions) {
|
|
1220
|
+
if (!isRecord(value))
|
|
1221
|
+
fail(SARVAM_LABEL + " returned an unexpected response.");
|
|
1222
|
+
const answers = Object.create(null);
|
|
1223
|
+
for (const [id, question] of Object.entries(questions)) {
|
|
1224
|
+
if (!Object.hasOwn(value, id))
|
|
1225
|
+
fail(SARVAM_LABEL + " did not return an answer for " + id + ".");
|
|
1226
|
+
const raw = value[id];
|
|
1227
|
+
if (question.type === "score" && isRecord(raw) && raw.probabilities === undefined)
|
|
1228
|
+
fail(SARVAM_LABEL + " did not return probabilities for score question " + id + ".");
|
|
1229
|
+
const expected = question.type === "bool" ? "noul" : question.type;
|
|
1230
|
+
answers[id] =
|
|
1231
|
+
isRecord(raw) && raw.type === undefined ? { ...raw, type: expected } : raw;
|
|
1232
|
+
}
|
|
1233
|
+
return parseTypedAnswers(SARVAM_LABEL, answers, questions);
|
|
1234
|
+
}
|
|
1235
|
+
async function classifySarvam(route, input, apiKey, signal) {
|
|
1236
|
+
const isClef = route.model === "clef";
|
|
1237
|
+
if (!isClef && (input.images.length > 0 || input.media.length > 0))
|
|
1238
|
+
throw new ClassifierError("capability", "Sarvam Prism accepts text/JSON only; Sarvam Clef accepts base64 images.");
|
|
1239
|
+
if (input.media.length > 0 || input.mode !== undefined)
|
|
1240
|
+
throw new ClassifierError("capability", "Sarvam does not accept media or web grounding.");
|
|
1241
|
+
const questions = Object.create(null);
|
|
1242
|
+
for (const [id, question] of Object.entries(input.questions))
|
|
1243
|
+
questions[id] = sarvamQuestion(id, question, isClef ? 1 : 2);
|
|
1244
|
+
const payload = { model: route.model, state: input.state, questions };
|
|
1245
|
+
if (isClef && input.images.length > 0)
|
|
1246
|
+
payload.images = input.images.map((image) => {
|
|
1247
|
+
if ("url" in image)
|
|
1248
|
+
throw new ClassifierError("capability", "Sarvam Clef requires local image data.");
|
|
1249
|
+
return imageUrl(image);
|
|
1250
|
+
});
|
|
1251
|
+
const { body, requestId } = await postJson(route, "systemone", payload, apiKey, signal, undefined, sarvamErrorDetail, sarvamHeaderRequestId);
|
|
1252
|
+
if (!isRecord(body))
|
|
1253
|
+
fail(SARVAM_LABEL + " returned an unexpected response.");
|
|
1254
|
+
if (body.model !== undefined && body.model !== route.model)
|
|
1255
|
+
fail(SARVAM_LABEL + " returned a model that does not match the selected route.");
|
|
1256
|
+
if (!isRecord(body.answers))
|
|
1257
|
+
fail(SARVAM_LABEL + " returned an unexpected response.");
|
|
1258
|
+
return finish(route, sarvamAnswers(body.answers, input.questions), body.usage, requestId ?? sarvamRequestId(body, apiKey));
|
|
476
1259
|
}
|
|
477
1260
|
/* Microsoft Foundry Decision-1 (text/JSON, API-key authentication) -------- */
|
|
478
1261
|
async function classifyMicrosoft(route, input, apiKey, signal) {
|
|
479
|
-
const label = "Microsoft Decision-1";
|
|
480
|
-
const
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
1262
|
+
const label = "Microsoft Foundry Decision-1.1";
|
|
1263
|
+
const assets = Object.create(null);
|
|
1264
|
+
const sharedRefs = [];
|
|
1265
|
+
const namedRefs = new Map();
|
|
1266
|
+
const used = new Set([...imageReferences(input.state), ...questionImageReferences(input.questions)]);
|
|
1267
|
+
for (const image of input.images) {
|
|
1268
|
+
if ("url" in image)
|
|
1269
|
+
throw new ClassifierError("capability", "Microsoft image assets require local images.");
|
|
1270
|
+
// Batching can remove a question or a criterion; unused assets are rejected upstream.
|
|
1271
|
+
if (image.id !== undefined && !used.has(image.id))
|
|
1272
|
+
continue;
|
|
1273
|
+
const ref = randomUUID();
|
|
1274
|
+
if (image.id === undefined)
|
|
1275
|
+
sharedRefs.push("image:" + ref);
|
|
1276
|
+
else
|
|
1277
|
+
namedRefs.set(image.id, ref);
|
|
1278
|
+
assets[ref] = {
|
|
1279
|
+
type: "image",
|
|
1280
|
+
format: image.mimeType === "image/png" ? "png" : "jpg",
|
|
1281
|
+
data_base64: image.data,
|
|
1282
|
+
};
|
|
1283
|
+
}
|
|
1284
|
+
const reference = (id) => {
|
|
1285
|
+
const ref = namedRefs.get(id);
|
|
1286
|
+
if (!ref)
|
|
1287
|
+
throw new ClassifierError("input", "Unknown named image reference.");
|
|
1288
|
+
return "image:" + ref;
|
|
1289
|
+
};
|
|
1290
|
+
let state = mapImageReferences(input.state, reference);
|
|
1291
|
+
if (sharedRefs.length > 0) {
|
|
1292
|
+
if (typeof state === "string")
|
|
1293
|
+
state = state + "\n" + sharedRefs.join(" ");
|
|
1294
|
+
else if (isRecord(state))
|
|
1295
|
+
state = { ...state, images: sharedRefs };
|
|
1296
|
+
else
|
|
1297
|
+
state = { state, images: sharedRefs };
|
|
1298
|
+
}
|
|
1299
|
+
const payload = {
|
|
1300
|
+
model: route.model, // Foundry deployment name, not necessarily the underlying model ID.
|
|
1301
|
+
state,
|
|
1302
|
+
questions: systemOneQuestions(input.questions, false, (value) => mapImageReferences(value, reference)),
|
|
1303
|
+
};
|
|
1304
|
+
if (Object.keys(assets).length > 0)
|
|
1305
|
+
payload.assets = assets;
|
|
1306
|
+
const { body, requestId } = await postJson(route, "providers/microsoft/v1/systemone", payload, apiKey, signal);
|
|
485
1307
|
if (!isRecord(body) || !isRecord(body.answers))
|
|
486
1308
|
fail(label + " returned an unexpected response.");
|
|
487
1309
|
// Some System One endpoints omit confidence; derive it only from validated probabilities.
|
|
@@ -553,8 +1375,11 @@ async function classifySystemOne(route, input, apiKey, signal) {
|
|
|
553
1375
|
payload.assets = assets;
|
|
554
1376
|
const experimentalHeader = Object.keys(assets).length > 0 ||
|
|
555
1377
|
Object.values(input.questions).some((question) => question.type === "box");
|
|
556
|
-
const extraHeaders = experimentalHeader
|
|
557
|
-
? {
|
|
1378
|
+
const extraHeaders = experimentalHeader || route.longContext
|
|
1379
|
+
? {
|
|
1380
|
+
...(experimentalHeader ? { "TypeSafe-Danger-Zone-Images": "true" } : {}),
|
|
1381
|
+
...(route.longContext ? { "TypeSafe-Danger-Zone-Long-Context": "true" } : {}),
|
|
1382
|
+
}
|
|
558
1383
|
: undefined;
|
|
559
1384
|
const { body, requestId } = await postJson(route, "systemone", payload, apiKey, signal, extraHeaders);
|
|
560
1385
|
if (!isRecord(body))
|
|
@@ -563,9 +1388,12 @@ async function classifySystemOne(route, input, apiKey, signal) {
|
|
|
563
1388
|
}
|
|
564
1389
|
/* Cloudflare Workers AI (Clef and third-party System One envelopes) ------- */
|
|
565
1390
|
function clefBodyModel(model) {
|
|
566
|
-
return /^@cf\/cloudflare\/(clef(?:-flash)?)$/.exec(model)?.[1];
|
|
1391
|
+
return /^@cf\/cloudflare\/(clef(?:-flash|-omni)?)$/.exec(model)?.[1];
|
|
1392
|
+
}
|
|
1393
|
+
function cloudflareMedia(media) {
|
|
1394
|
+
return media.map((entry) => ({ content_type: entry.mimeType, base64: entry.data }));
|
|
567
1395
|
}
|
|
568
|
-
function unwrapCloudflare(label, body) {
|
|
1396
|
+
export function unwrapCloudflare(label, body) {
|
|
569
1397
|
if (!isRecord(body))
|
|
570
1398
|
fail(label + " returned an unexpected response.");
|
|
571
1399
|
if (body.success === false)
|
|
@@ -602,11 +1430,17 @@ async function classifyCloudflare(route, input, apiKey, signal) {
|
|
|
602
1430
|
return { content_type: image.mimeType, base64: image.data };
|
|
603
1431
|
});
|
|
604
1432
|
}
|
|
1433
|
+
const audio = input.media.filter((media) => media.type === "audio");
|
|
1434
|
+
const videos = input.media.filter((media) => media.type === "video");
|
|
1435
|
+
if (audio.length)
|
|
1436
|
+
payload.audio = cloudflareMedia(audio);
|
|
1437
|
+
if (videos.length)
|
|
1438
|
+
payload.videos = cloudflareMedia(videos);
|
|
605
1439
|
path = "run/" + route.model;
|
|
606
1440
|
}
|
|
607
1441
|
else {
|
|
608
|
-
if (input.images.length > 0)
|
|
609
|
-
throw new ClassifierError("capability", "The selected route does not support
|
|
1442
|
+
if (input.images.length > 0 || input.media.length > 0)
|
|
1443
|
+
throw new ClassifierError("capability", "The selected route does not support media for this model.");
|
|
610
1444
|
payload = {
|
|
611
1445
|
model: route.model,
|
|
612
1446
|
input: {
|
|
@@ -625,3 +1459,260 @@ async function classifyCloudflare(route, input, apiKey, signal) {
|
|
|
625
1459
|
: undefined;
|
|
626
1460
|
return finish(route, parseTypedAnswers(CLOUDFLARE_LABEL, result.answers, input.questions), usage, requestId);
|
|
627
1461
|
}
|
|
1462
|
+
/* Liquid d1.2 System One extension --------------------------------------- */
|
|
1463
|
+
function liquidUnsupported(feature) {
|
|
1464
|
+
throw new ClassifierError("capability", "The selected route does not support " + feature + ".");
|
|
1465
|
+
}
|
|
1466
|
+
function liquidQuestion(id, question) {
|
|
1467
|
+
if (question.type === "extract")
|
|
1468
|
+
return liquidUnsupported("extract questions on Liquid routes");
|
|
1469
|
+
const wire = {
|
|
1470
|
+
type: question.type === "bool" ? "noul" : question.type,
|
|
1471
|
+
instructions: textContent(question.instructions),
|
|
1472
|
+
};
|
|
1473
|
+
switch (question.type) {
|
|
1474
|
+
case "bool":
|
|
1475
|
+
if (question.criteria)
|
|
1476
|
+
wire.criteria = Object.fromEntries(Object.entries(question.criteria).map(([key, value]) => [key, textContent(value)]));
|
|
1477
|
+
return wire;
|
|
1478
|
+
case "choice":
|
|
1479
|
+
case "multi_choice":
|
|
1480
|
+
wire.type = "choice";
|
|
1481
|
+
wire.criteria = Object.fromEntries(Object.entries(question.criteria).map(([key, value]) => [key, textContent(value)]));
|
|
1482
|
+
if (question.type === "multi_choice")
|
|
1483
|
+
wire.multiple = true;
|
|
1484
|
+
return wire;
|
|
1485
|
+
case "score":
|
|
1486
|
+
wire.criteria = question.criteria.map(textContent);
|
|
1487
|
+
return wire;
|
|
1488
|
+
case "number":
|
|
1489
|
+
if (question.unit !== undefined)
|
|
1490
|
+
wire.unit = question.unit;
|
|
1491
|
+
if (question.range !== undefined)
|
|
1492
|
+
wire.range = question.range;
|
|
1493
|
+
if (question.step !== undefined)
|
|
1494
|
+
wire.step = question.step;
|
|
1495
|
+
return wire;
|
|
1496
|
+
case "spans":
|
|
1497
|
+
case "boxes":
|
|
1498
|
+
if (question.max !== undefined)
|
|
1499
|
+
wire.max = question.max;
|
|
1500
|
+
return wire;
|
|
1501
|
+
case "estimate":
|
|
1502
|
+
wire.type = "number";
|
|
1503
|
+
wire.range = question.range;
|
|
1504
|
+
if (question.step !== undefined)
|
|
1505
|
+
wire.step = question.step;
|
|
1506
|
+
if (question.unit !== undefined)
|
|
1507
|
+
wire.unit = question.unit;
|
|
1508
|
+
return wire;
|
|
1509
|
+
case "text":
|
|
1510
|
+
case "date":
|
|
1511
|
+
case "box":
|
|
1512
|
+
return wire;
|
|
1513
|
+
case "locate":
|
|
1514
|
+
return liquidUnsupported("locate questions on Liquid routes");
|
|
1515
|
+
}
|
|
1516
|
+
}
|
|
1517
|
+
function stateText(state) {
|
|
1518
|
+
return typeof state === "string" ? state : JSON.stringify(state, null, 2);
|
|
1519
|
+
}
|
|
1520
|
+
function optionalCharSpan(label, value, field, text) {
|
|
1521
|
+
if (value === undefined)
|
|
1522
|
+
return undefined;
|
|
1523
|
+
if (value === null)
|
|
1524
|
+
return null;
|
|
1525
|
+
return charSpan(label, value, field, text);
|
|
1526
|
+
}
|
|
1527
|
+
function charSpan(label, value, field, text) {
|
|
1528
|
+
if (!Array.isArray(value) || value.length !== 2 ||
|
|
1529
|
+
value.some((entry) => !Number.isSafeInteger(entry) || entry < 0))
|
|
1530
|
+
fail(label + " returned an invalid " + field + ".");
|
|
1531
|
+
const start = value[0];
|
|
1532
|
+
const end = value[1];
|
|
1533
|
+
if (end < start || codePointSlice(text, start, end).length === 0 && end !== start)
|
|
1534
|
+
fail(label + " returned an invalid " + field + ".");
|
|
1535
|
+
return [start, end];
|
|
1536
|
+
}
|
|
1537
|
+
function optionalFound(label, answer, id) {
|
|
1538
|
+
return answer.found === undefined ? undefined : probability(label, answer.found, "found for " + id);
|
|
1539
|
+
}
|
|
1540
|
+
function optionalPath(label, answer, id) {
|
|
1541
|
+
if (answer.path === undefined)
|
|
1542
|
+
return undefined;
|
|
1543
|
+
if (typeof answer.path !== "string" || (answer.path !== "" && !answer.path.startsWith("/")))
|
|
1544
|
+
fail(label + " returned an invalid JSON pointer for " + id + ".");
|
|
1545
|
+
return answer.path;
|
|
1546
|
+
}
|
|
1547
|
+
function parseLiquidAnswer(label, id, question, answer, text) {
|
|
1548
|
+
if (!isRecord(answer))
|
|
1549
|
+
fail(label + " returned an invalid answer for " + id + ".");
|
|
1550
|
+
if (answer.type === "refusal")
|
|
1551
|
+
return { type: "refusal" };
|
|
1552
|
+
if (question.type === "bool" || question.type === "choice" || question.type === "score")
|
|
1553
|
+
return validateDecision(label, id, parseTypedAnswer(label, id, question, answer));
|
|
1554
|
+
const found = optionalFound(label, answer, id);
|
|
1555
|
+
if (question.type === "text") {
|
|
1556
|
+
if (typeof answer.text !== "string")
|
|
1557
|
+
fail(label + " returned an invalid text answer for " + id + ".");
|
|
1558
|
+
const result = { type: "text", text: answer.text };
|
|
1559
|
+
const span = optionalCharSpan(label, answer.span, "span for " + id, text);
|
|
1560
|
+
if (span !== undefined)
|
|
1561
|
+
result.span = span;
|
|
1562
|
+
if (found !== undefined)
|
|
1563
|
+
result.found = found;
|
|
1564
|
+
const path = optionalPath(label, answer, id);
|
|
1565
|
+
if (path !== undefined)
|
|
1566
|
+
result.path = path;
|
|
1567
|
+
return result;
|
|
1568
|
+
}
|
|
1569
|
+
if (question.type === "number") {
|
|
1570
|
+
if (answer.number !== null && (typeof answer.number !== "number" || !Number.isFinite(answer.number)))
|
|
1571
|
+
fail(label + " returned an invalid number answer for " + id + ".");
|
|
1572
|
+
const value = typeof answer.number === "number" ? answer.number : null;
|
|
1573
|
+
const result = { type: "number", value };
|
|
1574
|
+
if (typeof answer.unit === "string" || answer.unit === null)
|
|
1575
|
+
result.unit = answer.unit;
|
|
1576
|
+
if (typeof answer.text === "string" || answer.text === null)
|
|
1577
|
+
result.text = answer.text;
|
|
1578
|
+
const span = optionalCharSpan(label, answer.span, "span for " + id, text);
|
|
1579
|
+
if (span !== undefined)
|
|
1580
|
+
result.span = span;
|
|
1581
|
+
if (found !== undefined)
|
|
1582
|
+
result.found = found;
|
|
1583
|
+
const path = optionalPath(label, answer, id);
|
|
1584
|
+
if (path !== undefined)
|
|
1585
|
+
result.path = path;
|
|
1586
|
+
return result;
|
|
1587
|
+
}
|
|
1588
|
+
if (question.type === "date") {
|
|
1589
|
+
if (answer.date !== null && (typeof answer.date !== "string" || !/^\d{4}-\d{2}-\d{2}$/.test(answer.date)))
|
|
1590
|
+
fail(label + " returned an invalid date answer for " + id + ".");
|
|
1591
|
+
const date = typeof answer.date === "string" ? answer.date : null;
|
|
1592
|
+
const result = { type: "date", date };
|
|
1593
|
+
if (typeof answer.text === "string" || answer.text === null)
|
|
1594
|
+
result.text = answer.text;
|
|
1595
|
+
const span = optionalCharSpan(label, answer.span, "span for " + id, text);
|
|
1596
|
+
if (span !== undefined)
|
|
1597
|
+
result.span = span;
|
|
1598
|
+
if (found !== undefined)
|
|
1599
|
+
result.found = found;
|
|
1600
|
+
const path = optionalPath(label, answer, id);
|
|
1601
|
+
if (path !== undefined)
|
|
1602
|
+
result.path = path;
|
|
1603
|
+
return result;
|
|
1604
|
+
}
|
|
1605
|
+
if (question.type === "spans") {
|
|
1606
|
+
if (!Array.isArray(answer.spans) || !Array.isArray(answer.presence) ||
|
|
1607
|
+
!Number.isSafeInteger(answer.count) || answer.count < 0 ||
|
|
1608
|
+
typeof answer.at_least !== "boolean")
|
|
1609
|
+
fail(label + " returned an invalid spans answer for " + id + ".");
|
|
1610
|
+
const presence = answer.presence.map((entry) => probability(label, entry, "presence for " + id));
|
|
1611
|
+
return {
|
|
1612
|
+
type: "spans",
|
|
1613
|
+
spans: answer.spans.map((entry) => {
|
|
1614
|
+
if (!isRecord(entry) || typeof entry.text !== "string")
|
|
1615
|
+
fail(label + " returned an invalid span for " + id + ".");
|
|
1616
|
+
return {
|
|
1617
|
+
text: entry.text,
|
|
1618
|
+
span: charSpan(label, entry.span, "span for " + id, text),
|
|
1619
|
+
found: probability(label, entry.found, "span found for " + id),
|
|
1620
|
+
};
|
|
1621
|
+
}),
|
|
1622
|
+
count: answer.count,
|
|
1623
|
+
atLeast: answer.at_least,
|
|
1624
|
+
presence,
|
|
1625
|
+
};
|
|
1626
|
+
}
|
|
1627
|
+
if (question.type === "boxes") {
|
|
1628
|
+
if (!Array.isArray(answer.boxes) || !Array.isArray(answer.presence) ||
|
|
1629
|
+
!Number.isSafeInteger(answer.count) || answer.count < 0 ||
|
|
1630
|
+
typeof answer.at_least !== "boolean")
|
|
1631
|
+
fail(label + " returned an invalid boxes answer for " + id + ".");
|
|
1632
|
+
const presence = answer.presence.map((entry) => probability(label, entry, "presence for " + id));
|
|
1633
|
+
return {
|
|
1634
|
+
type: "boxes",
|
|
1635
|
+
boxes: answer.boxes.map((entry) => {
|
|
1636
|
+
const parsed = parseBox(label, id, isRecord(entry) ? entry.box : undefined, isRecord(entry) ? entry.found : undefined);
|
|
1637
|
+
if (parsed.type !== "box")
|
|
1638
|
+
fail(label + " returned an invalid box for " + id + ".");
|
|
1639
|
+
return {
|
|
1640
|
+
box: parsed.box,
|
|
1641
|
+
found: parsed.confidence,
|
|
1642
|
+
confidence: probability(label, isRecord(entry) ? entry.confidence : undefined, "box confidence for " + id),
|
|
1643
|
+
};
|
|
1644
|
+
}),
|
|
1645
|
+
count: answer.count,
|
|
1646
|
+
atLeast: answer.at_least,
|
|
1647
|
+
presence,
|
|
1648
|
+
};
|
|
1649
|
+
}
|
|
1650
|
+
if (question.type === "estimate") {
|
|
1651
|
+
const value = answer.number;
|
|
1652
|
+
if (typeof value !== "number" || !Number.isFinite(value) || !Array.isArray(answer.interval) ||
|
|
1653
|
+
answer.interval.length !== 2 ||
|
|
1654
|
+
answer.interval.some((entry) => typeof entry !== "number" || !Number.isFinite(entry)) ||
|
|
1655
|
+
answer.interval[0] > value || value > answer.interval[1])
|
|
1656
|
+
fail(label + " returned an invalid estimate for " + id + ".");
|
|
1657
|
+
const result = {
|
|
1658
|
+
type: "estimate",
|
|
1659
|
+
value,
|
|
1660
|
+
interval: [answer.interval[0], answer.interval[1]],
|
|
1661
|
+
};
|
|
1662
|
+
if (typeof answer.unit === "string")
|
|
1663
|
+
result.unit = answer.unit;
|
|
1664
|
+
return result;
|
|
1665
|
+
}
|
|
1666
|
+
if (question.type === "multi_choice") {
|
|
1667
|
+
if (!Array.isArray(answer.choices) || !isRecord(answer.probabilities))
|
|
1668
|
+
fail(label + " returned an invalid multi-choice answer for " + id + ".");
|
|
1669
|
+
const labels = Object.keys(question.criteria);
|
|
1670
|
+
const choices = independentLabelProbabilities(label, id, answer.probabilities, labels);
|
|
1671
|
+
for (const choice of answer.choices) {
|
|
1672
|
+
if (typeof choice !== "string" || !Object.hasOwn(question.criteria, choice))
|
|
1673
|
+
fail(label + " returned an unknown choice for " + id + ".");
|
|
1674
|
+
}
|
|
1675
|
+
return { type: "multi_choice", choices: answer.choices, probabilities: choices };
|
|
1676
|
+
}
|
|
1677
|
+
if (question.type === "box") {
|
|
1678
|
+
if (answer.box === null || (found !== undefined && found < 0.5))
|
|
1679
|
+
return { type: "no_match" };
|
|
1680
|
+
const parsed = parseBox(label, id, answer.box, answer.confidence);
|
|
1681
|
+
if (parsed.type !== "box")
|
|
1682
|
+
fail(label + " returned an invalid box for " + id + ".");
|
|
1683
|
+
return found === undefined ? parsed : { ...parsed, found };
|
|
1684
|
+
}
|
|
1685
|
+
return liquidUnsupported("question type " + question.type);
|
|
1686
|
+
}
|
|
1687
|
+
async function classifyLiquid(route, input, apiKey, signal) {
|
|
1688
|
+
if (Object.values(input.questions).some((question) => question.type === "locate"))
|
|
1689
|
+
return liquidUnsupported("locate questions on Liquid routes");
|
|
1690
|
+
const payload = {
|
|
1691
|
+
model: route.model,
|
|
1692
|
+
state: input.state,
|
|
1693
|
+
questions: Object.fromEntries(Object.entries(input.questions).map(([id, question]) => [id, liquidQuestion(id, question)])),
|
|
1694
|
+
};
|
|
1695
|
+
if (input.images.length) {
|
|
1696
|
+
payload.images = input.images.map((image) => {
|
|
1697
|
+
if ("url" in image)
|
|
1698
|
+
throw new ClassifierError("capability", "Liquid requires local images.");
|
|
1699
|
+
return { content_type: image.mimeType, base64: image.data };
|
|
1700
|
+
});
|
|
1701
|
+
}
|
|
1702
|
+
const audio = input.media.filter((media) => media.type === "audio");
|
|
1703
|
+
if (audio.length)
|
|
1704
|
+
payload.audio = audio.map((media) => ({ content_type: media.mimeType, base64: media.data }));
|
|
1705
|
+
const { body, requestId } = await postJson(route, "systemone", payload, apiKey, signal);
|
|
1706
|
+
if (!isRecord(body))
|
|
1707
|
+
fail("Liquid Decisions returned an unexpected response.");
|
|
1708
|
+
const text = stateText(input.state);
|
|
1709
|
+
const answers = Object.create(null);
|
|
1710
|
+
for (const [id, question] of Object.entries(input.questions)) {
|
|
1711
|
+
if (!isRecord(body.answers) || !Object.hasOwn(body.answers, id))
|
|
1712
|
+
fail("Liquid Decisions did not return an answer for " + id + ".");
|
|
1713
|
+
const parsed = parseLiquidAnswer("Liquid Decisions", id, question, body.answers[id], text);
|
|
1714
|
+
if (parsed !== undefined)
|
|
1715
|
+
answers[id] = parsed;
|
|
1716
|
+
}
|
|
1717
|
+
return finish(route, answers, body.usage, requestId);
|
|
1718
|
+
}
|