@abhishek944/pi-classifier 0.2.0 → 0.3.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/dist/index.js CHANGED
@@ -1,3 +1,4 @@
1
1
  export { classify, compareClassifiers } from "./classify.js";
2
+ export { classifyTree } from "./tree.js";
2
3
  export { loadClassifierSettings, resolveModel, listModels } from "./config.js";
3
4
  export { ClassifierError } from "./types.js";
package/dist/inputs.d.ts CHANGED
@@ -1,2 +1,4 @@
1
1
  import { type ClassifyParams, type PreparedInput, type ResolvedModel } from "./types.js";
2
2
  export declare function prepareInput(params: ClassifyParams, route: ResolvedModel, cwd: string, signal?: AbortSignal): Promise<PreparedInput>;
3
+ /** Verify containment of the opened descriptor, not a raceable pre-open path. */
4
+ export declare function verifyOpenedPath(fd: number, root: string, signal?: AbortSignal): Promise<void>;
package/dist/inputs.js CHANGED
@@ -155,7 +155,7 @@ async function decodeImage(bytes, signal) {
155
155
  }
156
156
  const execFileAsync = promisify(execFile);
157
157
  /** Verify containment of the opened descriptor, not a raceable pre-open path. */
158
- async function verifyOpenedPath(fd, root, signal) {
158
+ export async function verifyOpenedPath(fd, root, signal) {
159
159
  let openedPath;
160
160
  if (process.platform === "linux") {
161
161
  openedPath = await realpath("/proc/self/fd/" + fd);
@@ -173,7 +173,7 @@ async function verifyOpenedPath(fd, root, signal) {
173
173
  openedPath = paths[0].slice(1);
174
174
  }
175
175
  else {
176
- throw new ClassifierError("capability", "Safe local image loading currently supports macOS and Linux only. Text classification remains available.");
176
+ throw new ClassifierError("capability", "Safe local file loading currently supports macOS and Linux only. Inline text/JSON classification remains available.");
177
177
  }
178
178
  const inside = relative(root, openedPath);
179
179
  if (!inside ||
package/dist/providers.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import { randomUUID } from "node:crypto";
2
2
  import { postJson } from "./http.js";
3
+ import { estimateCost, tokenCount } from "./cost.js";
3
4
  import { ClassifierError, isRecord, } from "./types.js";
4
5
  /**
5
6
  * Provider protocol adapters. Every request goes through the shared `postJson` boundary, which
@@ -53,11 +54,6 @@ function unitInterval(label, value, field) {
53
54
  }
54
55
  return Math.min(1, Math.max(0, value));
55
56
  }
56
- function tokenCount(value) {
57
- return typeof value === "number" && Number.isSafeInteger(value) && value >= 0
58
- ? value
59
- : undefined;
60
- }
61
57
  function normalizedUsage(value) {
62
58
  if (!isRecord(value))
63
59
  return undefined;
@@ -68,18 +64,29 @@ function normalizedUsage(value) {
68
64
  const total = tokenCount(value.total_tokens) ?? tokenCount((input ?? 0) + (output ?? 0));
69
65
  if (total === undefined)
70
66
  return undefined;
71
- return {
67
+ const usage = {
72
68
  inputTokens: input ?? 0,
73
69
  outputTokens: output ?? 0,
74
70
  totalTokens: total,
75
71
  };
72
+ if (isRecord(value.input_tokens_details)) {
73
+ const cached = tokenCount(value.input_tokens_details.cached_tokens);
74
+ const writes = tokenCount(value.input_tokens_details.cache_write_tokens);
75
+ if (cached !== undefined)
76
+ usage.cachedInputTokens = cached;
77
+ if (writes !== undefined)
78
+ usage.cacheWriteTokens = writes;
79
+ }
80
+ return usage;
76
81
  }
77
- function finish(route, answers, usage, requestId) {
82
+ function finish(route, answers, rawUsage, requestId) {
78
83
  const result = {
79
84
  provider: route.route,
80
85
  model: route.model,
81
86
  answers,
87
+ cost: estimateCost(route, rawUsage),
82
88
  };
89
+ const usage = normalizedUsage(rawUsage);
83
90
  if (usage !== undefined)
84
91
  result.usage = usage;
85
92
  if (requestId !== undefined)
@@ -417,7 +424,7 @@ async function classifyOpenAi(route, input, apiKey, signal) {
417
424
  }, apiKey, signal);
418
425
  if (!isRecord(body))
419
426
  fail(OPENAI_LABEL + " returned an unexpected response.");
420
- return finish(route, parseOpenAiAnswers(OPENAI_LABEL, body.answers, input.questions), normalizedUsage(body.usage), requestId);
427
+ return finish(route, parseOpenAiAnswers(OPENAI_LABEL, body.answers, input.questions), body.usage, requestId);
421
428
  }
422
429
  /* Perplexity Decisions ---------------------------------------------------- */
423
430
  function systemOneQuestions(questions, allowBox) {
@@ -479,7 +486,7 @@ async function classifyPerplexity(route, input, apiKey, signal) {
479
486
  }, apiKey, signal);
480
487
  if (!isRecord(body))
481
488
  fail(PERPLEXITY_LABEL + " returned an unexpected response.");
482
- return finish(route, parseTypedAnswers(PERPLEXITY_LABEL, body.answers, input.questions), normalizedUsage(body.usage), requestId);
489
+ return finish(route, parseTypedAnswers(PERPLEXITY_LABEL, body.answers, input.questions), body.usage, requestId);
483
490
  }
484
491
  /* Microsoft Foundry Decision-1 (text/JSON, API-key authentication) -------- */
485
492
  async function classifyMicrosoft(route, input, apiKey, signal) {
@@ -515,7 +522,7 @@ async function classifyMicrosoft(route, input, apiKey, signal) {
515
522
  else
516
523
  answers[id] = answer;
517
524
  }
518
- return finish(route, parseTypedAnswers(label, answers, input.questions), normalizedUsage(body.usage), requestId);
525
+ return finish(route, parseTypedAnswers(label, answers, input.questions), body.usage, requestId);
519
526
  }
520
527
  /* TypeSafe System One (direct API and compatible gateways) --------------- */
521
528
  function withImageRefs(state, refs) {
@@ -550,7 +557,7 @@ async function classifySystemOne(route, input, apiKey, signal) {
550
557
  const { body, requestId } = await postJson(route, "systemone", payload, apiKey, signal, extraHeaders);
551
558
  if (!isRecord(body))
552
559
  fail(TYPESAFE_LABEL + " returned an unexpected response.");
553
- return finish(route, parseTypedAnswers(TYPESAFE_LABEL, body.answers, input.questions), normalizedUsage(body.usage), requestId);
560
+ return finish(route, parseTypedAnswers(TYPESAFE_LABEL, body.answers, input.questions), body.usage, requestId);
554
561
  }
555
562
  /* Cloudflare Workers AI (Clef and third-party System One envelopes) ------- */
556
563
  function clefBodyModel(model) {
@@ -608,7 +615,10 @@ async function classifyCloudflare(route, input, apiKey, signal) {
608
615
  }
609
616
  const { body, requestId } = await postJson(route, path, payload, apiKey, signal);
610
617
  const result = unwrapCloudflare(CLOUDFLARE_LABEL, body);
611
- const usage = normalizedUsage(result.usage) ??
612
- normalizedUsage(isRecord(body) ? body.usage : undefined);
618
+ const usage = normalizedUsage(result.usage) !== undefined
619
+ ? result.usage
620
+ : isRecord(body)
621
+ ? body.usage
622
+ : undefined;
613
623
  return finish(route, parseTypedAnswers(CLOUDFLARE_LABEL, result.answers, input.questions), usage, requestId);
614
624
  }
package/dist/tree.d.ts ADDED
@@ -0,0 +1,4 @@
1
+ import { type ClassifyOptions } from "./classify.js";
2
+ import { type ClassifierTreeResult } from "./types.js";
3
+ /** Greedy sibling decisions over an already validated classification tree; forced edges make no model call. */
4
+ export declare function classifyTree(params: unknown, options: ClassifyOptions): Promise<ClassifierTreeResult>;
package/dist/tree.js ADDED
@@ -0,0 +1,136 @@
1
+ import { classify } from "./classify.js";
2
+ import { choicePolicy } from "./choices.js";
3
+ import { resolveModel } from "./config.js";
4
+ import { sumCost, sumUsage } from "./cost.js";
5
+ import { loadTreeInput } from "./classification-tree.js";
6
+ import { ClassifierError, userError, } from "./types.js";
7
+ /** Greedy sibling decisions over an already validated classification tree; forced edges make no model call. */
8
+ export async function classifyTree(params, options) {
9
+ choicePolicy(options.settings);
10
+ const input = await loadTreeInput(params, options.cwd, options.signal);
11
+ const initial = resolveModel(options.settings);
12
+ const result = {
13
+ provider: initial.route,
14
+ model: initial.model,
15
+ status: "complete",
16
+ levels: Object.create(null),
17
+ steps: [],
18
+ providerCalls: 0,
19
+ usage: { inputTokens: 0, outputTokens: 0, totalTokens: 0 },
20
+ cost: {
21
+ status: "estimated",
22
+ currency: "USD",
23
+ source: "aggregated",
24
+ input: 0,
25
+ output: 0,
26
+ total: 0,
27
+ },
28
+ };
29
+ const path = [];
30
+ let siblings = input.tree.roots;
31
+ let pinned;
32
+ while (siblings.length > 0) {
33
+ if (options.signal?.aborted)
34
+ throw new ClassifierError("aborted", "Classification was cancelled.");
35
+ let selected;
36
+ let step;
37
+ const level = path.length + 1;
38
+ if (siblings.length === 1) {
39
+ selected = siblings[0];
40
+ step = { level, id: selected.id, source: "automatic" };
41
+ }
42
+ else {
43
+ // Non-numeric wire keys preserve array order through JS object enumeration and batching.
44
+ const candidates = new Map(siblings.map((node, index) => ["category_" + index, node]));
45
+ const instructions = (input.instructions ?? "Choose the most appropriate category for the supplied state.") +
46
+ "\nChoose one child of this selected parent path (JSON IDs): " + JSON.stringify(path) +
47
+ ". Use the option descriptions to decide which branch contains the best category. Do not choose a descendant directly.";
48
+ let branch;
49
+ try {
50
+ branch = await classify({
51
+ state: input.state,
52
+ questions: {
53
+ tree: {
54
+ type: "choice",
55
+ instructions,
56
+ criteria: Object.fromEntries([...candidates].map(([key, node]) => [
57
+ key, node.description?.trim() ? node.description : node.id,
58
+ ])),
59
+ },
60
+ },
61
+ ...(input.images !== undefined ? { images: input.images } : {}),
62
+ }, {
63
+ ...options,
64
+ // Only the first actual decision can select an explicitly configured fallback route.
65
+ settings: pinned
66
+ ? { ...options.settings, default: pinned, fallback: [] }
67
+ : options.settings,
68
+ });
69
+ }
70
+ catch (error) {
71
+ if (options.signal?.aborted ||
72
+ (error instanceof ClassifierError && error.code === "aborted"))
73
+ throw new ClassifierError("aborted", "Classification was cancelled.");
74
+ if (result.providerCalls > 0)
75
+ throw new ClassifierError("partial_classification", "Tree traversal stopped at Level" + level + " after " + result.providerCalls +
76
+ " completed provider request(s), which may be billed. No completed levels were replayed. " + userError(error));
77
+ throw error;
78
+ }
79
+ const usage = result.providerCalls === 0
80
+ ? branch.usage
81
+ : sumUsage(result.usage, branch.usage);
82
+ if (usage === undefined)
83
+ delete result.usage;
84
+ else
85
+ result.usage = usage;
86
+ result.cost = result.providerCalls === 0
87
+ ? branch.cost
88
+ : sumCost(result.cost, branch.cost);
89
+ result.providerCalls += branch.providerCalls ?? 1;
90
+ result.provider = branch.provider;
91
+ result.model = branch.model;
92
+ pinned = { provider: branch.provider, model: branch.model };
93
+ if (branch.attemptedRoutes !== undefined)
94
+ result.attemptedRoutes = branch.attemptedRoutes;
95
+ const answer = branch.answers.tree;
96
+ if (!answer)
97
+ throw new ClassifierError("response", "Tree branch returned no answer.");
98
+ if (answer.type === "no_match" || answer.type === "ambiguous" ||
99
+ answer.type === "refusal") {
100
+ result.status = answer.type;
101
+ break;
102
+ }
103
+ if (answer.type !== "choice")
104
+ throw new ClassifierError("response", "Tree branch did not return a choice answer.");
105
+ const probabilities = Object.entries(answer.probabilities);
106
+ const maximum = Math.max(...probabilities.map(([, probability]) => probability));
107
+ const winners = probabilities.filter(([, probability]) => probability === maximum);
108
+ if (winners.length !== 1) {
109
+ result.status = "ambiguous";
110
+ break;
111
+ }
112
+ const node = candidates.get(winners[0][0]);
113
+ if (!node)
114
+ throw new ClassifierError("response", "Tree branch selected an unknown category.");
115
+ selected = node;
116
+ step = {
117
+ level,
118
+ id: selected.id,
119
+ source: "model",
120
+ confidence: answer.confidence,
121
+ probabilityScope: answer.probabilityScope ?? "siblings",
122
+ };
123
+ if (answer.noneOfAboveProbability !== undefined)
124
+ step.noneOfAboveProbability = answer.noneOfAboveProbability;
125
+ }
126
+ path.push(selected.id);
127
+ result.levels["Level" + level] = selected.id;
128
+ result.steps.push(step);
129
+ siblings = selected.children ?? [];
130
+ }
131
+ if (options.signal?.aborted)
132
+ throw new ClassifierError("aborted", "Classification was cancelled.");
133
+ if (Buffer.byteLength(JSON.stringify(result, null, 2)) > 40 * 1024)
134
+ throw new ClassifierError("response", "Tree result exceeds the 40 KiB tool output limit.");
135
+ return result;
136
+ }
package/dist/types.d.ts CHANGED
@@ -26,6 +26,9 @@ export type Answer = {
26
26
  choice: string;
27
27
  probabilities: Record<string, number>;
28
28
  confidence: number;
29
+ /** Present when probabilities cover one internally processed batch, not the full list. */
30
+ probabilityScope?: "batch";
31
+ noneOfAboveProbability?: number;
29
32
  } | {
30
33
  type: "score";
31
34
  score: number;
@@ -42,6 +45,10 @@ export type Answer = {
42
45
  confidence: number;
43
46
  } | {
44
47
  type: "refusal";
48
+ } | {
49
+ type: "no_match";
50
+ } | {
51
+ type: "ambiguous";
45
52
  };
46
53
  export interface ClassifyParams {
47
54
  state: string | Record<string, unknown> | unknown[];
@@ -49,12 +56,72 @@ export interface ClassifyParams {
49
56
  /** Regular PNG/JPEG/WebP files inside cwd; attached in this order. */
50
57
  images?: string[];
51
58
  }
59
+ export type ClassificationTreeNode = {
60
+ id: string;
61
+ description?: string;
62
+ children?: ClassificationTreeNode[];
63
+ };
64
+ export type ClassificationTree = {
65
+ roots: ClassificationTreeNode[];
66
+ };
67
+ export type ClassifyTreeParams = {
68
+ state: ClassifyParams["state"];
69
+ tree: string | ClassificationTree;
70
+ instructions?: string;
71
+ images?: string[];
72
+ };
73
+ export type TreeStep = {
74
+ level: number;
75
+ id: string;
76
+ source: "automatic" | "model";
77
+ confidence?: number;
78
+ probabilityScope?: "siblings" | "batch";
79
+ noneOfAboveProbability?: number;
80
+ };
81
+ export type ClassifierTreeResult = {
82
+ provider: string;
83
+ model: string;
84
+ status: "complete" | "no_match" | "ambiguous" | "refusal";
85
+ levels: Record<string, string>;
86
+ steps: TreeStep[];
87
+ providerCalls: number;
88
+ cost: ClassifierCost;
89
+ usage?: NonNullable<ClassifierResult["usage"]>;
90
+ attemptedRoutes?: ClassifierRoute[];
91
+ };
52
92
  export interface ModelDefinition {
53
93
  id: string;
54
94
  name?: string;
55
95
  input?: ("text" | "image")[];
56
96
  box?: boolean;
57
97
  }
98
+ /** USD per million tokens. Cache counts, when reported, are part of input tokens. */
99
+ export type TokenPricing = {
100
+ inputPerMillion: number;
101
+ outputPerMillion: number;
102
+ cachedInputPerMillion?: number;
103
+ cacheWritePerMillion?: number;
104
+ };
105
+ export type ClassifierCost = {
106
+ status: "estimated";
107
+ currency: "USD";
108
+ input: number;
109
+ output: number;
110
+ total: number;
111
+ source: "builtin" | "configured";
112
+ rates: TokenPricing;
113
+ } | {
114
+ status: "estimated";
115
+ currency: "USD";
116
+ input: number;
117
+ output: number;
118
+ total: number;
119
+ source: "aggregated";
120
+ } | {
121
+ status: "unavailable";
122
+ currency: "USD";
123
+ reason: "unknown_pricing" | "missing_usage" | "invalid_usage" | "missing_cache_pricing" | "calculation_overflow";
124
+ };
58
125
  export interface ProviderSettings {
59
126
  apiKey?: string;
60
127
  baseUrl?: string;
@@ -62,6 +129,10 @@ export interface ProviderSettings {
62
129
  accountId?: string;
63
130
  experimentalImages?: boolean;
64
131
  experimentalBox?: boolean;
132
+ /** Model ID (or Azure deployment name) to explicit token rates. */
133
+ pricing?: Record<string, TokenPricing>;
134
+ /** Verified wire choice limit; needed for batching on endpoints without a known limit. */
135
+ maxChoices?: number;
65
136
  }
66
137
  export interface CustomProviderSettings extends ProviderSettings {
67
138
  api: ApiStyle;
@@ -72,6 +143,8 @@ export type ClassifierRoute = {
72
143
  model: string;
73
144
  };
74
145
  export interface ClassifierSettings {
146
+ none_of_above_choice?: boolean;
147
+ remove_choice_limits?: boolean;
75
148
  default?: ClassifierRoute;
76
149
  fallback?: ClassifierRoute[];
77
150
  compare?: ClassifierRoute[];
@@ -95,6 +168,11 @@ export interface ResolvedModel {
95
168
  box: boolean;
96
169
  experimentalImages: boolean;
97
170
  requestTimeoutMs: number;
171
+ pricing?: {
172
+ rates: TokenPricing;
173
+ source: "builtin" | "configured";
174
+ };
175
+ maxChoices?: number;
98
176
  }
99
177
  export interface PreparedImage {
100
178
  data: string;
@@ -115,7 +193,13 @@ export type ClassifierResult = {
115
193
  inputTokens: number;
116
194
  outputTokens: number;
117
195
  totalTokens: number;
196
+ cachedInputTokens?: number;
197
+ cacheWriteTokens?: number;
118
198
  };
199
+ /** Successful provider requests made by automatic choice processing. */
200
+ providerCalls?: number;
201
+ /** Estimate for completed requests in this result, not an invoice or total of failed attempts. */
202
+ cost: ClassifierCost;
119
203
  requestId?: string;
120
204
  attemptedRoutes?: ClassifierRoute[];
121
205
  };
@@ -38,12 +38,11 @@ export function validateParams(value) {
38
38
  invalid("choice criteria must map labels to descriptions.");
39
39
  const criteria = Object.entries(question.criteria);
40
40
  if (criteria.length < 1 ||
41
- criteria.length > 64 ||
42
41
  criteria.some(([key, entry]) => !key.trim() ||
43
42
  key.length > 128 ||
44
43
  typeof entry !== "string" ||
45
44
  entry.length > 4096))
46
- invalid("choice requires 1–64 labels with string descriptions.");
45
+ invalid("choice requires at least one label with a string description.");
47
46
  }
48
47
  else if (question.type === "score") {
49
48
  if (!Array.isArray(question.criteria) ||
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@abhishek944/pi-classifier",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "description": "Config-driven typed classification for Pi via Microsoft Decision-1, OpenAI Decisions, Perplexity, TypeSafe Jev and Cloudflare Clef, with selective fallback and explicit comparisons.",
5
5
  "keywords": [
6
6
  "pi-package",
package/src/choices.ts ADDED
@@ -0,0 +1,173 @@
1
+ import { sumCost, sumUsage } from "./cost.js";
2
+ import {
3
+ ClassifierError,
4
+ type Answer,
5
+ type ClassifierCost,
6
+ type ClassifierResult,
7
+ type ClassifierSettings,
8
+ type PreparedInput,
9
+ type Question,
10
+ type ResolvedModel,
11
+ } from "./types.js";
12
+
13
+ export type ChoicePolicy = { none: boolean; batch: boolean };
14
+
15
+ export function choicePolicy(settings: ClassifierSettings): ChoicePolicy {
16
+ for (const key of ["none_of_above_choice", "remove_choice_limits"] as const) {
17
+ if (settings[key] !== undefined && typeof settings[key] !== "boolean")
18
+ throw new ClassifierError("configuration", key + " must be a boolean.");
19
+ }
20
+ const none = settings.none_of_above_choice === true;
21
+ const batch = settings.remove_choice_limits === true;
22
+ if (batch && !none)
23
+ throw new ClassifierError(
24
+ "configuration",
25
+ "remove_choice_limits requires none_of_above_choice: true. No classifier request was sent.",
26
+ );
27
+ return { none, batch };
28
+ }
29
+
30
+ type ChoicePlan = {
31
+ question: Extract<Question, { type: "choice" }>;
32
+ entries: [string, string][];
33
+ offset: number;
34
+ sentinel: string;
35
+ };
36
+
37
+ const NONE_DESCRIPTION =
38
+ "None of the other options in this question applies to the supplied state. Select this only when every listed real option is unsuitable.";
39
+
40
+ /** Only this operation owns batching. Transport, images, credentials and routes stay with the caller. */
41
+ export async function executeChoices(
42
+ input: PreparedInput,
43
+ route: ResolvedModel,
44
+ policy: ChoicePolicy,
45
+ call: (questions: Record<string, Question>) => Promise<ClassifierResult>,
46
+ signal?: AbortSignal,
47
+ ): Promise<ClassifierResult> {
48
+ const plans = new Map<string, ChoicePlan>();
49
+ for (const [id, question] of Object.entries(input.questions)) {
50
+ if (question.type !== "choice") continue;
51
+ const entries = Object.entries(question.criteria);
52
+ if (policy.batch && route.maxChoices === undefined)
53
+ throw new ClassifierError(
54
+ "configuration",
55
+ "Automatic choice batching needs a verified provider limit. Set providers.<id>.maxChoices (or customProviders.<id>.maxChoices) for this endpoint. No classifier request was sent.",
56
+ );
57
+ const size = entries.length + (policy.none ? 1 : 0);
58
+ if (
59
+ !policy.batch &&
60
+ route.maxChoices !== undefined &&
61
+ size > route.maxChoices
62
+ )
63
+ throw new ClassifierError(
64
+ "input",
65
+ "Choice question " + id + " exceeds the selected provider's " +
66
+ route.maxChoices + " options per request" +
67
+ (policy.none ? " (including NONE OF THE ABOVE)" : "") +
68
+ ". Enable both none_of_above_choice and remove_choice_limits to batch choices, or reduce the list. No classifier request was sent.",
69
+ );
70
+ let sentinel = "__pi_none_of_above";
71
+ let suffix = 0;
72
+ while (Object.hasOwn(question.criteria, sentinel))
73
+ sentinel = "__pi_none_of_above_" + ++suffix;
74
+ plans.set(id, { question, entries, offset: 0, sentinel });
75
+ }
76
+ if (!policy.none || plans.size === 0) return call(input.questions);
77
+
78
+ const answers = Object.create(null) as Record<string, Answer>;
79
+ let calls = 0;
80
+ let last: ClassifierResult | undefined;
81
+ let usage: ClassifierResult["usage"];
82
+ let cost: ClassifierCost | undefined;
83
+ while (plans.size > 0) {
84
+ if (signal?.aborted)
85
+ throw new ClassifierError("aborted", "Classification was cancelled.");
86
+ const questions = Object.create(null) as Record<string, Question>;
87
+ // A bool/score/box is evaluated once, not charged again for later choice batches.
88
+ if (calls === 0) {
89
+ for (const [id, question] of Object.entries(input.questions))
90
+ if (question.type !== "choice") questions[id] = question;
91
+ }
92
+ for (const [id, plan] of plans) {
93
+ const capacity =
94
+ route.maxChoices === undefined
95
+ ? plan.entries.length
96
+ : route.maxChoices - 1;
97
+ const batch = plan.entries.slice(plan.offset, plan.offset + capacity);
98
+ plan.offset += batch.length;
99
+ questions[id] = {
100
+ ...plan.question,
101
+ criteria: Object.fromEntries([...batch, [plan.sentinel, NONE_DESCRIPTION]]),
102
+ };
103
+ }
104
+ let result: ClassifierResult;
105
+ try {
106
+ result = await call(questions);
107
+ } catch (error) {
108
+ // Never replay completed batches on another billing route after a later throttling/auth error.
109
+ if (
110
+ calls > 0 &&
111
+ error instanceof ClassifierError &&
112
+ error.code === "http" &&
113
+ [401, 404, 429].includes(error.httpStatus ?? 0)
114
+ )
115
+ throw new ClassifierError(
116
+ "partial_classification",
117
+ "Choice batching stopped after " + calls +
118
+ " completed provider request(s). No fallback was attempted after partial completion; completed requests may be billed.",
119
+ );
120
+ throw error;
121
+ }
122
+ usage = calls === 0 ? result.usage : sumUsage(usage, result.usage);
123
+ cost = cost === undefined ? result.cost : sumCost(cost, result.cost);
124
+ calls++;
125
+ last = result;
126
+ for (const [id, answer] of Object.entries(result.answers)) {
127
+ const plan = plans.get(id);
128
+ if (!plan) {
129
+ answers[id] = answer;
130
+ continue;
131
+ }
132
+ if (answer.type !== "choice") {
133
+ answers[id] = answer;
134
+ plans.delete(id);
135
+ continue;
136
+ }
137
+ const none = answer.probabilities[plan.sentinel]!;
138
+ const real = Object.entries(answer.probabilities).filter(
139
+ ([label]) => label !== plan.sentinel,
140
+ );
141
+ const maximum = Math.max(...real.map(([, probability]) => probability));
142
+ if (none > maximum) {
143
+ if (plan.offset < plan.entries.length) continue;
144
+ answers[id] = { type: "no_match" };
145
+ } else if (
146
+ none === maximum || real.filter(([, p]) => p === maximum).length !== 1
147
+ ) {
148
+ answers[id] = { type: "ambiguous" };
149
+ } else {
150
+ answers[id] = {
151
+ ...answer,
152
+ choice: real.find(([, p]) => p === maximum)![0],
153
+ probabilities: Object.fromEntries(real),
154
+ probabilityScope: "batch",
155
+ noneOfAboveProbability: none,
156
+ };
157
+ }
158
+ plans.delete(id);
159
+ }
160
+ }
161
+ // Validated inputs always contain questions; this loop executes at least once.
162
+ const combined: ClassifierResult = {
163
+ provider: last!.provider,
164
+ model: last!.model,
165
+ answers,
166
+ providerCalls: calls,
167
+ cost: cost!,
168
+ };
169
+ if (usage !== undefined) combined.usage = usage;
170
+ if (calls === 1 && last!.requestId !== undefined)
171
+ combined.requestId = last!.requestId;
172
+ return combined;
173
+ }