@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/CHANGELOG.md +12 -0
- package/README.md +189 -5
- package/dist/choices.d.ts +8 -0
- package/dist/choices.js +131 -0
- package/dist/classification-tree.d.ts +4 -0
- package/dist/classification-tree.js +143 -0
- package/dist/classify.d.ts +1 -2
- package/dist/classify.js +4 -1
- package/dist/config.js +40 -0
- package/dist/cost.d.ts +8 -0
- package/dist/cost.js +202 -0
- package/dist/extension.d.ts +127 -0
- package/dist/extension.js +129 -4
- package/dist/index.d.ts +2 -1
- package/dist/index.js +1 -0
- package/dist/inputs.d.ts +2 -0
- package/dist/inputs.js +2 -2
- package/dist/providers.js +23 -13
- package/dist/tree.d.ts +4 -0
- package/dist/tree.js +136 -0
- package/dist/types.d.ts +84 -0
- package/dist/validation.js +1 -2
- package/package.json +1 -1
- package/src/choices.ts +173 -0
- package/src/classification-tree.ts +181 -0
- package/src/classify.ts +12 -2
- package/src/config.ts +51 -0
- package/src/cost.ts +250 -0
- package/src/extension.ts +153 -4
- package/src/index.ts +8 -0
- package/src/inputs.ts +2 -2
- package/src/providers.ts +21 -14
- package/src/tree.ts +157 -0
- package/src/types.ts +98 -2
- package/src/validation.ts +1 -2
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,17 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.3.0
|
|
4
|
+
|
|
5
|
+
- Added `classify_tree` and `classifyTree` for nested `roots`/`id`/`description`/`children` classification trees supplied inline or as bounded local UTF-8 JSON files. Results contain selected Level1/Level2/etc, model-versus-automatic steps, partial statuses and accumulated token/cost/provider-call totals.
|
|
6
|
+
- Tree traversal skips sole-child model calls, reuses configured sibling choice batching, and pins the successful route across later levels. Zero-call chains return genuine zero usage/cost; greedy and structural-inference limits are explicit.
|
|
7
|
+
- Successful classification and comparison results now include estimated USD input/output/total cost with effective token rates, or an explicit unavailable reason instead of an assumed zero.
|
|
8
|
+
- Bundled standard rates for known official OpenAI Decisions, TypeSafe Jev, current Perplexity v1.2 and Cloudflare routes; model/deployment-keyed pricing overrides for custom endpoints, unverified prices and account-specific rates.
|
|
9
|
+
- Cache-aware cost calculation, optional reported cache usage, and documented provider choice limits. Costs are estimates, not invoices or Pi session billing totals.
|
|
10
|
+
- Removed the artificial 64-choice cap; known routes enforce their documented provider maximum. Optional `none_of_above_choice` and `remove_choice_limits` settings add NONE and sequential first-match batching. Enabling batching without NONE fails before provider requests.
|
|
11
|
+
- Explicit no-match/ambiguous outcomes, batch-local probability metadata, aggregate multi-call usage/cost and provider call counts. Unknown batching limits require verified provider `maxChoices`; later failures do not replay completed batches through fallback. The 32-question and byte/image/result protections remain.
|
|
12
|
+
|
|
13
|
+
Verification: typecheck, build, package dry run, whitespace checks, recursive tool-schema validation, and independent source reviews passed. No unit tests or live provider calls were run for this release. Classification-tree traversal is greedy; automatic sole-child steps are structural inference, not model confirmation. Bundled prices are estimates, not invoices, and unknown gateway/model limits require verified configuration for batching.
|
|
14
|
+
|
|
3
15
|
## 0.2.0
|
|
4
16
|
|
|
5
17
|
- Microsoft Decision-1 via Foundry resource endpoints and deployment names, API-key authentication, and text/JSON bool/choice/score questions.
|
package/README.md
CHANGED
|
@@ -9,7 +9,7 @@ One configured default, optional selective fallback, and explicit model comparis
|
|
|
9
9
|
Requires Node.js 22.19+ and Pi 1.2+. Install the tagged release from GitHub:
|
|
10
10
|
|
|
11
11
|
```sh
|
|
12
|
-
pi install git:github.com/abhishek944/pi-classifier@v0.
|
|
12
|
+
pi install git:github.com/abhishek944/pi-classifier@v0.3.0
|
|
13
13
|
```
|
|
14
14
|
|
|
15
15
|
The Pi package entrypoint is TypeScript source, so Git installs do not depend on committed build artifacts or a TypeScript compiler. Runtime dependencies are installed by Pi. The compiled `dist` exports remain available for library consumers after a build.
|
|
@@ -30,7 +30,7 @@ To install persistently after trying it:
|
|
|
30
30
|
pi install /absolute/path/to/pi-classifier
|
|
31
31
|
```
|
|
32
32
|
|
|
33
|
-
The package version and Git tag are `0.
|
|
33
|
+
The package version and Git tag are `0.3.0` / `v0.3.0`. Installation is explicit. This release is prepared for GitHub; npm publication is a separate manual step.
|
|
34
34
|
|
|
35
35
|
## Configuration: same shape as pi-image-gen
|
|
36
36
|
|
|
@@ -130,10 +130,194 @@ classify({
|
|
|
130
130
|
});
|
|
131
131
|
```
|
|
132
132
|
|
|
133
|
-
The tool takes no provider/model parameter. Its structured result identifies the configured route and model, typed answers, reported token usage and an available request ID. `bool.probability` is the probability of true; `choice` includes a probability per label and confidence; `score` is a probability-weighted level index (starting at zero), not necessarily an integer. Refusals are explicit typed answers. Token counts are reported
|
|
133
|
+
The tool takes no provider/model parameter. Its structured result identifies the configured route and model, typed answers, reported token usage, estimated USD cost (or an explicit unavailable reason) and an available request ID. `bool.probability` is the probability of true; `choice` includes a probability per label and confidence; `score` is a probability-weighted level index (starting at zero), not necessarily an integer. Refusals are explicit typed answers. Token counts are reported when available. Each successful result includes `cost`; classifier spending is not added to Pi's session billing totals. See [Per-call costs](#per-call-costs).
|
|
134
134
|
|
|
135
135
|
Provider results are checked for probability ranges/distribution sums and decision consistency (selected choices must be most likely; supplied score distributions must match the expected score within rounding tolerance). Low confidence is a valid answer, not an error. Calibrate thresholds on your own data; scores from different providers are not interchangeable.
|
|
136
136
|
|
|
137
|
+
## Classification trees: `classify_tree`
|
|
138
|
+
|
|
139
|
+
Use `classify_tree` to follow a **nested classification tree**, rather than supply every leaf as one flat choice list. The extension orchestrates ordinary model decisions; this is not a native provider tree API. Existing `classify` and `classify_compare` behavior is unchanged.
|
|
140
|
+
|
|
141
|
+
A classification tree is an object with `roots`. Each node has an `id`, optional `description`, and optional `children`:
|
|
142
|
+
|
|
143
|
+
```json
|
|
144
|
+
{
|
|
145
|
+
"roots": [
|
|
146
|
+
{
|
|
147
|
+
"id": "a",
|
|
148
|
+
"description": "Describe the domain covered by category a and its descendants.",
|
|
149
|
+
"children": [
|
|
150
|
+
{ "id": "b", "children": [{ "id": "c" }] },
|
|
151
|
+
{ "id": "c", "children": [{ "id": "d" }] }
|
|
152
|
+
]
|
|
153
|
+
},
|
|
154
|
+
{ "id": "c" },
|
|
155
|
+
{ "id": "d", "children": [{ "id": "e" }] }
|
|
156
|
+
]
|
|
157
|
+
}
|
|
158
|
+
```
|
|
159
|
+
|
|
160
|
+
IDs must be non-empty, at most 128 characters, and unique **among siblings**. Root `c` and `a > c` are different nodes. Descriptions are at most 4096 characters; use meaningful descriptions to explain which parent branch to choose. Missing or empty `children` means leaf. Only `roots`, `id`, `description` and `children` are supported; internal-node stopping flags, path-list imports and graph references are not implemented.
|
|
161
|
+
|
|
162
|
+
Supply the same shape inline or by local file:
|
|
163
|
+
|
|
164
|
+
```js
|
|
165
|
+
classify_tree({
|
|
166
|
+
state: "The content to classify",
|
|
167
|
+
tree: "./classification-tree.json",
|
|
168
|
+
instructions: "Choose the most appropriate category for this content."
|
|
169
|
+
});
|
|
170
|
+
|
|
171
|
+
classify_tree({
|
|
172
|
+
state: { ticket: "Refund requested for a duplicate payment." },
|
|
173
|
+
tree: {
|
|
174
|
+
roots: [
|
|
175
|
+
{ id: "billing", description: "Charges, invoices and refunds" },
|
|
176
|
+
{ id: "technical", description: "Errors, outages and integration problems" }
|
|
177
|
+
]
|
|
178
|
+
}
|
|
179
|
+
});
|
|
180
|
+
```
|
|
181
|
+
|
|
182
|
+
`instructions` is optional and at most 8192 characters. Text/JSON `state` and optional local `images` use the existing classifier input rules. No provider/model override is accepted. The library exports `classifyTree(params, { settings, cwd, signal? })` and the `ClassificationTree`, `ClassificationTreeNode`, `ClassifyTreeParams`, `TreeStep` and `ClassifierTreeResult` types.
|
|
183
|
+
|
|
184
|
+
### Traversal and results
|
|
185
|
+
|
|
186
|
+
The example first chooses among `a`, `c` and `d`. After choosing `a`, it chooses between `b` and `c`. If it chooses `b`, its sole child `c` is automatic. Relevant result fields are:
|
|
187
|
+
|
|
188
|
+
```json
|
|
189
|
+
{
|
|
190
|
+
"status": "complete",
|
|
191
|
+
"levels": { "Level1": "a", "Level2": "b", "Level3": "c" },
|
|
192
|
+
"steps": [
|
|
193
|
+
{ "level": 1, "id": "a", "source": "model", "confidence": 0.9, "probabilityScope": "siblings" },
|
|
194
|
+
{ "level": 2, "id": "b", "source": "model", "confidence": 0.8, "probabilityScope": "siblings" },
|
|
195
|
+
{ "level": 3, "id": "c", "source": "automatic" }
|
|
196
|
+
],
|
|
197
|
+
"providerCalls": 2
|
|
198
|
+
}
|
|
199
|
+
```
|
|
200
|
+
|
|
201
|
+
The confidence values above are illustrative. Full results also identify the configured/selected provider and model and include estimated `cost` plus reported `usage` when complete. Model confidence describes its sibling decision (or one batch), **not the whole path**. No artificial confidence is assigned to automatic steps.
|
|
202
|
+
|
|
203
|
+
- A sole sibling is followed automatically, including a sole root. This is structural inference, not model confirmation. It intentionally bypasses a possible NONE rejection of that sole option even when NONE is enabled.
|
|
204
|
+
- An entirely forced chain makes **zero provider calls**, needs no API key, and returns genuine zero token usage and estimated zero cost. It still requires a valid configured route. `complete` means a leaf was reached, not that the model verified the input fits that chain.
|
|
205
|
+
- NONE, strict ties and refusals stop the traversal with `status: "no_match"`, `"ambiguous"` or `"refusal"`. `levels` and `steps` retain only the selected prefix; no deeper category is fabricated. Exact top ties stop even when NONE is disabled.
|
|
206
|
+
- The selected parent path and current sibling descriptions inform each question. Unselected descendant branches are not uploaded wholesale, so parent descriptions must explain their coverage. Selection is greedy and cannot recover a wrong parent; no global best-path or calibrated path-probability claim is made.
|
|
207
|
+
- Configured NONE/batching behavior applies at each branching node. A wide level can consume multiple provider requests; `providerCalls`, usage and cost account for inner batches and all completed model decisions. Missing usage or unavailable prices do not become complete-looking numeric subtotals.
|
|
208
|
+
- The first actual decision may use configured selective fallback. After a successful decision the actual provider/model is pinned for the rest of that traversal; later failures do not replay completed levels on another route. Failures/cancellation may still have billed completed work. Images use the ordinary classifier validation and upload behavior on each branching call.
|
|
209
|
+
|
|
210
|
+
### Local-file and size limits
|
|
211
|
+
|
|
212
|
+
Classification trees must fit **2 MiB and 32 levels**; the full node structure is validated before any model call. Local files must be valid UTF-8 JSON regular files inside the session cwd with no symlink path components or URLs. Descriptor-based containment checks reuse the existing local-image boundary and support macOS/Linux; inline classification tree works on other platforms. Files are read once per `classify_tree` invocation; no persistent classification tree registry or cache is introduced.
|
|
213
|
+
|
|
214
|
+
Original classifier state/image/request protections remain. Each constructed branch question must fit the existing input limits, including its selected-path context. Tree results are bounded to 40 KiB. User-owned live verification should compare inline and file inputs, zero-call chains, deeper NONE/tie outcomes, wide sibling batching, and provider billing totals.
|
|
215
|
+
|
|
216
|
+
## Per-call costs
|
|
217
|
+
|
|
218
|
+
Every successful `classify` result and each successful `classify_compare` entry includes one of:
|
|
219
|
+
|
|
220
|
+
```json
|
|
221
|
+
{
|
|
222
|
+
"cost": {
|
|
223
|
+
"status": "estimated",
|
|
224
|
+
"currency": "USD",
|
|
225
|
+
"input": 0.000042,
|
|
226
|
+
"output": 0,
|
|
227
|
+
"total": 0.000042,
|
|
228
|
+
"source": "builtin",
|
|
229
|
+
"rates": { "inputPerMillion": 0.042, "outputPerMillion": 0 }
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
```
|
|
233
|
+
|
|
234
|
+
This example uses 1,000 Jev input tokens. Amounts are not rounded to cents; doing so would hide most classifier charges. `source` is `builtin` for the bundled standard public rates or `configured` for explicit rates. `rates` contains the effective USD-per-million rates used. Multi-call choice processing sums all completed calls and uses `source: "aggregated"` without a single misleading rates table; `providerCalls` reports the number of completed provider requests. Usage is omitted if any completed call lacks usage, and aggregate cost is unavailable if any call lacks an estimate. These are estimates, not provider invoices: taxes, credits, free allowances, account discounts and unreported billable activity are not included. There is no network pricing lookup.
|
|
235
|
+
|
|
236
|
+
| Official route/model | Input USD / 1M tokens | Output USD / 1M tokens |
|
|
237
|
+
| --- | ---: | ---: |
|
|
238
|
+
| OpenAI Decisions `gpt-6-luna` | 0.10 | 0 |
|
|
239
|
+
| TypeSafe `jev-1.13.0`, `jev-1.14.0`, `jev-latest`, `jev-preview` | 0.042 | 0 |
|
|
240
|
+
| Perplexity `pplx-decider-v1.2`, `pplx-decider-latest`, `pplx-decider-v1.1-27b`, `pplx-decider-v1-27b` | 0.02 | 0 |
|
|
241
|
+
| Perplexity `pplx-decider-flash-v1.2`, `pplx-decider-flash-latest` | 0.01 | 0 |
|
|
242
|
+
| Cloudflare `@cf/cloudflare/clef` | 0.24 | 0 |
|
|
243
|
+
| Cloudflare `@cf/cloudflare/clef-flash` | 0.038 | 0 |
|
|
244
|
+
| Cloudflare `typesafe/jev` | 0.042 | 0 |
|
|
245
|
+
|
|
246
|
+
Sources: [OpenAI Decisions pricing](https://developers.openai.com/api/docs/guides/decisions#pricing-and-availability), [OpenAI rates](https://developers.openai.com/api/docs/pricing), [TypeSafe models](https://docs.typesafe.ai/models), [Perplexity Decisions](https://docs.perplexity.ai/docs/decisions/quickstart#pricing), [Clef](https://developers.cloudflare.com/workers-ai/models/clef/), [Clef Flash](https://developers.cloudflare.com/workers-ai/models/clef-flash/), [Cloudflare Jev](https://developers.cloudflare.com/ai/models/typesafe/jev/). Aliases can move and public prices can change; explicit overrides take precedence. Perplexity's [model names](https://docs.perplexity.ai/docs/decisions/quickstart#model-names) documentation maps the older v1/v1.1 IDs in the discovery catalog to v1.2 and bills them at its rate. New text model IDs may already be selected through settings, but this cost feature does not change image capability declarations.
|
|
247
|
+
|
|
248
|
+
When reported, cache reads and writes are exposed as `usage.cachedInputTokens` and `usage.cacheWriteTokens`. They are **included** in input tokens, not additional tokens. Input cost is `(ordinary input × input rate + cache reads × cached-input rate + cache writes × cache-write rate) / 1,000,000`; output cost uses its separate rate. OpenAI's bundled cached-input rate is $0.01/M and default 30-minute write rate is $0.125/M, with all input rates doubled above 272,000 input tokens. Cloudflare Jev's bundled cached-input rate is zero. Unexpected 12-hour writes are unavailable rather than priced as 30-minute writes.
|
|
249
|
+
|
|
250
|
+
If pricing or usable token counts are missing, `cost` is `{ "status": "unavailable", "currency": "USD", "reason": "unknown_pricing" }` (or `missing_usage`, `invalid_usage`, `missing_cache_pricing`, `calculation_overflow`). No numeric amounts are returned in that case. Zero means a calculated zero, never an unknown charge. Failed or cancelled calls may still be billable but do not have reliable cost results; a fallback success reports only the successful request, not a total for prior attempts. Comparison callers must not treat a sum of available estimates as complete if any entries failed or have unavailable costs.
|
|
251
|
+
|
|
252
|
+
### Explicit deployment, gateway and custom pricing
|
|
253
|
+
|
|
254
|
+
Set `providers.<id>.pricing` to a map keyed by the **selected model ID** (Azure deployment name for Microsoft). Rates are non-negative finite USD per million tokens; input and output rates are required. Cache rates are optional, but reported cache activity needs the matching rate. Configured rates replace, rather than merge with, bundled rates. Custom providers accept the same `pricing` map.
|
|
255
|
+
|
|
256
|
+
```json
|
|
257
|
+
{
|
|
258
|
+
"pi-classifier": {
|
|
259
|
+
"providers": {
|
|
260
|
+
"microsoft": {
|
|
261
|
+
"pricing": {
|
|
262
|
+
"my-decision-deployment": {
|
|
263
|
+
"inputPerMillion": 0.1,
|
|
264
|
+
"outputPerMillion": 0
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
```
|
|
272
|
+
|
|
273
|
+
The numbers above are illustrative, **not a claim about Azure pricing**. Use your deployment's actual rates. Optional keys are `cachedInputPerMillion` and `cacheWritePerMillion`. Overrides specify effective rates; no automatic long-context multiplier is applied to them. Microsoft deployments, OpenRouter, unverified model IDs and custom or regional endpoints require verified explicit rates. Built-in prices apply only to exact known models on their official endpoint; a compatible gateway does not inherit the upstream provider's price. Misconfigured selected rates fail before a request; missing rates do not prevent classification.
|
|
274
|
+
|
|
275
|
+
## Choice limits by provider
|
|
276
|
+
|
|
277
|
+
The artificial **64-choice cap has been removed** from both runtime validation and the tool schema. Known official model routes use their documented 255-option wire maximum. Unknown model/endpoint limits are left to the provider unless you configure `providers.<id>.maxChoices` (also available on custom providers). The package still accepts **1–32 questions per call**. The 128-character limit applies to an option's name, not to the option count.
|
|
278
|
+
|
|
279
|
+
| Provider/model | Documented upstream choice options per question | Evidence/qualification |
|
|
280
|
+
| --- | --- | --- |
|
|
281
|
+
| TypeSafe Jev | Up to 255 | [Choice docs](https://docs.typesafe.ai/primitives/choice); current Jev service documentation |
|
|
282
|
+
| OpenAI Decisions `gpt-6-luna` | 2–255 | [API reference](https://developers.openai.com/api/reference/resources/decisions/methods/create), confirmed from official indexed search results; direct reference fetch returned 404 during this investigation |
|
|
283
|
+
| Perplexity `pplx-decider-v1.2`, Flash v1.2 and documented aliases (including catalog v1/v1.1 IDs) | 1–255 | [Request limits](https://docs.perplexity.ai/docs/decisions/quickstart#request-limits) and [model names](https://docs.perplexity.ai/docs/decisions/quickstart#model-names) |
|
|
284
|
+
| Cloudflare Clef | 2–255 | [Official input schema](https://developers.cloudflare.com/workers-ai/models/clef/schema-input.json) |
|
|
285
|
+
| Cloudflare Clef Flash | 2–255 | [Official input schema](https://developers.cloudflare.com/workers-ai/models/clef-flash/schema-input.json) |
|
|
286
|
+
| Cloudflare-hosted Jev | Not independently verified | Do not assume direct-TypeSafe limits apply to every gateway |
|
|
287
|
+
| Microsoft Decision-1 | Not specified in the fetched guide | [Foundry guide](https://learn.microsoft.com/en-us/azure/foundry/foundry-models/how-to/use-foundry-models-microsoft-decision) |
|
|
288
|
+
| OpenRouter-hosted Jev / custom routes | Endpoint-dependent; not verified | Requires the selected gateway/model's contract |
|
|
289
|
+
|
|
290
|
+
A documented upstream maximum is not a live deployment guarantee. Limits are matched to known model IDs on official endpoints; other deployments and gateways must not silently inherit an upstream model's limit. A configured `maxChoices` must be a safe integer of at least 2 and must reflect that endpoint's actual capability.
|
|
291
|
+
|
|
292
|
+
### Optional NONE and sequential choice batching
|
|
293
|
+
|
|
294
|
+
Both settings default to `false`:
|
|
295
|
+
|
|
296
|
+
```json
|
|
297
|
+
{
|
|
298
|
+
"pi-classifier": {
|
|
299
|
+
"none_of_above_choice": true,
|
|
300
|
+
"remove_choice_limits": true
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
```
|
|
304
|
+
|
|
305
|
+
`remove_choice_limits: true` **requires** `none_of_above_choice: true`. Both `classify` and `classify_compare` reject an invalid pair before any provider request, with:
|
|
306
|
+
|
|
307
|
+
```text
|
|
308
|
+
remove_choice_limits requires none_of_above_choice: true. No classifier request was sent.
|
|
309
|
+
```
|
|
310
|
+
|
|
311
|
+
With only `none_of_above_choice` enabled, the extension adds a collision-safe internal NONE option to every choice question. That option consumes one slot: a 255-option provider can accept 254 real choices plus NONE in a single request. If the list exceeds that capacity while `remove_choice_limits` is false, the call fails locally with instructions to enable both flags or reduce the list.
|
|
312
|
+
|
|
313
|
+
With both flags enabled, the extension walks the choices in their JavaScript/JSON object enumeration order, sending at most `maxChoices - 1` real choices plus NONE per batch. On a 255-option model this is **254 + 1**. A question advances only if NONE's probability is **strictly greater than every real option's probability**, not merely because the provider picked NONE and not necessarily greater than 50%. A unique real winner ends that question. An exact tie for top probability returns `{ "type": "ambiguous" }`. If all batches reject, the answer is `{ "type": "no_match" }`. Typed refusals stop that question without advancing.
|
|
314
|
+
|
|
315
|
+
Batching is **sequential first-match selection**, not a global best-choice guarantee. An early acceptable result can hide a better later option, and NONE itself can be unreliable. Returned choice probabilities cover only the winning batch's real options, with `probabilityScope: "batch"` and a separate `noneOfAboveProbability`; those real probabilities plus NONE sum to approximately one. Unseen options are not assigned fabricated zeros. The internal NONE label is never returned as the selected real choice. Ordinary calls without these flags retain their previous answer shapes.
|
|
316
|
+
|
|
317
|
+
Multiple choice questions progress independently in shared rounds; settled questions and bool/score/box questions are not resent. Images are prepared once per selected route and included in the required requests. Each request may be billed. Usage and estimated cost cover all completed calls in a successful result, with `providerCalls` for transparency. A multi-call result omits a single `requestId` because no one ID represents every request. If a later request fails after partial completion, the operation may have incurred charges; HTTP 401/404/429 after completed batches does not replay the operation on a fallback route.
|
|
318
|
+
|
|
319
|
+
For an endpoint without a known limit, automatic batching fails before any request until you set its verified `providers.<id>.maxChoices` or `customProviders.<id>.maxChoices`. This setting does not remove context-window, input-byte, image, output-size, timeout or cancellation protections. The 2 MiB original text/questions limit and 40 KiB returned-result limit remain in place. No automatic tree construction, retrieval, hidden model switching or cross-batch probability normalization is performed.
|
|
320
|
+
|
|
137
321
|
## Microsoft Decision-1 on Foundry
|
|
138
322
|
|
|
139
323
|
Deploy `Microsoft-Decision-1` in Microsoft Foundry, then configure the **resource endpoint**, API key, and actual **deployment name**:
|
|
@@ -156,11 +340,11 @@ The extension appends `/providers/microsoft/v1/systemone` and uses the `api-key`
|
|
|
156
340
|
|
|
157
341
|
## Fallback and explicit comparison
|
|
158
342
|
|
|
159
|
-
`classify` uses the default first. It tries configured `fallback` entries in order **only** after a missing API key or an explicit HTTP **401, 404, or 429**. Each resolved endpoint/model is
|
|
343
|
+
`classify` uses the default first. It tries configured `fallback` entries in order **only** after a missing API key or an explicit HTTP **401, 404, or 429**. Each resolved endpoint/model is selected at most once in the fallback chain; explicitly configured choice batching can make multiple requests on that selected route. When fallback is exercised, `attemptedRoutes` identifies the routes considered, including missing-key failures.
|
|
160
344
|
|
|
161
345
|
No automatic fallback occurs after 403/policy refusal, 400/422, 5xx, timeout, network failure, cancellation, malformed answers, input/capability/configuration errors, low confidence, or typed refusals. Each candidate validates the original input against its own capabilities; incompatible images or box questions stop the chain, never silently drop input. Every attempted request has its own timeout. Crossing billing providers and sharing state with them happens only through explicitly configured route pairs. Omit `fallback` or use `[]` to disable it.
|
|
162
346
|
|
|
163
|
-
Use **`classify_compare`** only when you explicitly want a model comparison. It accepts the same `{ state, questions, images? }` as `classify`, runs exactly the entries in `compare` sequentially, and never substitutes the default, uses fallback, or changes settings. Every entry is a separate potentially billable
|
|
347
|
+
Use **`classify_compare`** only when you explicitly want a model comparison. It accepts the same `{ state, questions, images? }` as `classify`, runs exactly the entries in `compare` sequentially, and never substitutes the default, uses fallback, or changes settings. Every entry is a separate potentially billable classification; configured choice batching can make multiple provider requests for that entry. Responses contain labeled `results` with status, duration in milliseconds, typed answers/token usage and estimated cost (or an unavailable reason) on success, or safe errors. A failed entry does not discard successes. Duplicate endpoint/model entries report an error without another call. Cancellation retains completed results, records an in-flight cancellation when present, sets `cancelled`, and prevents later requests. Scores from different models are not assumed to be calibrated equally.
|
|
164
348
|
|
|
165
349
|
You can also run `/classifier compare <JSON params>`, for example:
|
|
166
350
|
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import { type ClassifierResult, type ClassifierSettings, type PreparedInput, type Question, type ResolvedModel } from "./types.js";
|
|
2
|
+
export type ChoicePolicy = {
|
|
3
|
+
none: boolean;
|
|
4
|
+
batch: boolean;
|
|
5
|
+
};
|
|
6
|
+
export declare function choicePolicy(settings: ClassifierSettings): ChoicePolicy;
|
|
7
|
+
/** Only this operation owns batching. Transport, images, credentials and routes stay with the caller. */
|
|
8
|
+
export declare function executeChoices(input: PreparedInput, route: ResolvedModel, policy: ChoicePolicy, call: (questions: Record<string, Question>) => Promise<ClassifierResult>, signal?: AbortSignal): Promise<ClassifierResult>;
|
package/dist/choices.js
ADDED
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
import { sumCost, sumUsage } from "./cost.js";
|
|
2
|
+
import { ClassifierError, } from "./types.js";
|
|
3
|
+
export function choicePolicy(settings) {
|
|
4
|
+
for (const key of ["none_of_above_choice", "remove_choice_limits"]) {
|
|
5
|
+
if (settings[key] !== undefined && typeof settings[key] !== "boolean")
|
|
6
|
+
throw new ClassifierError("configuration", key + " must be a boolean.");
|
|
7
|
+
}
|
|
8
|
+
const none = settings.none_of_above_choice === true;
|
|
9
|
+
const batch = settings.remove_choice_limits === true;
|
|
10
|
+
if (batch && !none)
|
|
11
|
+
throw new ClassifierError("configuration", "remove_choice_limits requires none_of_above_choice: true. No classifier request was sent.");
|
|
12
|
+
return { none, batch };
|
|
13
|
+
}
|
|
14
|
+
const NONE_DESCRIPTION = "None of the other options in this question applies to the supplied state. Select this only when every listed real option is unsuitable.";
|
|
15
|
+
/** Only this operation owns batching. Transport, images, credentials and routes stay with the caller. */
|
|
16
|
+
export async function executeChoices(input, route, policy, call, signal) {
|
|
17
|
+
const plans = new Map();
|
|
18
|
+
for (const [id, question] of Object.entries(input.questions)) {
|
|
19
|
+
if (question.type !== "choice")
|
|
20
|
+
continue;
|
|
21
|
+
const entries = Object.entries(question.criteria);
|
|
22
|
+
if (policy.batch && route.maxChoices === undefined)
|
|
23
|
+
throw new ClassifierError("configuration", "Automatic choice batching needs a verified provider limit. Set providers.<id>.maxChoices (or customProviders.<id>.maxChoices) for this endpoint. No classifier request was sent.");
|
|
24
|
+
const size = entries.length + (policy.none ? 1 : 0);
|
|
25
|
+
if (!policy.batch &&
|
|
26
|
+
route.maxChoices !== undefined &&
|
|
27
|
+
size > route.maxChoices)
|
|
28
|
+
throw new ClassifierError("input", "Choice question " + id + " exceeds the selected provider's " +
|
|
29
|
+
route.maxChoices + " options per request" +
|
|
30
|
+
(policy.none ? " (including NONE OF THE ABOVE)" : "") +
|
|
31
|
+
". Enable both none_of_above_choice and remove_choice_limits to batch choices, or reduce the list. No classifier request was sent.");
|
|
32
|
+
let sentinel = "__pi_none_of_above";
|
|
33
|
+
let suffix = 0;
|
|
34
|
+
while (Object.hasOwn(question.criteria, sentinel))
|
|
35
|
+
sentinel = "__pi_none_of_above_" + ++suffix;
|
|
36
|
+
plans.set(id, { question, entries, offset: 0, sentinel });
|
|
37
|
+
}
|
|
38
|
+
if (!policy.none || plans.size === 0)
|
|
39
|
+
return call(input.questions);
|
|
40
|
+
const answers = Object.create(null);
|
|
41
|
+
let calls = 0;
|
|
42
|
+
let last;
|
|
43
|
+
let usage;
|
|
44
|
+
let cost;
|
|
45
|
+
while (plans.size > 0) {
|
|
46
|
+
if (signal?.aborted)
|
|
47
|
+
throw new ClassifierError("aborted", "Classification was cancelled.");
|
|
48
|
+
const questions = Object.create(null);
|
|
49
|
+
// A bool/score/box is evaluated once, not charged again for later choice batches.
|
|
50
|
+
if (calls === 0) {
|
|
51
|
+
for (const [id, question] of Object.entries(input.questions))
|
|
52
|
+
if (question.type !== "choice")
|
|
53
|
+
questions[id] = question;
|
|
54
|
+
}
|
|
55
|
+
for (const [id, plan] of plans) {
|
|
56
|
+
const capacity = route.maxChoices === undefined
|
|
57
|
+
? plan.entries.length
|
|
58
|
+
: route.maxChoices - 1;
|
|
59
|
+
const batch = plan.entries.slice(plan.offset, plan.offset + capacity);
|
|
60
|
+
plan.offset += batch.length;
|
|
61
|
+
questions[id] = {
|
|
62
|
+
...plan.question,
|
|
63
|
+
criteria: Object.fromEntries([...batch, [plan.sentinel, NONE_DESCRIPTION]]),
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
let result;
|
|
67
|
+
try {
|
|
68
|
+
result = await call(questions);
|
|
69
|
+
}
|
|
70
|
+
catch (error) {
|
|
71
|
+
// Never replay completed batches on another billing route after a later throttling/auth error.
|
|
72
|
+
if (calls > 0 &&
|
|
73
|
+
error instanceof ClassifierError &&
|
|
74
|
+
error.code === "http" &&
|
|
75
|
+
[401, 404, 429].includes(error.httpStatus ?? 0))
|
|
76
|
+
throw new ClassifierError("partial_classification", "Choice batching stopped after " + calls +
|
|
77
|
+
" completed provider request(s). No fallback was attempted after partial completion; completed requests may be billed.");
|
|
78
|
+
throw error;
|
|
79
|
+
}
|
|
80
|
+
usage = calls === 0 ? result.usage : sumUsage(usage, result.usage);
|
|
81
|
+
cost = cost === undefined ? result.cost : sumCost(cost, result.cost);
|
|
82
|
+
calls++;
|
|
83
|
+
last = result;
|
|
84
|
+
for (const [id, answer] of Object.entries(result.answers)) {
|
|
85
|
+
const plan = plans.get(id);
|
|
86
|
+
if (!plan) {
|
|
87
|
+
answers[id] = answer;
|
|
88
|
+
continue;
|
|
89
|
+
}
|
|
90
|
+
if (answer.type !== "choice") {
|
|
91
|
+
answers[id] = answer;
|
|
92
|
+
plans.delete(id);
|
|
93
|
+
continue;
|
|
94
|
+
}
|
|
95
|
+
const none = answer.probabilities[plan.sentinel];
|
|
96
|
+
const real = Object.entries(answer.probabilities).filter(([label]) => label !== plan.sentinel);
|
|
97
|
+
const maximum = Math.max(...real.map(([, probability]) => probability));
|
|
98
|
+
if (none > maximum) {
|
|
99
|
+
if (plan.offset < plan.entries.length)
|
|
100
|
+
continue;
|
|
101
|
+
answers[id] = { type: "no_match" };
|
|
102
|
+
}
|
|
103
|
+
else if (none === maximum || real.filter(([, p]) => p === maximum).length !== 1) {
|
|
104
|
+
answers[id] = { type: "ambiguous" };
|
|
105
|
+
}
|
|
106
|
+
else {
|
|
107
|
+
answers[id] = {
|
|
108
|
+
...answer,
|
|
109
|
+
choice: real.find(([, p]) => p === maximum)[0],
|
|
110
|
+
probabilities: Object.fromEntries(real),
|
|
111
|
+
probabilityScope: "batch",
|
|
112
|
+
noneOfAboveProbability: none,
|
|
113
|
+
};
|
|
114
|
+
}
|
|
115
|
+
plans.delete(id);
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
// Validated inputs always contain questions; this loop executes at least once.
|
|
119
|
+
const combined = {
|
|
120
|
+
provider: last.provider,
|
|
121
|
+
model: last.model,
|
|
122
|
+
answers,
|
|
123
|
+
providerCalls: calls,
|
|
124
|
+
cost: cost,
|
|
125
|
+
};
|
|
126
|
+
if (usage !== undefined)
|
|
127
|
+
combined.usage = usage;
|
|
128
|
+
if (calls === 1 && last.requestId !== undefined)
|
|
129
|
+
combined.requestId = last.requestId;
|
|
130
|
+
return combined;
|
|
131
|
+
}
|
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
import { constants } from "node:fs";
|
|
2
|
+
import { lstat, open, realpath } from "node:fs/promises";
|
|
3
|
+
import { isAbsolute, relative, resolve, sep } from "node:path";
|
|
4
|
+
import { verifyOpenedPath } from "./inputs.js";
|
|
5
|
+
import { ClassifierError, isRecord, } from "./types.js";
|
|
6
|
+
import { validateParams } from "./validation.js";
|
|
7
|
+
const MAX_TREE_BYTES = 2 * 1024 * 1024;
|
|
8
|
+
const MAX_DEPTH = 32;
|
|
9
|
+
function invalid(message) {
|
|
10
|
+
throw new ClassifierError("input", message);
|
|
11
|
+
}
|
|
12
|
+
export async function loadTreeInput(value, cwd, signal) {
|
|
13
|
+
cancelled(signal);
|
|
14
|
+
if (!isRecord(value) ||
|
|
15
|
+
Object.keys(value).some((key) => !["state", "tree", "instructions", "images"].includes(key)))
|
|
16
|
+
invalid("Expected state, tree and optional instructions/images; the route is selected in settings.");
|
|
17
|
+
if (value.instructions !== undefined &&
|
|
18
|
+
(typeof value.instructions !== "string" ||
|
|
19
|
+
!value.instructions.trim() || value.instructions.length > 8192))
|
|
20
|
+
invalid("Tree instructions must be a non-empty string of at most 8192 characters.");
|
|
21
|
+
// Reuse existing state/image-path validation without making a provider request.
|
|
22
|
+
const base = validateParams({
|
|
23
|
+
state: value.state,
|
|
24
|
+
questions: { tree: { type: "bool", instructions: "Validate tree input." } },
|
|
25
|
+
...(value.images !== undefined ? { images: value.images } : {}),
|
|
26
|
+
});
|
|
27
|
+
const raw = typeof value.tree === "string"
|
|
28
|
+
? await readTreeFile(value.tree, cwd, signal)
|
|
29
|
+
: value.tree;
|
|
30
|
+
if (!isRecord(raw) || Object.keys(raw).some((key) => key !== "roots"))
|
|
31
|
+
invalid("Classification tree must be an object containing roots.");
|
|
32
|
+
const ancestors = new Set();
|
|
33
|
+
const roots = nodes(raw.roots, 1, ancestors, { bytes: 0 });
|
|
34
|
+
const tree = { roots };
|
|
35
|
+
if (Buffer.byteLength(JSON.stringify(tree)) > MAX_TREE_BYTES)
|
|
36
|
+
invalid("Classification tree must be at most 2 MiB.");
|
|
37
|
+
cancelled(signal);
|
|
38
|
+
const result = {
|
|
39
|
+
state: base.state,
|
|
40
|
+
tree,
|
|
41
|
+
};
|
|
42
|
+
if (typeof value.instructions === "string")
|
|
43
|
+
result.instructions = value.instructions;
|
|
44
|
+
if (base.images !== undefined)
|
|
45
|
+
result.images = base.images;
|
|
46
|
+
return result;
|
|
47
|
+
}
|
|
48
|
+
function nodes(value, depth, ancestors, budget) {
|
|
49
|
+
if (!Array.isArray(value) || (depth === 1 && value.length === 0))
|
|
50
|
+
invalid("Classification tree roots must be non-empty and children must be arrays when supplied.");
|
|
51
|
+
if (depth > MAX_DEPTH && value.length > 0)
|
|
52
|
+
invalid("Classification tree must be at most 32 levels deep.");
|
|
53
|
+
const ids = new Set();
|
|
54
|
+
return value.map((entry) => {
|
|
55
|
+
if (!isRecord(entry) ||
|
|
56
|
+
Object.keys(entry).some((key) => !["id", "description", "children"].includes(key)) ||
|
|
57
|
+
typeof entry.id !== "string" ||
|
|
58
|
+
!entry.id.trim() || entry.id.length > 128 ||
|
|
59
|
+
(entry.description !== undefined &&
|
|
60
|
+
(typeof entry.description !== "string" || entry.description.length > 4096)))
|
|
61
|
+
invalid("Each classification tree node needs a non-empty id of at most 128 characters, optional description up to 4096 characters, and optional children.");
|
|
62
|
+
if (ids.has(entry.id))
|
|
63
|
+
invalid("Classification tree node IDs must be unique among siblings.");
|
|
64
|
+
if (ancestors.has(entry))
|
|
65
|
+
invalid("Classification tree must not contain cycles.");
|
|
66
|
+
ids.add(entry.id);
|
|
67
|
+
ancestors.add(entry);
|
|
68
|
+
const node = { id: entry.id };
|
|
69
|
+
if (typeof entry.description === "string")
|
|
70
|
+
node.description = entry.description;
|
|
71
|
+
// Bound normalization itself, including shared JS subtrees that expand when serialized.
|
|
72
|
+
budget.bytes += Buffer.byteLength(JSON.stringify(node));
|
|
73
|
+
if (budget.bytes > MAX_TREE_BYTES)
|
|
74
|
+
invalid("Classification tree must be at most 2 MiB.");
|
|
75
|
+
if (entry.children !== undefined)
|
|
76
|
+
node.children = nodes(entry.children, depth + 1, ancestors, budget);
|
|
77
|
+
ancestors.delete(entry);
|
|
78
|
+
return node;
|
|
79
|
+
});
|
|
80
|
+
}
|
|
81
|
+
async function readTreeFile(path, cwd, signal) {
|
|
82
|
+
if (!path.trim() || path.length > 4096 || /^[a-z]+:/i.test(path))
|
|
83
|
+
invalid("Classification tree must be an inline roots object or a local JSON path inside cwd, not a URL.");
|
|
84
|
+
let bytes;
|
|
85
|
+
try {
|
|
86
|
+
const root = await realpath(cwd);
|
|
87
|
+
const target = resolve(root, path);
|
|
88
|
+
const inside = relative(root, target);
|
|
89
|
+
if (!inside || inside === ".." ||
|
|
90
|
+
inside.startsWith(".." + sep) || isAbsolute(inside))
|
|
91
|
+
throw new Error();
|
|
92
|
+
let current = root;
|
|
93
|
+
for (const part of inside.split(sep)) {
|
|
94
|
+
cancelled(signal);
|
|
95
|
+
current = resolve(current, part);
|
|
96
|
+
const entry = await lstat(current);
|
|
97
|
+
if (entry.isSymbolicLink() ||
|
|
98
|
+
(current === target ? !entry.isFile() : !entry.isDirectory()))
|
|
99
|
+
throw new Error();
|
|
100
|
+
}
|
|
101
|
+
if (await realpath(target) !== target)
|
|
102
|
+
throw new Error();
|
|
103
|
+
const file = await open(target, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
|
|
104
|
+
try {
|
|
105
|
+
await verifyOpenedPath(file.fd, root, signal);
|
|
106
|
+
const stat = await file.stat();
|
|
107
|
+
if (!stat.isFile() || stat.size < 1 || stat.size > MAX_TREE_BYTES)
|
|
108
|
+
throw new Error();
|
|
109
|
+
const buffer = Buffer.alloc(MAX_TREE_BYTES + 1);
|
|
110
|
+
let offset = 0;
|
|
111
|
+
while (offset < buffer.length) {
|
|
112
|
+
cancelled(signal);
|
|
113
|
+
const next = await file.read(buffer, offset, buffer.length - offset, null);
|
|
114
|
+
if (!next.bytesRead)
|
|
115
|
+
break;
|
|
116
|
+
offset += next.bytesRead;
|
|
117
|
+
}
|
|
118
|
+
if (offset > MAX_TREE_BYTES)
|
|
119
|
+
throw new Error();
|
|
120
|
+
bytes = buffer.subarray(0, offset);
|
|
121
|
+
}
|
|
122
|
+
finally {
|
|
123
|
+
await file.close();
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
catch (error) {
|
|
127
|
+
cancelled(signal);
|
|
128
|
+
if (error instanceof ClassifierError)
|
|
129
|
+
throw error;
|
|
130
|
+
invalid("Classification tree must be a readable regular file inside cwd, without symlink components, and at most 2 MiB.");
|
|
131
|
+
}
|
|
132
|
+
cancelled(signal);
|
|
133
|
+
try {
|
|
134
|
+
return JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes));
|
|
135
|
+
}
|
|
136
|
+
catch {
|
|
137
|
+
invalid("Classification tree file must contain valid UTF-8 JSON.");
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
function cancelled(signal) {
|
|
141
|
+
if (signal?.aborted)
|
|
142
|
+
throw new ClassifierError("aborted", "Classification was cancelled.");
|
|
143
|
+
}
|
package/dist/classify.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { type ClassifierComparisonResult, type ClassifierResult, type ClassifierSettings } from "./types.js";
|
|
2
|
-
type ClassifyOptions = {
|
|
2
|
+
export type ClassifyOptions = {
|
|
3
3
|
settings: ClassifierSettings;
|
|
4
4
|
cwd: string;
|
|
5
5
|
signal?: AbortSignal;
|
|
@@ -8,4 +8,3 @@ type ClassifyOptions = {
|
|
|
8
8
|
export declare function classify(params: unknown, options: ClassifyOptions): Promise<ClassifierResult>;
|
|
9
9
|
/** Explicit comparisons only: configured entries, no default substitution or fallback. */
|
|
10
10
|
export declare function compareClassifiers(params: unknown, options: ClassifyOptions): Promise<ClassifierComparisonResult>;
|
|
11
|
-
export {};
|
package/dist/classify.js
CHANGED
|
@@ -2,6 +2,7 @@ import { performance } from "node:perf_hooks";
|
|
|
2
2
|
import { resolveApiKey } from "./auth.js";
|
|
3
3
|
import { configuredDefault, configuredRoutes, resolveModel } from "./config.js";
|
|
4
4
|
import { prepareInput } from "./inputs.js";
|
|
5
|
+
import { choicePolicy, executeChoices } from "./choices.js";
|
|
5
6
|
import { classifyWithProvider } from "./providers.js";
|
|
6
7
|
import { ClassifierError, userError, } from "./types.js";
|
|
7
8
|
import { validateParams } from "./validation.js";
|
|
@@ -20,7 +21,7 @@ async function classifyOnce(input, route, options) {
|
|
|
20
21
|
const prepared = await prepareInput(input, route, options.cwd, options.signal);
|
|
21
22
|
checkCancelled(options.signal);
|
|
22
23
|
const key = resolveApiKey(route);
|
|
23
|
-
const result = await classifyWithProvider(route, prepared, key, options.signal);
|
|
24
|
+
const result = await executeChoices(prepared, route, choicePolicy(options.settings), (questions) => classifyWithProvider(route, { ...prepared, questions }, key, options.signal), options.signal);
|
|
24
25
|
if (Buffer.byteLength(JSON.stringify(result, null, 2)) > 40 * 1024)
|
|
25
26
|
throw new ClassifierError("response", "Classifier result exceeds the 40 KiB tool output limit. Ask fewer questions.");
|
|
26
27
|
return result;
|
|
@@ -32,6 +33,7 @@ function permitsFallback(error) {
|
|
|
32
33
|
}
|
|
33
34
|
/** Default plus explicitly configured, selective fallback. Never retries a route. */
|
|
34
35
|
export async function classify(params, options) {
|
|
36
|
+
choicePolicy(options.settings);
|
|
35
37
|
const input = validateParams(params);
|
|
36
38
|
const candidates = [
|
|
37
39
|
configuredDefault(options.settings),
|
|
@@ -65,6 +67,7 @@ export async function classify(params, options) {
|
|
|
65
67
|
}
|
|
66
68
|
/** Explicit comparisons only: configured entries, no default substitution or fallback. */
|
|
67
69
|
export async function compareClassifiers(params, options) {
|
|
70
|
+
choicePolicy(options.settings);
|
|
68
71
|
const input = validateParams(params);
|
|
69
72
|
const candidates = configuredRoutes(options.settings, "compare");
|
|
70
73
|
if (candidates.length === 0)
|