@abhishek944/pi-classifier 0.6.0 → 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/CHANGELOG.md CHANGED
@@ -2,6 +2,19 @@
2
2
 
3
3
  ## Unreleased
4
4
 
5
+ ## 0.7.0 - 2026-12-03
6
+
7
+ - Separated the two tool surfaces. `classify` now accepts classification decisions only (`bool`, `choice`, `multi_choice`, `score`) and rejects `text`, `number`, `date`, `spans`, `boxes`, `box`, `locate`, `estimate` and Inception `extract` locally with a pointer to `classify_extract`.
8
+ - `classify_extract` now owns every read. It accepts exactly one of `fields` (Clairic-shaped field specifications on `clairic-api`, `openrouter-extractions-api` or `litellm-extraction-api`) or `questions` (typed extraction reads on the configured decision route). This makes direct `liquid-api` `d1.2`/`d1.2-ultra` reads reachable from `classify_extract`, and keeps Jev `box`, Perplexity `locate` and Inception `extract` supported instead of dropping them.
9
+ - Typed extraction answers use the extraction result shape `{ type, value, ...metadata }`, with `refusal`/`no_match`/`ambiguous` as explicit types and `value: null`. Question mode reports `truncated: false`, and passes through `citations`, `webGrounding` and `attemptedRoutes` when the answering route provides them. Default-then-fallback route selection is shared with `classify`, so moved questions keep their previous route behavior.
10
+ - Field mode keeps its local-path/`rotation` image contract and rejects `questions`, `media` and `mode`; question mode accepts local paths and named `{$image:id}` descriptors, media on routes that document it, and rejects `documents`, `referenceDate` and `options`. `classify_extract` parameter/result schemas, tool descriptions, extension guidance, MCP/durable contracts and README were updated together.
11
+ - Enforced Liquid's documented one-image rule for `box` and `boxes` on the now-exposed extraction path: direct `liquid-api` requests with zero or multiple images for those reads are rejected locally before any provider request. Other Liquid reads keep the eight-image limit, and non-Liquid box routes keep their own contracts.
12
+ - Added `subq-api` for SubQ Snap (`subq-snap-1.2`, `subq-snap-latest`) on `POST /v1/systemone` with the provider's `{mediaType, base64}` image objects, 128-question / 4-image / 384K-token limits, 4 MiB per image and 8 MiB combined, and the current $0.04 per million input-token rate.
13
+ - Added `alibaba-api` for Model Studio `decision-model` on `/compatible-mode/v1/systemone`. The route requires an operator-configured workspace gateway `baseUrl`, reuses `DASHSCOPE_API_KEY`, sends Alibaba's `image`/`images` data-URL entries, and encodes 16 questions, 16 request images and the 268,288-token context. `decision-model-preview` is not shipped.
14
+ - Added `fireworks-api` for the public Serverless `accounts/fireworks/models/rune` System One model on `/inference/v1/systemone`, text-only, with 256-question and 208-choice limits. The private-preview router id is not shipped.
15
+ - Added the built-in `litellm-decisions-api` route for LiteLLM `/v1/decisions` with operator-defined `model_name` aliases, `LITELLM_API_KEY`, `x-litellm-response-cost` reported as `providerCost`, and LiteLLM's validated 128-question / 255-choice ceiling. The README documents the `/v1/systemone` custom-provider form and hosted Laya on layahost and Berget AI.
16
+ - Marked the Inception `mercury-decide` built-in and both `inception/mercury-decide` OpenRouter rows with the documented 2026-12-28 shutdown; `/classifier list` now annotates lifecycle dates, and the routes remain selectable until the deadline.
17
+
5
18
  - Added `opencode-go-api` using OpenCode Go's official System One endpoint, Pi's `opencode-go` stored API-key credential or `OPENCODE_API_KEY`, and the documented `jev-1.14`, `gemini-decision-1`, and `gpt-6-luna-decision` models. The route exposes text/JSON bool, choice and score decisions with bundled public prices and the documented GPT-6-Luna long-context multiplier.
6
19
  - Added verified built-in routes for Vercel AI Gateway, Google Gemini Decision 1, Inception Mercury Decide, Parallel Decisions, OpenRouter alpha Decisions and Extractions, LiteLLM extraction, and self-hosted llama.cpp/vLLM/Strands/Laya/Nimble System One runtimes with explicit capability tiers.
7
20
  - Added Microsoft Foundry Decision-1.1 image assets and Entra bearer auth, TypeSafe long context, Liquid JSON `path` metadata, Clairic image rotation, OpenAI native `input_json`/boolean choices/score descriptions/image detail/prompt-cache controls, and per-route question/media limits.
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # pi-classifier
2
2
 
3
- A Pi extension for typed, probabilistic decisions across Microsoft Foundry Decision-1.1, OpenAI Decisions, Perplexity Decisions, Sarvam Prism, TypeSafe Jev, Liquid d1.2, Cloudflare Clef/Clef Flash/Clef-omni, Google Gemini Decision 1, OpenCode Go decisions, Inception Mercury Decide, Parallel Decisions, OpenRouter alpha Decisions, Vercel AI Gateway, self-hosted System One runtimes, and Clairic-shaped extraction. It also exposes Perplexity text-span location and web grounding, grounded Parallel citations, and typed reads from supported models.
3
+ A Pi extension for typed, probabilistic decisions across Microsoft Foundry Decision-1.1, OpenAI Decisions, Perplexity Decisions, Sarvam Prism, TypeSafe Jev, Liquid d1.2, Cloudflare Clef/Clef Flash/Clef-omni, Google Gemini Decision 1, OpenCode Go decisions, SubQ Snap, Alibaba Decision Model, Fireworks Rune, LiteLLM decision gateways, Inception Mercury Decide, Parallel Decisions, OpenRouter alpha Decisions, Vercel AI Gateway, self-hosted System One runtimes, and Clairic-shaped extraction. `classify` answers classification decisions (yes/no, category, multi-choice, score). `classify_extract` reads values (text, numbers, dates, passages, locations and estimates) through Clairic-shaped fields or typed extraction questions on decision routes, including direct Liquid d1.2 and d1.2-ultra. Web grounding and grounded Parallel citations stay on the classification tool.
4
4
 
5
5
  One configured default, optional selective fallback, and explicit model comparisons. No automatic retries or permission auto-approval.
6
6
 
@@ -90,7 +90,10 @@ Stored API-key values support literal strings and `$NAME`/`${NAME}` references,
90
90
  | `vercel-api` | `vercel` | `openai/gpt-6-luna-decisions`, `typesafe-ai/jev` | `VERCEL_AI_GATEWAY_API_KEY` |
91
91
  | `gemini-api` | `gemini` | `gemini-decision-1` | `GEMINI_API_KEY` |
92
92
  | `opencode-go-api` | `opencode-go` | `jev-1.14`, `gemini-decision-1`, `gpt-6-luna-decision` | Pi's `opencode-go` stored API key or `OPENCODE_API_KEY` |
93
- | `inception-api` | `inception` | `mercury-decide` | `INCEPTION_API_KEY` |
93
+ | `inception-api` | `inception` | `mercury-decide` (shuts down after 2026-12-28) | `INCEPTION_API_KEY` |
94
+ | `subq-api` | `subq` | `subq-snap-1.2`, `subq-snap-latest` | `SUBQ_API_KEY` |
95
+ | `alibaba-api` | `dashscope` | `decision-model`; requires your workspace gateway `baseUrl` | `DASHSCOPE_API_KEY` |
96
+ | `fireworks-api` | `fireworks` | `accounts/fireworks/models/rune` | `FIREWORKS_API_KEY` |
94
97
  | `parallel-api` | `parallel` | `parallel-decisions` | `PARALLEL_API_KEY` |
95
98
  | `perplexity-api` | `perplexity` | v1.3, Flash v1.3, v1.2, latest aliases, legacy v1/v1.1 IDs | `PERPLEXITY_API_KEY` |
96
99
  | `sarvam-api` | `sarvam` | `sarvam-prism` | `SARVAM_API_KEY` |
@@ -101,11 +104,15 @@ Stored API-key values support literal strings and `$NAME`/`${NAME}` references,
101
104
  | `openrouter-api` | `openrouter` | OpenRouter System One Jev models | `OPENROUTER_API_KEY` |
102
105
  | `openrouter-decisions-api` | `openrouter` | Jev 1.14/latest, Microsoft, Clef, Liquid, OpenAI, Gemini, HeyGen and other documented slugs | `OPENROUTER_API_KEY` |
103
106
  | `openrouter-extractions-api` | `openrouter` | `cloudflare/clairic`, Liquid, Perplexity, ScaleDown and other documented extraction slugs | `OPENROUTER_API_KEY` |
107
+ | `litellm-extraction-api` | `litellm` | `clairic`; requires `baseUrl` | `LITELLM_API_KEY` |
108
+ | `litellm-decisions-api` | `litellm` | your proxy `model_name` aliases (`luna` is only LiteLLM's documented example); requires `baseUrl` | `LITELLM_API_KEY` |
104
109
  | `llamacpp-api`, `vllm-api`, `strands-api`, `laya-api`, `nimble-api` | same route key | documented local model IDs; require `baseUrl` | none or runtime key |
105
110
 
111
+ `inception-api` and both `inception/mercury-decide` OpenRouter rows stay selectable until the vendor's documented shutdown on **2026-12-28**: after that date Inception stops serving API requests and deletes access to submitted data. `/classifier list` marks each affected model. Migrate before the deadline; SubQ Snap and Alibaba `decision-model` cover similar decision jobs.
112
+
106
113
  Cloudflare also needs `providers.cloudflare.accountId`, the stored `cloudflare-workers-ai` API-key credential's `env.CLOUDFLARE_ACCOUNT_ID`, or `CLOUDFLARE_ACCOUNT_ID`, in that order. Its stored API token lives under `cloudflare-workers-ai`, not `cloudflare`. Set `providers.cloudflare.gatewayId` to select an AI Gateway for Workers AI requests; the package sends it as `cf-aig-gateway-id`. An explicitly configured `headers["cf-aig-gateway-id"]` still works when `gatewayId` is absent; when both are present, `gatewayId` wins.
107
114
 
108
- A provider's `baseUrl` replaces the API root before the adapter's path: `decisions`, `alpha/decisions`, `alpha/extractions`, `systemone`, `v1/systemone`, `extraction`, Microsoft's `providers/microsoft/v1/systemone`, or Cloudflare's run path. Local runtimes take the server root, for example `http://127.0.0.1:8080`. Authentication/transport headers cannot be overridden. Custom headers are supported. HTTPS is required except for loopback HTTP.
115
+ A provider's `baseUrl` replaces the API root before the adapter's path: `decisions`, `alpha/decisions`, `alpha/extractions`, `systemone`, `v1/systemone`, `compatible-mode/v1/systemone`, `extraction`, Microsoft's `providers/microsoft/v1/systemone`, or Cloudflare's run path. Alibaba therefore takes the workspace gateway host (for example `https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com`), not the full endpoint. Local runtimes take the server root, for example `http://127.0.0.1:8080`. Authentication/transport headers cannot be overridden. Custom headers are supported. HTTPS is required except for loopback HTTP.
109
116
 
110
117
  New text model IDs on built-in routes can be selected without a package release. They must actually implement that route's API; a normal chat model is not a decision model. New image capabilities require a known model or explicit custom model declaration. Set `providers.<id>.limits` only for verified account-specific envelopes; it does not assert unsupported capability.
111
118
 
@@ -117,16 +124,20 @@ New text model IDs on built-in routes can be selected without a package release.
117
124
  | OpenRouter alpha Decisions | bool, choice, score; box only on TypeSafe Jev 1.14/latest | per-adapter image/audio/video/file placement; remote URLs only for documented models | `usage.cost` reported as `providerCost` | Alpha contract; media placement and limits are registry-driven.
118
125
  | Google Gemini Decisions | bool, choice, score | text, images, audio, video | no bundled rate | Direct `/v1beta/decisions` with `x-goog-api-key`; question media is rejected upstream.
119
126
  | OpenCode Go decisions | bool (`noul`), choice, score | text/JSON only | public USD list rates | Uses Go's System One endpoint; OpenAI Decisions is also available upstream but is not exposed here. No media or JSON-schema `response_format` claim.
120
- | Inception Mercury Decide | bool, choice, score, `extract` | text and inline images; no media with extract | no bundled rate | The Mercury API is documented to shut down after 2026-12-28.
127
+ | SubQ Snap | bool, choice, score | text and inline images | public USD rate | `images: [{mediaType, base64}]` with no URL and no data-URL prefix; 128 questions, 4 images (4 MiB each / 8 MiB total), 384K context.
128
+ | Alibaba Decision Model | bool, choice, score | text and inline images | no bundled rate | Workspace gateway `baseUrl` required; `image`/`images` entries carry a Base64 data URL; 16 questions, 16 images, 268,288-token context.
129
+ | Fireworks Rune | bool, choice, score | text/JSON only | no bundled rate | Public serverless `accounts/fireworks/models/rune`; 256 questions, 208 choice options, 256K context; images are rejected locally, and reasoning is not exposed.
130
+ | LiteLLM decisions | bool, choice, score | text/JSON; images only for a verified upstream model | `x-litellm-response-cost` reported as gateway cost | `/v1/decisions` through the built-in route with 128 questions and 255 choice options; `/v1/systemone` through `api: "system-one"`; aliases are operator-defined.
131
+ | Inception Mercury Decide | bool, choice, score; `extract` through `classify_extract` | text and inline images; no media with extract | no bundled rate | The Mercury API stops serving requests after 2026-12-28; the route and its two OpenRouter rows stay selectable until then and `/classifier list` marks them.
121
132
  | Parallel Decisions | bool, choice, score | text/JSON only | no bundled rate | Web grounding is intrinsic; request-wide citations are returned as `citations`.
122
133
  | Microsoft Foundry | bool, choice, score; no box | text/JSON and PNG/JPEG assets | account pricing | Entra bearer or API key; no published numeric image/context limits.
123
- | Perplexity | bool, choice, score, locate | text and images | token estimate plus non-token search fees | `max_staleness` is ignored upstream and is not exposed.
134
+ | Perplexity | bool, choice, score; `locate` through `classify_extract` | text and images | token estimate plus non-token search fees | `max_staleness` is ignored upstream and is not exposed.
124
135
  | Sarvam | bool, choice, score | text only for Prism; Clef images require Provisioned Throughput | INR pricing requires explicit USD override | Clef is not bundled as a default.
125
- | TypeSafe Jev | bool, choice, score, box on 1.14 | text and images | public USD rate | Images and box need experimental opt-ins; long context is `longContext: true`.
126
- | Liquid hosted | bool, choice, score and typed reads | text, images, audio | public USD rate | Typed reads need text or OCR text in `state`; JSON states expose RFC 6901 `path`.
136
+ | TypeSafe Jev | bool, choice, score; `box` on 1.14 through `classify_extract` | text and images | public USD rate | Images and box need experimental opt-ins; long context is `longContext: true`.
137
+ | Liquid hosted | bool, choice, score; typed reads through `classify_extract` | text, images, audio | public USD rate | Direct `liquid-api` reads text/number/date/spans/box/boxes/estimate through `classify_extract` questions; reads need text or OCR text in `state` and JSON states expose RFC 6901 `path`.
127
138
  | Cloudflare Clef family | bool, choice, score | text, images; Clef-omni also audio/video | public USD rate | Only Clef-omni's schema exposes `videos`.
128
139
  | Local System One runtimes | bool, choice, score | runtime/model specific | `unknown_pricing` | llama.cpp, vLLM, Strands, Laya and Nimble use explicit capability tiers; Transformers/mlx-vlm are in-process runtimes and have no HTTP endpoint in this package.
129
- | Extraction | Clairic fields | text, images, PDFs on direct Clairic; images on gateways | gateway cost captured when returned | Direct Cloudflare, OpenRouter alpha and LiteLLM extraction routes share validation but use separate transports.
140
+ | Extraction | Clairic fields or typed reads | text, images, PDFs on direct Clairic; images on gateways | gateway cost captured when returned | `classify_extract` owns all reads. Fields use direct Cloudflare, OpenRouter alpha and LiteLLM extraction routes; typed questions use a decision route that supports that read: Liquid typed reads, Jev `box`, Perplexity `locate`, Inception `extract`.
130
141
 
131
142
  Unresolved by design: no live entitlement, codec, hardware-fit, OpenCode Go response, or invoice check was run; OpenRouter alpha shapes and dynamic model catalogs can change; Cloudflare's direct Workers AI REST gateway-header requirement is internally inconsistent in official docs; and Microsoft does not publish a complete answer schema or numeric image limits. These are reported as limits, not filled with guessed support.
132
143
 
@@ -165,6 +176,8 @@ classify({
165
176
  });
166
177
  ```
167
178
 
179
+ `classify` accepts only classification decisions: `bool`, `choice`, `multi_choice` and `score`. Extraction reads are rejected locally with a pointer to `classify_extract`: `text`, `number`, `date`, `spans`, `box`, `boxes`, `locate`, `estimate`, and Inception `extract`. Send the identical question object to `classify_extract` to read a value instead of deciding a category.
180
+
168
181
  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).
169
182
 
170
183
  OpenAI-compatible routes can also send `conversation` input items (messages, function calls/outputs and custom tool calls/outputs) when judging a prior exchange. The package validates item types but preserves the documented fields; pair them with a `state` string when you also need shared context. It also sends structured JSON state as native `input_json`, supports boolean-valued two-option choices and score-level descriptions, accepts `imageDetail`, and exposes documented `promptCache` controls. These fields are rejected on routes without the same wire contract.
@@ -285,6 +298,7 @@ This example uses 1,000 Jev input tokens. Amounts are not rounded to cents; doin
285
298
  | Cloudflare `@cf/cloudflare/clairic` | 0.10 until 2026-12-01, then 0.24 | 0 |
286
299
  | Liquid `d1.2` | 0.02 | 0 |
287
300
  | Liquid `d1.2-ultra` | 0.042 | 0 |
301
+ | SubQ `subq-snap-1.2`, `subq-snap-latest` | 0.04 | 0 |
288
302
  | Cloudflare `typesafe/jev` | 0.042 | 0 |
289
303
 
290
304
  Sources: [OpenAI Decisions pricing](https://developers.openai.com/api/docs/guides/decisions#pricing-and-availability), [OpenAI rates](https://developers.openai.com/api/docs/pricing), [OpenCode Go](https://opencode.ai/docs/console/go/), [TypeSafe models](https://docs.typesafe.ai/models), [Perplexity Decisions](https://docs.perplexity.ai/docs/decisions/quickstart#pricing), [Perplexity changelog](https://docs.perplexity.ai/docs/resources/changelog), [Clef](https://developers.cloudflare.com/workers-ai/models/clef/), [Clef Flash](https://developers.cloudflare.com/workers-ai/models/clef-flash/), [Clef-omni](https://developers.cloudflare.com/workers-ai/models/clef-omni/), [Clairic](https://developers.cloudflare.com/workers-ai/models/clairic/), [Cloudflare Jev](https://developers.cloudflare.com/ai/models/typesafe/jev/), [Liquid d1.2](https://docs.liquid.ai/lfm/models/d1). Aliases can move and public prices can change; explicit overrides take precedence. Perplexity's `pplx-decider-latest` now selects v1.3 and `pplx-decider-flash-latest` selects Flash v1.3; revalidate thresholds tuned on earlier models. Its [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.
@@ -332,6 +346,10 @@ The artificial **64-choice cap has been removed** from both runtime validation a
332
346
  | Cloudflare Clef Flash | 2–255 | [Official input schema](https://developers.cloudflare.com/workers-ai/models/clef-flash/schema-input.json) |
333
347
  | Cloudflare Clef-omni | 2–255 | [Official input schema](https://developers.cloudflare.com/workers-ai/models/clef-omni/schema-input.json) |
334
348
  | Liquid `d1.2`, `d1.2-ultra` | 2–255 | [Liquid Decisions reference](https://docs.liquid.ai/api/reference/decision-models/make-decisions) |
349
+ | SubQ Snap | 2–255 | [Decisions API](https://docs.subq.ai/endpoints/decisions-api) |
350
+ | Alibaba `decision-model` | 1–255 | [Decision Model API](https://www.alibabacloud.com/help/en/model-studio/decision-model-api) |
351
+ | Fireworks Rune | Up to 208 | [System One decisions API](https://docs.fireworks.ai/api-reference/post-systemone) |
352
+ | LiteLLM decision gateways | 2–255 on `/v1/decisions`; 1–255 on `/v1/systemone` | [LiteLLM decisions](https://docs.litellm.ai/docs/decisions); LiteLLM validates 1–128 questions and the choice range before calling a provider |
335
353
  | OpenCode Go decision models | Not independently verified for this route | Automatic batching stays off unless `providers["opencode-go"].maxChoices` is set from a verified endpoint contract |
336
354
  | Cloudflare-hosted Jev | Not independently verified | Do not assume direct-TypeSafe limits apply to every gateway |
337
355
  | 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) |
@@ -362,20 +380,20 @@ With only `none_of_above_choice` enabled, the extension adds a collision-safe in
362
380
 
363
381
  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.
364
382
 
365
- With Perplexity web grounding, evidence from each completed batch is retained in call order under `webGrounding.searchResults`, and a grounded `locate.searchResult` index refers to that combined array rather than to a single batch. Fetched results are retained the same way.
383
+ With Perplexity web grounding, evidence from each completed batch is retained in call order under `webGrounding.searchResults`. Fetched results are retained the same way.
366
384
 
367
385
  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.
368
386
 
369
- 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.
387
+ Multiple choice questions progress independently in shared rounds; settled questions and bool/score 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.
370
388
 
371
389
  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.
372
390
 
373
391
  ## Perplexity `locate` and web grounding
374
392
 
375
- Perplexity v1.3 adds a `locate` question that returns verbatim text spans with Unicode-character offsets. It requires a string `state`, no images, and `pplx-decider-v1.3`, `pplx-decider-flash-v1.3`, or the matching `-latest` alias. Other routes reject it locally.
393
+ Perplexity v1.3 adds a `locate` question that returns verbatim text spans with Unicode-character offsets. `locate` is an extraction read, so it is sent through **`classify_extract`**. It requires a string `state`, no images, and `pplx-decider-v1.3`, `pplx-decider-flash-v1.3`, or the matching `-latest` alias. Other routes reject it locally.
376
394
 
377
395
  ```js
378
- classify({
396
+ classify_extract({
379
397
  state: "AeroPress arrived broken; email help@brewco.example.",
380
398
  questions: {
381
399
  products: { type: "locate", instructions: "Every product name mentioned" },
@@ -383,7 +401,7 @@ classify({
383
401
  });
384
402
  ```
385
403
 
386
- Each answer has `{ type: "locate", spans: [{ start, end, text, score, searchResult? }] }`. `end` is exclusive. The package checks each span against the original state or, when `searchResult` is present, against that search result's snippet. No span is fabricated when nothing matches.
404
+ Each answer has `{ type: "locate", value: [text...], spans: [{ start, end, text, score, searchResult? }] }`. `end` is exclusive. The package checks each span against the original state or, when `searchResult` is present, against that search result's snippet. No span is fabricated when nothing matches.
387
405
 
388
406
  Set `mode: "web_grounding"` only when the answer should use public web evidence. Perplexity sends one search query per question containing the question text and the start of `state`, then adds the results to the model's input. A URL-only string `state` is fetched before searching. Perplexity documents `max_staleness` as accepted but currently ignored, so this package does not expose a `maxStaleness` option and does not claim a page-age check.
389
407
 
@@ -397,27 +415,33 @@ classify({
397
415
 
398
416
  The result adds `webGrounding.searchResults` (and `webGrounding.fetchedResults` when a page was fetched). `cost.nonToken.webGrounding` reports the documented maximum search fee from one search per question and the exact successful-fetch fee. Perplexity does not report the number of searches actually billed, so the search amount is an upper bound: duplicate queries may share a search and failed searches are not billed. Fetched text and search evidence are already included in `usage.input_tokens`. Grounded requests are limited to 100 questions by the provider; the common 32-question package limit still applies.
399
417
 
400
- Grounded `locate` requires ordinary text state, not a URL-only state. A span found in search evidence has `searchResult`, and its offsets refer to that result's snippet.
418
+ Grounded `locate` requires ordinary text state, not a URL-only state, and is sent through `classify_extract` with `mode: "web_grounding"`; its result carries the same `webGrounding` evidence. A span found in search evidence has `searchResult`, and its offsets refer to that result's snippet.
401
419
 
402
420
  ## Liquid d1.2 typed reads and media
403
421
 
404
- `liquid-api` uses `POST https://api.liquid.ai/decisions/v1/systemone` with `LIQUID_API_KEY`. It supports bool, choice, score, box, and d1.2's typed reads and estimates. Values are read, not converted: a number answer keeps the printed `text`, `unit`, `span` and `found` probability when the provider reports them. Spans count Unicode code points; JSON object positions use the provider's two-space-indented rendering.
422
+ `liquid-api` uses `POST https://api.liquid.ai/decisions/v1/systemone` with `LIQUID_API_KEY`. Classification uses `classify` (bool, choice, multi_choice, score). Every read uses `classify_extract`: `text`, `number`, `date`, `spans`, `box`, `boxes` and `estimate`. Both tools select the same `d1.2` or `d1.2-ultra` route. Values are read, not converted: a number answer keeps the printed `text`, `unit`, `span` and `found` probability when the provider reports them. Spans count Unicode code points; JSON object positions use the provider's two-space-indented rendering.
405
423
 
406
424
  ```js
407
- classify({
425
+ classify_extract({
408
426
  state: "Invoice total: 1234.50 EUR, due 03/04/2026.",
409
427
  questions: {
410
428
  total: { type: "number", instructions: "Invoice total", unit: "EUR" },
411
429
  due: { type: "date", instructions: "Payment due date" },
412
430
  people: { type: "estimate", instructions: "How many people attended?", range: [0, 60], step: 1, unit: "people" },
431
+ },
432
+ });
433
+
434
+ classify({
435
+ state: "Invoice total: 1234.50 EUR, due 03/04/2026.",
436
+ questions: {
413
437
  topics: { type: "multi_choice", instructions: "Which topics apply?", criteria: { billing: "Charges", delivery: "Shipping" } },
414
438
  },
415
439
  });
416
440
  ```
417
441
 
418
- `text` returns a typed value. `number` and `date` preserve a present-but-unparseable value as `value: null` or `date: null`, together with the provider's `found`, `text` and `span` metadata; this is different from a field that was not found at all. `spans` and `boxes` return provider slot semantics: `presence` gives each slot's probability, `spans`/`boxes` retain slots at or above 0.5, and `atLeast: true` means more matches may exist. `estimate` returns `{ value, interval, unit? }`; request ranges and returned intervals may be negative or fractional. Multi-select answers use `choices` plus independent per-label probabilities that do **not** sum to one.
442
+ Each `classify_extract` answer uses the extraction shape: `{ type, value, ...metadata }`. `text` puts the read string in `value`. `number` and `date` keep a present-but-unparseable value as `value: null`, together with the provider's `found`, `text` and `span` metadata; this is different from a value that was not found at all. `spans` and `boxes` put the matched passage texts or box edges in `value` and return provider slot semantics separately: `presence` gives each slot's probability, `spans`/`boxes` retain slots at or above 0.5, and `atLeast: true` means more matches may exist. `box` returns one normalized box with `confidence`. `estimate` returns `value` with an `interval` and optional `unit`; request ranges and returned intervals may be negative or fractional. Multi-select answers stay in `classify` and use `choices` plus independent per-label probabilities that do **not** sum to one.
419
443
 
420
- Liquid images are top-level `{ content_type, base64 }` entries, not Jev assets. The package validates local PNG/JPEG/WebP files and allows eight images, each within 10,000 32×32 patches and a 100:1 aspect ratio. Audio is sent in a top-level `audio` array as WAV, MP3, FLAC or OGG; up to eight clips and 300 seconds total are documented by Liquid. Video is not documented for Liquid and is rejected locally. Codec compatibility and clip duration remain provider-owned; the package validates container bytes and transport size, not decoded audio length.
444
+ Liquid images are top-level `{ content_type, base64 }` entries, not Jev assets. The package validates local PNG/JPEG/WebP files and allows eight images, each within 10,000 32×32 patches and a 100:1 aspect ratio. Liquid documents exactly one image for `box` and `boxes` questions, so those reads are rejected locally unless exactly one image is supplied; other reads keep the eight-image limit. Reads and spans point into the state text; a value that appears only in an image is not found, so send the document's text or OCR text as `state`. Audio is sent in a top-level `audio` array as WAV, MP3, FLAC or OGG; up to eight clips and 300 seconds total are documented by Liquid. Video is not documented for Liquid and is rejected locally. Codec compatibility and clip duration remain provider-owned; the package validates container bytes and transport size, not decoded audio length.
421
445
 
422
446
  ## Clef-omni media
423
447
 
@@ -436,9 +460,14 @@ classify({
436
460
 
437
461
  Local audio may be WAV, MP3, FLAC or OGG; local video may be MP4 or WebM. Container bytes must match. The documented provider maxima are four audio clips of 8 MiB and 300 seconds each, and two videos of 16 MiB and 60 seconds each with at most 16 MiB combined audio/video. Existing package request and image limits still apply. Duration and codec compatibility are enforced by the provider, not by the package. Media on other Cloudflare models is rejected locally instead of being silently dropped.
438
462
 
439
- ## Cloudflare Clairic extraction
463
+ ## Extraction: `classify_extract`
464
+
465
+ Use **`classify_extract`** for every read; it never makes a classification decision. It selects the configured default route and accepts exactly one of two request shapes:
440
466
 
441
- Use **`classify_extract`** for structured extraction. It selects the configured default route and sends `fields`, not classifier questions; use `clairic-api`, `openrouter-extractions-api` or `litellm-extraction-api` as the default. The library exports `extract(params, { settings, cwd, signal? })`.
467
+ - `fields` sends Clairic-shaped field specifications to `clairic-api`, `openrouter-extractions-api` or `litellm-extraction-api`.
468
+ - `questions` sends typed extraction questions (`text`, `number`, `date`, `spans`, `box`, `boxes`, `locate`, `estimate` and Inception `extract`) to the configured decision route. This is how direct `liquid-api` `d1.2` and `d1.2-ultra` reads are reached, and it keeps Jev box, Perplexity locate and Inception extract reachable now that `classify` answers classification decisions only.
469
+
470
+ Route capability checks do not change with the tool. A route that never supported a read still rejects it locally, extraction-field routes reject typed questions, and a `bool`, `choice`, `multi_choice` or `score` question sent to `classify_extract` is rejected with a pointer to `classify`. The library exports `extract(params, { settings, cwd, signal? })`.
442
471
 
443
472
  ```js
444
473
  classify_extract({
@@ -456,6 +485,26 @@ Clairic field types are `text`, `number`, `compute`, `date`, `time`, `datetime`,
456
485
 
457
486
  Caller options use `includeQuantiles` and `returnStateText`; adapters send the documented snake_case wire keys. Direct Clairic accepts PNG/JPEG/WebP images and PDF documents as local files, with optional clockwise `rotation: 0 | 90 | 180 | 270` on an image descriptor. It allows at most four rendered images/PDF pages combined, 4 MiB per file and 8 MiB combined decoded media. OpenRouter Extractions uses `assets` instead, does not accept PDFs on the Clairic model, and enforces per-model field tiers and keys from its native schema. Liquid images require estimate-only fields with text list items; ScaleDown accepts one PDF or image and no simultaneous text state; LiteLLM `/v1/extraction` supports Clairic-shaped fields and images but not PDFs. Remote URLs and encrypted PDFs are rejected. Exact PDF page rendering and character-offset units remain provider-owned. Current direct Clairic pricing is $0.10 per million input tokens until 2026-12-01 and $0.24 afterward; output generation is not charged separately. Configure an explicit `pricing` override if your account has different rates.
458
487
 
488
+ ### Typed extraction questions
489
+
490
+ `questions` uses the same question objects previously accepted by `classify`, the same route capability checks, the same default-then-fallback policy, and the same usage/cost reporting. It returns extraction answers instead of decision answers:
491
+
492
+ ```js
493
+ classify_extract({
494
+ questions: {
495
+ total: { type: "number", instructions: "Invoice total", unit: "EUR" },
496
+ vendors: { type: "spans", instructions: "Every vendor name", max: 8 },
497
+ logo: { type: "box", instructions: "Locate the vendor logo on the attached page" },
498
+ },
499
+ state: "Invoice total: 1234.50 EUR. Vendor: Brew Co.",
500
+ images: ["invoice.png"],
501
+ });
502
+ ```
503
+
504
+ Every answer is `{ type, value, ...metadata }`, where `value` is the read itself and metadata is provider-reported: `span`, `found`, `path`, `unit`, `text`, `interval`, `confidence`, `presence`, `count`, `atLeast`, `spans`, `boxes` or `notStated` as applicable. `refusal`, `no_match` and `ambiguous` are explicit `type` values with `value: null`. `truncated` is always `false` here because typed reads validate values instead of generating fields. `citations`, `webGrounding` and `attemptedRoutes` appear when the answering route provides them.
505
+
506
+ Question mode accepts local path strings or named `{id, path}`/`{id, url}` images referenced with `{$image:id}`, media on routes that document it, and `mode: "web_grounding"` for Perplexity locate. Field mode keeps its local-path/`rotation` image contract. `documents`, `referenceDate` and `options` are field-mode only, and both modes are rejected together in one request.
507
+
459
508
  ## Microsoft Decision-1 on Foundry
460
509
 
461
510
  Deploy `Microsoft-Decision-1` in Microsoft Foundry, then configure the **resource endpoint**, API key, and actual **deployment name**:
@@ -530,7 +579,7 @@ The library exports `compareClassifiers(params, { settings, cwd, signal? })`. Ne
530
579
 
531
580
  Pass `images: ["photo.png"]`. Images are attached in order alongside state. OpenAI, Perplexity and Clef/Clef Flash support images. Cloudflare-hosted Jev and the built-in OpenRouter route are text-only in this package.
532
581
 
533
- Local image inputs are non-animated PNG/JPEG/WebP regular files inside the session cwd, with no symlink components or inline base64. Safe descriptor-based loading supports macOS (requires the OS `/usr/sbin/lsof`) and Linux (`/proc`). Images are fully decoded locally before upload. Per-route image limits come from the published contracts: eight on Perplexity and hosted Liquid, four on Clef and Clef-omni, eight on Microsoft per question, 16 on Inception and Mercury/Baseten OpenRouter adapters, 100 on HeyGen, 128 on GPT-6 Luna Decisions, and 128 as the package envelope. Each existing route keeps its documented byte and patch constraints; images are not silently resized. Text/JSON plus questions remain limited to 2 MiB, while the question count uses the documented envelope and each route's lower limit.
582
+ Local image inputs are non-animated PNG/JPEG/WebP regular files inside the session cwd, with no symlink components or inline base64. Safe descriptor-based loading supports macOS (requires the OS `/usr/sbin/lsof`) and Linux (`/proc`). Images are fully decoded locally before upload. Per-route image limits come from the published contracts: eight on Perplexity and hosted Liquid, four on Clef and Clef-omni, four on SubQ Snap (4 MiB each, 8 MiB combined), eight on Microsoft per question, 16 on Inception and Mercury/Baseten OpenRouter adapters, 16 on Alibaba Decision Model, 100 on HeyGen, 128 on GPT-6 Luna Decisions, and 128 as the package envelope. Each existing route keeps its documented byte and patch constraints; images are not silently resized. Text/JSON plus questions remain limited to 2 MiB, while the question count uses the documented envelope and each route's lower limit.
534
583
 
535
584
  Named hosted URLs on OpenAI and on OpenRouter's documented Gemini/HeyGen Decisions models do not require local file loading. They are passed directly to the selected endpoint, never downloaded by this package; OpenRouter adapters place them in top-level `state` image parts and reject other placements. The provider must be able to access them and enforces remote image format/size limits; local byte/pixel validation cannot inspect them. URLs must use HTTP(S), with no credentials or fragment. Do not send sensitive URLs unless you intend to share them with that endpoint.
536
585
 
@@ -551,7 +600,7 @@ TypeSafe Jev images are experimental and require opt-in. Use PNG/JPEG. Each side
551
600
  }
552
601
  ```
553
602
 
554
- With an image, a question such as `{ "type": "box", "instructions": "Find the mug in the first image." }` returns normalized `top`, `bottom`, `left`, `right` edges and confidence. Box needs Jev 1.14 (`jev-preview` or `jev-1.14.0`) and both opt-ins. It is not production-grade localization. A box does not mean the object exists: pair it with a bool existence question when necessary.
603
+ With an image, `classify_extract({ state, images: ["scene.png"], questions: { target: { "type": "box", "instructions": "Find the mug in the first image." } } })` returns normalized `top`, `bottom`, `left`, `right` edges and confidence as `{ type: "box", value: { top, bottom, left, right }, confidence }`. Box needs Jev 1.14 (`jev-preview` or `jev-1.14.0`) and both opt-ins. It is not production-grade localization. A box does not mean the object exists: pair it with a bool existence question sent through `classify` when necessary.
555
604
 
556
605
  ### Named images and composable image content
557
606
 
@@ -623,7 +672,7 @@ Clef-omni's official input schema establishes the hosted video contract used her
623
672
 
624
673
  ## Custom providers
625
674
 
626
- Like image-gen, `customProviders` adds a named endpoint and explicit model list. Supported protocols are `openai-decisions`, `openrouter-decisions`, `gemini-decisions`, `inception-decisions`, `parallel-decisions`, `local-system-one`, `perplexity-decisions`, `sarvam-system-one`, `system-one`, `liquid-system-one`, `cloudflare-system-one`, `cloudflare-clairic`, `openrouter-extractions`, `litellm-extraction`, and `microsoft-system-one` (Foundry resource root and API-key or Entra bearer authentication). A custom URL cannot make an arbitrary API compatible. Custom IDs must not shadow built-in provider/route IDs.
675
+ Like image-gen, `customProviders` adds a named endpoint and explicit model list. Supported protocols are `openai-decisions`, `openrouter-decisions`, `gemini-decisions`, `inception-decisions`, `parallel-decisions`, `local-system-one`, `perplexity-decisions`, `sarvam-system-one`, `system-one`, `liquid-system-one`, `cloudflare-system-one`, `cloudflare-clairic`, `openrouter-extractions`, `litellm-extraction`, and `microsoft-system-one` (Foundry resource root and API-key or Entra bearer authentication); `subq-system-one`, `alibaba-system-one` and `fireworks-system-one` exist for custom endpoints that reproduce those verified wire contracts. A custom URL cannot make an arbitrary API compatible. Custom IDs must not shadow built-in provider/route IDs.
627
676
 
628
677
  ```json
629
678
  {
@@ -646,19 +695,30 @@ Custom endpoints use their route ID as the Pi stored-credential provider ID. The
646
695
 
647
696
  ### LiteLLM decision gateways
648
697
 
649
- LiteLLM documents both `POST /v1/decisions` and `POST /v1/systemone` with bearer virtual keys. Add the decision model to LiteLLM's `model_list`, then configure either protocol explicitly:
698
+ LiteLLM serves decision models on `POST /v1/decisions` (OpenAI shape) and `POST /v1/systemone` (System One shape) with normal proxy virtual-key auth. Add the decision model to `model_list`; the client sends that deployment's `model_name` alias and LiteLLM resolves it to `litellm_params.model`. Aliases are operator-defined, so this package does not treat a backend model id as a universal alias.
699
+
700
+ The built-in `litellm-decisions-api` route uses the OpenAI Decisions wire against `/v1/decisions`. It requires `providers.litellm.baseUrl` (for example `https://litellm.example/v1`) and `LITELLM_API_KEY` or a stored `litellm` credential. The `luna` entry in `/classifier list` is LiteLLM's own documentation example; select any `model_name` from your proxy without a package release:
650
701
 
651
702
  ```json
652
703
  {
653
704
  "pi-classifier": {
654
- "default": { "provider": "litellm-decisions", "model": "luna" },
705
+ "default": { "provider": "litellm-decisions-api", "model": "my-decision-alias" }
706
+ }
707
+ }
708
+ ```
709
+
710
+ LiteLLM returns spend in `x-litellm-response-cost`, which is reported as `providerCost`; the token estimate is not replaced. LiteLLM validates 1–128 questions on both routes and 2–255 choice options on `/v1/decisions` before calling a provider, so the built-in route encodes 128 questions and 255 choices. Text-only payloads work on both routes. Image input depends on the selected upstream model and release, so the built-in route lists only a text model; declare images through a `customProviders` route for a model you have verified. The route uses the OpenAI Decisions wire, so OpenAI-only controls (`promptCache`, `conversation`, `imageDetail`) are forwarded as-is; a routed upstream that does not implement them may reject the request. For `/v1/systemone`, use `api: "system-one"` with the same base URL:
711
+
712
+ ```json
713
+ {
714
+ "pi-classifier": {
715
+ "default": { "provider": "litellm-systemone", "model": "my-decision-alias" },
655
716
  "customProviders": {
656
- "litellm-decisions": {
657
- "api": "openai-decisions",
717
+ "litellm-systemone": {
718
+ "api": "system-one",
658
719
  "baseUrl": "https://litellm.example/v1",
659
- "apiKey": "${LITELLM_VIRTUAL_KEY}",
660
- "models": [{ "id": "luna", "input": ["text"] }],
661
- "pricing": { "luna": { "inputPerMillion": 0.042, "outputPerMillion": 0 } },
720
+ "apiKey": "${LITELLM_API_KEY}",
721
+ "models": [{ "id": "my-decision-alias", "input": ["text"] }],
662
722
  "maxChoices": 255
663
723
  }
664
724
  }
@@ -666,7 +726,7 @@ LiteLLM documents both `POST /v1/decisions` and `POST /v1/systemone` with bearer
666
726
  }
667
727
  ```
668
728
 
669
- Because `litellm-decisions` is not a built-in route, it must be declared under `customProviders`; an unknown ID placed under `providers` is rejected. Use `"api": "system-one"` with `baseUrl: "https://litellm.example/v1"` to call `/v1/systemone` instead. The price above is illustrative; set it from your actual LiteLLM pricing. `maxChoices` must match the deployment's verified decision limit before choice batching. Text-only payloads fit both routes; LiteLLM image support depends on the selected upstream model and release, so declare image input only for a model you have verified. Custom gateways do not inherit bundled upstream prices.
729
+ Set `maxChoices` from the deployment's verified limit before choice batching. Custom gateways do not inherit bundled upstream prices; set `pricing` from your actual LiteLLM rates.
670
730
 
671
731
  ### OpenRouter pricing and choice limits
672
732
 
@@ -688,6 +748,31 @@ The built-in `openrouter-api` route targets the documented `POST /api/v1/systemo
688
748
 
689
749
  The legacy `openrouter-api` System One route remains text-only in this package. Use `openrouter-decisions-api` for `POST /api/alpha/decisions` and `openrouter-extractions-api` for `POST /api/alpha/extractions`. Both are alpha contracts: media placement, question support and extraction field tiers are selected by model/provider capability registries, and `usage.cost` is reported as `providerCost` without being substituted for the token estimate.
690
750
 
751
+ ### Hosted Laya (layahost and Berget AI)
752
+
753
+ The built-in `laya-api` route is a `local-system-one` transport that requires `baseUrl`; it always sends `model` and posts `v1/systemone`, so both hosts work by configuration:
754
+
755
+ | Host | `baseUrl` | Documented model ids | Credential |
756
+ | --- | --- | --- | --- |
757
+ | layahost | `https://layahost.com` | `laya-auto`, `laya-english`, `laya-multilingual`, `jev-latest` alias; hosted `clef`, `clef-flash` | `LAYAHOST_API_KEY` |
758
+ | Berget AI | `https://api.berget.ai` | `convaiinnovations/laya` (aliases `systemone-laya`, `laya-latest`), `Qwen/Qwen3.5-2B` (alias `systemone`), `Cloudflare/clef-flash` | Berget API key |
759
+
760
+ ```json
761
+ {
762
+ "pi-classifier": {
763
+ "default": { "provider": "laya-api", "model": "laya-auto" },
764
+ "providers": {
765
+ "laya": {
766
+ "baseUrl": "https://layahost.com",
767
+ "apiKey": "${LAYAHOST_API_KEY}"
768
+ }
769
+ }
770
+ }
771
+ }
772
+ ```
773
+
774
+ The route sends `model`, `state`, and `noul`/`choice`/`score` questions, and accepts text/JSON only. layahost's Laya checkpoints read about 1,024 tokens per request and truncate longer text, so put the material that matters first; its hosted Clef models read 64K. Berget lists its System One models as evaluation/preview. Neither host's prices are bundled; configure `pricing` or treat cost as unknown.
775
+
691
776
  ## Native Durable entrypoint (`/durable`)
692
777
 
693
778
  `@abhishek944/pi-classifier/durable` exposes `createClassifierExtension(settings, options?)`, a settings-only native Durable extension named `classifier` with `classify`, `classify_compare`, `classify_tree`, `classify_extract`, and `classifier_box_image`. Tool names, descriptions, and parameter/result schemas are shared with the desktop extension through `src/tool-contracts.ts`, so the two surfaces cannot drift. Desktop-only registration fields (labels, prompt guidance, annotations) stay with the desktop extension.
@@ -746,19 +831,19 @@ No provider calls are made by these commands. Live tests belong to the user:
746
831
 
747
832
  1. Keep Codex logged in and configure an OpenAI API key. Select `openai-api/gpt-6-luna`, classify one bool, and verify chat login did not change.
748
833
  2. Select each provider and ask bool/choice/score questions; check probabilities, selected model and usage.
749
- 3. Try a small PNG on OpenAI, Perplexity and Clef. Enable Jev images explicitly before trying its preview; verify box coordinates separately.
834
+ 3. Try a small PNG on OpenAI, Perplexity and Clef. Enable Jev images explicitly before trying its preview; verify box coordinates separately with `classify_extract`.
750
835
  4. Cancel an in-flight call and check a deliberately invalid model/key. Errors must be safe; only missing keys and HTTP 401/404/429 may select an explicitly configured fallback. Timeout/network/403/5xx/malformed results must not trigger another route.
751
836
  5. Use `/classifier use` in a trusted project and confirm unrelated settings and both route lists remain intact. Check legacy-only defaults as well as nested defaults.
752
837
  6. Configure your Foundry endpoint and deployment name, select `microsoft-api`, and verify bool/choice/score responses and token usage. Verify that a PNG image is sent through `assets` and that box is rejected locally; repeat with an Entra bearer token only when you own one.
753
838
  7. Configure two `compare` pairs and explicitly invoke `classify_compare`; confirm labeled successes/errors, duration, unchanged defaults, and that cancellation prevents subsequent calls. Each valid entry may be billed.
754
839
  8. In your own controlled deployment, verify missing keys and HTTP 401/404/429 allow only configured fallbacks; duplicate routes are never called twice. Verify low confidence and refusals return normally without switching models.
755
- 9. On Jev, enable the image/box flags and try the named scene/reference example above. Compare visual choice/score criteria, then a box plus a separate existence question. Verify repeated references and choice batching do not leave unreferenced assets. Try a 279-pixel side and confirm local rejection.
840
+ 9. On Jev, enable the image/box flags and try the named scene/reference example above. Compare visual choice/score criteria, then a box through `classify_extract` plus a separate existence bool through `classify`. Verify repeated references and choice batching do not leave unreferenced assets. Try a 279-pixel side and confirm local rejection.
756
841
  10. On OpenAI, try one shared named local image plus a question-specific local image, then replace the latter with a public HTTPS descriptor. Confirm references stay in their intended placements. On Perplexity, try named state references and eight small images; instruction/criterion images should fail locally.
757
- 11. Invoke `classifier_box_image` with the exact local scene and a returned box in both overlay and crop modes. Confirm pixel bounds and orientation visually, no files are written, invalid/reversed edges are rejected, and cancellation interrupts processing. Check EXIF-oriented photos carefully: no automatic rotation is applied.
758
- 12. On Perplexity v1.3, verify locate spans against the original text, then run a small web-grounded bool and inspect `search_results`, `fetched_results` and the non-token fee accounting. Do not enable grounding for sensitive state.
759
- 13. On Liquid d1.2, verify a typed read, a ranged estimate, a multi-select choice, one image and one audio clip. Confirm that unparseable values become `no_match` rather than converted guesses.
842
+ 11. Invoke `classifier_box_image` with the exact local scene and a box returned by `classify_extract` in both overlay and crop modes. Confirm pixel bounds and orientation visually, no files are written, invalid/reversed edges are rejected, and cancellation interrupts processing. Check EXIF-oriented photos carefully: no automatic rotation is applied.
843
+ 12. On Perplexity v1.3, verify `locate` spans through `classify_extract` against the original text, then run a small web-grounded bool through `classify` and inspect `search_results`, `fetched_results` and the non-token fee accounting. Do not enable grounding for sensitive state.
844
+ 13. On Liquid d1.2, verify a typed read, a ranged estimate and a box through `classify_extract`, then a multi-select choice, one image and one audio clip through `classify`. Confirm that unparseable number/date values stay `value: null` with their `text`, `span` and `found` metadata instead of becoming converted guesses, and that a value missing from `state` is reported as not found.
760
845
  14. On Clef-omni, verify text, one image, one audio clip and one video in one request, then confirm unsupported media on Clef Flash fails locally. On Clairic, verify a field contract with grounding metadata and `truncated` reporting.
761
846
 
762
847
  Provider schemas and previews can change; no live entitlement or model-accuracy claim is made by a local build.
763
848
 
764
- Sources: [Microsoft Decision-1.1](https://learn.microsoft.com/en-us/azure/foundry/foundry-models/how-to/use-foundry-models-microsoft-decision), [OpenAI Decisions](https://developers.openai.com/api/docs/guides/decisions), [OpenRouter Decisions](https://openrouter.ai/docs/guides/features/decisions), [OpenRouter multimodal contracts](https://openrouter.ai/docs/guides/community/multimodal-decisions), [OpenRouter Extractions](https://openrouter.ai/docs/guides/community/extractions), [Vercel Decisions](https://vercel.com/docs/ai-gateway/sdks-and-apis/openai-decisions), [Gemini Decisions API](https://aistudio.google.com/docs/decisions-api), [Inception Decisions](https://docs.inceptionlabs.ai/capabilities/decisions), [Parallel Decisions](https://docs.parallel.ai/decisions/decisions-quickstart), [Perplexity Decisions](https://docs.perplexity.ai/docs/decisions/decisions), [Sarvam Decisions](https://docs.sarvam.ai/api-reference/decisions/systemone), [TypeSafe images](https://docs.typesafe.ai/images), [TypeSafe box](https://docs.typesafe.ai/primitives/box), [Liquid decisions](https://docs.liquid.ai/api/guides/decisions), [Liquid open weights](https://docs.liquid.ai/lfm/models/decision-models), [Cloudflare Clef](https://developers.cloudflare.com/workers-ai/models/clef/), [Cloudflare Clairic](https://developers.cloudflare.com/workers-ai/models/clairic/), [LiteLLM decisions](https://docs.litellm.ai/docs/decisions), [LiteLLM extraction](https://docs.litellm.ai/docs/extraction), [Cloudflare AI Gateway REST API](https://developers.cloudflare.com/ai-gateway/usage/rest-api/).
849
+ Sources: [Microsoft Decision-1.1](https://learn.microsoft.com/en-us/azure/foundry/foundry-models/how-to/use-foundry-models-microsoft-decision), [OpenAI Decisions](https://developers.openai.com/api/docs/guides/decisions), [OpenRouter Decisions](https://openrouter.ai/docs/guides/features/decisions), [OpenRouter multimodal contracts](https://openrouter.ai/docs/guides/community/multimodal-decisions), [OpenRouter Extractions](https://openrouter.ai/docs/guides/community/extractions), [Vercel Decisions](https://vercel.com/docs/ai-gateway/sdks-and-apis/openai-decisions), [Gemini Decisions API](https://aistudio.google.com/docs/decisions-api), [Inception Decisions](https://docs.inceptionlabs.ai/capabilities/decisions), [Inception wind-down](https://docs.inceptionlabs.ai/support/wind-down), [Parallel Decisions](https://docs.parallel.ai/decisions/decisions-quickstart), [Perplexity Decisions](https://docs.perplexity.ai/docs/decisions/decisions), [Sarvam Decisions](https://docs.sarvam.ai/api-reference/decisions/systemone), [TypeSafe images](https://docs.typesafe.ai/images), [TypeSafe box](https://docs.typesafe.ai/primitives/box), [Liquid decisions](https://docs.liquid.ai/api/guides/decisions), [Liquid open weights](https://docs.liquid.ai/lfm/models/decision-models), [Cloudflare Clef](https://developers.cloudflare.com/workers-ai/models/clef/), [Cloudflare Clairic](https://developers.cloudflare.com/workers-ai/models/clairic/), [LiteLLM decisions](https://docs.litellm.ai/docs/decisions), [LiteLLM extraction](https://docs.litellm.ai/docs/extraction), [SubQ Decisions API](https://docs.subq.ai/endpoints/decisions-api), [SubQ models and pricing](https://docs.subq.ai/using-the-api/models), [SubQ rate limits](https://docs.subq.ai/using-the-api/rate-limits), [Alibaba Decision Model API](https://www.alibabacloud.com/help/en/model-studio/decision-model-api), [Fireworks System One](https://docs.fireworks.ai/api-reference/post-systemone), [layahost docs](https://layahost.com/docs), [Berget System One](https://berget.ai/en/blog/systemone-launch), [Cloudflare AI Gateway REST API](https://developers.cloudflare.com/ai-gateway/usage/rest-api/).
package/dist/choices.js CHANGED
@@ -69,7 +69,7 @@ export async function executeChoices(input, route, policy, call, signal) {
69
69
  if (signal?.aborted)
70
70
  throw new ClassifierError("aborted", "Classification was cancelled.");
71
71
  const questions = Object.create(null);
72
- // A bool/score/box is evaluated once, not charged again for later choice batches.
72
+ // A bool/score is evaluated once, not charged again for later choice batches.
73
73
  if (calls === 0) {
74
74
  for (const [id, question] of Object.entries(input.questions))
75
75
  if (question.type !== "choice")
@@ -1,6 +1,6 @@
1
1
  import { type CredentialSource } from "./auth.js";
2
2
  import { type MemoryImage } from "./inputs.js";
3
- import { type ClassifierComparisonResult, type ClassifierResult, type ClassifierSettings } from "./types.js";
3
+ import { type ClassifierComparisonResult, type ClassifierResult, type ClassifierSettings, type DecisionInput, type PreparedInput, type ResolvedModel } from "./types.js";
4
4
  export type ClassifyOptions = {
5
5
  settings: ClassifierSettings;
6
6
  cwd: string;
@@ -10,6 +10,14 @@ export type ClassifyOptions = {
10
10
  /** Trusted programmatic ingress; all bytes still pass normal image validation. */
11
11
  memoryImages?: readonly MemoryImage[];
12
12
  };
13
+ /**
14
+ * Shared default-then-configured-fallback orchestration for typed-question requests. Classification
15
+ * and typed extraction both use it so a moved question keeps the same route behavior.
16
+ */
17
+ export declare function runDecisionRequest(input: DecisionInput, options: ClassifyOptions, execute: (prepared: PreparedInput, route: ResolvedModel, apiKey: string) => Promise<ClassifierResult>): Promise<{
18
+ result: ClassifierResult;
19
+ route: ResolvedModel;
20
+ }>;
13
21
  /** Default plus explicitly configured, selective fallback. Never retries a route. */
14
22
  export declare function classify(params: unknown, options: ClassifyOptions): Promise<ClassifierResult>;
15
23
  /** Explicit comparisons only: configured entries, no default substitution or fallback. */
package/dist/classify.js CHANGED
@@ -16,25 +16,29 @@ function routeKey(route) {
16
16
  function routePair(route) {
17
17
  return { provider: route.route, model: route.model };
18
18
  }
19
+ async function decideWithRoute(prepared, route, apiKey, options) {
20
+ const result = await executeChoices(prepared, route, choicePolicy(options.settings), (questions) => classifyWithProvider(route, { ...prepared, questions }, apiKey, options.signal), options.signal);
21
+ if (Buffer.byteLength(JSON.stringify(result, null, 2)) > 40 * 1024)
22
+ throw new ClassifierError("response", "Classifier result exceeds the 40 KiB tool output limit. Ask fewer questions.");
23
+ return result;
24
+ }
19
25
  async function classifyOnce(input, route, options) {
20
26
  checkCancelled(options.signal);
21
27
  const prepared = await prepareInput(input, route, options.cwd, options.signal, options.memoryImages);
22
28
  checkCancelled(options.signal);
23
29
  const key = resolveApiKey(route, options.credentialSource ?? "pi-store");
24
- const result = await executeChoices(prepared, route, choicePolicy(options.settings), (questions) => classifyWithProvider(route, { ...prepared, questions }, key, options.signal), options.signal);
25
- if (Buffer.byteLength(JSON.stringify(result, null, 2)) > 40 * 1024)
26
- throw new ClassifierError("response", "Classifier result exceeds the 40 KiB tool output limit. Ask fewer questions.");
27
- return result;
30
+ return decideWithRoute(prepared, route, key, options);
28
31
  }
29
32
  function permitsFallback(error) {
30
33
  return (error instanceof ClassifierError &&
31
34
  (error.code === "missing_credentials" ||
32
35
  (error.code === "http" && [401, 404, 429].includes(error.httpStatus ?? 0))));
33
36
  }
34
- /** Default plus explicitly configured, selective fallback. Never retries a route. */
35
- export async function classify(params, options) {
36
- choicePolicy(options.settings);
37
- const input = validateParams(params);
37
+ /**
38
+ * Shared default-then-configured-fallback orchestration for typed-question requests. Classification
39
+ * and typed extraction both use it so a moved question keeps the same route behavior.
40
+ */
41
+ export async function runDecisionRequest(input, options, execute) {
38
42
  const candidates = [
39
43
  configuredDefault(options.settings),
40
44
  ...configuredRoutes(options.settings, "fallback"),
@@ -51,10 +55,13 @@ export async function classify(params, options) {
51
55
  seen.add(key);
52
56
  attemptedRoutes.push(routePair(route));
53
57
  try {
54
- const result = await classifyOnce(input, route, options);
58
+ const prepared = await prepareInput(input, route, options.cwd, options.signal, options.memoryImages);
59
+ checkCancelled(options.signal);
60
+ const apiKey = resolveApiKey(route, options.credentialSource ?? "pi-store");
61
+ const result = await execute(prepared, route, apiKey);
55
62
  if (attemptedRoutes.length > 1)
56
63
  result.attemptedRoutes = attemptedRoutes;
57
- return result;
64
+ return { result, route };
58
65
  }
59
66
  catch (error) {
60
67
  checkCancelled(options.signal);
@@ -65,6 +72,13 @@ export async function classify(params, options) {
65
72
  }
66
73
  throw lastError;
67
74
  }
75
+ /** Default plus explicitly configured, selective fallback. Never retries a route. */
76
+ export async function classify(params, options) {
77
+ choicePolicy(options.settings);
78
+ const input = validateParams(params);
79
+ const { result } = await runDecisionRequest(input, options, (prepared, route, apiKey) => decideWithRoute(prepared, route, apiKey, options));
80
+ return result;
81
+ }
68
82
  /** Explicit comparisons only: configured entries, no default substitution or fallback. */
69
83
  export async function compareClassifiers(params, options) {
70
84
  choicePolicy(options.settings);
package/dist/config.d.ts CHANGED
@@ -19,10 +19,15 @@ export declare const BUILT_INS: ({
19
19
  baseUrl: string;
20
20
  credentialProvider: string;
21
21
  envVar: string;
22
- models: {
22
+ models: ({
23
23
  id: string;
24
24
  input: ("text" | "image")[];
25
- }[];
25
+ shutdown?: never;
26
+ } | {
27
+ id: string;
28
+ input: "text"[];
29
+ shutdown: string;
30
+ })[];
26
31
  } | {
27
32
  id: string;
28
33
  route: string;
@@ -88,6 +93,7 @@ export declare const BUILT_INS: ({
88
93
  models: {
89
94
  id: string;
90
95
  input: ("text" | "image")[];
96
+ shutdown: string;
91
97
  }[];
92
98
  } | {
93
99
  id: string;
@@ -111,6 +117,39 @@ export declare const BUILT_INS: ({
111
117
  id: string;
112
118
  input: ("text" | "image")[];
113
119
  }[];
120
+ } | {
121
+ id: string;
122
+ route: string;
123
+ api: "subq-system-one";
124
+ baseUrl: string;
125
+ credentialProvider: string;
126
+ envVar: string;
127
+ models: {
128
+ id: string;
129
+ input: ("text" | "image")[];
130
+ }[];
131
+ } | {
132
+ id: string;
133
+ route: string;
134
+ api: "alibaba-system-one";
135
+ baseUrl: string;
136
+ credentialProvider: string;
137
+ envVar: string;
138
+ models: {
139
+ id: string;
140
+ input: ("text" | "image")[];
141
+ }[];
142
+ } | {
143
+ id: string;
144
+ route: string;
145
+ api: "fireworks-system-one";
146
+ baseUrl: string;
147
+ credentialProvider: string;
148
+ envVar: string;
149
+ models: {
150
+ id: string;
151
+ input: "text"[];
152
+ }[];
114
153
  } | {
115
154
  id: string;
116
155
  route: string;
@@ -185,10 +224,17 @@ export declare const BUILT_INS: ({
185
224
  id: string;
186
225
  input: ("text" | "image")[];
187
226
  box: true;
227
+ shutdown?: never;
188
228
  } | {
189
229
  id: string;
190
230
  input: ("audio" | "video" | "text" | "image")[];
191
231
  box?: never;
232
+ shutdown?: never;
233
+ } | {
234
+ id: string;
235
+ input: ("text" | "image")[];
236
+ shutdown: string;
237
+ box?: never;
192
238
  })[];
193
239
  })[];
194
240
  export type OpenRouterExtractionCapabilities = {