@abhishek944/pi-classifier 0.3.0 → 0.5.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 +48 -0
- package/COMPUTER_USE.md +117 -0
- package/README.md +344 -30
- package/dist/auth.d.ts +4 -2
- package/dist/auth.js +18 -2
- package/dist/box-tool.d.ts +4 -0
- package/dist/box-tool.js +79 -0
- package/dist/box.d.ts +32 -0
- package/dist/box.js +148 -0
- package/dist/choices.js +35 -1
- package/dist/classify.d.ts +6 -0
- package/dist/classify.js +4 -4
- package/dist/computer-use-state.d.ts +9 -0
- package/dist/computer-use-state.js +160 -0
- package/dist/computer-use-tool.d.ts +52 -0
- package/dist/computer-use-tool.js +78 -0
- package/dist/computer-use-types.d.ts +132 -0
- package/dist/computer-use-types.js +1 -0
- package/dist/computer-use.d.ts +22 -0
- package/dist/computer-use.js +223 -0
- package/dist/config.d.ts +140 -3
- package/dist/config.js +405 -20
- package/dist/cost.js +42 -4
- package/dist/durable.d.ts +34 -0
- package/dist/durable.js +237 -0
- package/dist/extension.d.ts +2 -247
- package/dist/extension.js +53 -190
- package/dist/extract.d.ts +11 -0
- package/dist/extract.js +191 -0
- package/dist/http.d.ts +6 -1
- package/dist/http.js +64 -28
- package/dist/image-content.d.ts +12 -0
- package/dist/image-content.js +90 -0
- package/dist/index.d.ts +10 -1
- package/dist/index.js +3 -0
- package/dist/inputs.d.ts +24 -2
- package/dist/inputs.js +565 -134
- package/dist/mcp-cli.d.ts +2 -0
- package/dist/mcp-cli.js +39 -0
- package/dist/mcp-server.d.ts +28 -0
- package/dist/mcp-server.js +121 -0
- package/dist/mcp-tool-definitions.d.ts +19 -0
- package/dist/mcp-tool-definitions.js +64 -0
- package/dist/providers.d.ts +1 -0
- package/dist/providers.js +1218 -124
- package/dist/tool-contracts.d.ts +785 -0
- package/dist/tool-contracts.js +530 -0
- package/dist/tree.js +1 -1
- package/dist/types.d.ts +314 -20
- package/dist/validation.js +181 -44
- package/package.json +33 -5
- package/src/auth.ts +26 -2
- package/src/box-tool.ts +110 -0
- package/src/box.ts +253 -0
- package/src/choices.ts +44 -2
- package/src/classify.ts +10 -6
- package/src/computer-use-state.ts +145 -0
- package/src/computer-use-tool.ts +76 -0
- package/src/computer-use-types.ts +127 -0
- package/src/computer-use.ts +216 -0
- package/src/config.ts +454 -23
- package/src/cost.ts +42 -4
- package/src/durable.ts +298 -0
- package/src/extension.ts +79 -265
- package/src/extract.ts +228 -0
- package/src/http.ts +63 -32
- package/src/image-content.ts +77 -0
- package/src/index.ts +25 -0
- package/src/inputs.ts +603 -184
- package/src/mcp-cli.ts +44 -0
- package/src/mcp-server.ts +179 -0
- package/src/mcp-tool-definitions.ts +104 -0
- package/src/providers.ts +1398 -144
- package/src/tool-contracts.ts +785 -0
- package/src/tree.ts +1 -1
- package/src/types.ts +248 -11
- package/src/validation.ts +169 -96
package/dist/extension.js
CHANGED
|
@@ -1,204 +1,35 @@
|
|
|
1
1
|
import { isProjectTrusted } from "@amaster.ai/pi-shared/settings";
|
|
2
2
|
import { defineTool, } from "@earendil-works/pi-coding-agent";
|
|
3
|
-
import { Type } from "typebox";
|
|
4
3
|
import { classify, compareClassifiers } from "./classify.js";
|
|
4
|
+
import { extract } from "./extract.js";
|
|
5
|
+
import { CLASSIFY_EXTRACT_TOOL, CLASSIFY_EXTRACT_TOOL_DESCRIPTION, classifyExtractOutput, classifyExtractParameters, CLASSIFY_COMPARE_TOOL, CLASSIFY_COMPARE_TOOL_DESCRIPTION, CLASSIFY_TOOL, CLASSIFY_TOOL_DESCRIPTION, CLASSIFY_TREE_TOOL, CLASSIFY_TREE_TOOL_DESCRIPTION, classifyCompareOutput, classifyOutput, classifyParameters, classifyTreeOutput, classifyTreeParameters, } from "./tool-contracts.js";
|
|
5
6
|
import { classifyTree } from "./tree.js";
|
|
7
|
+
import { registerBoxTool } from "./box-tool.js";
|
|
8
|
+
import { registerComputerUseTool } from "./computer-use-tool.js";
|
|
6
9
|
import { configuredRoutes, listModels, loadClassifierSettings, resolveModel, } from "./config.js";
|
|
7
10
|
import { updateProjectClassifierSettings } from "./settings-write.js";
|
|
8
11
|
import { ClassifierError, userError } from "./types.js";
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
}, { additionalProperties: false }),
|
|
16
|
-
Type.Object({
|
|
17
|
-
type: Type.Literal("choice"),
|
|
18
|
-
instructions: Type.String({ minLength: 1, maxLength: 16384 }),
|
|
19
|
-
criteria: Type.Record(Type.String({ minLength: 1, maxLength: 128 }), shortText, { minProperties: 1 }),
|
|
20
|
-
}, { additionalProperties: false }),
|
|
21
|
-
Type.Object({
|
|
22
|
-
type: Type.Literal("score"),
|
|
23
|
-
instructions: Type.String({ minLength: 1, maxLength: 16384 }),
|
|
24
|
-
criteria: Type.Array(Type.String({ minLength: 1, maxLength: 4096 }), {
|
|
25
|
-
minItems: 2,
|
|
26
|
-
maxItems: 10,
|
|
27
|
-
}),
|
|
28
|
-
}, { additionalProperties: false }),
|
|
29
|
-
Type.Object({
|
|
30
|
-
type: Type.Literal("box"),
|
|
31
|
-
instructions: Type.String({ minLength: 1, maxLength: 16384 }),
|
|
32
|
-
}, { additionalProperties: false }),
|
|
33
|
-
]);
|
|
34
|
-
export const classifyParameters = Type.Object({
|
|
35
|
-
state: Type.Union([
|
|
36
|
-
Type.String(),
|
|
37
|
-
Type.Record(Type.String(), Type.Unknown()),
|
|
38
|
-
Type.Array(Type.Unknown()),
|
|
39
|
-
], {
|
|
40
|
-
description: "Text or JSON data to classify. All questions refer to this same state.",
|
|
41
|
-
}),
|
|
42
|
-
questions: Type.Record(Type.String({ pattern: "^[a-zA-Z0-9_-]{1,64}$" }), question, { minProperties: 1, maxProperties: 32 }),
|
|
43
|
-
images: Type.Optional(Type.Array(Type.String({ minLength: 1, maxLength: 4096 }), {
|
|
44
|
-
maxItems: 5,
|
|
45
|
-
description: "Local PNG/JPEG/WebP files inside cwd, in order. No URLs, symlinks or inline base64. Requires an image-capable model.",
|
|
46
|
-
})),
|
|
47
|
-
}, { additionalProperties: false });
|
|
48
|
-
const tokenPricing = Type.Object({
|
|
49
|
-
inputPerMillion: Type.Number({ minimum: 0 }),
|
|
50
|
-
outputPerMillion: Type.Number({ minimum: 0 }),
|
|
51
|
-
cachedInputPerMillion: Type.Optional(Type.Number({ minimum: 0 })),
|
|
52
|
-
cacheWritePerMillion: Type.Optional(Type.Number({ minimum: 0 })),
|
|
53
|
-
});
|
|
54
|
-
export const classifyOutput = Type.Object({
|
|
55
|
-
provider: Type.String(),
|
|
56
|
-
model: Type.String(),
|
|
57
|
-
answers: Type.Record(Type.String(), Type.Union([
|
|
58
|
-
Type.Object({
|
|
59
|
-
type: Type.Literal("bool"),
|
|
60
|
-
probability: Type.Number({ minimum: 0, maximum: 1 }),
|
|
61
|
-
}),
|
|
62
|
-
Type.Object({
|
|
63
|
-
type: Type.Literal("choice"),
|
|
64
|
-
choice: Type.String(),
|
|
65
|
-
probabilities: Type.Record(Type.String(), Type.Number({ minimum: 0, maximum: 1 })),
|
|
66
|
-
confidence: Type.Number({ minimum: 0, maximum: 1 }),
|
|
67
|
-
probabilityScope: Type.Optional(Type.Literal("batch")),
|
|
68
|
-
noneOfAboveProbability: Type.Optional(Type.Number({ minimum: 0, maximum: 1 })),
|
|
69
|
-
}),
|
|
70
|
-
Type.Object({
|
|
71
|
-
type: Type.Literal("score"),
|
|
72
|
-
score: Type.Number(),
|
|
73
|
-
confidence: Type.Number({ minimum: 0, maximum: 1 }),
|
|
74
|
-
probabilities: Type.Optional(Type.Record(Type.String(), Type.Number({ minimum: 0, maximum: 1 }))),
|
|
75
|
-
}),
|
|
76
|
-
Type.Object({
|
|
77
|
-
type: Type.Literal("box"),
|
|
78
|
-
box: Type.Object({
|
|
79
|
-
top: Type.Number(),
|
|
80
|
-
bottom: Type.Number(),
|
|
81
|
-
left: Type.Number(),
|
|
82
|
-
right: Type.Number(),
|
|
83
|
-
}),
|
|
84
|
-
confidence: Type.Number({ minimum: 0, maximum: 1 }),
|
|
85
|
-
}),
|
|
86
|
-
Type.Object({ type: Type.Literal("refusal") }),
|
|
87
|
-
Type.Object({ type: Type.Literal("no_match") }),
|
|
88
|
-
Type.Object({ type: Type.Literal("ambiguous") }),
|
|
89
|
-
])),
|
|
90
|
-
providerCalls: Type.Optional(Type.Integer({ minimum: 1 })),
|
|
91
|
-
usage: Type.Optional(Type.Object({
|
|
92
|
-
inputTokens: Type.Number(),
|
|
93
|
-
outputTokens: Type.Number(),
|
|
94
|
-
totalTokens: Type.Number(),
|
|
95
|
-
cachedInputTokens: Type.Optional(Type.Number()),
|
|
96
|
-
cacheWriteTokens: Type.Optional(Type.Number()),
|
|
97
|
-
})),
|
|
98
|
-
cost: Type.Union([
|
|
99
|
-
Type.Object({
|
|
100
|
-
status: Type.Literal("estimated"),
|
|
101
|
-
currency: Type.Literal("USD"),
|
|
102
|
-
input: Type.Number({ minimum: 0 }),
|
|
103
|
-
output: Type.Number({ minimum: 0 }),
|
|
104
|
-
total: Type.Number({ minimum: 0 }),
|
|
105
|
-
source: Type.Union([Type.Literal("builtin"), Type.Literal("configured")]),
|
|
106
|
-
rates: tokenPricing,
|
|
107
|
-
}),
|
|
108
|
-
Type.Object({
|
|
109
|
-
status: Type.Literal("estimated"),
|
|
110
|
-
currency: Type.Literal("USD"),
|
|
111
|
-
input: Type.Number({ minimum: 0 }),
|
|
112
|
-
output: Type.Number({ minimum: 0 }),
|
|
113
|
-
total: Type.Number({ minimum: 0 }),
|
|
114
|
-
source: Type.Literal("aggregated"),
|
|
115
|
-
}),
|
|
116
|
-
Type.Object({
|
|
117
|
-
status: Type.Literal("unavailable"),
|
|
118
|
-
currency: Type.Literal("USD"),
|
|
119
|
-
reason: Type.Union([
|
|
120
|
-
Type.Literal("unknown_pricing"),
|
|
121
|
-
Type.Literal("missing_usage"),
|
|
122
|
-
Type.Literal("invalid_usage"),
|
|
123
|
-
Type.Literal("missing_cache_pricing"),
|
|
124
|
-
Type.Literal("calculation_overflow"),
|
|
125
|
-
]),
|
|
126
|
-
}),
|
|
127
|
-
]),
|
|
128
|
-
requestId: Type.Optional(Type.String()),
|
|
129
|
-
attemptedRoutes: Type.Optional(Type.Array(Type.Object({ provider: Type.String(), model: Type.String() }))),
|
|
130
|
-
});
|
|
131
|
-
export const classifyCompareOutput = Type.Object({
|
|
132
|
-
cancelled: Type.Boolean(),
|
|
133
|
-
results: Type.Array(Type.Union([
|
|
134
|
-
Type.Object({
|
|
135
|
-
provider: Type.String(),
|
|
136
|
-
model: Type.String(),
|
|
137
|
-
durationMs: Type.Number(),
|
|
138
|
-
status: Type.Literal("success"),
|
|
139
|
-
result: classifyOutput,
|
|
140
|
-
}),
|
|
141
|
-
Type.Object({
|
|
142
|
-
provider: Type.String(),
|
|
143
|
-
model: Type.String(),
|
|
144
|
-
durationMs: Type.Number(),
|
|
145
|
-
status: Type.Literal("error"),
|
|
146
|
-
error: Type.Object({ code: Type.String(), message: Type.String() }),
|
|
147
|
-
}),
|
|
148
|
-
])),
|
|
149
|
-
});
|
|
150
|
-
const classificationTreeNode = Type.Object({
|
|
151
|
-
id: Type.String({ minLength: 1, maxLength: 128 }),
|
|
152
|
-
description: Type.Optional(Type.String({ maxLength: 4096 })),
|
|
153
|
-
children: Type.Optional(Type.Array(Type.Ref("#/$defs/ClassificationTreeNode"))),
|
|
154
|
-
}, { additionalProperties: false });
|
|
155
|
-
export const classifyTreeParameters = Type.Object({
|
|
156
|
-
state: classifyParameters.properties.state,
|
|
157
|
-
tree: Type.Union([
|
|
158
|
-
Type.String({
|
|
159
|
-
minLength: 1,
|
|
160
|
-
maxLength: 4096,
|
|
161
|
-
description: "Local UTF-8 JSON file inside cwd; no URLs or symlinks.",
|
|
162
|
-
}),
|
|
163
|
-
Type.Object({ roots: Type.Array(Type.Ref("#/$defs/ClassificationTreeNode"), { minItems: 1 }) }, { additionalProperties: false }),
|
|
164
|
-
]),
|
|
165
|
-
instructions: Type.Optional(Type.String({ minLength: 1, maxLength: 8192 })),
|
|
166
|
-
images: classifyParameters.properties.images,
|
|
167
|
-
}, { additionalProperties: false, $defs: { ClassificationTreeNode: classificationTreeNode } });
|
|
168
|
-
export const classifyTreeOutput = Type.Object({
|
|
169
|
-
provider: Type.String(),
|
|
170
|
-
model: Type.String(),
|
|
171
|
-
status: Type.Union([
|
|
172
|
-
Type.Literal("complete"),
|
|
173
|
-
Type.Literal("no_match"),
|
|
174
|
-
Type.Literal("ambiguous"),
|
|
175
|
-
Type.Literal("refusal"),
|
|
176
|
-
]),
|
|
177
|
-
levels: Type.Record(Type.String({ pattern: "^Level[1-9][0-9]*$" }), Type.String()),
|
|
178
|
-
steps: Type.Array(Type.Object({
|
|
179
|
-
level: Type.Integer({ minimum: 1 }),
|
|
180
|
-
id: Type.String(),
|
|
181
|
-
source: Type.Union([Type.Literal("automatic"), Type.Literal("model")]),
|
|
182
|
-
confidence: Type.Optional(Type.Number({ minimum: 0, maximum: 1 })),
|
|
183
|
-
probabilityScope: Type.Optional(Type.Union([Type.Literal("siblings"), Type.Literal("batch")])),
|
|
184
|
-
noneOfAboveProbability: Type.Optional(Type.Number({ minimum: 0, maximum: 1 })),
|
|
185
|
-
})),
|
|
186
|
-
providerCalls: Type.Integer({ minimum: 0 }),
|
|
187
|
-
cost: classifyOutput.properties.cost,
|
|
188
|
-
usage: classifyOutput.properties.usage,
|
|
189
|
-
attemptedRoutes: classifyOutput.properties.attemptedRoutes,
|
|
190
|
-
});
|
|
12
|
+
// Re-exported so existing deep imports from "./extension.js" keep working.
|
|
13
|
+
export { classifyCompareOutput, classifyOutput, classifyParameters, classifyTreeOutput, classifyTreeParameters, classifyExtractOutput, classifyExtractParameters, };
|
|
14
|
+
// Tool names, descriptions, parameters and result schemas are shared with the
|
|
15
|
+
// native Durable factory through ./tool-contracts.js so the two surfaces cannot drift.
|
|
16
|
+
// Pi-only registration fields (label, prompt guidance, annotations, outputSchema)
|
|
17
|
+
// stay with these desktop registrations.
|
|
191
18
|
export default function piClassifier(pi) {
|
|
19
|
+
registerBoxTool(pi);
|
|
20
|
+
registerComputerUseTool(pi);
|
|
192
21
|
pi.registerTool(defineTool({
|
|
193
|
-
name:
|
|
22
|
+
name: CLASSIFY_TOOL,
|
|
194
23
|
label: "Classify",
|
|
195
|
-
description:
|
|
24
|
+
description: CLASSIFY_TOOL_DESCRIPTION,
|
|
196
25
|
promptSnippet: "Classify text, JSON or supported images into typed probabilistic decisions.",
|
|
197
26
|
promptGuidelines: [
|
|
198
27
|
"Use for bounded judgments, classification and rubric scoring, not open-ended prose.",
|
|
199
28
|
"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.",
|
|
200
29
|
"Handle no_match and ambiguous answers explicitly. probabilityScope=batch and noneOfAboveProbability describe only the winning batch; they are not a full-list probability distribution.",
|
|
201
|
-
"Send only data the user intends to share with the configured provider.",
|
|
30
|
+
"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
|
+
"Audio and video are accepted only by routes with documented media contracts. Duration and codec compatibility remain provider-owned.",
|
|
202
33
|
"Ask /classifier status for the active model. Do not change provider settings without user direction.",
|
|
203
34
|
],
|
|
204
35
|
parameters: classifyParameters,
|
|
@@ -229,9 +60,9 @@ export default function piClassifier(pi) {
|
|
|
229
60
|
},
|
|
230
61
|
}));
|
|
231
62
|
pi.registerTool(defineTool({
|
|
232
|
-
name:
|
|
63
|
+
name: CLASSIFY_COMPARE_TOOL,
|
|
233
64
|
label: "Compare classifiers",
|
|
234
|
-
description:
|
|
65
|
+
description: CLASSIFY_COMPARE_TOOL_DESCRIPTION,
|
|
235
66
|
promptSnippet: "Compare configured decision models only when the user explicitly requests a model comparison.",
|
|
236
67
|
promptGuidelines: [
|
|
237
68
|
"Use only when the user explicitly asks to compare classifier models; never use automatically for low confidence or refusals.",
|
|
@@ -263,9 +94,9 @@ export default function piClassifier(pi) {
|
|
|
263
94
|
},
|
|
264
95
|
}));
|
|
265
96
|
pi.registerTool(defineTool({
|
|
266
|
-
name:
|
|
97
|
+
name: CLASSIFY_TREE_TOOL,
|
|
267
98
|
label: "Classify tree",
|
|
268
|
-
description:
|
|
99
|
+
description: CLASSIFY_TREE_TOOL_DESCRIPTION,
|
|
269
100
|
promptSnippet: "Classify through a supplied classification tree and return the selected levels.",
|
|
270
101
|
promptGuidelines: [
|
|
271
102
|
"Use classify_tree only when the user supplies or requests a classification tree; do not invent category branches.",
|
|
@@ -298,6 +129,38 @@ export default function piClassifier(pi) {
|
|
|
298
129
|
}
|
|
299
130
|
},
|
|
300
131
|
}));
|
|
132
|
+
pi.registerTool(defineTool({
|
|
133
|
+
name: CLASSIFY_EXTRACT_TOOL,
|
|
134
|
+
label: "Extract structured fields",
|
|
135
|
+
description: CLASSIFY_EXTRACT_TOOL_DESCRIPTION,
|
|
136
|
+
promptSnippet: "Extract typed fields with Cloudflare Clairic into a caller-defined field contract.",
|
|
137
|
+
promptGuidelines: [
|
|
138
|
+
"Use fields that describe the value you need; do not invent provider field types or keys.",
|
|
139
|
+
"Clairic renders values from text and media. A result is not proof that a fact is correct; use grounded spans and confidence when available.",
|
|
140
|
+
"truncated means generated fields are incomplete or invalid. Do not treat truncated output as complete extraction.",
|
|
141
|
+
"The configured clairic-api route receives state, fields and media. Do not send data the user does not intend to share with Cloudflare.",
|
|
142
|
+
],
|
|
143
|
+
parameters: classifyExtractParameters,
|
|
144
|
+
outputSchema: classifyExtractOutput,
|
|
145
|
+
annotations: { readOnlyHint: true, destructiveHint: false, openWorldHint: true },
|
|
146
|
+
async execute(_id, params, signal, _onUpdate, ctx) {
|
|
147
|
+
try {
|
|
148
|
+
const result = await extract(params, {
|
|
149
|
+
settings: loadClassifierSettings(ctx.cwd, isProjectTrusted(ctx)),
|
|
150
|
+
cwd: ctx.cwd,
|
|
151
|
+
...(signal ? { signal } : {}),
|
|
152
|
+
});
|
|
153
|
+
return {
|
|
154
|
+
content: [{ type: "text", text: JSON.stringify(result, null, 2) }],
|
|
155
|
+
details: result,
|
|
156
|
+
structuredContent: { ...result },
|
|
157
|
+
};
|
|
158
|
+
}
|
|
159
|
+
catch (error) {
|
|
160
|
+
throw new Error(userError(error));
|
|
161
|
+
}
|
|
162
|
+
},
|
|
163
|
+
}));
|
|
301
164
|
pi.registerCommand("classifier", {
|
|
302
165
|
description: "Classifier: status, list, reload, use <route> <model>, compare <JSON params>. Use writes trusted project defaults; compare makes potentially billable calls.",
|
|
303
166
|
handler: async (args, ctx) => {
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { type CredentialSource } from "./auth.js";
|
|
2
|
+
import { userError, type ExtractResult } from "./types.js";
|
|
3
|
+
export type ExtractOptions = {
|
|
4
|
+
settings: import("./types.js").ClassifierSettings;
|
|
5
|
+
cwd: string;
|
|
6
|
+
signal?: AbortSignal;
|
|
7
|
+
credentialSource?: CredentialSource;
|
|
8
|
+
};
|
|
9
|
+
/** Cloudflare Clairic structured extraction through the configured clairic-api route. */
|
|
10
|
+
export declare function extract(params: unknown, options: ExtractOptions): Promise<ExtractResult>;
|
|
11
|
+
export { userError };
|
package/dist/extract.js
ADDED
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
import { resolveApiKey } from "./auth.js";
|
|
2
|
+
import { resolveModel } from "./config.js";
|
|
3
|
+
import { estimateCost, tokenCount } from "./cost.js";
|
|
4
|
+
import { postJson } from "./http.js";
|
|
5
|
+
import { prepareExtractionInput } from "./inputs.js";
|
|
6
|
+
import { unwrapCloudflare } from "./providers.js";
|
|
7
|
+
import { ClassifierError, isRecord, userError, } from "./types.js";
|
|
8
|
+
const CLAIRIC_LABEL = "Cloudflare Clairic";
|
|
9
|
+
const ANSWER_METADATA = [
|
|
10
|
+
"valid", "complete", "decoder", "tokens", "raw", "retry_input_tokens", "null_recovered",
|
|
11
|
+
"guess", "p_null", "p_null_method", "p_nulls", "confidence", "confidences", "confidence_method", "log_probability",
|
|
12
|
+
"span", "spans", "path", "property_spans", "span_method", "grounding_method", "printed_value", "normalization_method", "failure_reason", "source",
|
|
13
|
+
"unit", "mean", "median", "p10", "p90", "p_below", "p_above", "quantiles", "steps",
|
|
14
|
+
];
|
|
15
|
+
function usageFrom(value) {
|
|
16
|
+
if (!isRecord(value))
|
|
17
|
+
return undefined;
|
|
18
|
+
const input = tokenCount(value.input_tokens);
|
|
19
|
+
const output = tokenCount(value.output_tokens);
|
|
20
|
+
if (input === undefined || output === undefined)
|
|
21
|
+
return undefined;
|
|
22
|
+
return { inputTokens: input, outputTokens: output, totalTokens: input + output };
|
|
23
|
+
}
|
|
24
|
+
function reportedCost(value) {
|
|
25
|
+
if (!isRecord(value) || typeof value.cost !== "number" || !Number.isFinite(value.cost) || value.cost < 0)
|
|
26
|
+
return undefined;
|
|
27
|
+
return { currency: "USD", total: value.cost, source: "provider" };
|
|
28
|
+
}
|
|
29
|
+
function jsonLike(value) {
|
|
30
|
+
if (value === null || typeof value === "string" || typeof value === "boolean")
|
|
31
|
+
return true;
|
|
32
|
+
if (typeof value === "number")
|
|
33
|
+
return Number.isFinite(value);
|
|
34
|
+
if (Array.isArray(value))
|
|
35
|
+
return value.every(jsonLike);
|
|
36
|
+
if (!isRecord(value))
|
|
37
|
+
return false;
|
|
38
|
+
return Object.values(value).every(jsonLike);
|
|
39
|
+
}
|
|
40
|
+
function parseAnswers(value, fields) {
|
|
41
|
+
if (!isRecord(value))
|
|
42
|
+
throw new ClassifierError("response", CLAIRIC_LABEL + " returned invalid answers.");
|
|
43
|
+
const answers = Object.create(null);
|
|
44
|
+
for (const name of Object.keys(fields)) {
|
|
45
|
+
const answer = Object.hasOwn(value, name) ? value[name] : undefined;
|
|
46
|
+
if (!isRecord(answer) || typeof answer.type !== "string" || !Object.hasOwn(answer, "value"))
|
|
47
|
+
throw new ClassifierError("response", CLAIRIC_LABEL + " returned an invalid answer for " + name + ".");
|
|
48
|
+
if (!jsonLike(answer.value))
|
|
49
|
+
throw new ClassifierError("response", CLAIRIC_LABEL + " returned a non-JSON value for " + name + ".");
|
|
50
|
+
const parsed = { type: answer.type, value: answer.value };
|
|
51
|
+
for (const field of ANSWER_METADATA) {
|
|
52
|
+
const metadata = answer[field];
|
|
53
|
+
if (metadata !== undefined && jsonLike(metadata))
|
|
54
|
+
parsed[field] = metadata;
|
|
55
|
+
}
|
|
56
|
+
answers[name] = parsed;
|
|
57
|
+
}
|
|
58
|
+
return answers;
|
|
59
|
+
}
|
|
60
|
+
/** Cloudflare Clairic structured extraction through the configured clairic-api route. */
|
|
61
|
+
export async function extract(params, options) {
|
|
62
|
+
if (params === null || typeof params !== "object" || Array.isArray(params))
|
|
63
|
+
throw new ClassifierError("input", "extract requires an object with fields and optional state/media.");
|
|
64
|
+
const input = params;
|
|
65
|
+
if (options.signal?.aborted)
|
|
66
|
+
throw new ClassifierError("aborted", "Extraction was cancelled.");
|
|
67
|
+
const route = resolveModel(options.settings, undefined, options.credentialSource ?? "pi-store");
|
|
68
|
+
const apiKey = route.authMode === "none" ? "" : resolveApiKey(route, options.credentialSource ?? "pi-store");
|
|
69
|
+
const prepared = await prepareExtractionInput(input, route, options.cwd, options.signal);
|
|
70
|
+
if (options.signal?.aborted)
|
|
71
|
+
throw new ClassifierError("aborted", "Extraction was cancelled.");
|
|
72
|
+
if (route.api === "openrouter-extractions")
|
|
73
|
+
return extractWithOpenRouter(route, prepared, apiKey, options.signal);
|
|
74
|
+
if (route.api === "litellm-extraction")
|
|
75
|
+
return extractWithLiteLLM(route, prepared, apiKey, options.signal);
|
|
76
|
+
const payload = {
|
|
77
|
+
model: "clairic",
|
|
78
|
+
fields: prepared.fields,
|
|
79
|
+
};
|
|
80
|
+
if (prepared.state !== "")
|
|
81
|
+
payload.state = prepared.state;
|
|
82
|
+
if (prepared.referenceDate !== undefined)
|
|
83
|
+
payload.reference_date = prepared.referenceDate;
|
|
84
|
+
if (prepared.options !== undefined) {
|
|
85
|
+
// Public callers use camelCase; Clairic's wire contract uses snake_case.
|
|
86
|
+
const wireOptions = {};
|
|
87
|
+
if (prepared.options.includeQuantiles !== undefined)
|
|
88
|
+
wireOptions.include_quantiles = prepared.options.includeQuantiles;
|
|
89
|
+
if (prepared.options.returnStateText !== undefined)
|
|
90
|
+
wireOptions.return_state_text = prepared.options.returnStateText;
|
|
91
|
+
if (Object.keys(wireOptions).length > 0)
|
|
92
|
+
payload.options = wireOptions;
|
|
93
|
+
}
|
|
94
|
+
if (prepared.images.length)
|
|
95
|
+
payload.images = prepared.images.map((image) => ({
|
|
96
|
+
content_type: image.mimeType,
|
|
97
|
+
base64: image.data,
|
|
98
|
+
...(image.rotation !== undefined ? { rotation: image.rotation } : {}),
|
|
99
|
+
}));
|
|
100
|
+
if (prepared.documents.length)
|
|
101
|
+
payload.documents = prepared.documents.map((document) => ({
|
|
102
|
+
content_type: document.mimeType,
|
|
103
|
+
base64: document.data,
|
|
104
|
+
}));
|
|
105
|
+
const { body, requestId } = await postJson(route, "run/" + route.model, payload, apiKey, options.signal);
|
|
106
|
+
const result = unwrapCloudflare(CLAIRIC_LABEL, body);
|
|
107
|
+
return finalizeExtraction(route, result, prepared, costOf(route, result.usage), requestId);
|
|
108
|
+
}
|
|
109
|
+
function costOf(route, usage) {
|
|
110
|
+
return estimateCost(route, usage);
|
|
111
|
+
}
|
|
112
|
+
function finalizeExtraction(route, result, prepared, cost, requestId, providerCost, stateText) {
|
|
113
|
+
if (typeof result.truncated !== "boolean")
|
|
114
|
+
throw new ClassifierError("response", "Extraction did not report whether output was truncated.");
|
|
115
|
+
const extracted = {
|
|
116
|
+
provider: route.route,
|
|
117
|
+
model: route.model,
|
|
118
|
+
answers: parseAnswers(result.answers, prepared.fields),
|
|
119
|
+
truncated: result.truncated,
|
|
120
|
+
cost,
|
|
121
|
+
};
|
|
122
|
+
const usage = usageFrom(result.usage);
|
|
123
|
+
if (usage !== undefined)
|
|
124
|
+
extracted.usage = usage;
|
|
125
|
+
if (requestId !== undefined)
|
|
126
|
+
extracted.requestId = requestId;
|
|
127
|
+
if (providerCost !== undefined)
|
|
128
|
+
extracted.providerCost = providerCost;
|
|
129
|
+
const text = stateText ?? (prepared.options?.returnStateText && typeof result.state_text === "string" ? result.state_text : undefined);
|
|
130
|
+
if (text !== undefined)
|
|
131
|
+
extracted.stateText = text;
|
|
132
|
+
if (Buffer.byteLength(JSON.stringify(extracted, null, 2)) > 40 * 1024)
|
|
133
|
+
throw new ClassifierError("response", "Extraction result exceeds the 40 KiB tool output limit. Ask for fewer or smaller fields.");
|
|
134
|
+
return extracted;
|
|
135
|
+
}
|
|
136
|
+
function extractionOptions(prepared) {
|
|
137
|
+
if (prepared.options === undefined)
|
|
138
|
+
return undefined;
|
|
139
|
+
const wire = {};
|
|
140
|
+
if (prepared.options.includeQuantiles !== undefined)
|
|
141
|
+
wire.include_quantiles = prepared.options.includeQuantiles;
|
|
142
|
+
if (prepared.options.returnStateText !== undefined)
|
|
143
|
+
wire.return_state_text = prepared.options.returnStateText;
|
|
144
|
+
return Object.keys(wire).length > 0 ? wire : undefined;
|
|
145
|
+
}
|
|
146
|
+
async function extractWithOpenRouter(route, prepared, apiKey, signal) {
|
|
147
|
+
const payload = { model: route.model, fields: prepared.fields };
|
|
148
|
+
const media = [
|
|
149
|
+
...prepared.images.map((image) => ({
|
|
150
|
+
type: "image",
|
|
151
|
+
format: image.mimeType === "image/png" ? "png" : image.mimeType === "image/jpeg" ? "jpg" : "webp",
|
|
152
|
+
data_base64: image.data,
|
|
153
|
+
})),
|
|
154
|
+
...prepared.documents.map((document) => ({ type: "document", format: "pdf", data_base64: document.data })),
|
|
155
|
+
];
|
|
156
|
+
const refs = media.map((_, index) => "asset-" + index);
|
|
157
|
+
let state = typeof prepared.state === "string" ? prepared.state : JSON.stringify(prepared.state);
|
|
158
|
+
if (refs.length > 0 && state !== "")
|
|
159
|
+
state = state + "\n" + refs.join(" ");
|
|
160
|
+
if (state !== "")
|
|
161
|
+
payload.state = state;
|
|
162
|
+
if (refs.length > 0)
|
|
163
|
+
payload.assets = Object.fromEntries(media.map((entry, index) => [refs[index], entry]));
|
|
164
|
+
if (prepared.referenceDate !== undefined)
|
|
165
|
+
payload.reference_date = prepared.referenceDate;
|
|
166
|
+
const options = extractionOptions(prepared);
|
|
167
|
+
if (options)
|
|
168
|
+
payload.provider = { options: { cloudflare: options } };
|
|
169
|
+
const { body, requestId } = await postJson(route, "alpha/extractions", payload, apiKey, signal);
|
|
170
|
+
if (!isRecord(body))
|
|
171
|
+
throw new ClassifierError("response", "OpenRouter Extractions returned an unexpected response.");
|
|
172
|
+
return finalizeExtraction(route, body, prepared, estimateCost(route, body.usage), requestId, reportedCost(body.usage));
|
|
173
|
+
}
|
|
174
|
+
async function extractWithLiteLLM(route, prepared, apiKey, signal) {
|
|
175
|
+
const payload = { model: route.model, fields: prepared.fields };
|
|
176
|
+
if (prepared.state !== "")
|
|
177
|
+
payload.state = prepared.state;
|
|
178
|
+
if (prepared.referenceDate !== undefined)
|
|
179
|
+
payload.reference_date = prepared.referenceDate;
|
|
180
|
+
const options = extractionOptions(prepared);
|
|
181
|
+
if (options)
|
|
182
|
+
payload.options = options;
|
|
183
|
+
if (prepared.images.length)
|
|
184
|
+
payload.images = prepared.images.map((image) => ({ content_type: image.mimeType, base64: image.data }));
|
|
185
|
+
const { body, requestId, costHeader } = await postJson(route, "extraction", payload, apiKey, signal);
|
|
186
|
+
if (!isRecord(body))
|
|
187
|
+
throw new ClassifierError("response", "LiteLLM extraction returned an unexpected response.");
|
|
188
|
+
const providerCost = costHeader ? { currency: "USD", total: Number(costHeader), source: "gateway" } : undefined;
|
|
189
|
+
return finalizeExtraction(route, body, prepared, estimateCost(route, body.usage), requestId, providerCost);
|
|
190
|
+
}
|
|
191
|
+
export { userError };
|
package/dist/http.d.ts
CHANGED
|
@@ -1,5 +1,10 @@
|
|
|
1
1
|
import { type ResolvedModel } from "./types.js";
|
|
2
|
-
|
|
2
|
+
/** Optional bounded parser for provider error envelopes; receives the active key so echoed credentials can be omitted. */
|
|
3
|
+
export type JsonErrorDetail = (status: number, body: unknown, apiKey: string) => string | undefined;
|
|
4
|
+
/** Optional sanitizer for a validated response-header request ID; omitted values fall back to provider-body IDs. */
|
|
5
|
+
export type JsonRequestIdDetail = (value: string, apiKey: string) => string | undefined;
|
|
6
|
+
export declare function postJson(route: ResolvedModel, path: string, body: unknown, apiKey: string, signal?: AbortSignal, extraHeaders?: Record<string, string>, errorDetail?: JsonErrorDetail, requestIdDetail?: JsonRequestIdDetail): Promise<{
|
|
3
7
|
body: unknown;
|
|
4
8
|
requestId?: string;
|
|
9
|
+
costHeader?: string;
|
|
5
10
|
}>;
|
package/dist/http.js
CHANGED
|
@@ -1,5 +1,29 @@
|
|
|
1
1
|
import { ClassifierError } from "./types.js";
|
|
2
|
-
|
|
2
|
+
async function readBoundedText(response) {
|
|
3
|
+
const reader = response.body?.getReader();
|
|
4
|
+
if (!reader)
|
|
5
|
+
throw new ClassifierError("response", "Classifier returned an empty response.");
|
|
6
|
+
const chunks = [];
|
|
7
|
+
let size = 0;
|
|
8
|
+
try {
|
|
9
|
+
while (true) {
|
|
10
|
+
const next = await reader.read();
|
|
11
|
+
if (next.done)
|
|
12
|
+
break;
|
|
13
|
+
size += next.value.length;
|
|
14
|
+
if (size > 1024 * 1024) {
|
|
15
|
+
await reader.cancel();
|
|
16
|
+
throw new ClassifierError("response", "Classifier response exceeds 1 MiB.");
|
|
17
|
+
}
|
|
18
|
+
chunks.push(next.value);
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
finally {
|
|
22
|
+
reader.releaseLock();
|
|
23
|
+
}
|
|
24
|
+
return Buffer.concat(chunks).toString("utf8");
|
|
25
|
+
}
|
|
26
|
+
export async function postJson(route, path, body, apiKey, signal, extraHeaders, errorDetail, requestIdDetail) {
|
|
3
27
|
if (signal?.aborted)
|
|
4
28
|
throw new ClassifierError("aborted", "Classification was cancelled.");
|
|
5
29
|
const encoded = JSON.stringify(body);
|
|
@@ -13,7 +37,19 @@ export async function postJson(route, path, body, apiKey, signal, extraHeaders)
|
|
|
13
37
|
const headers = new Headers(route.headers);
|
|
14
38
|
for (const [key, value] of Object.entries(extraHeaders ?? {}))
|
|
15
39
|
headers.set(key, value);
|
|
16
|
-
if (route.
|
|
40
|
+
if (route.authMode === "none") {
|
|
41
|
+
// Local runtimes are reached over loopback without an API key.
|
|
42
|
+
}
|
|
43
|
+
else if (route.authMode === "subscription-key") {
|
|
44
|
+
headers.set("api-subscription-key", apiKey);
|
|
45
|
+
}
|
|
46
|
+
else if (route.authMode === "google-api-key") {
|
|
47
|
+
headers.set("x-goog-api-key", apiKey);
|
|
48
|
+
}
|
|
49
|
+
else if (route.authMode === "parallel-api-key") {
|
|
50
|
+
headers.set("x-api-key", apiKey);
|
|
51
|
+
}
|
|
52
|
+
else if (route.authMode === "api-key") {
|
|
17
53
|
headers.set("api-key", apiKey);
|
|
18
54
|
}
|
|
19
55
|
else {
|
|
@@ -29,35 +65,29 @@ export async function postJson(route, path, body, apiKey, signal, extraHeaders)
|
|
|
29
65
|
redirect: "error",
|
|
30
66
|
});
|
|
31
67
|
if (!response.ok) {
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
let size = 0;
|
|
42
|
-
try {
|
|
43
|
-
while (true) {
|
|
44
|
-
const next = await reader.read();
|
|
45
|
-
if (next.done)
|
|
46
|
-
break;
|
|
47
|
-
size += next.value.length;
|
|
48
|
-
if (size > 1024 * 1024) {
|
|
49
|
-
await reader.cancel();
|
|
50
|
-
throw new ClassifierError("response", "Classifier response exceeds 1 MiB.");
|
|
68
|
+
let detail;
|
|
69
|
+
if (errorDetail) {
|
|
70
|
+
try {
|
|
71
|
+
const raw = await readBoundedText(response);
|
|
72
|
+
if (raw)
|
|
73
|
+
detail = errorDetail(response.status, JSON.parse(raw), apiKey);
|
|
74
|
+
}
|
|
75
|
+
catch {
|
|
76
|
+
// Keep the generic error when an error body is absent, oversized or not JSON.
|
|
51
77
|
}
|
|
52
|
-
chunks.push(next.value);
|
|
53
78
|
}
|
|
79
|
+
else {
|
|
80
|
+
await response.body?.cancel();
|
|
81
|
+
}
|
|
82
|
+
throw new ClassifierError("http", "Classifier request failed (HTTP " +
|
|
83
|
+
response.status +
|
|
84
|
+
"). Check credentials, model, limits and provider availability." +
|
|
85
|
+
(detail ? " " + detail : ""), response.status);
|
|
54
86
|
}
|
|
55
|
-
|
|
56
|
-
reader.releaseLock();
|
|
57
|
-
}
|
|
87
|
+
const raw = await readBoundedText(response);
|
|
58
88
|
let parsed;
|
|
59
89
|
try {
|
|
60
|
-
parsed = JSON.parse(
|
|
90
|
+
parsed = JSON.parse(raw);
|
|
61
91
|
}
|
|
62
92
|
catch {
|
|
63
93
|
throw new ClassifierError("response", "Classifier returned invalid JSON.");
|
|
@@ -65,8 +95,14 @@ export async function postJson(route, path, body, apiKey, signal, extraHeaders)
|
|
|
65
95
|
const result = { body: parsed };
|
|
66
96
|
const id = response.headers.get("x-request-id") ??
|
|
67
97
|
response.headers.get("request-id");
|
|
68
|
-
if (id && /^[a-zA-Z0-9_.:-]{1,128}$/.test(id))
|
|
69
|
-
|
|
98
|
+
if (id && /^[a-zA-Z0-9_.:-]{1,128}$/.test(id)) {
|
|
99
|
+
const safeId = requestIdDetail ? requestIdDetail(id, apiKey) : id;
|
|
100
|
+
if (safeId !== undefined)
|
|
101
|
+
result.requestId = safeId;
|
|
102
|
+
}
|
|
103
|
+
const cost = response.headers.get("x-litellm-response-cost");
|
|
104
|
+
if (cost && /^\d+(?:\.\d+)?(?:e[+-]?\d+)?$/i.test(cost))
|
|
105
|
+
result.costHeader = cost;
|
|
70
106
|
return result;
|
|
71
107
|
}
|
|
72
108
|
catch (error) {
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { type ImageReference, type PreparedImage, type Question } from "./types.js";
|
|
2
|
+
export declare function isImageReference(value: unknown): value is ImageReference;
|
|
3
|
+
/** Only explicit reference objects are special; provider-native-looking user JSON stays data. */
|
|
4
|
+
export declare function imageReferences(value: unknown): string[];
|
|
5
|
+
export declare function questionImageReferences(questions: Record<string, Question>): string[];
|
|
6
|
+
export declare function mapImageReferences(value: unknown, image: (id: string) => unknown): unknown;
|
|
7
|
+
export declare function namedImage(images: PreparedImage[], id: string): PreparedImage;
|
|
8
|
+
export declare function imageUrl(image: PreparedImage): string;
|
|
9
|
+
/** Preserve JSON punctuation as text, interleaving only explicitly referenced images.
|
|
10
|
+
* Raw user objects never become provider-native content parts.
|
|
11
|
+
*/
|
|
12
|
+
export declare function imageContentParts(value: unknown, image: (id: string) => unknown): unknown[];
|