@abhishek944/pi-classifier 0.2.0 → 0.4.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.
Files changed (57) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/COMPUTER_USE.md +117 -0
  3. package/README.md +268 -8
  4. package/dist/box-tool.d.ts +26 -0
  5. package/dist/box-tool.js +109 -0
  6. package/dist/box.d.ts +32 -0
  7. package/dist/box.js +148 -0
  8. package/dist/choices.d.ts +8 -0
  9. package/dist/choices.js +131 -0
  10. package/dist/classification-tree.d.ts +4 -0
  11. package/dist/classification-tree.js +143 -0
  12. package/dist/classify.d.ts +4 -2
  13. package/dist/classify.js +5 -2
  14. package/dist/computer-use-state.d.ts +9 -0
  15. package/dist/computer-use-state.js +160 -0
  16. package/dist/computer-use-tool.d.ts +52 -0
  17. package/dist/computer-use-tool.js +78 -0
  18. package/dist/computer-use-types.d.ts +132 -0
  19. package/dist/computer-use-types.js +1 -0
  20. package/dist/computer-use.d.ts +22 -0
  21. package/dist/computer-use.js +223 -0
  22. package/dist/config.js +44 -0
  23. package/dist/cost.d.ts +8 -0
  24. package/dist/cost.js +202 -0
  25. package/dist/extension.d.ts +164 -9
  26. package/dist/extension.js +164 -14
  27. package/dist/image-content.d.ts +12 -0
  28. package/dist/image-content.js +90 -0
  29. package/dist/index.d.ts +9 -1
  30. package/dist/index.js +3 -0
  31. package/dist/inputs.d.ts +11 -2
  32. package/dist/inputs.js +155 -131
  33. package/dist/providers.js +113 -100
  34. package/dist/tree.d.ts +4 -0
  35. package/dist/tree.js +136 -0
  36. package/dist/types.d.ts +113 -11
  37. package/dist/validation.js +63 -39
  38. package/package.json +2 -1
  39. package/src/box-tool.ts +145 -0
  40. package/src/box.ts +253 -0
  41. package/src/choices.ts +174 -0
  42. package/src/classification-tree.ts +181 -0
  43. package/src/classify.ts +16 -4
  44. package/src/computer-use-state.ts +145 -0
  45. package/src/computer-use-tool.ts +76 -0
  46. package/src/computer-use-types.ts +127 -0
  47. package/src/computer-use.ts +216 -0
  48. package/src/config.ts +55 -0
  49. package/src/cost.ts +250 -0
  50. package/src/extension.ts +191 -15
  51. package/src/image-content.ts +77 -0
  52. package/src/index.ts +18 -0
  53. package/src/inputs.ts +163 -185
  54. package/src/providers.ts +113 -119
  55. package/src/tree.ts +157 -0
  56. package/src/types.ts +117 -10
  57. package/src/validation.ts +62 -95
package/src/types.ts CHANGED
@@ -5,15 +5,23 @@ export type ApiStyle =
5
5
  | "cloudflare-system-one"
6
6
  | "microsoft-system-one";
7
7
 
8
+ /** Explicit references are resolved only from the request's named images. */
9
+ export type ImageReference = { $image: string };
10
+ export type QuestionContent = string | (string | ImageReference)[];
11
+ export type ImageInput =
12
+ | string
13
+ | { id: string; path: string }
14
+ | { id: string; url: string };
15
+
8
16
  export type Question =
9
17
  | {
10
18
  type: "bool";
11
- instructions: string;
12
- criteria?: { true?: string; false?: string };
19
+ instructions: QuestionContent;
20
+ criteria?: { true?: QuestionContent; false?: QuestionContent };
13
21
  }
14
- | { type: "choice"; instructions: string; criteria: Record<string, string> }
15
- | { type: "score"; instructions: string; criteria: string[] }
16
- | { type: "box"; instructions: string };
22
+ | { type: "choice"; instructions: QuestionContent; criteria: Record<string, QuestionContent> }
23
+ | { type: "score"; instructions: QuestionContent; criteria: QuestionContent[] }
24
+ | { type: "box"; instructions: QuestionContent };
17
25
 
18
26
  export type Answer =
19
27
  | { type: "bool"; probability: number }
@@ -22,6 +30,9 @@ export type Answer =
22
30
  choice: string;
23
31
  probabilities: Record<string, number>;
24
32
  confidence: number;
33
+ /** Present when probabilities cover one internally processed batch, not the full list. */
34
+ probabilityScope?: "batch";
35
+ noneOfAboveProbability?: number;
25
36
  }
26
37
  | {
27
38
  type: "score";
@@ -34,15 +45,53 @@ export type Answer =
34
45
  box: { top: number; bottom: number; left: number; right: number };
35
46
  confidence: number;
36
47
  }
37
- | { type: "refusal" };
48
+ | { type: "refusal" }
49
+ | { type: "no_match" }
50
+ | { type: "ambiguous" };
38
51
 
39
52
  export interface ClassifyParams {
40
53
  state: string | Record<string, unknown> | unknown[];
41
54
  questions: Record<string, Question>;
42
- /** Regular PNG/JPEG/WebP files inside cwd; attached in this order. */
43
- images?: string[];
55
+ /** Legacy paths are shared in order. Named images require explicit {$image:id} references. */
56
+ images?: ImageInput[];
44
57
  }
45
58
 
59
+ export type ClassificationTreeNode = {
60
+ id: string;
61
+ description?: string;
62
+ children?: ClassificationTreeNode[];
63
+ };
64
+
65
+ export type ClassificationTree = { roots: ClassificationTreeNode[] };
66
+
67
+ export type ClassifyTreeParams = {
68
+ state: ClassifyParams["state"];
69
+ tree: string | ClassificationTree;
70
+ instructions?: string;
71
+ images?: ImageInput[];
72
+ };
73
+
74
+ export type TreeStep = {
75
+ level: number;
76
+ id: string;
77
+ source: "automatic" | "model";
78
+ confidence?: number;
79
+ probabilityScope?: "siblings" | "batch";
80
+ noneOfAboveProbability?: number;
81
+ };
82
+
83
+ export type ClassifierTreeResult = {
84
+ provider: string;
85
+ model: string;
86
+ status: "complete" | "no_match" | "ambiguous" | "refusal";
87
+ levels: Record<string, string>;
88
+ steps: TreeStep[];
89
+ providerCalls: number;
90
+ cost: ClassifierCost;
91
+ usage?: NonNullable<ClassifierResult["usage"]>;
92
+ attemptedRoutes?: ClassifierRoute[];
93
+ };
94
+
46
95
  export interface ModelDefinition {
47
96
  id: string;
48
97
  name?: string;
@@ -50,6 +99,43 @@ export interface ModelDefinition {
50
99
  box?: boolean;
51
100
  }
52
101
 
102
+ /** USD per million tokens. Cache counts, when reported, are part of input tokens. */
103
+ export type TokenPricing = {
104
+ inputPerMillion: number;
105
+ outputPerMillion: number;
106
+ cachedInputPerMillion?: number;
107
+ cacheWritePerMillion?: number;
108
+ };
109
+
110
+ export type ClassifierCost =
111
+ | {
112
+ status: "estimated";
113
+ currency: "USD";
114
+ input: number;
115
+ output: number;
116
+ total: number;
117
+ source: "builtin" | "configured";
118
+ rates: TokenPricing;
119
+ }
120
+ | {
121
+ status: "estimated";
122
+ currency: "USD";
123
+ input: number;
124
+ output: number;
125
+ total: number;
126
+ source: "aggregated";
127
+ }
128
+ | {
129
+ status: "unavailable";
130
+ currency: "USD";
131
+ reason:
132
+ | "unknown_pricing"
133
+ | "missing_usage"
134
+ | "invalid_usage"
135
+ | "missing_cache_pricing"
136
+ | "calculation_overflow";
137
+ };
138
+
53
139
  export interface ProviderSettings {
54
140
  apiKey?: string;
55
141
  baseUrl?: string;
@@ -57,6 +143,10 @@ export interface ProviderSettings {
57
143
  accountId?: string;
58
144
  experimentalImages?: boolean;
59
145
  experimentalBox?: boolean;
146
+ /** Model ID (or Azure deployment name) to explicit token rates. */
147
+ pricing?: Record<string, TokenPricing>;
148
+ /** Verified wire choice limit; needed for batching on endpoints without a known limit. */
149
+ maxChoices?: number;
60
150
  }
61
151
 
62
152
  export interface CustomProviderSettings extends ProviderSettings {
@@ -70,6 +160,9 @@ export type ClassifierRoute = {
70
160
  };
71
161
 
72
162
  export interface ClassifierSettings {
163
+ computerUse?: import("./computer-use-types.js").ComputerUseSettings;
164
+ none_of_above_choice?: boolean;
165
+ remove_choice_limits?: boolean;
73
166
  default?: ClassifierRoute;
74
167
  fallback?: ClassifierRoute[];
75
168
  compare?: ClassifierRoute[];
@@ -94,15 +187,19 @@ export interface ResolvedModel {
94
187
  box: boolean;
95
188
  experimentalImages: boolean;
96
189
  requestTimeoutMs: number;
190
+ pricing?: { rates: TokenPricing; source: "builtin" | "configured" };
191
+ maxChoices?: number;
97
192
  }
98
193
 
99
- export interface PreparedImage {
194
+ export interface PreparedLocalImage {
100
195
  data: string;
101
196
  mimeType: "image/png" | "image/jpeg" | "image/webp";
102
197
  width: number;
103
198
  height: number;
104
199
  }
105
200
 
201
+ export type PreparedImage = (PreparedLocalImage | { url: string }) & { id?: string };
202
+
106
203
  export interface PreparedInput {
107
204
  state: ClassifyParams["state"];
108
205
  questions: Record<string, Question>;
@@ -113,7 +210,17 @@ export type ClassifierResult = {
113
210
  provider: string;
114
211
  model: string;
115
212
  answers: Record<string, Answer>;
116
- usage?: { inputTokens: number; outputTokens: number; totalTokens: number };
213
+ usage?: {
214
+ inputTokens: number;
215
+ outputTokens: number;
216
+ totalTokens: number;
217
+ cachedInputTokens?: number;
218
+ cacheWriteTokens?: number;
219
+ };
220
+ /** Successful provider requests made by automatic choice processing. */
221
+ providerCalls?: number;
222
+ /** Estimate for completed requests in this result, not an invoice or total of failed attempts. */
223
+ cost: ClassifierCost;
117
224
  requestId?: string;
118
225
  attemptedRoutes?: ClassifierRoute[];
119
226
  };
package/src/validation.ts CHANGED
@@ -4,134 +4,101 @@ import {
4
4
  type ClassifyParams,
5
5
  type Question,
6
6
  } from "./types.js";
7
+ import { imageReferences, isImageReference, questionImageReferences } from "./image-content.js";
7
8
 
8
9
  function invalid(message: string): never {
9
10
  throw new ClassifierError("input", message);
10
11
  }
12
+ const imageId = /^[a-zA-Z0-9_-]{1,64}$/;
13
+
14
+ function content(value: unknown, maxLength: number, nonempty = false): boolean {
15
+ if (typeof value === "string") return value.length <= maxLength && (!nonempty || Boolean(value.trim()));
16
+ if (!Array.isArray(value) || value.length < 1 || value.length > 128) return false;
17
+ if (!value.every((part) => typeof part === "string" || isImageReference(part))) return false;
18
+ validateJson(value, 0);
19
+ return Buffer.byteLength(JSON.stringify(value)) <= maxLength &&
20
+ (!nonempty || value.some((part) => typeof part !== "string" || Boolean(part.trim())));
21
+ }
11
22
 
12
23
  export function validateParams(value: unknown): ClassifyParams {
13
- if (
14
- !isRecord(value) ||
15
- Object.keys(value).some(
16
- (key) => !["state", "questions", "images"].includes(key),
17
- )
18
- )
19
- invalid(
20
- "Expected state, questions and optional images; provider/model are selected in settings.",
21
- );
22
- if (
23
- !(
24
- typeof value.state === "string" ||
25
- Array.isArray(value.state) ||
26
- isRecord(value.state)
27
- )
28
- )
24
+ if (!isRecord(value) || Object.keys(value).some((key) => !["state", "questions", "images"].includes(key)))
25
+ invalid("Expected state, questions and optional images; provider/model are selected in settings.");
26
+ if (!(typeof value.state === "string" || Array.isArray(value.state) || isRecord(value.state)))
29
27
  invalid("state must be text, a JSON object or an array.");
30
28
  validateJson(value.state, 0);
31
- if (!isRecord(value.questions))
32
- invalid("questions must be a map keyed by question ID.");
29
+ if (!isRecord(value.questions)) invalid("questions must be a map keyed by question ID.");
33
30
  const entries = Object.entries(value.questions);
34
- if (entries.length < 1 || entries.length > 32)
35
- invalid("Supply between 1 and 32 questions.");
31
+ if (entries.length < 1 || entries.length > 32) invalid("Supply between 1 and 32 questions.");
36
32
  for (const [id, question] of entries) {
37
33
  if (!/^[a-zA-Z0-9_-]{1,64}$/.test(id) || !isRecord(question))
38
- invalid(
39
- "Question IDs must be 1–64 letters, digits, underscores or hyphens.",
40
- );
41
- if (
42
- Object.keys(question).some(
43
- (key) => !["type", "instructions", "criteria"].includes(key),
44
- )
45
- )
34
+ invalid("Question IDs must be 1–64 letters, digits, underscores or hyphens.");
35
+ if (Object.keys(question).some((key) => !["type", "instructions", "criteria"].includes(key)))
46
36
  invalid("Unknown question field.");
47
- if (
48
- typeof question.instructions !== "string" ||
49
- !question.instructions.trim() ||
50
- question.instructions.length > 16_384
51
- )
52
- invalid(
53
- "Each question needs non-empty instructions, at most 16384 characters.",
54
- );
37
+ if (!content(question.instructions, 16_384, true))
38
+ invalid("Each question needs non-empty text or ordered text/image-reference instructions, at most 16384 characters/bytes.");
55
39
  if (question.type === "bool") {
56
- if (
57
- question.criteria !== undefined &&
58
- (!isRecord(question.criteria) ||
59
- Object.entries(question.criteria).some(
60
- ([key, entry]) =>
61
- !["true", "false"].includes(key) ||
62
- typeof entry !== "string" ||
63
- entry.length > 4096,
64
- ))
65
- )
66
- invalid("bool criteria must contain optional true/false descriptions.");
40
+ if (question.criteria !== undefined && (!isRecord(question.criteria) ||
41
+ Object.entries(question.criteria).some(([key, entry]) => !["true", "false"].includes(key) || !content(entry, 4096))))
42
+ invalid("bool criteria must contain optional true/false descriptions or image content.");
67
43
  } else if (question.type === "choice") {
68
- if (!isRecord(question.criteria))
69
- invalid("choice criteria must map labels to descriptions.");
44
+ if (!isRecord(question.criteria)) invalid("choice criteria must map labels to descriptions.");
70
45
  const criteria = Object.entries(question.criteria);
71
- if (
72
- criteria.length < 1 ||
73
- criteria.length > 64 ||
74
- criteria.some(
75
- ([key, entry]) =>
76
- !key.trim() ||
77
- key.length > 128 ||
78
- typeof entry !== "string" ||
79
- entry.length > 4096,
80
- )
81
- )
82
- invalid("choice requires 1–64 labels with string descriptions.");
46
+ if (criteria.length < 1 || criteria.some(([key, entry]) => !key.trim() || key.length > 128 || !content(entry, 4096)))
47
+ invalid("choice requires at least one label with a text or image-content description.");
83
48
  } else if (question.type === "score") {
84
- if (
85
- !Array.isArray(question.criteria) ||
86
- question.criteria.length < 2 ||
87
- question.criteria.length > 10 ||
88
- question.criteria.some(
89
- (entry) =>
90
- typeof entry !== "string" || !entry.trim() || entry.length > 4096,
91
- )
92
- )
93
- invalid(
94
- "score criteria must contain 2–10 non-empty ordered descriptions.",
95
- );
49
+ if (!Array.isArray(question.criteria) || question.criteria.length < 2 || question.criteria.length > 10 ||
50
+ question.criteria.some((entry) => !content(entry, 4096, true)))
51
+ invalid("score criteria must contain 2–10 non-empty ordered descriptions or image content.");
96
52
  } else if (question.type === "box") {
97
- if (question.criteria !== undefined)
98
- invalid("box does not accept criteria.");
53
+ if (question.criteria !== undefined) invalid("box does not accept criteria.");
99
54
  } else invalid("Question type must be bool, choice, score or box.");
100
55
  }
101
- if (
102
- value.images !== undefined &&
103
- (!Array.isArray(value.images) ||
104
- value.images.length > 5 ||
105
- value.images.some(
106
- (path) =>
107
- typeof path !== "string" || !path.trim() || path.length > 4096,
108
- ))
109
- )
110
- invalid("images must contain at most five local file paths.");
111
- const encoded = JSON.stringify(value);
112
- if (Buffer.byteLength(encoded) > 2 * 1024 * 1024)
56
+ const ids = new Set<string>();
57
+ if (value.images !== undefined) {
58
+ if (!Array.isArray(value.images) || value.images.length > 8)
59
+ invalid("images must contain at most eight local paths or named path/url descriptors; route-specific limits also apply.");
60
+ for (const image of value.images) {
61
+ if (typeof image === "string") {
62
+ if (!image.trim() || image.length > 4096) invalid("Image paths must be non-empty, at most 4096 characters.");
63
+ continue;
64
+ }
65
+ if (!isRecord(image) || typeof image.id !== "string" || !imageId.test(image.id) ||
66
+ Object.keys(image).some((key) => !["id", "path", "url"].includes(key)) ||
67
+ (Object.hasOwn(image, "path") === Object.hasOwn(image, "url")))
68
+ invalid("Named images require a unique id and exactly one path or url.");
69
+ const source = image.path ?? image.url;
70
+ if (typeof source !== "string" || !source.trim() || source.length > 4096)
71
+ invalid("Image path/url must be non-empty, at most 4096 characters.");
72
+ if (ids.has(image.id)) invalid("Named image IDs must be unique.");
73
+ ids.add(image.id);
74
+ }
75
+ }
76
+ const references = [...imageReferences(value.state), ...questionImageReferences(value.questions as Record<string, Question>)];
77
+ for (const id of references) if (!ids.has(id)) invalid("Every image reference must name an image descriptor in images.");
78
+ for (const id of ids) if (!references.includes(id)) invalid("Every named image must be referenced in state, instructions or criteria.");
79
+ if (Buffer.byteLength(JSON.stringify(value)) > 2 * 1024 * 1024)
113
80
  invalid("Classification text and questions must be at most 2 MiB.");
114
81
  return value as unknown as ClassifyParams;
115
82
  }
116
83
 
117
84
  function validateJson(value: unknown, depth: number): void {
118
- if (depth > 32) invalid("state must be at most 32 levels deep.");
119
- if (value === null || typeof value === "string" || typeof value === "boolean")
85
+ if (depth > 32) invalid("JSON content must be at most 32 levels deep.");
86
+ if (isImageReference(value)) {
87
+ if (Object.keys(value).length !== 1 || typeof value.$image !== "string" || !imageId.test(value.$image))
88
+ invalid("An image reference must be exactly {$image: id} with a 1–64 character image ID.");
120
89
  return;
90
+ }
91
+ if (value === null || typeof value === "string" || typeof value === "boolean") return;
121
92
  if (typeof value === "number" && Number.isFinite(value)) return;
122
93
  if (Array.isArray(value)) {
123
94
  for (const entry of value) validateJson(entry, depth + 1);
124
95
  return;
125
96
  }
126
- if (
127
- isRecord(value) &&
128
- (Object.getPrototypeOf(value) === Object.prototype ||
129
- Object.getPrototypeOf(value) === null)
130
- ) {
97
+ if (isRecord(value) && (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null)) {
131
98
  for (const entry of Object.values(value)) validateJson(entry, depth + 1);
132
99
  return;
133
100
  }
134
- invalid("state must contain only finite JSON values.");
101
+ invalid("Content must contain only finite JSON values.");
135
102
  }
136
103
 
137
104
  export function hasBox(questions: Record<string, Question>): boolean {