@abhishek944/pi-classifier 0.5.1 → 0.7.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 +14 -0
- package/README.md +150 -41
- package/dist/choices.js +1 -1
- package/dist/classify.d.ts +9 -1
- package/dist/classify.js +24 -10
- package/dist/config.d.ts +48 -2
- package/dist/config.js +90 -6
- package/dist/cost.js +23 -2
- package/dist/extension.js +7 -5
- package/dist/extract.d.ts +5 -1
- package/dist/extract.js +190 -3
- package/dist/index.d.ts +1 -1
- package/dist/inputs.d.ts +2 -2
- package/dist/inputs.js +47 -14
- package/dist/providers.js +62 -0
- package/dist/tool-contracts.d.ts +101 -226
- package/dist/tool-contracts.js +61 -116
- package/dist/types.d.ts +42 -8
- package/dist/validation.d.ts +8 -1
- package/dist/validation.js +158 -125
- package/package.json +3 -2
- package/src/choices.ts +1 -1
- package/src/classify.ts +44 -15
- package/src/config.ts +93 -6
- package/src/cost.ts +24 -2
- package/src/extension.ts +7 -5
- package/src/extract.ts +194 -5
- package/src/index.ts +3 -0
- package/src/inputs.ts +51 -18
- package/src/providers.ts +108 -0
- package/src/tool-contracts.ts +107 -150
- package/src/types.ts +46 -7
- package/src/validation.ts +142 -105
package/src/cost.ts
CHANGED
|
@@ -39,6 +39,20 @@ const PRICES: Record<string, Record<string, TokenPricing>> = {
|
|
|
39
39
|
"d1.2": { inputPerMillion: 0.02, outputPerMillion: 0 },
|
|
40
40
|
"d1.2-ultra": { inputPerMillion: 0.042, outputPerMillion: 0 },
|
|
41
41
|
},
|
|
42
|
+
subq: {
|
|
43
|
+
"subq-snap-1.2": { inputPerMillion: 0.04, outputPerMillion: 0 },
|
|
44
|
+
"subq-snap-latest": { inputPerMillion: 0.04, outputPerMillion: 0 },
|
|
45
|
+
},
|
|
46
|
+
"opencode-go": {
|
|
47
|
+
"jev-1.14": { inputPerMillion: 0.042, outputPerMillion: 0 },
|
|
48
|
+
"gemini-decision-1": { inputPerMillion: 0.1, outputPerMillion: 0 },
|
|
49
|
+
"gpt-6-luna-decision": {
|
|
50
|
+
inputPerMillion: 0.1,
|
|
51
|
+
outputPerMillion: 0,
|
|
52
|
+
cachedInputPerMillion: 0.01,
|
|
53
|
+
cacheWritePerMillion: 0.125,
|
|
54
|
+
},
|
|
55
|
+
},
|
|
42
56
|
cloudflare: {
|
|
43
57
|
"@cf/cloudflare/clef": { inputPerMillion: 0.24, outputPerMillion: 0 },
|
|
44
58
|
"@cf/cloudflare/clef-flash": { inputPerMillion: 0.038, outputPerMillion: 0 },
|
|
@@ -102,6 +116,9 @@ export function resolvePricing(
|
|
|
102
116
|
(provider === "typesafe" && baseUrl === "https://api.typesafe.ai/v1") ||
|
|
103
117
|
(provider === "perplexity" && baseUrl === "https://api.perplexity.ai/v1") ||
|
|
104
118
|
(provider === "liquid" && baseUrl === "https://api.liquid.ai/decisions/v1") ||
|
|
119
|
+
(provider === "subq" && baseUrl === "https://api.subq.ai") ||
|
|
120
|
+
(provider === "opencode-go" &&
|
|
121
|
+
baseUrl === "https://opencode.ai/inference/go/systemone/v1") ||
|
|
105
122
|
((provider === "cloudflare" || provider === "clairic") &&
|
|
106
123
|
/^https:\/\/api\.cloudflare\.com\/client\/v4\/accounts\/[^/]+\/ai$/.test(baseUrl));
|
|
107
124
|
const catalogKey = provider === "clairic" ? "cloudflare" : provider;
|
|
@@ -195,9 +212,14 @@ export function estimateCost(
|
|
|
195
212
|
(writes > 0 && rates.cacheWritePerMillion === undefined)
|
|
196
213
|
)
|
|
197
214
|
return unavailable("missing_cache_pricing");
|
|
198
|
-
// OpenAI
|
|
215
|
+
// OpenAI and OpenCode Go double these decision models' rates for >272K context.
|
|
216
|
+
// Overrides already define effective rates.
|
|
217
|
+
const longContextRoute =
|
|
218
|
+
route.provider === "openai" ||
|
|
219
|
+
(route.provider === "opencode-go" &&
|
|
220
|
+
route.model === "gpt-6-luna-decision");
|
|
199
221
|
if (
|
|
200
|
-
|
|
222
|
+
longContextRoute &&
|
|
201
223
|
route.pricing.source === "builtin" &&
|
|
202
224
|
inputTokens > 272_000
|
|
203
225
|
) {
|
package/src/extension.ts
CHANGED
|
@@ -63,10 +63,10 @@ export default function piClassifier(pi: ExtensionAPI): void {
|
|
|
63
63
|
"Classify text, JSON or supported images into typed probabilistic decisions.",
|
|
64
64
|
promptGuidelines: [
|
|
65
65
|
"Use for bounded judgments, classification and rubric scoring, not open-ended prose.",
|
|
66
|
+
"Use only bool, choice, multi_choice and score. Extraction reads (text, number, date, spans, box, boxes, locate, estimate, extract) belong to classify_extract and are rejected here.",
|
|
66
67
|
"Treat low confidence as uncertainty, not permission to switch models or retry. Only configured remove_choice_limits with none_of_above_choice permits internal sequential choice batches; this is first-match selection, not a global ranking.",
|
|
67
68
|
"Handle no_match and ambiguous answers explicitly. probabilityScope=batch and noneOfAboveProbability describe only the winning batch; they are not a full-list probability distribution.",
|
|
68
69
|
"Send only data the user intends to share with the configured provider. Web grounding sends question text and the start of state to Perplexity Search and incurs per-search fees.",
|
|
69
|
-
"Liquid reads and estimates are provider-rendered values, not conversions. Spans and locate offsets count Unicode characters; boxes are localization hints, not proof of presence.",
|
|
70
70
|
"Audio and video are accepted only by routes with documented media contracts. Duration and codec compatibility remain provider-owned.",
|
|
71
71
|
"Ask /classifier status for the active model. Do not change provider settings without user direction.",
|
|
72
72
|
],
|
|
@@ -180,12 +180,14 @@ export default function piClassifier(pi: ExtensionAPI): void {
|
|
|
180
180
|
name: CLASSIFY_EXTRACT_TOOL,
|
|
181
181
|
label: "Extract structured fields",
|
|
182
182
|
description: CLASSIFY_EXTRACT_TOOL_DESCRIPTION,
|
|
183
|
-
promptSnippet: "Extract typed
|
|
183
|
+
promptSnippet: "Extract typed values with field specs or typed reads (text, number, date, spans, boxes, locate, estimate) on decision routes including direct Liquid.",
|
|
184
184
|
promptGuidelines: [
|
|
185
|
+
"Use for reads, not decisions: yes/no, category, multi-choice and score questions belong to classify.",
|
|
186
|
+
"Supply exactly one of fields or questions. fields needs a clairic-api, openrouter-extractions-api or litellm-extraction-api route; questions uses the configured decision route, including direct liquid-api d1.2 and d1.2-ultra.",
|
|
185
187
|
"Use fields that describe the value you need; do not invent provider field types or keys.",
|
|
186
|
-
"
|
|
187
|
-
"
|
|
188
|
-
"The configured
|
|
188
|
+
"Liquid reads and spans point into the state text; a value that appears only in an image is not found. Spans and locate offsets count Unicode characters; boxes are localization hints, not proof of presence.",
|
|
189
|
+
"A result is not proof that a fact is correct; use grounded spans and confidence when available. truncated means generated field output is incomplete.",
|
|
190
|
+
"The configured route receives state, fields or questions and media. Do not send data the user does not intend to share with that provider.",
|
|
189
191
|
],
|
|
190
192
|
parameters: classifyExtractParameters,
|
|
191
193
|
outputSchema: classifyExtractOutput,
|
package/src/extract.ts
CHANGED
|
@@ -1,17 +1,26 @@
|
|
|
1
1
|
import { resolveApiKey, type CredentialSource } from "./auth.js";
|
|
2
|
+
import { runDecisionRequest } from "./classify.js";
|
|
2
3
|
import { resolveModel } from "./config.js";
|
|
3
4
|
import { estimateCost, tokenCount } from "./cost.js";
|
|
4
5
|
import { postJson } from "./http.js";
|
|
5
6
|
import { prepareExtractionInput, type PreparedExtractionInput } from "./inputs.js";
|
|
6
|
-
import { unwrapCloudflare } from "./providers.js";
|
|
7
|
+
import { classifyWithProvider, unwrapCloudflare } from "./providers.js";
|
|
8
|
+
import { validateExtractionQuestions, validateImageDescriptors } from "./validation.js";
|
|
7
9
|
import {
|
|
8
10
|
ClassifierError,
|
|
9
11
|
isRecord,
|
|
10
12
|
userError,
|
|
13
|
+
type Answer,
|
|
11
14
|
type ClassifierCost,
|
|
15
|
+
type ClassifierResult,
|
|
16
|
+
type DecisionInput,
|
|
12
17
|
type ExtractParams,
|
|
13
|
-
type JsonLike,
|
|
14
18
|
type ExtractResult,
|
|
19
|
+
type ExtractionAnswer,
|
|
20
|
+
type ExtractionQuestion,
|
|
21
|
+
type ImageInput,
|
|
22
|
+
type JsonLike,
|
|
23
|
+
type ResolvedModel,
|
|
15
24
|
} from "./types.js";
|
|
16
25
|
|
|
17
26
|
export type ExtractOptions = {
|
|
@@ -51,7 +60,7 @@ function jsonLike(value: unknown): value is JsonLike {
|
|
|
51
60
|
return Object.values(value).every(jsonLike);
|
|
52
61
|
}
|
|
53
62
|
|
|
54
|
-
function parseAnswers(value: unknown, fields: ExtractParams["fields"]): Record<string, ExtractResult["answers"][string]> {
|
|
63
|
+
function parseAnswers(value: unknown, fields: NonNullable<ExtractParams["fields"]>): Record<string, ExtractResult["answers"][string]> {
|
|
55
64
|
if (!isRecord(value)) throw new ClassifierError("response", CLAIRIC_LABEL + " returned invalid answers.");
|
|
56
65
|
const answers: Record<string, ExtractResult["answers"][string]> = Object.create(null);
|
|
57
66
|
for (const name of Object.keys(fields)) {
|
|
@@ -70,13 +79,20 @@ function parseAnswers(value: unknown, fields: ExtractParams["fields"]): Record<s
|
|
|
70
79
|
return answers;
|
|
71
80
|
}
|
|
72
81
|
|
|
73
|
-
/**
|
|
82
|
+
/**
|
|
83
|
+
* `classify_extract` entry point. Two exclusive modes share the extraction result contract:
|
|
84
|
+
* `fields` for Clairic-shaped field specs on extraction routes, and `questions` for typed
|
|
85
|
+
* extraction reads on decision routes, including direct Liquid `d1.2`/`d1.2-ultra`.
|
|
86
|
+
*/
|
|
74
87
|
export async function extract(params: unknown, options: ExtractOptions): Promise<ExtractResult> {
|
|
75
88
|
if (params === null || typeof params !== "object" || Array.isArray(params))
|
|
76
|
-
throw new ClassifierError("input", "extract requires an object with fields and optional state/media.");
|
|
89
|
+
throw new ClassifierError("input", "extract requires an object with fields or questions and optional state/media.");
|
|
77
90
|
const input = params as ExtractParams;
|
|
78
91
|
if (options.signal?.aborted)
|
|
79
92
|
throw new ClassifierError("aborted", "Extraction was cancelled.");
|
|
93
|
+
if ((input.fields === undefined) === (input.questions === undefined))
|
|
94
|
+
throw new ClassifierError("input", "classify_extract needs exactly one of fields (field specifications) or questions (typed extraction reads).");
|
|
95
|
+
if (input.questions !== undefined) return extractQuestions(input, options);
|
|
80
96
|
const route = resolveModel(options.settings, undefined, options.credentialSource ?? "pi-store");
|
|
81
97
|
const apiKey = route.authMode === "none" ? "" : resolveApiKey(route, options.credentialSource ?? "pi-store");
|
|
82
98
|
const prepared = await prepareExtractionInput(
|
|
@@ -132,6 +148,179 @@ function costOf(route: import("./types.js").ResolvedModel, usage: unknown): Clas
|
|
|
132
148
|
return estimateCost(route, usage);
|
|
133
149
|
}
|
|
134
150
|
|
|
151
|
+
/** Result-value view of one extraction answer; the read itself stays in metadata. */
|
|
152
|
+
function extractionAnswer(answer: Answer): ExtractionAnswer {
|
|
153
|
+
switch (answer.type) {
|
|
154
|
+
case "text": {
|
|
155
|
+
const parsed: ExtractionAnswer = { type: "text", value: answer.text };
|
|
156
|
+
if (answer.span !== undefined) parsed.span = answer.span;
|
|
157
|
+
if (answer.found !== undefined) parsed.found = answer.found;
|
|
158
|
+
if (answer.path !== undefined) parsed.path = answer.path;
|
|
159
|
+
return parsed;
|
|
160
|
+
}
|
|
161
|
+
case "number": {
|
|
162
|
+
const parsed: ExtractionAnswer = { type: "number", value: answer.value };
|
|
163
|
+
if (answer.unit !== undefined) parsed.unit = answer.unit;
|
|
164
|
+
if (answer.text !== undefined) parsed.text = answer.text;
|
|
165
|
+
if (answer.span !== undefined) parsed.span = answer.span;
|
|
166
|
+
if (answer.found !== undefined) parsed.found = answer.found;
|
|
167
|
+
if (answer.path !== undefined) parsed.path = answer.path;
|
|
168
|
+
return parsed;
|
|
169
|
+
}
|
|
170
|
+
case "date": {
|
|
171
|
+
const parsed: ExtractionAnswer = { type: "date", value: answer.date };
|
|
172
|
+
if (answer.text !== undefined) parsed.text = answer.text;
|
|
173
|
+
if (answer.span !== undefined) parsed.span = answer.span;
|
|
174
|
+
if (answer.found !== undefined) parsed.found = answer.found;
|
|
175
|
+
if (answer.path !== undefined) parsed.path = answer.path;
|
|
176
|
+
return parsed;
|
|
177
|
+
}
|
|
178
|
+
case "estimate": {
|
|
179
|
+
const parsed: ExtractionAnswer = { type: "estimate", value: answer.value, interval: answer.interval };
|
|
180
|
+
if (answer.unit !== undefined) parsed.unit = answer.unit;
|
|
181
|
+
return parsed;
|
|
182
|
+
}
|
|
183
|
+
case "spans": {
|
|
184
|
+
const parsed: ExtractionAnswer = {
|
|
185
|
+
type: "spans",
|
|
186
|
+
value: answer.spans.map((span) => span.text),
|
|
187
|
+
spans: answer.spans.map((span) => ({ text: span.text, span: span.span, found: span.found })),
|
|
188
|
+
count: answer.count,
|
|
189
|
+
atLeast: answer.atLeast,
|
|
190
|
+
presence: answer.presence,
|
|
191
|
+
};
|
|
192
|
+
return parsed;
|
|
193
|
+
}
|
|
194
|
+
case "boxes": {
|
|
195
|
+
const parsed: ExtractionAnswer = {
|
|
196
|
+
type: "boxes",
|
|
197
|
+
value: answer.boxes.map((entry) => entry.box),
|
|
198
|
+
boxes: answer.boxes.map((entry) => ({ box: entry.box, found: entry.found, confidence: entry.confidence })),
|
|
199
|
+
count: answer.count,
|
|
200
|
+
atLeast: answer.atLeast,
|
|
201
|
+
presence: answer.presence,
|
|
202
|
+
};
|
|
203
|
+
return parsed;
|
|
204
|
+
}
|
|
205
|
+
case "box": {
|
|
206
|
+
const parsed: ExtractionAnswer = { type: "box", value: answer.box, confidence: answer.confidence };
|
|
207
|
+
if (answer.found !== undefined) parsed.found = answer.found;
|
|
208
|
+
return parsed;
|
|
209
|
+
}
|
|
210
|
+
case "locate": {
|
|
211
|
+
const parsed: ExtractionAnswer = {
|
|
212
|
+
type: "locate",
|
|
213
|
+
value: answer.spans.map((span) => span.text),
|
|
214
|
+
spans: answer.spans.map((span) => ({
|
|
215
|
+
start: span.start,
|
|
216
|
+
end: span.end,
|
|
217
|
+
text: span.text,
|
|
218
|
+
score: span.score,
|
|
219
|
+
...(span.searchResult !== undefined ? { searchResult: span.searchResult } : {}),
|
|
220
|
+
})),
|
|
221
|
+
};
|
|
222
|
+
return parsed;
|
|
223
|
+
}
|
|
224
|
+
case "extract": {
|
|
225
|
+
const parsed: ExtractionAnswer = {
|
|
226
|
+
type: "extract",
|
|
227
|
+
value: Object.fromEntries(
|
|
228
|
+
Object.entries(answer.spans).map(([field, spans]) => [field, spans.map((span) => span.text)]),
|
|
229
|
+
),
|
|
230
|
+
spans: Object.fromEntries(
|
|
231
|
+
Object.entries(answer.spans).map(([field, spans]) => [
|
|
232
|
+
field,
|
|
233
|
+
spans.map((span) => ({
|
|
234
|
+
start: span.start,
|
|
235
|
+
end: span.end,
|
|
236
|
+
text: span.text,
|
|
237
|
+
score: span.score,
|
|
238
|
+
...(span.searchResult !== undefined ? { searchResult: span.searchResult } : {}),
|
|
239
|
+
})),
|
|
240
|
+
]),
|
|
241
|
+
),
|
|
242
|
+
notStated: answer.notStated,
|
|
243
|
+
};
|
|
244
|
+
return parsed;
|
|
245
|
+
}
|
|
246
|
+
case "refusal":
|
|
247
|
+
case "no_match":
|
|
248
|
+
case "ambiguous":
|
|
249
|
+
return { type: answer.type, value: null };
|
|
250
|
+
default:
|
|
251
|
+
throw new ClassifierError(
|
|
252
|
+
"response",
|
|
253
|
+
"Extraction questions returned a " + answer.type + " decision, which is not an extraction read.",
|
|
254
|
+
);
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
function questionExtractionResult(
|
|
259
|
+
route: ResolvedModel,
|
|
260
|
+
result: ClassifierResult,
|
|
261
|
+
questions: Record<string, ExtractionQuestion>,
|
|
262
|
+
): ExtractResult {
|
|
263
|
+
const answers: Record<string, ExtractionAnswer> = Object.create(null);
|
|
264
|
+
for (const id of Object.keys(questions)) {
|
|
265
|
+
const answer = result.answers[id];
|
|
266
|
+
if (answer === undefined)
|
|
267
|
+
throw new ClassifierError("response", "The selected route did not return an answer for " + id + ".");
|
|
268
|
+
answers[id] = extractionAnswer(answer);
|
|
269
|
+
}
|
|
270
|
+
const extracted: ExtractResult = {
|
|
271
|
+
provider: route.route,
|
|
272
|
+
model: route.model,
|
|
273
|
+
answers,
|
|
274
|
+
// Typed reads return provider-validated values; no generated field output can truncate.
|
|
275
|
+
truncated: false,
|
|
276
|
+
cost: result.cost,
|
|
277
|
+
};
|
|
278
|
+
if (result.usage !== undefined) extracted.usage = result.usage;
|
|
279
|
+
if (result.providerCost !== undefined) extracted.providerCost = result.providerCost;
|
|
280
|
+
if (result.requestId !== undefined) extracted.requestId = result.requestId;
|
|
281
|
+
if (result.citations !== undefined) extracted.citations = result.citations;
|
|
282
|
+
if (result.webGrounding !== undefined) extracted.webGrounding = result.webGrounding;
|
|
283
|
+
if (result.attemptedRoutes !== undefined) extracted.attemptedRoutes = result.attemptedRoutes;
|
|
284
|
+
if (Buffer.byteLength(JSON.stringify(extracted, null, 2)) > 40 * 1024)
|
|
285
|
+
throw new ClassifierError("response", "Extraction result exceeds the 40 KiB tool output limit. Ask for fewer or narrower reads.");
|
|
286
|
+
return extracted;
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
/** Typed extraction questions on a decision route; the route itself supplies the read primitives. */
|
|
290
|
+
async function extractQuestions(input: ExtractParams, options: ExtractOptions): Promise<ExtractResult> {
|
|
291
|
+
const questions = validateExtractionQuestions(input.questions);
|
|
292
|
+
if (input.documents !== undefined)
|
|
293
|
+
throw new ClassifierError("capability", "PDF documents are accepted only by field extraction. Send the document's text as state for typed reads.");
|
|
294
|
+
if (input.referenceDate !== undefined || input.options !== undefined)
|
|
295
|
+
throw new ClassifierError("capability", "referenceDate and options apply only to field extraction.");
|
|
296
|
+
if (input.state === undefined)
|
|
297
|
+
throw new ClassifierError("input", "Extraction questions require state: pass text or JSON. An empty string is allowed for image-only reads.");
|
|
298
|
+
const decision: DecisionInput = { state: input.state, questions };
|
|
299
|
+
const images: ImageInput[] = [];
|
|
300
|
+
for (const image of input.images ?? []) {
|
|
301
|
+
if (typeof image === "string") {
|
|
302
|
+
images.push(image);
|
|
303
|
+
} else if ("id" in image) {
|
|
304
|
+
images.push("path" in image ? { id: image.id, path: image.path } : { id: image.id, url: image.url });
|
|
305
|
+
} else {
|
|
306
|
+
throw new ClassifierError(
|
|
307
|
+
"input",
|
|
308
|
+
"Extraction question images must be local path strings or named {id, path}/{id, url} descriptors. Rotation applies only to direct Clairic field extraction.",
|
|
309
|
+
);
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
validateImageDescriptors(images, input.state, questions);
|
|
313
|
+
if (images.length > 0) decision.images = images;
|
|
314
|
+
if (input.media !== undefined) decision.media = input.media;
|
|
315
|
+
if (input.mode !== undefined) decision.mode = input.mode;
|
|
316
|
+
const { result, route } = await runDecisionRequest(
|
|
317
|
+
decision,
|
|
318
|
+
options,
|
|
319
|
+
(prepared, selected, apiKey) => classifyWithProvider(selected, prepared, apiKey, options.signal),
|
|
320
|
+
);
|
|
321
|
+
return questionExtractionResult(route, result, questions);
|
|
322
|
+
}
|
|
323
|
+
|
|
135
324
|
function finalizeExtraction(
|
|
136
325
|
route: import("./types.js").ResolvedModel,
|
|
137
326
|
result: Record<string, unknown>,
|
package/src/index.ts
CHANGED
package/src/inputs.ts
CHANGED
|
@@ -7,7 +7,7 @@ import sharp from "sharp";
|
|
|
7
7
|
import {
|
|
8
8
|
ClassifierError,
|
|
9
9
|
isRecord,
|
|
10
|
-
type
|
|
10
|
+
type DecisionInput,
|
|
11
11
|
type ExtractParams,
|
|
12
12
|
type PreparedImage,
|
|
13
13
|
type PreparedLocalImage,
|
|
@@ -31,7 +31,7 @@ export interface MemoryImage {
|
|
|
31
31
|
}
|
|
32
32
|
|
|
33
33
|
export async function prepareInput(
|
|
34
|
-
params:
|
|
34
|
+
params: DecisionInput,
|
|
35
35
|
route: ResolvedModel,
|
|
36
36
|
cwd: string,
|
|
37
37
|
signal?: AbortSignal,
|
|
@@ -46,15 +46,23 @@ export async function prepareInput(
|
|
|
46
46
|
if (route.api === "perplexity-decisions" && params.mode === "web_grounding" && questionCount > 100)
|
|
47
47
|
throw new ClassifierError("input", "Perplexity web grounding accepts at most 100 questions.");
|
|
48
48
|
const openRouter = route.api === "openrouter-decisions" ? openRouterDecisionCapabilities(route.model) : undefined;
|
|
49
|
+
const liquid = route.api === "liquid-system-one";
|
|
49
50
|
const imageCount = (params.images?.length ?? 0) + memoryImages.length;
|
|
50
51
|
if (imageCount && !route.images)
|
|
51
52
|
throw new ClassifierError("capability", "The selected model does not support images, or experimental Jev images are disabled.");
|
|
53
|
+
// Liquid documents exactly one image for box and boxes questions; other routes do not publish that rule.
|
|
54
|
+
const liquidLocationRead = liquid &&
|
|
55
|
+
Object.values(params.questions).some((question) => question.type === "box" || question.type === "boxes");
|
|
56
|
+
if (liquidLocationRead && imageCount !== 1)
|
|
57
|
+
throw new ClassifierError("input", "Liquid box and boxes questions require exactly one image per request; " + imageCount + " supplied. Send one image or split the reads across requests.");
|
|
52
58
|
if (hasBox(params.questions) && (!route.box || !imageCount))
|
|
53
59
|
throw new ClassifierError("capability", "box requires an enabled Jev 1.14 model, experimentalImages/experimentalBox and an image.");
|
|
54
60
|
if (params.mode === "web_grounding" && route.api !== "perplexity-decisions")
|
|
55
61
|
throw new ClassifierError("capability", "Web grounding is supported only by Perplexity Decisions routes.");
|
|
56
62
|
if (route.api === "cloudflare-clairic")
|
|
57
|
-
throw new ClassifierError("capability", "Clairic
|
|
63
|
+
throw new ClassifierError("capability", "Clairic reads fields through classify_extract; it has no typed-question surface.");
|
|
64
|
+
if (route.api === "openrouter-extractions" || route.api === "litellm-extraction")
|
|
65
|
+
throw new ClassifierError("capability", "The selected extraction route reads fields only. Typed extraction questions need a decision route such as liquid-api, typesafe-api, perplexity-decisions or inception-api.");
|
|
58
66
|
if (params.imageDetail !== undefined && !["openai-decisions", "openrouter-decisions"].includes(route.api))
|
|
59
67
|
throw new ClassifierError("capability", "imageDetail is supported only by OpenAI-compatible and OpenRouter Decisions routes.");
|
|
60
68
|
if (params.promptCache !== undefined && route.api !== "openai-decisions")
|
|
@@ -75,7 +83,7 @@ export async function prepareInput(
|
|
|
75
83
|
? sarvamQuestions
|
|
76
84
|
: route.api === "inception-decisions"
|
|
77
85
|
? [...coreQuestions, "extract"]
|
|
78
|
-
: ["gemini-decisions", "parallel-decisions", "local-system-one"].includes(route.api)
|
|
86
|
+
: ["gemini-decisions", "parallel-decisions", "local-system-one", "subq-system-one", "alibaba-system-one", "fireworks-system-one"].includes(route.api)
|
|
79
87
|
? coreQuestions
|
|
80
88
|
: openRouter
|
|
81
89
|
? openRouterQuestions
|
|
@@ -112,7 +120,7 @@ export async function prepareInput(
|
|
|
112
120
|
throw new ClassifierError("input", "locate requires a string state. Offsets are defined only for text.");
|
|
113
121
|
}
|
|
114
122
|
const clef = route.api === "cloudflare-system-one" && route.images;
|
|
115
|
-
const
|
|
123
|
+
const tightImages = clef || route.api === "subq-system-one";
|
|
116
124
|
if (imageCount > route.limits.maxImages)
|
|
117
125
|
throw new ClassifierError("input", "The selected route accepts at most " + route.limits.maxImages + " images in this package.");
|
|
118
126
|
const flexibleReferences = openRouter?.flexibleImagePlacement === true;
|
|
@@ -153,7 +161,7 @@ export async function prepareInput(
|
|
|
153
161
|
];
|
|
154
162
|
for (const entry of sources) {
|
|
155
163
|
cancelled(signal);
|
|
156
|
-
const maxBytes = (
|
|
164
|
+
const maxBytes = (tightImages ? 4 : 5) * 1024 * 1024;
|
|
157
165
|
let image: PreparedLocalImage;
|
|
158
166
|
let id: string | undefined;
|
|
159
167
|
if ("memory" in entry) {
|
|
@@ -168,7 +176,7 @@ export async function prepareInput(
|
|
|
168
176
|
if (typeof source !== "string") id = source.id;
|
|
169
177
|
}
|
|
170
178
|
totalBytes += Buffer.byteLength(image.data, "base64");
|
|
171
|
-
if (totalBytes > (
|
|
179
|
+
if (totalBytes > (tightImages ? 8 : 10) * 1024 * 1024)
|
|
172
180
|
throw new ClassifierError("input", "Images exceed the selected route's total upload byte limit.");
|
|
173
181
|
if (route.api === "microsoft-system-one" && image.mimeType === "image/webp")
|
|
174
182
|
throw new ClassifierError("input", "Microsoft Foundry Decision-1.1 image assets accept PNG and JPEG only.");
|
|
@@ -391,7 +399,7 @@ async function loadMediaFile(
|
|
|
391
399
|
}
|
|
392
400
|
|
|
393
401
|
async function prepareMedia(
|
|
394
|
-
sources: NonNullable<
|
|
402
|
+
sources: NonNullable<DecisionInput["media"]>,
|
|
395
403
|
route: ResolvedModel,
|
|
396
404
|
cwd: string,
|
|
397
405
|
signal?: AbortSignal,
|
|
@@ -421,6 +429,29 @@ async function prepareMedia(
|
|
|
421
429
|
|
|
422
430
|
export type PreparedExtractionImage = PreparedLocalImage & { rotation?: 0 | 90 | 180 | 270 };
|
|
423
431
|
|
|
432
|
+
type FieldExtractionImage = string | { path: string; rotation?: 0 | 90 | 180 | 270 };
|
|
433
|
+
|
|
434
|
+
/** Field extraction keeps its local-path/rotation image contract; question mode uses shared images. */
|
|
435
|
+
function fieldExtractionImages(value: ExtractParams["images"]): FieldExtractionImage[] {
|
|
436
|
+
if (value === undefined) return [];
|
|
437
|
+
if (!Array.isArray(value)) throw new ClassifierError("input", "images must be an array.");
|
|
438
|
+
return value.map((image): FieldExtractionImage => {
|
|
439
|
+
if (typeof image === "string") {
|
|
440
|
+
if (!image.trim() || image.length > 4096)
|
|
441
|
+
throw new ClassifierError("input", "Image paths must be non-empty, at most 4096 characters.");
|
|
442
|
+
return image;
|
|
443
|
+
}
|
|
444
|
+
const spec: unknown = image;
|
|
445
|
+
if (!isRecord(spec) || Object.keys(spec).some((key) => key !== "path" && key !== "rotation") ||
|
|
446
|
+
typeof spec.path !== "string" || !spec.path.trim() || spec.path.length > 4096 ||
|
|
447
|
+
(spec.rotation !== undefined && ![0, 90, 180, 270].includes(spec.rotation as number)))
|
|
448
|
+
throw new ClassifierError("input", "Field extraction images must be local path strings or {path, rotation} objects. Named and hosted images are accepted only by extraction questions.");
|
|
449
|
+
return spec.rotation === undefined
|
|
450
|
+
? { path: spec.path }
|
|
451
|
+
: { path: spec.path, rotation: spec.rotation as 0 | 90 | 180 | 270 };
|
|
452
|
+
});
|
|
453
|
+
}
|
|
454
|
+
|
|
424
455
|
export type PreparedExtractionInput = {
|
|
425
456
|
state: string | Record<string, unknown> | unknown[];
|
|
426
457
|
fields: NonNullable<ExtractParams["fields"]>;
|
|
@@ -571,12 +602,18 @@ export async function prepareExtractionInput(
|
|
|
571
602
|
cwd: string,
|
|
572
603
|
signal?: AbortSignal,
|
|
573
604
|
): Promise<PreparedExtractionInput> {
|
|
605
|
+
if (params.questions !== undefined)
|
|
606
|
+
throw new ClassifierError("input", "Extraction questions use the typed-question path, not fields.");
|
|
607
|
+
if (params.media !== undefined || params.mode !== undefined)
|
|
608
|
+
throw new ClassifierError("capability", "Field extraction does not accept media or web grounding. Use extraction questions on a decision route instead.");
|
|
574
609
|
if (!["cloudflare-clairic", "openrouter-extractions", "litellm-extraction"].includes(route.api))
|
|
575
|
-
throw new ClassifierError("capability", "
|
|
610
|
+
throw new ClassifierError("capability", "Field extraction requires a clairic-api, openrouter-extractions-api or litellm-extraction-api route. Use questions for typed extraction on a decision route.");
|
|
576
611
|
if (params.state !== undefined &&
|
|
577
612
|
!(typeof params.state === "string" || Array.isArray(params.state) || isRecord(params.state)))
|
|
578
613
|
throw new ClassifierError("input", "state must be text, a JSON object or an array.");
|
|
579
614
|
const extractionCaps = route.api === "openrouter-extractions" ? openRouterExtractionCapabilities(route.model) : undefined;
|
|
615
|
+
if (params.fields === undefined)
|
|
616
|
+
throw new ClassifierError("input", "Field extraction requires a non-empty fields map.");
|
|
580
617
|
const fields = validateExtractionFields(
|
|
581
618
|
params.fields,
|
|
582
619
|
extractionCaps ? new Set(extractionCaps.fieldTypes) : EXTRACTION_TYPES,
|
|
@@ -595,14 +632,10 @@ export async function prepareExtractionInput(
|
|
|
595
632
|
Object.values(params.options).some((value) => typeof value !== "boolean"))
|
|
596
633
|
throw new ClassifierError("input", "options may only set includeQuantiles and returnStateText to booleans.");
|
|
597
634
|
}
|
|
598
|
-
if (params.images !== undefined &&
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
typeof image.path !== "string" || !image.path.trim() || image.path.length > 4096 ||
|
|
603
|
-
(image.rotation !== undefined && ![0, 90, 180, 270].includes(image.rotation as number)))))
|
|
604
|
-
throw new ClassifierError("input", "images must be local path strings or {path, rotation} objects with rotation 0, 90, 180 or 270.");
|
|
605
|
-
if (route.api !== "cloudflare-clairic" && (params.images ?? []).some((image) => typeof image !== "string" && image.rotation !== undefined))
|
|
635
|
+
if (params.images !== undefined && !Array.isArray(params.images))
|
|
636
|
+
throw new ClassifierError("input", "images must be an array.");
|
|
637
|
+
const fieldImages = fieldExtractionImages(params.images);
|
|
638
|
+
if (route.api !== "cloudflare-clairic" && fieldImages.some((image) => typeof image !== "string" && image.rotation !== undefined))
|
|
606
639
|
throw new ClassifierError("capability", "Image rotation is documented only for direct Cloudflare Clairic.");
|
|
607
640
|
if (params.documents !== undefined && (!Array.isArray(params.documents) || params.documents.some((document) => typeof document !== "string" || !document.trim() || document.length > 4096)))
|
|
608
641
|
throw new ClassifierError("input", "documents must be local PDF path strings inside cwd.");
|
|
@@ -616,7 +649,7 @@ export async function prepareExtractionInput(
|
|
|
616
649
|
const isScaleDown = route.api === "openrouter-extractions" && route.model === "scaledown/extract";
|
|
617
650
|
if (isScaleDown && (params.images?.length ?? 0) + (params.documents?.length ?? 0) > 0 && params.state !== undefined && params.state !== "")
|
|
618
651
|
throw new ClassifierError("input", "ScaleDown Extract reads either text state or one asset, not both. Omit state when sending a PDF or image.");
|
|
619
|
-
const images = await Promise.all(
|
|
652
|
+
const images = await Promise.all(fieldImages.map(async (image) => {
|
|
620
653
|
const spec = typeof image === "string" ? { path: image } : image;
|
|
621
654
|
const loaded = await loadLocalImage(spec.path, cwd, signal, 4 * 1024 * 1024);
|
|
622
655
|
return spec.rotation === undefined ? loaded : { ...loaded, rotation: spec.rotation as 0 | 90 | 180 | 270 };
|
package/src/providers.ts
CHANGED
|
@@ -61,6 +61,12 @@ export async function classifyWithProvider(
|
|
|
61
61
|
return classifySarvam(route, input, apiKey, signal);
|
|
62
62
|
case "system-one":
|
|
63
63
|
return classifySystemOne(route, input, apiKey, signal);
|
|
64
|
+
case "subq-system-one":
|
|
65
|
+
return classifySubQ(route, input, apiKey, signal);
|
|
66
|
+
case "alibaba-system-one":
|
|
67
|
+
return classifyAlibaba(route, input, apiKey, signal);
|
|
68
|
+
case "fireworks-system-one":
|
|
69
|
+
return classifyFireworks(route, input, apiKey, signal);
|
|
64
70
|
case "liquid-system-one":
|
|
65
71
|
return classifyLiquid(route, input, apiKey, signal);
|
|
66
72
|
case "microsoft-system-one":
|
|
@@ -1801,6 +1807,108 @@ async function classifySystemOne(
|
|
|
1801
1807
|
);
|
|
1802
1808
|
}
|
|
1803
1809
|
|
|
1810
|
+
/* SubQ Snap --------------------------------------------------------------- */
|
|
1811
|
+
|
|
1812
|
+
const SUBQ_LABEL = "SubQ Snap";
|
|
1813
|
+
|
|
1814
|
+
async function classifySubQ(
|
|
1815
|
+
route: ResolvedModel,
|
|
1816
|
+
input: PreparedInput,
|
|
1817
|
+
apiKey: string,
|
|
1818
|
+
signal?: AbortSignal,
|
|
1819
|
+
): Promise<ClassifierResult> {
|
|
1820
|
+
const payload: Record<string, unknown> = {
|
|
1821
|
+
model: route.model,
|
|
1822
|
+
state: input.state,
|
|
1823
|
+
questions: systemOneQuestions(input.questions, false),
|
|
1824
|
+
};
|
|
1825
|
+
if (input.images.length > 0)
|
|
1826
|
+
payload.images = input.images.map((image) => {
|
|
1827
|
+
if ("url" in image)
|
|
1828
|
+
throw new ClassifierError("capability", "SubQ accepts inline image bytes only.");
|
|
1829
|
+
return { mediaType: image.mimeType, base64: image.data };
|
|
1830
|
+
});
|
|
1831
|
+
const { body, requestId } = await postJson(route, "v1/systemone", payload, apiKey, signal);
|
|
1832
|
+
if (!isRecord(body)) fail(SUBQ_LABEL + " returned an unexpected response.");
|
|
1833
|
+
return finish(
|
|
1834
|
+
route,
|
|
1835
|
+
parseTypedAnswers(SUBQ_LABEL, body.answers, input.questions),
|
|
1836
|
+
body.usage,
|
|
1837
|
+
requestId,
|
|
1838
|
+
);
|
|
1839
|
+
}
|
|
1840
|
+
|
|
1841
|
+
/* Alibaba Model Studio Decision Model ------------------------------------ */
|
|
1842
|
+
|
|
1843
|
+
const ALIBABA_LABEL = "Alibaba Decision Model";
|
|
1844
|
+
|
|
1845
|
+
async function classifyAlibaba(
|
|
1846
|
+
route: ResolvedModel,
|
|
1847
|
+
input: PreparedInput,
|
|
1848
|
+
apiKey: string,
|
|
1849
|
+
signal?: AbortSignal,
|
|
1850
|
+
): Promise<ClassifierResult> {
|
|
1851
|
+
const payload: Record<string, unknown> = {
|
|
1852
|
+
model: route.model,
|
|
1853
|
+
state: input.state,
|
|
1854
|
+
questions: systemOneQuestions(input.questions, false),
|
|
1855
|
+
};
|
|
1856
|
+
if (input.images.length > 0) {
|
|
1857
|
+
// Alibaba takes its own `image`/`images` entries whose `url` accepts a Base64 data URL.
|
|
1858
|
+
const images = input.images.map((image) => {
|
|
1859
|
+
if ("url" in image)
|
|
1860
|
+
throw new ClassifierError("capability", "Alibaba Decision Model requires local image data.");
|
|
1861
|
+
return { url: imageUrl(image) };
|
|
1862
|
+
});
|
|
1863
|
+
if (images.length === 1) payload.image = images[0];
|
|
1864
|
+
else payload.images = images;
|
|
1865
|
+
}
|
|
1866
|
+
const { body, requestId } = await postJson(
|
|
1867
|
+
route,
|
|
1868
|
+
"compatible-mode/v1/systemone",
|
|
1869
|
+
payload,
|
|
1870
|
+
apiKey,
|
|
1871
|
+
signal,
|
|
1872
|
+
);
|
|
1873
|
+
if (!isRecord(body)) fail(ALIBABA_LABEL + " returned an unexpected response.");
|
|
1874
|
+
return finish(
|
|
1875
|
+
route,
|
|
1876
|
+
parseTypedAnswers(ALIBABA_LABEL, body.answers, input.questions),
|
|
1877
|
+
body.usage,
|
|
1878
|
+
requestId,
|
|
1879
|
+
);
|
|
1880
|
+
}
|
|
1881
|
+
|
|
1882
|
+
/* Fireworks Rune ---------------------------------------------------------- */
|
|
1883
|
+
|
|
1884
|
+
const FIREWORKS_LABEL = "Fireworks System One";
|
|
1885
|
+
|
|
1886
|
+
async function classifyFireworks(
|
|
1887
|
+
route: ResolvedModel,
|
|
1888
|
+
input: PreparedInput,
|
|
1889
|
+
apiKey: string,
|
|
1890
|
+
signal?: AbortSignal,
|
|
1891
|
+
): Promise<ClassifierResult> {
|
|
1892
|
+
const { body, requestId } = await postJson(
|
|
1893
|
+
route,
|
|
1894
|
+
"systemone",
|
|
1895
|
+
{
|
|
1896
|
+
model: route.model,
|
|
1897
|
+
state: input.state,
|
|
1898
|
+
questions: systemOneQuestions(input.questions, false),
|
|
1899
|
+
},
|
|
1900
|
+
apiKey,
|
|
1901
|
+
signal,
|
|
1902
|
+
);
|
|
1903
|
+
if (!isRecord(body)) fail(FIREWORKS_LABEL + " returned an unexpected response.");
|
|
1904
|
+
return finish(
|
|
1905
|
+
route,
|
|
1906
|
+
parseTypedAnswers(FIREWORKS_LABEL, body.answers, input.questions),
|
|
1907
|
+
body.usage,
|
|
1908
|
+
requestId,
|
|
1909
|
+
);
|
|
1910
|
+
}
|
|
1911
|
+
|
|
1804
1912
|
/* Cloudflare Workers AI (Clef and third-party System One envelopes) ------- */
|
|
1805
1913
|
|
|
1806
1914
|
function clefBodyModel(model: string): string | undefined {
|