@abhishek944/pi-classifier 0.0.0-stage → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +37 -0
- package/LICENSE +201 -0
- package/README.md +425 -2
- package/THIRD_PARTY_NOTICES.md +48 -0
- package/dist/auth.d.ts +5 -0
- package/dist/auth.js +56 -0
- package/dist/choices.d.ts +8 -0
- package/dist/choices.js +131 -0
- package/dist/classification-tree.d.ts +4 -0
- package/dist/classification-tree.js +143 -0
- package/dist/classify.d.ts +10 -0
- package/dist/classify.js +120 -0
- package/dist/config.d.ts +82 -0
- package/dist/config.js +338 -0
- package/dist/cost.d.ts +8 -0
- package/dist/cost.js +202 -0
- package/dist/extension.d.ts +249 -0
- package/dist/extension.js +380 -0
- package/dist/http.d.ts +5 -0
- package/dist/http.js +85 -0
- package/dist/index.d.ts +5 -0
- package/dist/index.js +4 -0
- package/dist/inputs.d.ts +4 -0
- package/dist/inputs.js +184 -0
- package/dist/providers.d.ts +2 -0
- package/dist/providers.js +624 -0
- package/dist/settings-write.d.ts +10 -0
- package/dist/settings-write.js +110 -0
- package/dist/tree.d.ts +4 -0
- package/dist/tree.js +136 -0
- package/dist/types.d.ts +228 -0
- package/dist/types.js +18 -0
- package/dist/validation.d.ts +3 -0
- package/dist/validation.js +94 -0
- package/package.json +72 -4
- package/src/auth.ts +74 -0
- package/src/choices.ts +173 -0
- package/src/classification-tree.ts +181 -0
- package/src/classify.ts +167 -0
- package/src/config.ts +442 -0
- package/src/cost.ts +250 -0
- package/src/extension.ts +511 -0
- package/src/http.ts +108 -0
- package/src/index.ts +25 -0
- package/src/inputs.ts +239 -0
- package/src/providers.ts +905 -0
- package/src/settings-write.ts +145 -0
- package/src/tree.ts +157 -0
- package/src/types.ts +248 -0
- package/src/validation.ts +138 -0
package/src/providers.ts
ADDED
|
@@ -0,0 +1,905 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { postJson } from "./http.js";
|
|
3
|
+
import { estimateCost, tokenCount } from "./cost.js";
|
|
4
|
+
import {
|
|
5
|
+
ClassifierError,
|
|
6
|
+
isRecord,
|
|
7
|
+
type Answer,
|
|
8
|
+
type ClassifierResult,
|
|
9
|
+
type PreparedImage,
|
|
10
|
+
type PreparedInput,
|
|
11
|
+
type Question,
|
|
12
|
+
type ResolvedModel,
|
|
13
|
+
} from "./types.js";
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Provider protocol adapters. Every request goes through the shared `postJson` boundary, which
|
|
17
|
+
* owns timeouts, cancellation, bounded reads and safe errors. Each adapter call classifies once;
|
|
18
|
+
* route orchestration belongs to classify.ts. Answers are rebuilt field by field from validated values, so raw provider
|
|
19
|
+
* bodies and provider error text never reach callers.
|
|
20
|
+
*/
|
|
21
|
+
|
|
22
|
+
const OPENAI_LABEL = "OpenAI Decisions";
|
|
23
|
+
const PERPLEXITY_LABEL = "Perplexity Decisions";
|
|
24
|
+
const TYPESAFE_LABEL = "TypeSafe System One";
|
|
25
|
+
const CLOUDFLARE_LABEL = "Cloudflare Workers AI";
|
|
26
|
+
const EPSILON = 1e-6;
|
|
27
|
+
const DISTRIBUTION_TOLERANCE = 0.01;
|
|
28
|
+
|
|
29
|
+
export async function classifyWithProvider(
|
|
30
|
+
route: ResolvedModel,
|
|
31
|
+
input: PreparedInput,
|
|
32
|
+
apiKey: string,
|
|
33
|
+
signal?: AbortSignal,
|
|
34
|
+
): Promise<ClassifierResult> {
|
|
35
|
+
switch (route.api) {
|
|
36
|
+
case "openai-decisions":
|
|
37
|
+
return classifyOpenAi(route, input, apiKey, signal);
|
|
38
|
+
case "perplexity-decisions":
|
|
39
|
+
return classifyPerplexity(route, input, apiKey, signal);
|
|
40
|
+
case "system-one":
|
|
41
|
+
return classifySystemOne(route, input, apiKey, signal);
|
|
42
|
+
case "microsoft-system-one":
|
|
43
|
+
return classifyMicrosoft(route, input, apiKey, signal);
|
|
44
|
+
case "cloudflare-system-one":
|
|
45
|
+
return classifyCloudflare(route, input, apiKey, signal);
|
|
46
|
+
default:
|
|
47
|
+
throw new ClassifierError(
|
|
48
|
+
"configuration",
|
|
49
|
+
"Unsupported classifier API protocol.",
|
|
50
|
+
);
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/* Shared validation ------------------------------------------------------- */
|
|
55
|
+
|
|
56
|
+
function fail(message: string): never {
|
|
57
|
+
throw new ClassifierError("response", message);
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function unsupportedBox(): ClassifierError {
|
|
61
|
+
return new ClassifierError(
|
|
62
|
+
"capability",
|
|
63
|
+
"The selected route does not support box questions. Box requires an experimental Jev 1.14 route with images enabled.",
|
|
64
|
+
);
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
function probability(label: string, value: unknown, field: string): number {
|
|
68
|
+
if (
|
|
69
|
+
typeof value !== "number" ||
|
|
70
|
+
!Number.isFinite(value) ||
|
|
71
|
+
value < 0 ||
|
|
72
|
+
value > 1
|
|
73
|
+
)
|
|
74
|
+
fail(label + " returned an invalid " + field + ".");
|
|
75
|
+
return value;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function unitInterval(label: string, value: unknown, field: string): number {
|
|
79
|
+
if (
|
|
80
|
+
typeof value !== "number" ||
|
|
81
|
+
!Number.isFinite(value) ||
|
|
82
|
+
value < -EPSILON ||
|
|
83
|
+
value > 1 + EPSILON
|
|
84
|
+
) {
|
|
85
|
+
fail(label + " returned an invalid " + field + ".");
|
|
86
|
+
}
|
|
87
|
+
return Math.min(1, Math.max(0, value));
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function normalizedUsage(
|
|
91
|
+
value: unknown,
|
|
92
|
+
): ClassifierResult["usage"] | undefined {
|
|
93
|
+
if (!isRecord(value)) return undefined;
|
|
94
|
+
const input = tokenCount(value.input_tokens);
|
|
95
|
+
const output = tokenCount(value.output_tokens);
|
|
96
|
+
if (input === undefined && output === undefined) return undefined;
|
|
97
|
+
const total =
|
|
98
|
+
tokenCount(value.total_tokens) ?? tokenCount((input ?? 0) + (output ?? 0));
|
|
99
|
+
if (total === undefined) return undefined;
|
|
100
|
+
const usage: NonNullable<ClassifierResult["usage"]> = {
|
|
101
|
+
inputTokens: input ?? 0,
|
|
102
|
+
outputTokens: output ?? 0,
|
|
103
|
+
totalTokens: total,
|
|
104
|
+
};
|
|
105
|
+
if (isRecord(value.input_tokens_details)) {
|
|
106
|
+
const cached = tokenCount(value.input_tokens_details.cached_tokens);
|
|
107
|
+
const writes = tokenCount(value.input_tokens_details.cache_write_tokens);
|
|
108
|
+
if (cached !== undefined) usage.cachedInputTokens = cached;
|
|
109
|
+
if (writes !== undefined) usage.cacheWriteTokens = writes;
|
|
110
|
+
}
|
|
111
|
+
return usage;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
function finish(
|
|
115
|
+
route: ResolvedModel,
|
|
116
|
+
answers: Record<string, Answer>,
|
|
117
|
+
rawUsage: unknown,
|
|
118
|
+
requestId: string | undefined,
|
|
119
|
+
): ClassifierResult {
|
|
120
|
+
const result: ClassifierResult = {
|
|
121
|
+
provider: route.route,
|
|
122
|
+
model: route.model,
|
|
123
|
+
answers,
|
|
124
|
+
cost: estimateCost(route, rawUsage),
|
|
125
|
+
};
|
|
126
|
+
const usage = normalizedUsage(rawUsage);
|
|
127
|
+
if (usage !== undefined) result.usage = usage;
|
|
128
|
+
if (requestId !== undefined) result.requestId = requestId;
|
|
129
|
+
return result;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
function dataUrl(image: PreparedImage): string {
|
|
133
|
+
return "data:" + image.mimeType + ";base64," + image.data;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/* Answer parsing for map-shaped answers (Perplexity, System One, Clef) --- */
|
|
137
|
+
|
|
138
|
+
function labelProbabilities(
|
|
139
|
+
label: string,
|
|
140
|
+
id: string,
|
|
141
|
+
value: unknown,
|
|
142
|
+
labels: string[],
|
|
143
|
+
): Record<string, number> {
|
|
144
|
+
if (!isRecord(value))
|
|
145
|
+
fail(label + " returned invalid probabilities for " + id + ".");
|
|
146
|
+
const result = Object.create(null) as Record<string, number>;
|
|
147
|
+
for (const [key, entry] of Object.entries(value)) {
|
|
148
|
+
if (!labels.includes(key))
|
|
149
|
+
fail(
|
|
150
|
+
label +
|
|
151
|
+
" returned an unknown option in the probabilities for " +
|
|
152
|
+
id +
|
|
153
|
+
".",
|
|
154
|
+
);
|
|
155
|
+
result[key] = probability(
|
|
156
|
+
label,
|
|
157
|
+
entry,
|
|
158
|
+
"probability for " + id + "." + key,
|
|
159
|
+
);
|
|
160
|
+
}
|
|
161
|
+
for (const key of labels) {
|
|
162
|
+
if (!Object.hasOwn(result, key))
|
|
163
|
+
fail(label + " did not return a probability for " + id + "." + key + ".");
|
|
164
|
+
}
|
|
165
|
+
return checkDistribution(label, id, result);
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/** Probability mass must be close to 1; it is never renormalized on the caller's behalf. */
|
|
169
|
+
function checkDistribution(
|
|
170
|
+
label: string,
|
|
171
|
+
id: string,
|
|
172
|
+
probabilities: Record<string, number>,
|
|
173
|
+
): Record<string, number> {
|
|
174
|
+
let total = 0;
|
|
175
|
+
for (const value of Object.values(probabilities)) total += value;
|
|
176
|
+
if (Math.abs(total - 1) > DISTRIBUTION_TOLERANCE)
|
|
177
|
+
fail(
|
|
178
|
+
label + " returned probabilities that do not sum to 1 for " + id + ".",
|
|
179
|
+
);
|
|
180
|
+
return probabilities;
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
function levelProbabilities(
|
|
184
|
+
label: string,
|
|
185
|
+
id: string,
|
|
186
|
+
value: unknown,
|
|
187
|
+
levels: number,
|
|
188
|
+
): Record<string, number> {
|
|
189
|
+
if (!isRecord(value))
|
|
190
|
+
fail(label + " returned invalid probabilities for " + id + ".");
|
|
191
|
+
const result = Object.create(null) as Record<string, number>;
|
|
192
|
+
for (const [key, entry] of Object.entries(value)) {
|
|
193
|
+
const index = Number(key);
|
|
194
|
+
if (
|
|
195
|
+
!/^\d+$/.test(key) ||
|
|
196
|
+
!Number.isInteger(index) ||
|
|
197
|
+
index < 0 ||
|
|
198
|
+
index >= levels
|
|
199
|
+
) {
|
|
200
|
+
fail(
|
|
201
|
+
label +
|
|
202
|
+
" returned an unknown level in the probabilities for " +
|
|
203
|
+
id +
|
|
204
|
+
".",
|
|
205
|
+
);
|
|
206
|
+
}
|
|
207
|
+
const normalized = String(index);
|
|
208
|
+
if (Object.hasOwn(result, normalized))
|
|
209
|
+
fail(label + " returned duplicate probabilities for " + id + ".");
|
|
210
|
+
result[normalized] = probability(
|
|
211
|
+
label,
|
|
212
|
+
entry,
|
|
213
|
+
"probability for " + id + "." + key,
|
|
214
|
+
);
|
|
215
|
+
}
|
|
216
|
+
for (let index = 0; index < levels; index += 1) {
|
|
217
|
+
if (!Object.hasOwn(result, String(index)))
|
|
218
|
+
fail(
|
|
219
|
+
label + " did not return a probability for " + id + "." + index + ".",
|
|
220
|
+
);
|
|
221
|
+
}
|
|
222
|
+
return checkDistribution(label, id, result);
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
function scoreValue(
|
|
226
|
+
label: string,
|
|
227
|
+
id: string,
|
|
228
|
+
value: unknown,
|
|
229
|
+
levels: number,
|
|
230
|
+
): number {
|
|
231
|
+
if (typeof value !== "number" || !Number.isFinite(value))
|
|
232
|
+
fail(label + " returned an invalid score for " + id + ".");
|
|
233
|
+
const maximum = levels - 1;
|
|
234
|
+
if (value < -EPSILON || value > maximum + EPSILON)
|
|
235
|
+
fail(label + " returned a score outside the rubric for " + id + ".");
|
|
236
|
+
return Math.min(maximum, Math.max(0, value));
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
function parseBox(
|
|
240
|
+
label: string,
|
|
241
|
+
id: string,
|
|
242
|
+
value: unknown,
|
|
243
|
+
confidence: unknown,
|
|
244
|
+
): Answer {
|
|
245
|
+
if (!isRecord(value))
|
|
246
|
+
fail(label + " returned an invalid box for " + id + ".");
|
|
247
|
+
const top = unitInterval(label, value.top, "box edge for " + id);
|
|
248
|
+
const bottom = unitInterval(label, value.bottom, "box edge for " + id);
|
|
249
|
+
const left = unitInterval(label, value.left, "box edge for " + id);
|
|
250
|
+
const right = unitInterval(label, value.right, "box edge for " + id);
|
|
251
|
+
if (left >= right)
|
|
252
|
+
fail(
|
|
253
|
+
label +
|
|
254
|
+
" returned a box for " +
|
|
255
|
+
id +
|
|
256
|
+
" whose left edge is not before its right edge.",
|
|
257
|
+
);
|
|
258
|
+
if (top >= bottom)
|
|
259
|
+
fail(
|
|
260
|
+
label +
|
|
261
|
+
" returned a box for " +
|
|
262
|
+
id +
|
|
263
|
+
" whose top edge is not above its bottom edge.",
|
|
264
|
+
);
|
|
265
|
+
return {
|
|
266
|
+
type: "box",
|
|
267
|
+
box: { top, bottom, left, right },
|
|
268
|
+
confidence: probability(label, confidence, "confidence for " + id),
|
|
269
|
+
};
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
function parseTypedAnswer(
|
|
273
|
+
label: string,
|
|
274
|
+
id: string,
|
|
275
|
+
question: Question,
|
|
276
|
+
answer: unknown,
|
|
277
|
+
): Answer {
|
|
278
|
+
if (!isRecord(answer))
|
|
279
|
+
fail(label + " returned an invalid answer for " + id + ".");
|
|
280
|
+
if (answer.type === "refusal") return { type: "refusal" };
|
|
281
|
+
if (question.type === "bool") {
|
|
282
|
+
if (answer.type !== "noul")
|
|
283
|
+
fail(label + " did not return a yes/no answer for " + id + ".");
|
|
284
|
+
return {
|
|
285
|
+
type: "bool",
|
|
286
|
+
probability: probability(label, answer.noul, "probability for " + id),
|
|
287
|
+
};
|
|
288
|
+
}
|
|
289
|
+
if (question.type === "choice") {
|
|
290
|
+
if (answer.type !== "choice" || typeof answer.choice !== "string")
|
|
291
|
+
fail(label + " did not return a choice answer for " + id + ".");
|
|
292
|
+
if (!Object.hasOwn(question.criteria, answer.choice))
|
|
293
|
+
fail(label + " returned an unknown choice for " + id + ".");
|
|
294
|
+
const probabilities = labelProbabilities(
|
|
295
|
+
label,
|
|
296
|
+
id,
|
|
297
|
+
answer.probabilities,
|
|
298
|
+
Object.keys(question.criteria),
|
|
299
|
+
);
|
|
300
|
+
return {
|
|
301
|
+
type: "choice",
|
|
302
|
+
choice: answer.choice,
|
|
303
|
+
probabilities,
|
|
304
|
+
confidence: probability(label, answer.confidence, "confidence for " + id),
|
|
305
|
+
};
|
|
306
|
+
}
|
|
307
|
+
if (question.type === "score") {
|
|
308
|
+
if (answer.type !== "score")
|
|
309
|
+
fail(label + " did not return a score answer for " + id + ".");
|
|
310
|
+
const base = {
|
|
311
|
+
type: "score" as const,
|
|
312
|
+
score: scoreValue(label, id, answer.score, question.criteria.length),
|
|
313
|
+
confidence: probability(label, answer.confidence, "confidence for " + id),
|
|
314
|
+
};
|
|
315
|
+
if (answer.probabilities === undefined) return base;
|
|
316
|
+
return {
|
|
317
|
+
...base,
|
|
318
|
+
probabilities: levelProbabilities(
|
|
319
|
+
label,
|
|
320
|
+
id,
|
|
321
|
+
answer.probabilities,
|
|
322
|
+
question.criteria.length,
|
|
323
|
+
),
|
|
324
|
+
};
|
|
325
|
+
}
|
|
326
|
+
if (answer.type !== "box")
|
|
327
|
+
fail(label + " did not return a box answer for " + id + ".");
|
|
328
|
+
return parseBox(label, id, answer.box, answer.confidence);
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
function validateDecision(label: string, id: string, answer: Answer): Answer {
|
|
332
|
+
if (answer.type === "choice") {
|
|
333
|
+
const maximum = Math.max(...Object.values(answer.probabilities));
|
|
334
|
+
if (maximum - answer.probabilities[answer.choice]! > EPSILON)
|
|
335
|
+
fail(
|
|
336
|
+
label +
|
|
337
|
+
" returned a choice inconsistent with its probabilities for " +
|
|
338
|
+
id +
|
|
339
|
+
".",
|
|
340
|
+
);
|
|
341
|
+
} else if (answer.type === "score" && answer.probabilities) {
|
|
342
|
+
const entries = Object.entries(answer.probabilities);
|
|
343
|
+
const expected = entries.reduce(
|
|
344
|
+
(total, [level, probability]) => total + Number(level) * probability,
|
|
345
|
+
0,
|
|
346
|
+
);
|
|
347
|
+
if (
|
|
348
|
+
Math.abs(answer.score - expected) >
|
|
349
|
+
DISTRIBUTION_TOLERANCE * Math.max(1, entries.length - 1)
|
|
350
|
+
)
|
|
351
|
+
fail(
|
|
352
|
+
label +
|
|
353
|
+
" returned a score inconsistent with its probabilities for " +
|
|
354
|
+
id +
|
|
355
|
+
".",
|
|
356
|
+
);
|
|
357
|
+
}
|
|
358
|
+
return answer;
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
function parseTypedAnswers(
|
|
362
|
+
label: string,
|
|
363
|
+
value: unknown,
|
|
364
|
+
questions: Record<string, Question>,
|
|
365
|
+
): Record<string, Answer> {
|
|
366
|
+
if (!isRecord(value)) fail(label + " returned an unexpected response.");
|
|
367
|
+
// Question IDs may be "__proto__", so answers are collected without a prototype.
|
|
368
|
+
const answers = Object.create(null) as Record<string, Answer>;
|
|
369
|
+
for (const [id, question] of Object.entries(questions)) {
|
|
370
|
+
if (!Object.hasOwn(value, id))
|
|
371
|
+
fail(label + " did not return an answer for " + id + ".");
|
|
372
|
+
answers[id] = validateDecision(
|
|
373
|
+
label,
|
|
374
|
+
id,
|
|
375
|
+
parseTypedAnswer(label, id, question, value[id]),
|
|
376
|
+
);
|
|
377
|
+
}
|
|
378
|
+
return answers;
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
/* OpenAI Decisions -------------------------------------------------------- */
|
|
382
|
+
|
|
383
|
+
function predicateInstructions(
|
|
384
|
+
question: Extract<Question, { type: "bool" }>,
|
|
385
|
+
): string {
|
|
386
|
+
const meanings: string[] = [];
|
|
387
|
+
if (question.criteria?.true)
|
|
388
|
+
meanings.push("True means: " + question.criteria.true);
|
|
389
|
+
if (question.criteria?.false)
|
|
390
|
+
meanings.push("False means: " + question.criteria.false);
|
|
391
|
+
return meanings.length > 0
|
|
392
|
+
? question.instructions + "\n" + meanings.join("\n")
|
|
393
|
+
: question.instructions;
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
function openAiQuestion(
|
|
397
|
+
id: string,
|
|
398
|
+
question: Question,
|
|
399
|
+
): Record<string, unknown> {
|
|
400
|
+
if (question.type === "bool")
|
|
401
|
+
return {
|
|
402
|
+
type: "predicate",
|
|
403
|
+
name: id,
|
|
404
|
+
instructions: predicateInstructions(question),
|
|
405
|
+
};
|
|
406
|
+
if (question.type === "choice") {
|
|
407
|
+
return {
|
|
408
|
+
type: "choice",
|
|
409
|
+
name: id,
|
|
410
|
+
instructions: question.instructions,
|
|
411
|
+
choices: Object.entries(question.criteria).map(
|
|
412
|
+
([value, description]) => ({ value, description }),
|
|
413
|
+
),
|
|
414
|
+
};
|
|
415
|
+
}
|
|
416
|
+
if (question.type === "score") {
|
|
417
|
+
return {
|
|
418
|
+
type: "score",
|
|
419
|
+
name: id,
|
|
420
|
+
instructions: question.instructions,
|
|
421
|
+
levels: question.criteria.map((label) => ({ label })),
|
|
422
|
+
};
|
|
423
|
+
}
|
|
424
|
+
throw unsupportedBox();
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
function openAiInput(input: PreparedInput): unknown {
|
|
428
|
+
const text =
|
|
429
|
+
typeof input.state === "string" ? input.state : JSON.stringify(input.state);
|
|
430
|
+
if (input.images.length === 0) return text;
|
|
431
|
+
return [
|
|
432
|
+
{
|
|
433
|
+
role: "user",
|
|
434
|
+
content: [
|
|
435
|
+
{ type: "input_text", text },
|
|
436
|
+
...input.images.map((image) => ({
|
|
437
|
+
type: "input_image",
|
|
438
|
+
image_url: dataUrl(image),
|
|
439
|
+
})),
|
|
440
|
+
],
|
|
441
|
+
},
|
|
442
|
+
];
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
function openAiChoiceProbabilities(
|
|
446
|
+
label: string,
|
|
447
|
+
id: string,
|
|
448
|
+
value: unknown,
|
|
449
|
+
labels: string[],
|
|
450
|
+
): Record<string, number> {
|
|
451
|
+
if (!Array.isArray(value))
|
|
452
|
+
fail(label + " returned invalid probabilities for " + id + ".");
|
|
453
|
+
const mapped = Object.create(null) as Record<string, unknown>;
|
|
454
|
+
for (const entry of value) {
|
|
455
|
+
if (
|
|
456
|
+
!isRecord(entry) ||
|
|
457
|
+
typeof entry.value !== "string" ||
|
|
458
|
+
!labels.includes(entry.value)
|
|
459
|
+
) {
|
|
460
|
+
fail(
|
|
461
|
+
label +
|
|
462
|
+
" returned an unknown option in the probabilities for " +
|
|
463
|
+
id +
|
|
464
|
+
".",
|
|
465
|
+
);
|
|
466
|
+
}
|
|
467
|
+
if (Object.hasOwn(mapped, entry.value))
|
|
468
|
+
fail(label + " returned duplicate probabilities for " + id + ".");
|
|
469
|
+
mapped[entry.value] = entry.probability;
|
|
470
|
+
}
|
|
471
|
+
return labelProbabilities(label, id, mapped, labels);
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
function openAiLevelProbabilities(
|
|
475
|
+
label: string,
|
|
476
|
+
id: string,
|
|
477
|
+
value: unknown,
|
|
478
|
+
levels: number,
|
|
479
|
+
): Record<string, number> {
|
|
480
|
+
if (!Array.isArray(value))
|
|
481
|
+
fail(label + " returned invalid probabilities for " + id + ".");
|
|
482
|
+
const mapped = Object.create(null) as Record<string, unknown>;
|
|
483
|
+
for (const entry of value) {
|
|
484
|
+
if (!isRecord(entry) || !Number.isInteger(entry.value))
|
|
485
|
+
fail(
|
|
486
|
+
label +
|
|
487
|
+
" returned an unknown level in the probabilities for " +
|
|
488
|
+
id +
|
|
489
|
+
".",
|
|
490
|
+
);
|
|
491
|
+
const index = entry.value as number;
|
|
492
|
+
if (index < 0 || index >= levels || Object.hasOwn(mapped, String(index))) {
|
|
493
|
+
fail(
|
|
494
|
+
label +
|
|
495
|
+
" returned an unknown level in the probabilities for " +
|
|
496
|
+
id +
|
|
497
|
+
".",
|
|
498
|
+
);
|
|
499
|
+
}
|
|
500
|
+
mapped[String(index)] = entry.probability;
|
|
501
|
+
}
|
|
502
|
+
return levelProbabilities(label, id, mapped, levels);
|
|
503
|
+
}
|
|
504
|
+
|
|
505
|
+
function parseOpenAiAnswer(
|
|
506
|
+
label: string,
|
|
507
|
+
id: string,
|
|
508
|
+
question: Question,
|
|
509
|
+
answer: unknown,
|
|
510
|
+
): Answer {
|
|
511
|
+
if (!isRecord(answer))
|
|
512
|
+
fail(label + " returned an invalid answer for " + id + ".");
|
|
513
|
+
if (answer.type === "refusal") return { type: "refusal" };
|
|
514
|
+
if (question.type === "bool") {
|
|
515
|
+
if (answer.type !== "predicate")
|
|
516
|
+
fail(label + " did not return a yes/no answer for " + id + ".");
|
|
517
|
+
return {
|
|
518
|
+
type: "bool",
|
|
519
|
+
probability: probability(
|
|
520
|
+
label,
|
|
521
|
+
answer.probability,
|
|
522
|
+
"probability for " + id,
|
|
523
|
+
),
|
|
524
|
+
};
|
|
525
|
+
}
|
|
526
|
+
if (question.type === "choice") {
|
|
527
|
+
if (answer.type !== "choice" || typeof answer.choice !== "string")
|
|
528
|
+
fail(label + " did not return a choice answer for " + id + ".");
|
|
529
|
+
if (!Object.hasOwn(question.criteria, answer.choice))
|
|
530
|
+
fail(label + " returned an unknown choice for " + id + ".");
|
|
531
|
+
return {
|
|
532
|
+
type: "choice",
|
|
533
|
+
choice: answer.choice,
|
|
534
|
+
probabilities: openAiChoiceProbabilities(
|
|
535
|
+
label,
|
|
536
|
+
id,
|
|
537
|
+
answer.probabilities,
|
|
538
|
+
Object.keys(question.criteria),
|
|
539
|
+
),
|
|
540
|
+
confidence: probability(label, answer.confidence, "confidence for " + id),
|
|
541
|
+
};
|
|
542
|
+
}
|
|
543
|
+
if (question.type === "score") {
|
|
544
|
+
if (answer.type !== "score")
|
|
545
|
+
fail(label + " did not return a score answer for " + id + ".");
|
|
546
|
+
const base = {
|
|
547
|
+
type: "score" as const,
|
|
548
|
+
score: scoreValue(label, id, answer.score, question.criteria.length),
|
|
549
|
+
confidence: probability(label, answer.confidence, "confidence for " + id),
|
|
550
|
+
};
|
|
551
|
+
if (answer.probabilities === undefined) return base;
|
|
552
|
+
return {
|
|
553
|
+
...base,
|
|
554
|
+
probabilities: openAiLevelProbabilities(
|
|
555
|
+
label,
|
|
556
|
+
id,
|
|
557
|
+
answer.probabilities,
|
|
558
|
+
question.criteria.length,
|
|
559
|
+
),
|
|
560
|
+
};
|
|
561
|
+
}
|
|
562
|
+
throw unsupportedBox();
|
|
563
|
+
}
|
|
564
|
+
|
|
565
|
+
function parseOpenAiAnswers(
|
|
566
|
+
label: string,
|
|
567
|
+
value: unknown,
|
|
568
|
+
questions: Record<string, Question>,
|
|
569
|
+
): Record<string, Answer> {
|
|
570
|
+
if (!Array.isArray(value)) fail(label + " returned an unexpected response.");
|
|
571
|
+
const byName = new Map<string, unknown>();
|
|
572
|
+
for (const entry of value) {
|
|
573
|
+
if (!isRecord(entry) || typeof entry.name !== "string")
|
|
574
|
+
fail(label + " returned an unexpected response.");
|
|
575
|
+
if (byName.has(entry.name)) fail(label + " returned duplicate answers.");
|
|
576
|
+
byName.set(entry.name, entry);
|
|
577
|
+
}
|
|
578
|
+
// Question IDs may be "__proto__", so answers are collected without a prototype.
|
|
579
|
+
const answers = Object.create(null) as Record<string, Answer>;
|
|
580
|
+
for (const [id, question] of Object.entries(questions)) {
|
|
581
|
+
const answer = byName.get(id);
|
|
582
|
+
if (answer === undefined)
|
|
583
|
+
fail(label + " did not return an answer for " + id + ".");
|
|
584
|
+
answers[id] = validateDecision(
|
|
585
|
+
label,
|
|
586
|
+
id,
|
|
587
|
+
parseOpenAiAnswer(label, id, question, answer),
|
|
588
|
+
);
|
|
589
|
+
}
|
|
590
|
+
return answers;
|
|
591
|
+
}
|
|
592
|
+
|
|
593
|
+
async function classifyOpenAi(
|
|
594
|
+
route: ResolvedModel,
|
|
595
|
+
input: PreparedInput,
|
|
596
|
+
apiKey: string,
|
|
597
|
+
signal?: AbortSignal,
|
|
598
|
+
): Promise<ClassifierResult> {
|
|
599
|
+
const questions = Object.entries(input.questions).map(([id, question]) =>
|
|
600
|
+
openAiQuestion(id, question),
|
|
601
|
+
);
|
|
602
|
+
const { body, requestId } = await postJson(
|
|
603
|
+
route,
|
|
604
|
+
"decisions",
|
|
605
|
+
{
|
|
606
|
+
model: route.model,
|
|
607
|
+
input: openAiInput(input),
|
|
608
|
+
questions,
|
|
609
|
+
},
|
|
610
|
+
apiKey,
|
|
611
|
+
signal,
|
|
612
|
+
);
|
|
613
|
+
if (!isRecord(body)) fail(OPENAI_LABEL + " returned an unexpected response.");
|
|
614
|
+
return finish(
|
|
615
|
+
route,
|
|
616
|
+
parseOpenAiAnswers(OPENAI_LABEL, body.answers, input.questions),
|
|
617
|
+
body.usage,
|
|
618
|
+
requestId,
|
|
619
|
+
);
|
|
620
|
+
}
|
|
621
|
+
|
|
622
|
+
/* Perplexity Decisions ---------------------------------------------------- */
|
|
623
|
+
|
|
624
|
+
function systemOneQuestions(
|
|
625
|
+
questions: Record<string, Question>,
|
|
626
|
+
allowBox: boolean,
|
|
627
|
+
): Record<string, unknown> {
|
|
628
|
+
// Question IDs may be "__proto__", so the wire map is collected without a prototype.
|
|
629
|
+
const result = Object.create(null) as Record<string, unknown>;
|
|
630
|
+
for (const [id, question] of Object.entries(questions)) {
|
|
631
|
+
if (question.type === "bool") {
|
|
632
|
+
const wire: Record<string, unknown> = {
|
|
633
|
+
type: "noul",
|
|
634
|
+
instructions: question.instructions,
|
|
635
|
+
};
|
|
636
|
+
if (question.criteria !== undefined) wire.criteria = question.criteria;
|
|
637
|
+
result[id] = wire;
|
|
638
|
+
} else if (question.type === "choice") {
|
|
639
|
+
result[id] = {
|
|
640
|
+
type: "choice",
|
|
641
|
+
instructions: question.instructions,
|
|
642
|
+
criteria: question.criteria,
|
|
643
|
+
};
|
|
644
|
+
} else if (question.type === "score") {
|
|
645
|
+
result[id] = {
|
|
646
|
+
type: "score",
|
|
647
|
+
instructions: question.instructions,
|
|
648
|
+
criteria: question.criteria,
|
|
649
|
+
};
|
|
650
|
+
} else if (allowBox) {
|
|
651
|
+
result[id] = { type: "box", instructions: question.instructions };
|
|
652
|
+
} else {
|
|
653
|
+
throw unsupportedBox();
|
|
654
|
+
}
|
|
655
|
+
}
|
|
656
|
+
return result;
|
|
657
|
+
}
|
|
658
|
+
|
|
659
|
+
function perplexityState(input: PreparedInput): unknown {
|
|
660
|
+
// Perplexity interprets native image parts inside state. Caller JSON is text;
|
|
661
|
+
// only locally validated images may become provider-native image parts.
|
|
662
|
+
const text =
|
|
663
|
+
typeof input.state === "string" ? input.state : JSON.stringify(input.state);
|
|
664
|
+
if (input.images.length === 0) return text;
|
|
665
|
+
return [
|
|
666
|
+
text,
|
|
667
|
+
...input.images.map((image) => ({
|
|
668
|
+
type: "image_url",
|
|
669
|
+
image_url: { url: dataUrl(image) },
|
|
670
|
+
})),
|
|
671
|
+
];
|
|
672
|
+
}
|
|
673
|
+
|
|
674
|
+
async function classifyPerplexity(
|
|
675
|
+
route: ResolvedModel,
|
|
676
|
+
input: PreparedInput,
|
|
677
|
+
apiKey: string,
|
|
678
|
+
signal?: AbortSignal,
|
|
679
|
+
): Promise<ClassifierResult> {
|
|
680
|
+
const state = perplexityState(input);
|
|
681
|
+
const { body, requestId } = await postJson(
|
|
682
|
+
route,
|
|
683
|
+
"decisions",
|
|
684
|
+
{
|
|
685
|
+
model: route.model,
|
|
686
|
+
state,
|
|
687
|
+
questions: systemOneQuestions(input.questions, false),
|
|
688
|
+
},
|
|
689
|
+
apiKey,
|
|
690
|
+
signal,
|
|
691
|
+
);
|
|
692
|
+
if (!isRecord(body))
|
|
693
|
+
fail(PERPLEXITY_LABEL + " returned an unexpected response.");
|
|
694
|
+
return finish(
|
|
695
|
+
route,
|
|
696
|
+
parseTypedAnswers(PERPLEXITY_LABEL, body.answers, input.questions),
|
|
697
|
+
body.usage,
|
|
698
|
+
requestId,
|
|
699
|
+
);
|
|
700
|
+
}
|
|
701
|
+
|
|
702
|
+
/* Microsoft Foundry Decision-1 (text/JSON, API-key authentication) -------- */
|
|
703
|
+
|
|
704
|
+
async function classifyMicrosoft(
|
|
705
|
+
route: ResolvedModel,
|
|
706
|
+
input: PreparedInput,
|
|
707
|
+
apiKey: string,
|
|
708
|
+
signal?: AbortSignal,
|
|
709
|
+
): Promise<ClassifierResult> {
|
|
710
|
+
const label = "Microsoft Decision-1";
|
|
711
|
+
const { body, requestId } = await postJson(
|
|
712
|
+
route,
|
|
713
|
+
"providers/microsoft/v1/systemone",
|
|
714
|
+
{
|
|
715
|
+
model: route.model, // Foundry deployment name, not necessarily the catalog model ID.
|
|
716
|
+
state: input.state,
|
|
717
|
+
questions: systemOneQuestions(input.questions, false),
|
|
718
|
+
},
|
|
719
|
+
apiKey,
|
|
720
|
+
signal,
|
|
721
|
+
);
|
|
722
|
+
if (!isRecord(body) || !isRecord(body.answers))
|
|
723
|
+
fail(label + " returned an unexpected response.");
|
|
724
|
+
// Some System One endpoints omit confidence; derive it only from validated probabilities.
|
|
725
|
+
const answers = Object.create(null) as Record<string, unknown>;
|
|
726
|
+
for (const [id, question] of Object.entries(input.questions)) {
|
|
727
|
+
const answer = Object.hasOwn(body.answers, id) ? body.answers[id] : undefined;
|
|
728
|
+
if (
|
|
729
|
+
isRecord(answer) &&
|
|
730
|
+
answer.confidence === undefined &&
|
|
731
|
+
answer.type !== "refusal"
|
|
732
|
+
) {
|
|
733
|
+
if (question.type === "choice" && typeof answer.choice === "string") {
|
|
734
|
+
const probabilities = labelProbabilities(
|
|
735
|
+
label,
|
|
736
|
+
id,
|
|
737
|
+
answer.probabilities,
|
|
738
|
+
Object.keys(question.criteria),
|
|
739
|
+
);
|
|
740
|
+
answers[id] = { ...answer, confidence: probabilities[answer.choice] };
|
|
741
|
+
} else if (question.type === "score") {
|
|
742
|
+
const probabilities = levelProbabilities(
|
|
743
|
+
label,
|
|
744
|
+
id,
|
|
745
|
+
answer.probabilities,
|
|
746
|
+
question.criteria.length,
|
|
747
|
+
);
|
|
748
|
+
answers[id] = {
|
|
749
|
+
...answer,
|
|
750
|
+
confidence: Math.max(...Object.values(probabilities)),
|
|
751
|
+
};
|
|
752
|
+
} else answers[id] = answer;
|
|
753
|
+
} else answers[id] = answer;
|
|
754
|
+
}
|
|
755
|
+
return finish(
|
|
756
|
+
route,
|
|
757
|
+
parseTypedAnswers(label, answers, input.questions),
|
|
758
|
+
body.usage,
|
|
759
|
+
requestId,
|
|
760
|
+
);
|
|
761
|
+
}
|
|
762
|
+
|
|
763
|
+
/* TypeSafe System One (direct API and compatible gateways) --------------- */
|
|
764
|
+
|
|
765
|
+
function withImageRefs(state: PreparedInput["state"], refs: string[]): unknown {
|
|
766
|
+
if (isRecord(state) && !Object.hasOwn(state, "images"))
|
|
767
|
+
return { ...state, images: refs };
|
|
768
|
+
return { state, images: refs };
|
|
769
|
+
}
|
|
770
|
+
|
|
771
|
+
async function classifySystemOne(
|
|
772
|
+
route: ResolvedModel,
|
|
773
|
+
input: PreparedInput,
|
|
774
|
+
apiKey: string,
|
|
775
|
+
signal?: AbortSignal,
|
|
776
|
+
): Promise<ClassifierResult> {
|
|
777
|
+
const assets = Object.create(null) as Record<string, unknown>;
|
|
778
|
+
const refs: string[] = [];
|
|
779
|
+
for (const image of input.images) {
|
|
780
|
+
const ref = randomUUID();
|
|
781
|
+
refs.push(ref);
|
|
782
|
+
assets[ref] = {
|
|
783
|
+
type: "image",
|
|
784
|
+
format: image.mimeType === "image/png" ? "png" : "jpg",
|
|
785
|
+
data_base64: image.data,
|
|
786
|
+
};
|
|
787
|
+
}
|
|
788
|
+
const payload: Record<string, unknown> = {
|
|
789
|
+
model: route.model,
|
|
790
|
+
state: refs.length === 0 ? input.state : withImageRefs(input.state, refs),
|
|
791
|
+
questions: systemOneQuestions(input.questions, true),
|
|
792
|
+
};
|
|
793
|
+
if (refs.length > 0) payload.assets = assets;
|
|
794
|
+
const experimentalHeader =
|
|
795
|
+
refs.length > 0 ||
|
|
796
|
+
Object.values(input.questions).some((question) => question.type === "box");
|
|
797
|
+
const extraHeaders = experimentalHeader
|
|
798
|
+
? { "TypeSafe-Danger-Zone-Images": "true" }
|
|
799
|
+
: undefined;
|
|
800
|
+
const { body, requestId } = await postJson(
|
|
801
|
+
route,
|
|
802
|
+
"systemone",
|
|
803
|
+
payload,
|
|
804
|
+
apiKey,
|
|
805
|
+
signal,
|
|
806
|
+
extraHeaders,
|
|
807
|
+
);
|
|
808
|
+
if (!isRecord(body))
|
|
809
|
+
fail(TYPESAFE_LABEL + " returned an unexpected response.");
|
|
810
|
+
return finish(
|
|
811
|
+
route,
|
|
812
|
+
parseTypedAnswers(TYPESAFE_LABEL, body.answers, input.questions),
|
|
813
|
+
body.usage,
|
|
814
|
+
requestId,
|
|
815
|
+
);
|
|
816
|
+
}
|
|
817
|
+
|
|
818
|
+
/* Cloudflare Workers AI (Clef and third-party System One envelopes) ------- */
|
|
819
|
+
|
|
820
|
+
function clefBodyModel(model: string): string | undefined {
|
|
821
|
+
return /^@cf\/cloudflare\/(clef(?:-flash)?)$/.exec(model)?.[1];
|
|
822
|
+
}
|
|
823
|
+
|
|
824
|
+
function unwrapCloudflare(
|
|
825
|
+
label: string,
|
|
826
|
+
body: unknown,
|
|
827
|
+
): Record<string, unknown> {
|
|
828
|
+
if (!isRecord(body)) fail(label + " returned an unexpected response.");
|
|
829
|
+
if (body.success === false)
|
|
830
|
+
fail(
|
|
831
|
+
label +
|
|
832
|
+
" reported that the request failed. Check credentials, model, limits and provider availability.",
|
|
833
|
+
);
|
|
834
|
+
let candidate: Record<string, unknown> = body;
|
|
835
|
+
if (body.result !== undefined) {
|
|
836
|
+
if (!isRecord(body.result))
|
|
837
|
+
fail(label + " returned an unexpected response.");
|
|
838
|
+
candidate = body.result;
|
|
839
|
+
}
|
|
840
|
+
if (isRecord(candidate.answers)) return candidate;
|
|
841
|
+
if (candidate.state !== undefined && candidate.state !== "Completed")
|
|
842
|
+
fail(label + " did not complete the request.");
|
|
843
|
+
if (isRecord(candidate.result) && isRecord(candidate.result.answers))
|
|
844
|
+
return candidate.result;
|
|
845
|
+
fail(label + " returned an unexpected response.");
|
|
846
|
+
}
|
|
847
|
+
|
|
848
|
+
async function classifyCloudflare(
|
|
849
|
+
route: ResolvedModel,
|
|
850
|
+
input: PreparedInput,
|
|
851
|
+
apiKey: string,
|
|
852
|
+
signal?: AbortSignal,
|
|
853
|
+
): Promise<ClassifierResult> {
|
|
854
|
+
const clefModel = clefBodyModel(route.model);
|
|
855
|
+
let path: string;
|
|
856
|
+
let payload: Record<string, unknown>;
|
|
857
|
+
if (clefModel !== undefined) {
|
|
858
|
+
payload = {
|
|
859
|
+
model: clefModel,
|
|
860
|
+
state: input.state,
|
|
861
|
+
questions: systemOneQuestions(input.questions, false),
|
|
862
|
+
};
|
|
863
|
+
if (input.images.length > 0) {
|
|
864
|
+
payload.images = input.images.map((image) => ({
|
|
865
|
+
content_type: image.mimeType,
|
|
866
|
+
base64: image.data,
|
|
867
|
+
}));
|
|
868
|
+
}
|
|
869
|
+
path = "run/" + route.model;
|
|
870
|
+
} else {
|
|
871
|
+
if (input.images.length > 0)
|
|
872
|
+
throw new ClassifierError(
|
|
873
|
+
"capability",
|
|
874
|
+
"The selected route does not support images for this model.",
|
|
875
|
+
);
|
|
876
|
+
payload = {
|
|
877
|
+
model: route.model,
|
|
878
|
+
input: {
|
|
879
|
+
state: input.state,
|
|
880
|
+
questions: systemOneQuestions(input.questions, false),
|
|
881
|
+
},
|
|
882
|
+
};
|
|
883
|
+
path = "run";
|
|
884
|
+
}
|
|
885
|
+
const { body, requestId } = await postJson(
|
|
886
|
+
route,
|
|
887
|
+
path,
|
|
888
|
+
payload,
|
|
889
|
+
apiKey,
|
|
890
|
+
signal,
|
|
891
|
+
);
|
|
892
|
+
const result = unwrapCloudflare(CLOUDFLARE_LABEL, body);
|
|
893
|
+
const usage =
|
|
894
|
+
normalizedUsage(result.usage) !== undefined
|
|
895
|
+
? result.usage
|
|
896
|
+
: isRecord(body)
|
|
897
|
+
? body.usage
|
|
898
|
+
: undefined;
|
|
899
|
+
return finish(
|
|
900
|
+
route,
|
|
901
|
+
parseTypedAnswers(CLOUDFLARE_LABEL, result.answers, input.questions),
|
|
902
|
+
usage,
|
|
903
|
+
requestId,
|
|
904
|
+
);
|
|
905
|
+
}
|