@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/src/validation.ts CHANGED
@@ -2,6 +2,7 @@ import {
2
2
  ClassifierError,
3
3
  isRecord,
4
4
  type ClassifyParams,
5
+ type ExtractionQuestion,
5
6
  type Question,
6
7
  } from "./types.js";
7
8
  import { imageReferences, isImageReference, questionImageReferences } from "./image-content.js";
@@ -20,6 +21,116 @@ function content(value: unknown, maxLength: number, nonempty = false): boolean {
20
21
  (!nonempty || value.some((part) => typeof part !== "string" || Boolean(part.trim())));
21
22
  }
22
23
 
24
+ const CLASSIFICATION_QUESTION_TYPES = new Set(["bool", "choice", "score", "multi_choice"]);
25
+ const EXTRACTION_QUESTION_TYPES = new Set(["extract", "box", "locate", "text", "number", "date", "spans", "boxes", "estimate"]);
26
+
27
+ /** Per-type field rules; both tools validate against the same definitions. */
28
+ function validateQuestion(question: Record<string, unknown>): void {
29
+ const allowed = question.type === "number" || question.type === "estimate"
30
+ ? ["type", "instructions", "unit", "range", "step"]
31
+ : question.type === "spans" || question.type === "boxes"
32
+ ? ["type", "instructions", "max"]
33
+ : question.type === "choice"
34
+ ? ["type", "instructions", "criteria", "booleanValues"]
35
+ : question.type === "score"
36
+ ? ["type", "instructions", "criteria", "descriptions"]
37
+ : question.type === "extract"
38
+ ? ["type", "instructions", "criteria", "source", "threshold", "snapToWords", "debug"]
39
+ : ["type", "instructions", "criteria"];
40
+ if (Object.keys(question).some((key) => !allowed.includes(key)))
41
+ invalid("Unknown question field for " + String(question.type) + ".");
42
+ if (question.type !== "extract" && !content(question.instructions, 16_384, true))
43
+ invalid("Each question needs non-empty text or ordered text/image-reference instructions, at most 16384 characters/bytes.");
44
+ if (question.type === "extract" && question.instructions !== undefined && !content(question.instructions, 16_384))
45
+ invalid("Extract instructions must be text or ordered text/image-reference content, at most 16384 characters/bytes.");
46
+ if (question.type === "bool") {
47
+ if (question.criteria !== undefined && (!isRecord(question.criteria) ||
48
+ Object.entries(question.criteria).some(([key, entry]) => !["true", "false"].includes(key) || !content(entry, 4096))))
49
+ invalid("bool criteria must contain optional true/false descriptions or image content.");
50
+ } else if (question.type === "choice") {
51
+ if (!isRecord(question.criteria)) invalid("choice criteria must map labels to descriptions.");
52
+ const criteria = Object.entries(question.criteria);
53
+ if (criteria.length < 1 || criteria.some(([key, entry]) => !key.trim() || key.length > 128 || !content(entry, 4096)))
54
+ invalid("choice requires at least one label with a text or image-content description.");
55
+ if (question.booleanValues !== undefined) {
56
+ if (typeof question.booleanValues !== "boolean")
57
+ invalid("choice.booleanValues must be a boolean.");
58
+ if (question.booleanValues && criteria.some(([key]) => key !== "true" && key !== "false"))
59
+ invalid("Boolean-valued choices must use the labels true and false.");
60
+ }
61
+ } else if (question.type === "score") {
62
+ if (!Array.isArray(question.criteria) || question.criteria.length < 2 || question.criteria.length > 10 ||
63
+ question.criteria.some((entry) => !content(entry, 4096, true)))
64
+ invalid("score criteria must contain 2–10 non-empty ordered descriptions or image content.");
65
+ if (question.descriptions !== undefined &&
66
+ (!Array.isArray(question.descriptions) || question.descriptions.length !== question.criteria.length ||
67
+ question.descriptions.some((entry) => typeof entry !== "string" || entry.length > 4096)))
68
+ invalid("score descriptions must contain one string per criterion, at most 4096 characters each.");
69
+ } else if (question.type === "box") {
70
+ if (question.criteria !== undefined) invalid("box does not accept criteria.");
71
+ } else if (question.type === "locate" || question.type === "text" || question.type === "date") {
72
+ if (question.criteria !== undefined) invalid(question.type + " does not accept criteria.");
73
+ } else if (question.type === "spans" || question.type === "boxes") {
74
+ if (question.criteria !== undefined) invalid(question.type + " does not accept criteria.");
75
+ if (question.max !== undefined &&
76
+ (!Number.isSafeInteger(question.max) || (question.max as number) < 1 || (question.max as number) > 64))
77
+ invalid(question.type + ".max must be an integer from 1 to 64.");
78
+ } else if (question.type === "number" || question.type === "estimate") {
79
+ if (question.unit !== undefined && (typeof question.unit !== "string" || question.unit.length > 128))
80
+ invalid("unit must be a string of at most 128 characters.");
81
+ if (question.step !== undefined && (typeof question.step !== "number" || !Number.isFinite(question.step) || question.step <= 0))
82
+ invalid("step must be a positive finite number.");
83
+ const range = question.range;
84
+ if (question.type === "estimate" && !Array.isArray(range))
85
+ invalid("estimate requires a [low, high] range.");
86
+ if (range !== undefined && (!Array.isArray(range) || range.length !== 2 ||
87
+ range.some((entry) => typeof entry !== "number" || !Number.isFinite(entry)) ||
88
+ (range[0] as number) >= (range[1] as number)))
89
+ invalid("range must be a finite [low, high] pair with low below high.");
90
+ } else if (question.type === "extract") {
91
+ if (!isRecord(question.criteria))
92
+ invalid("extract criteria must map field names to descriptions.");
93
+ const criteria = Object.entries(question.criteria);
94
+ if (criteria.length < 1 || criteria.length > 26 || criteria.some(([key, entry]) => !key.trim() || key.length > 128 || !content(entry, 4096)))
95
+ invalid("extract requires 1–26 fields with text descriptions.");
96
+ if (question.source !== undefined && (typeof question.source !== "string" || !question.source.trim() || question.source.length > 4096))
97
+ invalid("extract.source must be a non-empty string of at most 4096 characters.");
98
+ if (question.threshold !== undefined && (typeof question.threshold !== "number" || !Number.isFinite(question.threshold) || question.threshold < 0 || question.threshold > 1))
99
+ invalid("extract.threshold must be a number between 0 and 1.");
100
+ if (question.snapToWords !== undefined && typeof question.snapToWords !== "boolean")
101
+ invalid("extract.snapToWords must be a boolean.");
102
+ if (question.debug !== undefined && typeof question.debug !== "boolean")
103
+ invalid("extract.debug must be a boolean.");
104
+ } else if (question.type === "multi_choice") {
105
+ if (!isRecord(question.criteria))
106
+ invalid("multi_choice criteria must map labels to descriptions.");
107
+ const criteria = Object.entries(question.criteria);
108
+ if (criteria.length < 2 || criteria.some(([key, entry]) => !key.trim() || key.length > 128 || !content(entry, 4096)))
109
+ invalid("multi_choice requires at least two labels with text or image-content descriptions.");
110
+ } else invalid("Question type must be a supported classification or extraction question type.");
111
+ }
112
+
113
+ /**
114
+ * `classify_extract` question mode. Extraction question types only, validated against the same
115
+ * per-type rules the provider adapters rely on. Route capability checks stay in prepareInput.
116
+ */
117
+ export function validateExtractionQuestions(value: unknown): Record<string, ExtractionQuestion> {
118
+ if (!isRecord(value)) invalid("questions must be a map keyed by question ID.");
119
+ const entries = Object.entries(value);
120
+ if (entries.length < 1 || entries.length > 1000)
121
+ invalid("Supply between 1 and 1000 extraction questions; the selected route enforces its own lower limit.");
122
+ for (const [id, question] of entries) {
123
+ if (!/^[a-zA-Z0-9_-]{1,64}$/.test(id) || !isRecord(question))
124
+ invalid("Question IDs must be 1–64 letters, digits, underscores or hyphens.");
125
+ if (typeof question.type === "string" && CLASSIFICATION_QUESTION_TYPES.has(question.type))
126
+ invalid("classify_extract reads values, not classification decisions. " + question.type + " belongs in classify.");
127
+ validateQuestion(question);
128
+ }
129
+ if (Buffer.byteLength(JSON.stringify(value)) > 2 * 1024 * 1024)
130
+ invalid("Extraction questions must be at most 2 MiB.");
131
+ return value as Record<string, ExtractionQuestion>;
132
+ }
133
+
23
134
  export function validateParams(value: unknown): ClassifyParams {
24
135
  if (!isRecord(value) || Object.keys(value).some((key) => !["state", "questions", "images", "media", "mode", "conversation", "imageDetail", "promptCache"].includes(key)))
25
136
  invalid("Expected state, questions and optional images, media, mode, conversation, imageDetail or promptCache; provider/model are selected in settings.");
@@ -32,88 +143,9 @@ export function validateParams(value: unknown): ClassifyParams {
32
143
  for (const [id, question] of entries) {
33
144
  if (!/^[a-zA-Z0-9_-]{1,64}$/.test(id) || !isRecord(question))
34
145
  invalid("Question IDs must be 1–64 letters, digits, underscores or hyphens.");
35
- const allowed = question.type === "number" || question.type === "estimate"
36
- ? ["type", "instructions", "unit", "range", "step"]
37
- : question.type === "spans" || question.type === "boxes"
38
- ? ["type", "instructions", "max"]
39
- : question.type === "choice"
40
- ? ["type", "instructions", "criteria", "booleanValues"]
41
- : question.type === "score"
42
- ? ["type", "instructions", "criteria", "descriptions"]
43
- : question.type === "extract"
44
- ? ["type", "instructions", "criteria", "source", "threshold", "snapToWords", "debug"]
45
- : ["type", "instructions", "criteria"];
46
- if (Object.keys(question).some((key) => !allowed.includes(key)))
47
- invalid("Unknown question field for " + String(question.type) + ".");
48
- if (question.type !== "extract" && !content(question.instructions, 16_384, true))
49
- invalid("Each question needs non-empty text or ordered text/image-reference instructions, at most 16384 characters/bytes.");
50
- if (question.type === "extract" && question.instructions !== undefined && !content(question.instructions, 16_384))
51
- invalid("Extract instructions must be text or ordered text/image-reference content, at most 16384 characters/bytes.");
52
- if (question.type === "bool") {
53
- if (question.criteria !== undefined && (!isRecord(question.criteria) ||
54
- Object.entries(question.criteria).some(([key, entry]) => !["true", "false"].includes(key) || !content(entry, 4096))))
55
- invalid("bool criteria must contain optional true/false descriptions or image content.");
56
- } else if (question.type === "choice") {
57
- if (!isRecord(question.criteria)) invalid("choice criteria must map labels to descriptions.");
58
- const criteria = Object.entries(question.criteria);
59
- if (criteria.length < 1 || criteria.some(([key, entry]) => !key.trim() || key.length > 128 || !content(entry, 4096)))
60
- invalid("choice requires at least one label with a text or image-content description.");
61
- if (question.booleanValues !== undefined) {
62
- if (typeof question.booleanValues !== "boolean")
63
- invalid("choice.booleanValues must be a boolean.");
64
- if (question.booleanValues && criteria.some(([key]) => key !== "true" && key !== "false"))
65
- invalid("Boolean-valued choices must use the labels true and false.");
66
- }
67
- } else if (question.type === "score") {
68
- if (!Array.isArray(question.criteria) || question.criteria.length < 2 || question.criteria.length > 10 ||
69
- question.criteria.some((entry) => !content(entry, 4096, true)))
70
- invalid("score criteria must contain 2–10 non-empty ordered descriptions or image content.");
71
- if (question.descriptions !== undefined &&
72
- (!Array.isArray(question.descriptions) || question.descriptions.length !== question.criteria.length ||
73
- question.descriptions.some((entry) => typeof entry !== "string" || entry.length > 4096)))
74
- invalid("score descriptions must contain one string per criterion, at most 4096 characters each.");
75
- } else if (question.type === "box") {
76
- if (question.criteria !== undefined) invalid("box does not accept criteria.");
77
- } else if (question.type === "locate" || question.type === "text" || question.type === "date") {
78
- if (question.criteria !== undefined) invalid(question.type + " does not accept criteria.");
79
- } else if (question.type === "spans" || question.type === "boxes") {
80
- if (question.criteria !== undefined) invalid(question.type + " does not accept criteria.");
81
- if (question.max !== undefined &&
82
- (!Number.isSafeInteger(question.max) || (question.max as number) < 1 || (question.max as number) > 64))
83
- invalid(question.type + ".max must be an integer from 1 to 64.");
84
- } else if (question.type === "number" || question.type === "estimate") {
85
- if (question.unit !== undefined && (typeof question.unit !== "string" || question.unit.length > 128))
86
- invalid("unit must be a string of at most 128 characters.");
87
- if (question.step !== undefined && (typeof question.step !== "number" || !Number.isFinite(question.step) || question.step <= 0))
88
- invalid("step must be a positive finite number.");
89
- const range = question.range;
90
- if (question.type === "estimate" && !Array.isArray(range))
91
- invalid("estimate requires a [low, high] range.");
92
- if (range !== undefined && (!Array.isArray(range) || range.length !== 2 ||
93
- range.some((entry) => typeof entry !== "number" || !Number.isFinite(entry)) ||
94
- (range[0] as number) >= (range[1] as number)))
95
- invalid("range must be a finite [low, high] pair with low below high.");
96
- } else if (question.type === "extract") {
97
- if (!isRecord(question.criteria))
98
- invalid("extract criteria must map field names to descriptions.");
99
- const criteria = Object.entries(question.criteria);
100
- if (criteria.length < 1 || criteria.length > 26 || criteria.some(([key, entry]) => !key.trim() || key.length > 128 || !content(entry, 4096)))
101
- invalid("extract requires 1–26 fields with text descriptions.");
102
- if (question.source !== undefined && (typeof question.source !== "string" || !question.source.trim() || question.source.length > 4096))
103
- invalid("extract.source must be a non-empty string of at most 4096 characters.");
104
- if (question.threshold !== undefined && (typeof question.threshold !== "number" || !Number.isFinite(question.threshold) || question.threshold < 0 || question.threshold > 1))
105
- invalid("extract.threshold must be a number between 0 and 1.");
106
- if (question.snapToWords !== undefined && typeof question.snapToWords !== "boolean")
107
- invalid("extract.snapToWords must be a boolean.");
108
- if (question.debug !== undefined && typeof question.debug !== "boolean")
109
- invalid("extract.debug must be a boolean.");
110
- } else if (question.type === "multi_choice") {
111
- if (!isRecord(question.criteria))
112
- invalid("multi_choice criteria must map labels to descriptions.");
113
- const criteria = Object.entries(question.criteria);
114
- if (criteria.length < 2 || criteria.some(([key, entry]) => !key.trim() || key.length > 128 || !content(entry, 4096)))
115
- invalid("multi_choice requires at least two labels with text or image-content descriptions.");
116
- } else invalid("Question type must be a supported typed decision or read.");
146
+ if (typeof question.type === "string" && EXTRACTION_QUESTION_TYPES.has(question.type))
147
+ invalid("classify answers classification decisions only. " + question.type + " is an extraction read; send the same question to classify_extract instead.");
148
+ validateQuestion(question);
117
149
  }
118
150
  if (value.media !== undefined) {
119
151
  if (!Array.isArray(value.media))
@@ -154,29 +186,7 @@ export function validateParams(value: unknown): ClassifyParams {
154
186
  if (value.promptCache.breakpoints !== undefined && typeof value.promptCache.breakpoints !== "boolean")
155
187
  invalid("promptCache.breakpoints must be a boolean.");
156
188
  }
157
- const ids = new Set<string>();
158
- if (value.images !== undefined) {
159
- if (!Array.isArray(value.images) || value.images.length > 128)
160
- invalid("images must contain at most 128 local paths or named path/url descriptors; route-specific limits also apply.");
161
- for (const image of value.images) {
162
- if (typeof image === "string") {
163
- if (!image.trim() || image.length > 4096) invalid("Image paths must be non-empty, at most 4096 characters.");
164
- continue;
165
- }
166
- if (!isRecord(image) || typeof image.id !== "string" || !imageId.test(image.id) ||
167
- Object.keys(image).some((key) => !["id", "path", "url"].includes(key)) ||
168
- (Object.hasOwn(image, "path") === Object.hasOwn(image, "url")))
169
- invalid("Named images require a unique id and exactly one path or url.");
170
- const source = image.path ?? image.url;
171
- if (typeof source !== "string" || !source.trim() || source.length > 4096)
172
- invalid("Image path/url must be non-empty, at most 4096 characters.");
173
- if (ids.has(image.id)) invalid("Named image IDs must be unique.");
174
- ids.add(image.id);
175
- }
176
- }
177
- const references = [...imageReferences(value.state), ...questionImageReferences(value.questions as Record<string, Question>)];
178
- for (const id of references) if (!ids.has(id)) invalid("Every image reference must name an image descriptor in images.");
179
- for (const id of ids) if (!references.includes(id)) invalid("Every named image must be referenced in state, instructions or criteria.");
189
+ validateImageDescriptors(value.images, value.state, value.questions);
180
190
  if (value.mode === "web_grounding" &&
181
191
  Object.values(value.questions).some((question) => isRecord(question) && question.type === "locate") &&
182
192
  typeof value.state !== "string")
@@ -206,6 +216,33 @@ function validateJson(value: unknown, depth: number): void {
206
216
  invalid("Content must contain only finite JSON values.");
207
217
  }
208
218
 
219
+ /** Named/shared image descriptors and {$image:id} resolution, shared by both tools. */
220
+ export function validateImageDescriptors(images: unknown, state: unknown, questions: unknown): void {
221
+ const ids = new Set<string>();
222
+ if (images !== undefined) {
223
+ if (!Array.isArray(images) || images.length > 128)
224
+ invalid("images must contain at most 128 local paths or named path/url descriptors; route-specific limits also apply.");
225
+ for (const image of images) {
226
+ if (typeof image === "string") {
227
+ if (!image.trim() || image.length > 4096) invalid("Image paths must be non-empty, at most 4096 characters.");
228
+ continue;
229
+ }
230
+ if (!isRecord(image) || typeof image.id !== "string" || !imageId.test(image.id) ||
231
+ Object.keys(image).some((key) => !["id", "path", "url"].includes(key)) ||
232
+ (Object.hasOwn(image, "path") === Object.hasOwn(image, "url")))
233
+ invalid("Named images require a unique id and exactly one path or url.");
234
+ const source = image.path ?? image.url;
235
+ if (typeof source !== "string" || !source.trim() || source.length > 4096)
236
+ invalid("Image path/url must be non-empty, at most 4096 characters.");
237
+ if (ids.has(image.id)) invalid("Named image IDs must be unique.");
238
+ ids.add(image.id);
239
+ }
240
+ }
241
+ const references = [...imageReferences(state), ...questionImageReferences(questions as Record<string, Question>)];
242
+ for (const id of references) if (!ids.has(id)) invalid("Every image reference must name an image descriptor in images.");
243
+ for (const id of ids) if (!references.includes(id)) invalid("Every named image must be referenced in state, instructions or criteria.");
244
+ }
245
+
209
246
  export function hasBox(questions: Record<string, Question>): boolean {
210
247
  return Object.values(questions).some((question) => question.type === "box");
211
248
  }