@abhishek944/pi-classifier 0.6.0 → 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 +13 -0
- package/README.md +122 -37
- 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 +77 -6
- package/dist/cost.js +5 -0
- 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 +1 -1
- package/src/choices.ts +1 -1
- package/src/classify.ts +44 -15
- package/src/config.ts +80 -6
- package/src/cost.ts +5 -0
- 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/dist/config.js
CHANGED
|
@@ -73,7 +73,7 @@ export const BUILT_INS = [
|
|
|
73
73
|
envVar: "OPENROUTER_API_KEY",
|
|
74
74
|
models: [
|
|
75
75
|
{ id: "cloudflare/clairic", input: ["text", "image"] },
|
|
76
|
-
{ id: "inception/mercury-decide", input: ["text"] },
|
|
76
|
+
{ id: "inception/mercury-decide", input: ["text"], shutdown: "2026-12-28" },
|
|
77
77
|
{ id: "liquid/d1.2", input: ["text", "image"] },
|
|
78
78
|
{ id: "liquid/d1.2-ultra", input: ["text", "image"] },
|
|
79
79
|
{ id: "perplexity/pplx-decider-v1.3", input: ["text"] },
|
|
@@ -90,6 +90,16 @@ export const BUILT_INS = [
|
|
|
90
90
|
envVar: "LITELLM_API_KEY",
|
|
91
91
|
models: [{ id: "clairic", input: ["text", "image"] }],
|
|
92
92
|
},
|
|
93
|
+
{
|
|
94
|
+
id: "litellm",
|
|
95
|
+
route: "litellm-decisions-api",
|
|
96
|
+
api: "openai-decisions",
|
|
97
|
+
baseUrl: "",
|
|
98
|
+
credentialProvider: "litellm",
|
|
99
|
+
envVar: "LITELLM_API_KEY",
|
|
100
|
+
// The declared alias is LiteLLM's own documentation example; any proxy model_name resolves.
|
|
101
|
+
models: [{ id: "luna", input: ["text"] }],
|
|
102
|
+
},
|
|
93
103
|
{
|
|
94
104
|
id: "microsoft",
|
|
95
105
|
route: "microsoft-api",
|
|
@@ -166,7 +176,7 @@ export const BUILT_INS = [
|
|
|
166
176
|
baseUrl: "https://api.inceptionlabs.ai/v1",
|
|
167
177
|
credentialProvider: "inception",
|
|
168
178
|
envVar: "INCEPTION_API_KEY",
|
|
169
|
-
models: [{ id: "mercury-decide", input: ["text", "image"] }],
|
|
179
|
+
models: [{ id: "mercury-decide", input: ["text", "image"], shutdown: "2026-12-28" }],
|
|
170
180
|
},
|
|
171
181
|
{
|
|
172
182
|
id: "parallel",
|
|
@@ -195,6 +205,37 @@ export const BUILT_INS = [
|
|
|
195
205
|
{ id: "pplx-decider-v1-27b", input: ["text", "image"] },
|
|
196
206
|
],
|
|
197
207
|
},
|
|
208
|
+
{
|
|
209
|
+
id: "subq",
|
|
210
|
+
route: "subq-api",
|
|
211
|
+
api: "subq-system-one",
|
|
212
|
+
baseUrl: "https://api.subq.ai",
|
|
213
|
+
credentialProvider: "subq",
|
|
214
|
+
envVar: "SUBQ_API_KEY",
|
|
215
|
+
models: [
|
|
216
|
+
{ id: "subq-snap-1.2", input: ["text", "image"] },
|
|
217
|
+
{ id: "subq-snap-latest", input: ["text", "image"] },
|
|
218
|
+
],
|
|
219
|
+
},
|
|
220
|
+
{
|
|
221
|
+
id: "dashscope",
|
|
222
|
+
route: "alibaba-api",
|
|
223
|
+
api: "alibaba-system-one",
|
|
224
|
+
// Decision Model endpoints are workspace- and region-scoped; the operator supplies the gateway host.
|
|
225
|
+
baseUrl: "",
|
|
226
|
+
credentialProvider: "dashscope",
|
|
227
|
+
envVar: "DASHSCOPE_API_KEY",
|
|
228
|
+
models: [{ id: "decision-model", input: ["text", "image"] }],
|
|
229
|
+
},
|
|
230
|
+
{
|
|
231
|
+
id: "fireworks",
|
|
232
|
+
route: "fireworks-api",
|
|
233
|
+
api: "fireworks-system-one",
|
|
234
|
+
baseUrl: "https://api.fireworks.ai/inference/v1",
|
|
235
|
+
credentialProvider: "fireworks",
|
|
236
|
+
envVar: "FIREWORKS_API_KEY",
|
|
237
|
+
models: [{ id: "accounts/fireworks/models/rune", input: ["text"] }],
|
|
238
|
+
},
|
|
198
239
|
{
|
|
199
240
|
id: "liquid",
|
|
200
241
|
route: "liquid-api",
|
|
@@ -267,7 +308,7 @@ export const BUILT_INS = [
|
|
|
267
308
|
{ id: "microsoft/microsoft-decision-1.1", input: ["text", "image"] },
|
|
268
309
|
{ id: "cloudflare/clef-flash", input: ["text", "image"] },
|
|
269
310
|
{ id: "cloudflare/clef-omni", input: ["text", "image", "audio", "video"] },
|
|
270
|
-
{ id: "inception/mercury-decide", input: ["text", "image"] },
|
|
311
|
+
{ id: "inception/mercury-decide", input: ["text", "image"], shutdown: "2026-12-28" },
|
|
271
312
|
{ id: "liquid/d1.2", input: ["text", "image"] },
|
|
272
313
|
{ id: "liquid/d1.2-ultra", input: ["text", "image"] },
|
|
273
314
|
{ id: "openai/gpt-6-luna-decisions", input: ["text", "image"] },
|
|
@@ -336,8 +377,18 @@ export function openRouterDecisionCapabilities(model) {
|
|
|
336
377
|
return { flexibleImagePlacement: false, box: false, remoteImageUrls: false, images: 0, audio: 0, video: 0 };
|
|
337
378
|
}
|
|
338
379
|
function builtInLimits(api, provider, model) {
|
|
339
|
-
if (api === "openai-decisions")
|
|
380
|
+
if (api === "openai-decisions") {
|
|
381
|
+
// LiteLLM validates 1-128 questions on both decision routes before calling a provider.
|
|
382
|
+
if (provider === "litellm")
|
|
383
|
+
return { ...DEFAULT_LIMITS, maxQuestions: 128 };
|
|
340
384
|
return { ...DEFAULT_LIMITS, maxQuestions: 400 };
|
|
385
|
+
}
|
|
386
|
+
if (api === "subq-system-one")
|
|
387
|
+
return { ...DEFAULT_LIMITS, maxQuestions: 128, maxImages: 4, maxAudio: 0, maxVideo: 0 };
|
|
388
|
+
if (api === "alibaba-system-one")
|
|
389
|
+
return { ...DEFAULT_LIMITS, maxQuestions: 16, maxImages: 16, maxAudio: 0, maxVideo: 0 };
|
|
390
|
+
if (api === "fireworks-system-one")
|
|
391
|
+
return { ...DEFAULT_LIMITS, maxQuestions: 256, maxImages: 0, maxAudio: 0, maxVideo: 0 };
|
|
341
392
|
if (api === "openrouter-extractions") {
|
|
342
393
|
const caps = openRouterExtractionCapabilities(model);
|
|
343
394
|
return { ...DEFAULT_LIMITS, maxImages: caps.maxImages, maxAudio: 0, maxVideo: 0 };
|
|
@@ -555,6 +606,9 @@ export function resolveModel(settings, selected = configuredDefault(settings), s
|
|
|
555
606
|
"openrouter-extractions",
|
|
556
607
|
"litellm-extraction",
|
|
557
608
|
"microsoft-system-one",
|
|
609
|
+
"subq-system-one",
|
|
610
|
+
"alibaba-system-one",
|
|
611
|
+
"fireworks-system-one",
|
|
558
612
|
].includes(api))
|
|
559
613
|
return configuration("Unsupported classifier API protocol.");
|
|
560
614
|
const models = builtIn?.models ?? custom.models;
|
|
@@ -601,7 +655,7 @@ export function resolveModel(settings, selected = configuredDefault(settings), s
|
|
|
601
655
|
cloudflareAccountId(optionalString(raw.accountId, "accountId"), source) +
|
|
602
656
|
"/ai";
|
|
603
657
|
if (!baseUrl)
|
|
604
|
-
return configuration("The selected provider requires a baseUrl. Microsoft uses your Foundry resource endpoint
|
|
658
|
+
return configuration("The selected provider requires a baseUrl. Microsoft uses your Foundry resource endpoint, Alibaba uses your Model Studio workspace gateway host, and local runtimes use your server URL.");
|
|
605
659
|
const timeout = settings.requestTimeoutMs ?? 30_000;
|
|
606
660
|
if (!Number.isInteger(timeout) || timeout < 100 || timeout > 300_000)
|
|
607
661
|
return configuration("requestTimeoutMs must be between 100 and 300000.");
|
|
@@ -722,10 +776,27 @@ function knownMaxChoices(route) {
|
|
|
722
776
|
const liquid = route.provider === "liquid" &&
|
|
723
777
|
route.baseUrl === "https://api.liquid.ai/decisions/v1" &&
|
|
724
778
|
["d1.2", "d1.2-ultra"].includes(route.model);
|
|
779
|
+
const subq = route.provider === "subq" &&
|
|
780
|
+
route.baseUrl === "https://api.subq.ai" &&
|
|
781
|
+
["subq-snap-1.2", "subq-snap-latest"].includes(route.model);
|
|
782
|
+
const alibaba = route.api === "alibaba-system-one" &&
|
|
783
|
+
route.provider === "dashscope" &&
|
|
784
|
+
route.model === "decision-model";
|
|
785
|
+
const fireworks = route.provider === "fireworks" &&
|
|
786
|
+
route.baseUrl === "https://api.fireworks.ai/inference/v1" &&
|
|
787
|
+
route.model === "accounts/fireworks/models/rune";
|
|
788
|
+
const litellm = route.route === "litellm-decisions-api";
|
|
789
|
+
if (subq || alibaba || litellm)
|
|
790
|
+
return 255;
|
|
791
|
+
if (fireworks)
|
|
792
|
+
return 208;
|
|
725
793
|
return directJev || sarvam || openai || perplexity || clef || liquid ? 255 : undefined;
|
|
726
794
|
}
|
|
727
795
|
export function listModels(settings) {
|
|
728
|
-
const lines = BUILT_INS.flatMap((provider) => provider.models.map((model) => provider.route +
|
|
796
|
+
const lines = BUILT_INS.flatMap((provider) => provider.models.map((model) => provider.route +
|
|
797
|
+
" " +
|
|
798
|
+
model.id +
|
|
799
|
+
(model.shutdown ? " (shuts down " + model.shutdown + ")" : "")));
|
|
729
800
|
for (const [id, provider] of Object.entries(settings.customProviders ?? {})) {
|
|
730
801
|
if (Array.isArray(provider?.models))
|
|
731
802
|
for (const model of provider.models)
|
package/dist/cost.js
CHANGED
|
@@ -29,6 +29,10 @@ const PRICES = {
|
|
|
29
29
|
"d1.2": { inputPerMillion: 0.02, outputPerMillion: 0 },
|
|
30
30
|
"d1.2-ultra": { inputPerMillion: 0.042, outputPerMillion: 0 },
|
|
31
31
|
},
|
|
32
|
+
subq: {
|
|
33
|
+
"subq-snap-1.2": { inputPerMillion: 0.04, outputPerMillion: 0 },
|
|
34
|
+
"subq-snap-latest": { inputPerMillion: 0.04, outputPerMillion: 0 },
|
|
35
|
+
},
|
|
32
36
|
"opencode-go": {
|
|
33
37
|
"jev-1.14": { inputPerMillion: 0.042, outputPerMillion: 0 },
|
|
34
38
|
"gemini-decision-1": { inputPerMillion: 0.1, outputPerMillion: 0 },
|
|
@@ -85,6 +89,7 @@ export function resolvePricing(provider, model, baseUrl, overrides) {
|
|
|
85
89
|
(provider === "typesafe" && baseUrl === "https://api.typesafe.ai/v1") ||
|
|
86
90
|
(provider === "perplexity" && baseUrl === "https://api.perplexity.ai/v1") ||
|
|
87
91
|
(provider === "liquid" && baseUrl === "https://api.liquid.ai/decisions/v1") ||
|
|
92
|
+
(provider === "subq" && baseUrl === "https://api.subq.ai") ||
|
|
88
93
|
(provider === "opencode-go" &&
|
|
89
94
|
baseUrl === "https://opencode.ai/inference/go/systemone/v1") ||
|
|
90
95
|
((provider === "cloudflare" || provider === "clairic") &&
|
package/dist/extension.js
CHANGED
|
@@ -25,10 +25,10 @@ export default function piClassifier(pi) {
|
|
|
25
25
|
promptSnippet: "Classify text, JSON or supported images into typed probabilistic decisions.",
|
|
26
26
|
promptGuidelines: [
|
|
27
27
|
"Use for bounded judgments, classification and rubric scoring, not open-ended prose.",
|
|
28
|
+
"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.",
|
|
28
29
|
"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.",
|
|
29
30
|
"Handle no_match and ambiguous answers explicitly. probabilityScope=batch and noneOfAboveProbability describe only the winning batch; they are not a full-list probability distribution.",
|
|
30
31
|
"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.",
|
|
31
|
-
"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.",
|
|
32
32
|
"Audio and video are accepted only by routes with documented media contracts. Duration and codec compatibility remain provider-owned.",
|
|
33
33
|
"Ask /classifier status for the active model. Do not change provider settings without user direction.",
|
|
34
34
|
],
|
|
@@ -133,12 +133,14 @@ export default function piClassifier(pi) {
|
|
|
133
133
|
name: CLASSIFY_EXTRACT_TOOL,
|
|
134
134
|
label: "Extract structured fields",
|
|
135
135
|
description: CLASSIFY_EXTRACT_TOOL_DESCRIPTION,
|
|
136
|
-
promptSnippet: "Extract typed
|
|
136
|
+
promptSnippet: "Extract typed values with field specs or typed reads (text, number, date, spans, boxes, locate, estimate) on decision routes including direct Liquid.",
|
|
137
137
|
promptGuidelines: [
|
|
138
|
+
"Use for reads, not decisions: yes/no, category, multi-choice and score questions belong to classify.",
|
|
139
|
+
"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.",
|
|
138
140
|
"Use fields that describe the value you need; do not invent provider field types or keys.",
|
|
139
|
-
"
|
|
140
|
-
"
|
|
141
|
-
"The configured
|
|
141
|
+
"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.",
|
|
142
|
+
"A result is not proof that a fact is correct; use grounded spans and confidence when available. truncated means generated field output is incomplete.",
|
|
143
|
+
"The configured route receives state, fields or questions and media. Do not send data the user does not intend to share with that provider.",
|
|
142
144
|
],
|
|
143
145
|
parameters: classifyExtractParameters,
|
|
144
146
|
outputSchema: classifyExtractOutput,
|
package/dist/extract.d.ts
CHANGED
|
@@ -6,6 +6,10 @@ export type ExtractOptions = {
|
|
|
6
6
|
signal?: AbortSignal;
|
|
7
7
|
credentialSource?: CredentialSource;
|
|
8
8
|
};
|
|
9
|
-
/**
|
|
9
|
+
/**
|
|
10
|
+
* `classify_extract` entry point. Two exclusive modes share the extraction result contract:
|
|
11
|
+
* `fields` for Clairic-shaped field specs on extraction routes, and `questions` for typed
|
|
12
|
+
* extraction reads on decision routes, including direct Liquid `d1.2`/`d1.2-ultra`.
|
|
13
|
+
*/
|
|
10
14
|
export declare function extract(params: unknown, options: ExtractOptions): Promise<ExtractResult>;
|
|
11
15
|
export { userError };
|
package/dist/extract.js
CHANGED
|
@@ -1,9 +1,11 @@
|
|
|
1
1
|
import { resolveApiKey } 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 } 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 { ClassifierError, isRecord, userError, } from "./types.js";
|
|
8
10
|
const CLAIRIC_LABEL = "Cloudflare Clairic";
|
|
9
11
|
const ANSWER_METADATA = [
|
|
@@ -57,13 +59,21 @@ function parseAnswers(value, fields) {
|
|
|
57
59
|
}
|
|
58
60
|
return answers;
|
|
59
61
|
}
|
|
60
|
-
/**
|
|
62
|
+
/**
|
|
63
|
+
* `classify_extract` entry point. Two exclusive modes share the extraction result contract:
|
|
64
|
+
* `fields` for Clairic-shaped field specs on extraction routes, and `questions` for typed
|
|
65
|
+
* extraction reads on decision routes, including direct Liquid `d1.2`/`d1.2-ultra`.
|
|
66
|
+
*/
|
|
61
67
|
export async function extract(params, options) {
|
|
62
68
|
if (params === null || typeof params !== "object" || Array.isArray(params))
|
|
63
|
-
throw new ClassifierError("input", "extract requires an object with fields and optional state/media.");
|
|
69
|
+
throw new ClassifierError("input", "extract requires an object with fields or questions and optional state/media.");
|
|
64
70
|
const input = params;
|
|
65
71
|
if (options.signal?.aborted)
|
|
66
72
|
throw new ClassifierError("aborted", "Extraction was cancelled.");
|
|
73
|
+
if ((input.fields === undefined) === (input.questions === undefined))
|
|
74
|
+
throw new ClassifierError("input", "classify_extract needs exactly one of fields (field specifications) or questions (typed extraction reads).");
|
|
75
|
+
if (input.questions !== undefined)
|
|
76
|
+
return extractQuestions(input, options);
|
|
67
77
|
const route = resolveModel(options.settings, undefined, options.credentialSource ?? "pi-store");
|
|
68
78
|
const apiKey = route.authMode === "none" ? "" : resolveApiKey(route, options.credentialSource ?? "pi-store");
|
|
69
79
|
const prepared = await prepareExtractionInput(input, route, options.cwd, options.signal);
|
|
@@ -109,6 +119,183 @@ export async function extract(params, options) {
|
|
|
109
119
|
function costOf(route, usage) {
|
|
110
120
|
return estimateCost(route, usage);
|
|
111
121
|
}
|
|
122
|
+
/** Result-value view of one extraction answer; the read itself stays in metadata. */
|
|
123
|
+
function extractionAnswer(answer) {
|
|
124
|
+
switch (answer.type) {
|
|
125
|
+
case "text": {
|
|
126
|
+
const parsed = { type: "text", value: answer.text };
|
|
127
|
+
if (answer.span !== undefined)
|
|
128
|
+
parsed.span = answer.span;
|
|
129
|
+
if (answer.found !== undefined)
|
|
130
|
+
parsed.found = answer.found;
|
|
131
|
+
if (answer.path !== undefined)
|
|
132
|
+
parsed.path = answer.path;
|
|
133
|
+
return parsed;
|
|
134
|
+
}
|
|
135
|
+
case "number": {
|
|
136
|
+
const parsed = { type: "number", value: answer.value };
|
|
137
|
+
if (answer.unit !== undefined)
|
|
138
|
+
parsed.unit = answer.unit;
|
|
139
|
+
if (answer.text !== undefined)
|
|
140
|
+
parsed.text = answer.text;
|
|
141
|
+
if (answer.span !== undefined)
|
|
142
|
+
parsed.span = answer.span;
|
|
143
|
+
if (answer.found !== undefined)
|
|
144
|
+
parsed.found = answer.found;
|
|
145
|
+
if (answer.path !== undefined)
|
|
146
|
+
parsed.path = answer.path;
|
|
147
|
+
return parsed;
|
|
148
|
+
}
|
|
149
|
+
case "date": {
|
|
150
|
+
const parsed = { type: "date", value: answer.date };
|
|
151
|
+
if (answer.text !== undefined)
|
|
152
|
+
parsed.text = answer.text;
|
|
153
|
+
if (answer.span !== undefined)
|
|
154
|
+
parsed.span = answer.span;
|
|
155
|
+
if (answer.found !== undefined)
|
|
156
|
+
parsed.found = answer.found;
|
|
157
|
+
if (answer.path !== undefined)
|
|
158
|
+
parsed.path = answer.path;
|
|
159
|
+
return parsed;
|
|
160
|
+
}
|
|
161
|
+
case "estimate": {
|
|
162
|
+
const parsed = { type: "estimate", value: answer.value, interval: answer.interval };
|
|
163
|
+
if (answer.unit !== undefined)
|
|
164
|
+
parsed.unit = answer.unit;
|
|
165
|
+
return parsed;
|
|
166
|
+
}
|
|
167
|
+
case "spans": {
|
|
168
|
+
const parsed = {
|
|
169
|
+
type: "spans",
|
|
170
|
+
value: answer.spans.map((span) => span.text),
|
|
171
|
+
spans: answer.spans.map((span) => ({ text: span.text, span: span.span, found: span.found })),
|
|
172
|
+
count: answer.count,
|
|
173
|
+
atLeast: answer.atLeast,
|
|
174
|
+
presence: answer.presence,
|
|
175
|
+
};
|
|
176
|
+
return parsed;
|
|
177
|
+
}
|
|
178
|
+
case "boxes": {
|
|
179
|
+
const parsed = {
|
|
180
|
+
type: "boxes",
|
|
181
|
+
value: answer.boxes.map((entry) => entry.box),
|
|
182
|
+
boxes: answer.boxes.map((entry) => ({ box: entry.box, found: entry.found, confidence: entry.confidence })),
|
|
183
|
+
count: answer.count,
|
|
184
|
+
atLeast: answer.atLeast,
|
|
185
|
+
presence: answer.presence,
|
|
186
|
+
};
|
|
187
|
+
return parsed;
|
|
188
|
+
}
|
|
189
|
+
case "box": {
|
|
190
|
+
const parsed = { type: "box", value: answer.box, confidence: answer.confidence };
|
|
191
|
+
if (answer.found !== undefined)
|
|
192
|
+
parsed.found = answer.found;
|
|
193
|
+
return parsed;
|
|
194
|
+
}
|
|
195
|
+
case "locate": {
|
|
196
|
+
const parsed = {
|
|
197
|
+
type: "locate",
|
|
198
|
+
value: answer.spans.map((span) => span.text),
|
|
199
|
+
spans: answer.spans.map((span) => ({
|
|
200
|
+
start: span.start,
|
|
201
|
+
end: span.end,
|
|
202
|
+
text: span.text,
|
|
203
|
+
score: span.score,
|
|
204
|
+
...(span.searchResult !== undefined ? { searchResult: span.searchResult } : {}),
|
|
205
|
+
})),
|
|
206
|
+
};
|
|
207
|
+
return parsed;
|
|
208
|
+
}
|
|
209
|
+
case "extract": {
|
|
210
|
+
const parsed = {
|
|
211
|
+
type: "extract",
|
|
212
|
+
value: Object.fromEntries(Object.entries(answer.spans).map(([field, spans]) => [field, spans.map((span) => span.text)])),
|
|
213
|
+
spans: Object.fromEntries(Object.entries(answer.spans).map(([field, spans]) => [
|
|
214
|
+
field,
|
|
215
|
+
spans.map((span) => ({
|
|
216
|
+
start: span.start,
|
|
217
|
+
end: span.end,
|
|
218
|
+
text: span.text,
|
|
219
|
+
score: span.score,
|
|
220
|
+
...(span.searchResult !== undefined ? { searchResult: span.searchResult } : {}),
|
|
221
|
+
})),
|
|
222
|
+
])),
|
|
223
|
+
notStated: answer.notStated,
|
|
224
|
+
};
|
|
225
|
+
return parsed;
|
|
226
|
+
}
|
|
227
|
+
case "refusal":
|
|
228
|
+
case "no_match":
|
|
229
|
+
case "ambiguous":
|
|
230
|
+
return { type: answer.type, value: null };
|
|
231
|
+
default:
|
|
232
|
+
throw new ClassifierError("response", "Extraction questions returned a " + answer.type + " decision, which is not an extraction read.");
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
function questionExtractionResult(route, result, questions) {
|
|
236
|
+
const answers = Object.create(null);
|
|
237
|
+
for (const id of Object.keys(questions)) {
|
|
238
|
+
const answer = result.answers[id];
|
|
239
|
+
if (answer === undefined)
|
|
240
|
+
throw new ClassifierError("response", "The selected route did not return an answer for " + id + ".");
|
|
241
|
+
answers[id] = extractionAnswer(answer);
|
|
242
|
+
}
|
|
243
|
+
const extracted = {
|
|
244
|
+
provider: route.route,
|
|
245
|
+
model: route.model,
|
|
246
|
+
answers,
|
|
247
|
+
// Typed reads return provider-validated values; no generated field output can truncate.
|
|
248
|
+
truncated: false,
|
|
249
|
+
cost: result.cost,
|
|
250
|
+
};
|
|
251
|
+
if (result.usage !== undefined)
|
|
252
|
+
extracted.usage = result.usage;
|
|
253
|
+
if (result.providerCost !== undefined)
|
|
254
|
+
extracted.providerCost = result.providerCost;
|
|
255
|
+
if (result.requestId !== undefined)
|
|
256
|
+
extracted.requestId = result.requestId;
|
|
257
|
+
if (result.citations !== undefined)
|
|
258
|
+
extracted.citations = result.citations;
|
|
259
|
+
if (result.webGrounding !== undefined)
|
|
260
|
+
extracted.webGrounding = result.webGrounding;
|
|
261
|
+
if (result.attemptedRoutes !== undefined)
|
|
262
|
+
extracted.attemptedRoutes = result.attemptedRoutes;
|
|
263
|
+
if (Buffer.byteLength(JSON.stringify(extracted, null, 2)) > 40 * 1024)
|
|
264
|
+
throw new ClassifierError("response", "Extraction result exceeds the 40 KiB tool output limit. Ask for fewer or narrower reads.");
|
|
265
|
+
return extracted;
|
|
266
|
+
}
|
|
267
|
+
/** Typed extraction questions on a decision route; the route itself supplies the read primitives. */
|
|
268
|
+
async function extractQuestions(input, options) {
|
|
269
|
+
const questions = validateExtractionQuestions(input.questions);
|
|
270
|
+
if (input.documents !== undefined)
|
|
271
|
+
throw new ClassifierError("capability", "PDF documents are accepted only by field extraction. Send the document's text as state for typed reads.");
|
|
272
|
+
if (input.referenceDate !== undefined || input.options !== undefined)
|
|
273
|
+
throw new ClassifierError("capability", "referenceDate and options apply only to field extraction.");
|
|
274
|
+
if (input.state === undefined)
|
|
275
|
+
throw new ClassifierError("input", "Extraction questions require state: pass text or JSON. An empty string is allowed for image-only reads.");
|
|
276
|
+
const decision = { state: input.state, questions };
|
|
277
|
+
const images = [];
|
|
278
|
+
for (const image of input.images ?? []) {
|
|
279
|
+
if (typeof image === "string") {
|
|
280
|
+
images.push(image);
|
|
281
|
+
}
|
|
282
|
+
else if ("id" in image) {
|
|
283
|
+
images.push("path" in image ? { id: image.id, path: image.path } : { id: image.id, url: image.url });
|
|
284
|
+
}
|
|
285
|
+
else {
|
|
286
|
+
throw new ClassifierError("input", "Extraction question images must be local path strings or named {id, path}/{id, url} descriptors. Rotation applies only to direct Clairic field extraction.");
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
validateImageDescriptors(images, input.state, questions);
|
|
290
|
+
if (images.length > 0)
|
|
291
|
+
decision.images = images;
|
|
292
|
+
if (input.media !== undefined)
|
|
293
|
+
decision.media = input.media;
|
|
294
|
+
if (input.mode !== undefined)
|
|
295
|
+
decision.mode = input.mode;
|
|
296
|
+
const { result, route } = await runDecisionRequest(decision, options, (prepared, selected, apiKey) => classifyWithProvider(selected, prepared, apiKey, options.signal));
|
|
297
|
+
return questionExtractionResult(route, result, questions);
|
|
298
|
+
}
|
|
112
299
|
function finalizeExtraction(route, result, prepared, cost, requestId, providerCost, stateText) {
|
|
113
300
|
if (typeof result.truncated !== "boolean")
|
|
114
301
|
throw new ClassifierError("response", "Extraction did not report whether output was truncated.");
|
package/dist/index.d.ts
CHANGED
|
@@ -10,5 +10,5 @@ export { classifyTree } from "./tree.js";
|
|
|
10
10
|
export { renderClassifierBox } from "./box.js";
|
|
11
11
|
export type { ClassifierBoxMode, ClassifierBoxEdges, ClassifierBoxPixelBox, ClassifierBoxResult } from "./box.js";
|
|
12
12
|
export { loadClassifierSettings, resolveModel, listModels } from "./config.js";
|
|
13
|
-
export type { Answer, Question, QuestionContent, ImageInput, ImageReference, ClassifierResult, ClassifierCost, TokenPricing, ClassifierRoute, ClassifierComparisonEntry, ClassifierComparisonResult, ClassifierSettings, ClassifyParams, ClassifyTreeParams, ClassifierTreeResult, ClassificationTree, ClassificationTreeNode, TreeStep, CustomProviderSettings, ModelDefinition, ProviderSettings, ApiStyle, MediaInput, PreparedMedia, TextSpan, BoxEdges, CharSpan, NonTokenCost, WebSearchResult, WebFetchedResult, ExtractionField, ExtractParams, ExtractResult, ExtractionAnswer, JsonLike, } from "./types.js";
|
|
13
|
+
export type { Answer, Question, ClassificationQuestion, ExtractionQuestion, DecisionInput, QuestionContent, ImageInput, ImageReference, ClassifierResult, ClassifierCost, TokenPricing, ClassifierRoute, ClassifierComparisonEntry, ClassifierComparisonResult, ClassifierSettings, ClassifyParams, ClassifyTreeParams, ClassifierTreeResult, ClassificationTree, ClassificationTreeNode, TreeStep, CustomProviderSettings, ModelDefinition, ProviderSettings, ApiStyle, MediaInput, PreparedMedia, TextSpan, BoxEdges, CharSpan, NonTokenCost, WebSearchResult, WebFetchedResult, ExtractionField, ExtractParams, ExtractResult, ExtractionAnswer, JsonLike, } from "./types.js";
|
|
14
14
|
export { ClassifierError } from "./types.js";
|
package/dist/inputs.d.ts
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
import { type
|
|
1
|
+
import { type DecisionInput, type ExtractParams, type PreparedLocalImage, type PreparedInput, type ResolvedModel } from "./types.js";
|
|
2
2
|
/** Programmatic image ingress. Never accepted as model-facing tool arguments. */
|
|
3
3
|
export interface MemoryImage {
|
|
4
4
|
bytes: Uint8Array;
|
|
5
5
|
mimeType: "image/png" | "image/jpeg" | "image/webp";
|
|
6
6
|
}
|
|
7
|
-
export declare function prepareInput(params:
|
|
7
|
+
export declare function prepareInput(params: DecisionInput, route: ResolvedModel, cwd: string, signal?: AbortSignal, memoryImages?: readonly MemoryImage[]): Promise<PreparedInput>;
|
|
8
8
|
/** Bounded, fully decoded local image; shared by uploads and local box rendering. */
|
|
9
9
|
export declare function loadLocalImage(path: string, cwd: string, signal?: AbortSignal, maxBytes?: number): Promise<PreparedLocalImage>;
|
|
10
10
|
/** Verify containment of the opened descriptor, not a raceable pre-open path. */
|
package/dist/inputs.js
CHANGED
|
@@ -20,15 +20,23 @@ export async function prepareInput(params, route, cwd, signal, memoryImages = []
|
|
|
20
20
|
if (route.api === "perplexity-decisions" && params.mode === "web_grounding" && questionCount > 100)
|
|
21
21
|
throw new ClassifierError("input", "Perplexity web grounding accepts at most 100 questions.");
|
|
22
22
|
const openRouter = route.api === "openrouter-decisions" ? openRouterDecisionCapabilities(route.model) : undefined;
|
|
23
|
+
const liquid = route.api === "liquid-system-one";
|
|
23
24
|
const imageCount = (params.images?.length ?? 0) + memoryImages.length;
|
|
24
25
|
if (imageCount && !route.images)
|
|
25
26
|
throw new ClassifierError("capability", "The selected model does not support images, or experimental Jev images are disabled.");
|
|
27
|
+
// Liquid documents exactly one image for box and boxes questions; other routes do not publish that rule.
|
|
28
|
+
const liquidLocationRead = liquid &&
|
|
29
|
+
Object.values(params.questions).some((question) => question.type === "box" || question.type === "boxes");
|
|
30
|
+
if (liquidLocationRead && imageCount !== 1)
|
|
31
|
+
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.");
|
|
26
32
|
if (hasBox(params.questions) && (!route.box || !imageCount))
|
|
27
33
|
throw new ClassifierError("capability", "box requires an enabled Jev 1.14 model, experimentalImages/experimentalBox and an image.");
|
|
28
34
|
if (params.mode === "web_grounding" && route.api !== "perplexity-decisions")
|
|
29
35
|
throw new ClassifierError("capability", "Web grounding is supported only by Perplexity Decisions routes.");
|
|
30
36
|
if (route.api === "cloudflare-clairic")
|
|
31
|
-
throw new ClassifierError("capability", "Clairic
|
|
37
|
+
throw new ClassifierError("capability", "Clairic reads fields through classify_extract; it has no typed-question surface.");
|
|
38
|
+
if (route.api === "openrouter-extractions" || route.api === "litellm-extraction")
|
|
39
|
+
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.");
|
|
32
40
|
if (params.imageDetail !== undefined && !["openai-decisions", "openrouter-decisions"].includes(route.api))
|
|
33
41
|
throw new ClassifierError("capability", "imageDetail is supported only by OpenAI-compatible and OpenRouter Decisions routes.");
|
|
34
42
|
if (params.promptCache !== undefined && route.api !== "openai-decisions")
|
|
@@ -48,7 +56,7 @@ export async function prepareInput(params, route, cwd, signal, memoryImages = []
|
|
|
48
56
|
? sarvamQuestions
|
|
49
57
|
: route.api === "inception-decisions"
|
|
50
58
|
? [...coreQuestions, "extract"]
|
|
51
|
-
: ["gemini-decisions", "parallel-decisions", "local-system-one"].includes(route.api)
|
|
59
|
+
: ["gemini-decisions", "parallel-decisions", "local-system-one", "subq-system-one", "alibaba-system-one", "fireworks-system-one"].includes(route.api)
|
|
52
60
|
? coreQuestions
|
|
53
61
|
: openRouter
|
|
54
62
|
? openRouterQuestions
|
|
@@ -85,7 +93,7 @@ export async function prepareInput(params, route, cwd, signal, memoryImages = []
|
|
|
85
93
|
throw new ClassifierError("input", "locate requires a string state. Offsets are defined only for text.");
|
|
86
94
|
}
|
|
87
95
|
const clef = route.api === "cloudflare-system-one" && route.images;
|
|
88
|
-
const
|
|
96
|
+
const tightImages = clef || route.api === "subq-system-one";
|
|
89
97
|
if (imageCount > route.limits.maxImages)
|
|
90
98
|
throw new ClassifierError("input", "The selected route accepts at most " + route.limits.maxImages + " images in this package.");
|
|
91
99
|
const flexibleReferences = openRouter?.flexibleImagePlacement === true;
|
|
@@ -125,7 +133,7 @@ export async function prepareInput(params, route, cwd, signal, memoryImages = []
|
|
|
125
133
|
];
|
|
126
134
|
for (const entry of sources) {
|
|
127
135
|
cancelled(signal);
|
|
128
|
-
const maxBytes = (
|
|
136
|
+
const maxBytes = (tightImages ? 4 : 5) * 1024 * 1024;
|
|
129
137
|
let image;
|
|
130
138
|
let id;
|
|
131
139
|
if ("memory" in entry) {
|
|
@@ -142,7 +150,7 @@ export async function prepareInput(params, route, cwd, signal, memoryImages = []
|
|
|
142
150
|
id = source.id;
|
|
143
151
|
}
|
|
144
152
|
totalBytes += Buffer.byteLength(image.data, "base64");
|
|
145
|
-
if (totalBytes > (
|
|
153
|
+
if (totalBytes > (tightImages ? 8 : 10) * 1024 * 1024)
|
|
146
154
|
throw new ClassifierError("input", "Images exceed the selected route's total upload byte limit.");
|
|
147
155
|
if (route.api === "microsoft-system-one" && image.mimeType === "image/webp")
|
|
148
156
|
throw new ClassifierError("input", "Microsoft Foundry Decision-1.1 image assets accept PNG and JPEG only.");
|
|
@@ -401,6 +409,28 @@ async function prepareMedia(sources, route, cwd, signal) {
|
|
|
401
409
|
}
|
|
402
410
|
return result;
|
|
403
411
|
}
|
|
412
|
+
/** Field extraction keeps its local-path/rotation image contract; question mode uses shared images. */
|
|
413
|
+
function fieldExtractionImages(value) {
|
|
414
|
+
if (value === undefined)
|
|
415
|
+
return [];
|
|
416
|
+
if (!Array.isArray(value))
|
|
417
|
+
throw new ClassifierError("input", "images must be an array.");
|
|
418
|
+
return value.map((image) => {
|
|
419
|
+
if (typeof image === "string") {
|
|
420
|
+
if (!image.trim() || image.length > 4096)
|
|
421
|
+
throw new ClassifierError("input", "Image paths must be non-empty, at most 4096 characters.");
|
|
422
|
+
return image;
|
|
423
|
+
}
|
|
424
|
+
const spec = image;
|
|
425
|
+
if (!isRecord(spec) || Object.keys(spec).some((key) => key !== "path" && key !== "rotation") ||
|
|
426
|
+
typeof spec.path !== "string" || !spec.path.trim() || spec.path.length > 4096 ||
|
|
427
|
+
(spec.rotation !== undefined && ![0, 90, 180, 270].includes(spec.rotation)))
|
|
428
|
+
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.");
|
|
429
|
+
return spec.rotation === undefined
|
|
430
|
+
? { path: spec.path }
|
|
431
|
+
: { path: spec.path, rotation: spec.rotation };
|
|
432
|
+
});
|
|
433
|
+
}
|
|
404
434
|
const EXTRACTION_TYPES = new Set([
|
|
405
435
|
"text", "number", "compute", "date", "time", "datetime", "duration",
|
|
406
436
|
"boolean", "enum", "object", "list", "estimate", "forecast",
|
|
@@ -533,12 +563,18 @@ async function loadDocumentFile(path, cwd, signal) {
|
|
|
533
563
|
}
|
|
534
564
|
}
|
|
535
565
|
export async function prepareExtractionInput(params, route, cwd, signal) {
|
|
566
|
+
if (params.questions !== undefined)
|
|
567
|
+
throw new ClassifierError("input", "Extraction questions use the typed-question path, not fields.");
|
|
568
|
+
if (params.media !== undefined || params.mode !== undefined)
|
|
569
|
+
throw new ClassifierError("capability", "Field extraction does not accept media or web grounding. Use extraction questions on a decision route instead.");
|
|
536
570
|
if (!["cloudflare-clairic", "openrouter-extractions", "litellm-extraction"].includes(route.api))
|
|
537
|
-
throw new ClassifierError("capability", "
|
|
571
|
+
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.");
|
|
538
572
|
if (params.state !== undefined &&
|
|
539
573
|
!(typeof params.state === "string" || Array.isArray(params.state) || isRecord(params.state)))
|
|
540
574
|
throw new ClassifierError("input", "state must be text, a JSON object or an array.");
|
|
541
575
|
const extractionCaps = route.api === "openrouter-extractions" ? openRouterExtractionCapabilities(route.model) : undefined;
|
|
576
|
+
if (params.fields === undefined)
|
|
577
|
+
throw new ClassifierError("input", "Field extraction requires a non-empty fields map.");
|
|
542
578
|
const fields = validateExtractionFields(params.fields, extractionCaps ? new Set(extractionCaps.fieldTypes) : EXTRACTION_TYPES, extractionCaps?.maxFields);
|
|
543
579
|
if (route.api === "openrouter-extractions")
|
|
544
580
|
validateOpenRouterExtractionFields(fields, route.model);
|
|
@@ -553,13 +589,10 @@ export async function prepareExtractionInput(params, route, cwd, signal) {
|
|
|
553
589
|
Object.values(params.options).some((value) => typeof value !== "boolean"))
|
|
554
590
|
throw new ClassifierError("input", "options may only set includeQuantiles and returnStateText to booleans.");
|
|
555
591
|
}
|
|
556
|
-
if (params.images !== undefined &&
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
(image.rotation !== undefined && ![0, 90, 180, 270].includes(image.rotation)))))
|
|
561
|
-
throw new ClassifierError("input", "images must be local path strings or {path, rotation} objects with rotation 0, 90, 180 or 270.");
|
|
562
|
-
if (route.api !== "cloudflare-clairic" && (params.images ?? []).some((image) => typeof image !== "string" && image.rotation !== undefined))
|
|
592
|
+
if (params.images !== undefined && !Array.isArray(params.images))
|
|
593
|
+
throw new ClassifierError("input", "images must be an array.");
|
|
594
|
+
const fieldImages = fieldExtractionImages(params.images);
|
|
595
|
+
if (route.api !== "cloudflare-clairic" && fieldImages.some((image) => typeof image !== "string" && image.rotation !== undefined))
|
|
563
596
|
throw new ClassifierError("capability", "Image rotation is documented only for direct Cloudflare Clairic.");
|
|
564
597
|
if (params.documents !== undefined && (!Array.isArray(params.documents) || params.documents.some((document) => typeof document !== "string" || !document.trim() || document.length > 4096)))
|
|
565
598
|
throw new ClassifierError("input", "documents must be local PDF path strings inside cwd.");
|
|
@@ -573,7 +606,7 @@ export async function prepareExtractionInput(params, route, cwd, signal) {
|
|
|
573
606
|
const isScaleDown = route.api === "openrouter-extractions" && route.model === "scaledown/extract";
|
|
574
607
|
if (isScaleDown && (params.images?.length ?? 0) + (params.documents?.length ?? 0) > 0 && params.state !== undefined && params.state !== "")
|
|
575
608
|
throw new ClassifierError("input", "ScaleDown Extract reads either text state or one asset, not both. Omit state when sending a PDF or image.");
|
|
576
|
-
const images = await Promise.all(
|
|
609
|
+
const images = await Promise.all(fieldImages.map(async (image) => {
|
|
577
610
|
const spec = typeof image === "string" ? { path: image } : image;
|
|
578
611
|
const loaded = await loadLocalImage(spec.path, cwd, signal, 4 * 1024 * 1024);
|
|
579
612
|
return spec.rotation === undefined ? loaded : { ...loaded, rotation: spec.rotation };
|