Open-source inference server and production cluster for all the models your agent needs.
Python bgecolbertdata-pipelinedeep-learningembeddingsinferenceinference-serverinformation-retrievalllmmlmlopsnatural-language-processingnlppythonrerankingretrievalretrieval-augmented-generationsemantic-searchspladevector-search
feat(sdk): add system_one to the Python and TypeScript clients
Rahul Parundekar85b72f86f727
diff --git a/packages/sie_sdk/src/sie_sdk/client/async_.py b/packages/sie_sdk/src/sie_sdk/client/async_.pyindex 75ddd09d7..b80ae5465 100644--- a/packages/sie_sdk/src/sie_sdk/client/async_.py+++ b/packages/sie_sdk/src/sie_sdk/client/async_.py@@ -57,6 +57,7 @@ from sie_sdk.jobs import (require_connection_schema_policy,require_connector_idempotency_key,)+from sie_sdk.systemone import SYSTEM_ONE_OPTIONS, system_one_request, system_one_resultfrom sie_sdk.types import (Batch,BatchList,@@ -70,6 +71,7 @@ from sie_sdk.types import (CostEstimate,EncodeResult,ExtractResult,+ SystemOneResult,File,FileDeleted,FileList,@@ -1728,6 +1730,66 @@ class SIEAsyncClient:return cast("Recommendation", response.json())+ async def system_one(+ self,+ model: str,+ state: str | Mapping[str, Any] | list[Any],+ questions: Mapping[str, Any],+ *,+ options: dict[str, Any] | None = None,+ gpu: str | None = None,+ wait_for_capacity: bool = True,+ provision_timeout_s: float | None = None,+ ) -> SystemOneResult:+ """Answer typed questions about one state (System One).++ Answers ``noul`` (yes/no), ``choice`` (pick one) and ``score``+ (ordinal) questions about a text, a JSON object, or a list of+ conversation turns with a decision model, in the response shape of+ SIE's System One-compatible ``POST /v1/systemone``. It runs as one+ ``extract`` call, so it waits for capacity and model loading like+ :meth:`extract`. A state or question set that does not fit the model's+ window raises instead of being truncated.++ Args:+ model: A decision model, e.g. ``"fastino/GLiNER2.5-Decide"``.+ state: The text to judge, a JSON object, or a list of turns.+ questions: Typed questions by id, ``{"type", "instructions"?,+ "criteria"?}``; a score question takes at most 10 levels.+ options: Runtime options, as for :meth:`extract`.+ gpu: Target GPU type, as for :meth:`extract`.+ wait_for_capacity: As for :meth:`extract`.+ provision_timeout_s: As for :meth:`extract`.++ Returns:+ ``{"model", "answers", "usage"}``, one answer per question id.++ Raises:+ RequestError: A malformed question or state, input that does not+ fit the model's window, or a model that does not answer typed+ questions. Otherwise as :meth:`extract`.++ Example:+ >>> result = await client.system_one(+ ... "fastino/GLiNER2.5-Decide",+ ... "I was charged twice. Please fix this ASAP.",+ ... {"spam": {"type": "noul", "instructions": "Is this spam?"}},+ ... )+ >>> sorted(result["answers"]["spam"])+ ['answer', 'confidence', 'noul', 'type']+ """+ item, output_schema = system_one_request(state, questions)+ result = await self.extract(+ model,+ item,+ output_schema=output_schema,+ options={**(options or {}), **SYSTEM_ONE_OPTIONS},+ gpu=gpu,+ wait_for_capacity=wait_for_capacity,+ provision_timeout_s=provision_timeout_s,+ )+ return system_one_result(model, result, output_schema)+async def estimate(self,endpoint: str,diff --git a/packages/sie_sdk/src/sie_sdk/client/sync.py b/packages/sie_sdk/src/sie_sdk/client/sync.pyindex 1d5b9293d..7be4bc3fc 100644--- a/packages/sie_sdk/src/sie_sdk/client/sync.py+++ b/packages/sie_sdk/src/sie_sdk/client/sync.py@@ -65,6 +65,7 @@ from sie_sdk.jobs import (require_connection_schema_policy,require_connector_idempotency_key,)+from sie_sdk.systemone import SYSTEM_ONE_OPTIONS, system_one_request, system_one_resultfrom sie_sdk.types import (Batch,BatchList,@@ -78,6 +79,7 @@ from sie_sdk.types import (CostEstimate,EncodeResult,ExtractResult,+ SystemOneResult,File,FileDeleted,FileList,@@ -1716,6 +1718,66 @@ class SIEClient:data = response.json()return data["models"]+ def system_one(+ self,+ model: str,+ state: str | Mapping[str, Any] | list[Any],+ questions: Mapping[str, Any],+ *,+ options: dict[str, Any] | None = None,+ gpu: str | None = None,+ wait_for_capacity: bool = True,+ provision_timeout_s: float | None = None,+ ) -> SystemOneResult:+ """Answer typed questions about one state (System One).++ Answers ``noul`` (yes/no), ``choice`` (pick one) and ``score``+ (ordinal) questions about a text, a JSON object, or a list of+ conversation turns with a decision model, in the response shape of+ SIE's System One-compatible ``POST /v1/systemone``. It runs as one+ ``extract`` call, so it waits for capacity and model loading like+ :meth:`extract`. A state or question set that does not fit the model's+ window raises instead of being truncated.++ Args:+ model: A decision model, e.g. ``"fastino/GLiNER2.5-Decide"``.+ state: The text to judge, a JSON object, or a list of turns.+ questions: Typed questions by id, ``{"type", "instructions"?,+ "criteria"?}``; a score question takes at most 10 levels.+ options: Runtime options, as for :meth:`extract`.+ gpu: Target GPU type, as for :meth:`extract`.+ wait_for_capacity: As for :meth:`extract`.+ provision_timeout_s: As for :meth:`extract`.++ Returns:+ ``{"model", "answers", "usage"}``, one answer per question id.++ Raises:+ RequestError: A malformed question or state, input that does not+ fit the model's window, or a model that does not answer typed+ questions. Otherwise as :meth:`extract`.++ Example:+ >>> result = client.system_one(+ ... "fastino/GLiNER2.5-Decide",+ ... "I was charged twice. Please fix this ASAP.",+ ... {"spam": {"type": "noul", "instructions": "Is this spam?"}},+ ... )+ >>> sorted(result["answers"]["spam"])+ ['answer', 'confidence', 'noul', 'type']+ """+ item, output_schema = system_one_request(state, questions)+ result = self.extract(+ model,+ item,+ output_schema=output_schema,+ options={**(options or {}), **SYSTEM_ONE_OPTIONS},+ gpu=gpu,+ wait_for_capacity=wait_for_capacity,+ provision_timeout_s=provision_timeout_s,+ )+ return system_one_result(model, result, output_schema)+def estimate(self,endpoint: str,diff --git a/packages/sie_sdk/src/sie_sdk/systemone.py b/packages/sie_sdk/src/sie_sdk/systemone.pynew file mode 100644index 000000000..85a1c410e--- /dev/null+++ b/packages/sie_sdk/src/sie_sdk/systemone.py@@ -0,0 +1,124 @@+"""System One typed decisions on top of ``extract``.++``SIEClient.system_one`` answers one state against typed ``noul``, ``choice``+and ``score`` questions with a decision model, and returns the System One+response shape (``{model, answers, usage}``) that SIE's ``POST /v1/systemone``+serves. It runs as an ``extract`` call, so it waits for capacity and model+loading like every other SDK call.+"""++from __future__ import annotations++from collections.abc import Mapping+from typing import Any++from sie_sdk.client.errors import RequestError+from sie_sdk.types import ExtractResult, Item, SystemOneResult++# Score levels per question, as the System One API accepts.+MAX_SCORE_LEVELS = 10++# Options every System One call sends: input that does not fit the model's row+# is refused instead of being cut.+SYSTEM_ONE_OPTIONS: dict[str, Any] = {"overflow_policy": "error"}+++def system_one_request(state: Any, questions: Mapping[str, Any]) -> tuple[Item, dict[str, Any]]:+ """The extract item and ``output_schema`` for a System One call.++ A string state is the item's text; an object or a list of turns rides in+ ``metadata.state``. A question may omit ``instructions``; a score question+ takes 1 to 10 levels, none of them ``None``.++ Raises:+ RequestError: The state or a question is malformed.+ """+ item: Item+ if isinstance(state, str):+ item = Item(text=state)+ elif isinstance(state, (Mapping, list)):+ item = Item(metadata={"state": state})+ else:+ raise RequestError("state must be a string, a mapping, or a list", code="INVALID_INPUT")+ if not isinstance(questions, Mapping) or not questions:+ raise RequestError("questions must be a non-empty mapping of questions by id", code="INVALID_INPUT")+ schema: dict[str, Any] = {}+ for qid, question in questions.items():+ if not isinstance(question, Mapping):+ raise RequestError(f"question {qid!r} must be a mapping", code="INVALID_INPUT")+ normalized = dict(question)+ if normalized.get("instructions") is None:+ normalized["instructions"] = ""+ levels = normalized.get("criteria")+ if normalized.get("type") == "score" and isinstance(levels, list):+ if len(levels) > MAX_SCORE_LEVELS:+ raise RequestError(+ f"score question {qid!r} has {len(levels)} levels; at most {MAX_SCORE_LEVELS} are allowed",+ code="INVALID_INPUT",+ )+ if any(level is None for level in levels):+ raise RequestError(f"score question {qid!r} has a None level", code="INVALID_INPUT")+ schema[str(qid)] = normalized+ return item, schema+++def choice_confidence(probabilities: list[float]) -> float:+ """System One choice confidence: ``(p_max - 1/n) / (1 - 1/n)``, within [0, 1]."""+ n = len(probabilities)+ if n <= 1:+ return 1.0+ floor = 1.0 / n+ return min(1.0, max(0.0, (max(probabilities) - floor) / (1.0 - floor)))+++def score_confidence(probabilities: list[float]) -> float:+ """System One score confidence: ``max(0, 1 - spread / even)``.++ ``spread`` is the expected distance from the most likely level and+ ``even`` that of a uniform distribution from the middle level.+ """+ n = len(probabilities)+ if n <= 1:+ return 1.0+ mode = max(range(n), key=lambda i: probabilities[i])+ spread = sum(p * abs(i - mode) for i, p in enumerate(probabilities))+ even = sum(abs(i - (n - 1) / 2) for i in range(n)) / n+ return min(1.0, max(0.0, 1.0 - spread / even))+++def _answer(answer: Mapping[str, Any]) -> dict[str, Any]:+ result = dict(answer)+ probabilities = result.get("probabilities")+ if result.get("type") == "choice" and isinstance(probabilities, Mapping):+ result["confidence"] = choice_confidence([float(p) for p in probabilities.values()])+ elif result.get("type") == "score" and isinstance(probabilities, Mapping):+ ordered = [float(probabilities[key]) for key in sorted(probabilities, key=lambda key: int(key))]+ result["confidence"] = score_confidence(ordered)+ return result+++def system_one_result(model: str, result: ExtractResult, questions: Mapping[str, Any]) -> SystemOneResult:+ """An extract result in the System One response shape.++ Raises:+ RequestError: The model refused the state (for example, it does not fit+ the model's window), or answered no question of the request.+ """+ error = result.get("error")+ if error:+ raise RequestError(error["message"], code=error["code"], status_code=422, param="state")+ data = result.get("data") or {}+ missing = [qid for qid in questions if not isinstance(data.get(qid), Mapping)]+ if missing:+ raise RequestError(+ f"model {model!r} returned no answer for questions {missing}; use a decision model "+ "such as fastino/GLiNER2.5-Decide",+ code="INVALID_RESPONSE",+ )+ usage = result.get("request", {}).get("usage", {})+ input_tokens = usage.get("input_tokens", 0)+ return {+ "model": model,+ "answers": {qid: _answer(data[qid]) for qid in questions},+ "usage": {"input_tokens": input_tokens if isinstance(input_tokens, int) else 0, "output_tokens": 0},+ }diff --git a/packages/sie_sdk/src/sie_sdk/types.py b/packages/sie_sdk/src/sie_sdk/types.pyindex b734115e8..f4aca4e1c 100644--- a/packages/sie_sdk/src/sie_sdk/types.py+++ b/packages/sie_sdk/src/sie_sdk/types.py@@ -428,6 +428,10 @@ class ModelInfo(TypedDict, total=False):dims: ModelDimsmax_sequence_length: int | Nonerevision: str | None+ description: str+ """One line about the model; ``""`` when the catalog sets none."""+ release_date: str+ """Release date of the served weights, ``YYYY-MM-DD``; ``""`` when the catalog sets none."""profiles: dict[str, ProfileInfo]"""Servable profiles keyed by name; address one as ``"model@profile"``."""@@ -598,6 +602,35 @@ class ExtractResult(TypedDict, total=False):request: RequestMetadata+class SystemOneUsage(TypedDict):+ """Tokens a System One call read. Decision models generate none.++ ``input_tokens`` is the metered count the response reported (SIE+ Serverless meters every request); ``0`` when the deployment reports no+ metering. ``POST /v1/systemone`` itself always returns the worker's count.+ """++ input_tokens: int+ output_tokens: int+++class SystemOneResult(TypedDict):+ """Answers to typed questions, in the System One response shape.++ Attributes:+ model: The decision model that answered.+ answers: One answer per question id. ``noul``: ``noul``, the+ probability of yes. ``choice``: ``choice``, ``confidence`` and+ ``probabilities`` by option. ``score``: ``score``, ``confidence``,+ and ``legend`` and ``probabilities`` by level index (``"0"``...).+ usage: Tokens the model read.+ """++ model: str+ answers: dict[str, dict[str, Any]]+ usage: SystemOneUsage++# Streaming generation result. Streaming happens inside the gateway/worker;# the SDK surfaces the aggregated outcome plus SIE-native timing metadata# (TTFT, TPOT, attempt_id). Future SDK additions may surface chunks as andiff --git a/packages/sie_sdk/tests/client/test_system_one.py b/packages/sie_sdk/tests/client/test_system_one.pynew file mode 100644index 000000000..8cf824ebf--- /dev/null+++ b/packages/sie_sdk/tests/client/test_system_one.py@@ -0,0 +1,130 @@+"""SIEClient.system_one: System One typed decisions over extract."""++import json+from pathlib import Path+from typing import Any+from unittest.mock import AsyncMock, MagicMock, patch++import msgpack+import pytest+from sie_sdk import SIEAsyncClient, SIEClient+from sie_sdk.client.async_ import _AioResponse+from sie_sdk.client.errors import RequestError+from sie_sdk.systemone import choice_confidence, score_confidence, system_one_request++FIXTURE = json.loads(+ (Path(__file__).resolve().parents[3] / "wire-fixtures" / "systemone.json").read_text(encoding="utf-8")+)+RESPONSE_CASE = FIXTURE["responses"][0]+MODEL = RESPONSE_CASE["model"]+QUESTIONS = {qid: {"type": "noul"} for qid in RESPONSE_CASE["questions"]}+++def _extract_response(item: dict[str, Any]) -> bytes:+ body = {"model": MODEL, "items": [item], "usage": {"input_tokens": RESPONSE_CASE["input_tokens"]}}+ return msgpack.packb(body, use_bin_type=True)+++def _answers_item() -> dict[str, Any]:+ return {"id": "item-0", "entities": [], "data": RESPONSE_CASE["data"]}+++def _assert_close(actual: Any, expected: Any) -> None:+ if isinstance(expected, dict):+ assert set(actual) == set(expected)+ for key, value in expected.items():+ _assert_close(actual[key], value)+ elif isinstance(expected, float):+ assert actual == pytest.approx(expected)+ else:+ assert actual == expected+++def test_sync_system_one_sends_one_strict_extract_item_and_reshapes_the_answers() -> None:+ response = MagicMock(status_code=200, content=_extract_response(_answers_item()), headers={})+ with patch("sie_sdk.client.sync.httpx.Client") as http_client:+ http_client.return_value.post.return_value = response+ client = SIEClient("http://localhost:8080")+ result = client.system_one(MODEL, "I was charged twice.", QUESTIONS)+ call = http_client.return_value.post.call_args+ client.close()++ assert call.args[0] == f"/v1/extract/{MODEL}"+ body = msgpack.unpackb(call.kwargs["content"], raw=False)+ assert body["items"] == [{"text": "I was charged twice."}]+ assert body["params"]["options"]["overflow_policy"] == "error"+ assert body["params"]["output_schema"] == {qid: {"type": "noul", "instructions": ""} for qid in QUESTIONS}+ expected = dict(RESPONSE_CASE["response"])+ # Usage is the metered count the response reports in its X-SIE-Units-*+ # headers; this response carries none.+ expected["usage"] = {"input_tokens": 0, "output_tokens": 0}+ _assert_close(result, expected)+++def test_system_one_reports_metered_input_tokens() -> None:+ response = MagicMock(+ status_code=200,+ content=_extract_response(_answers_item()),+ headers={"X-SIE-Units-Input-Tokens": "42"},+ )+ with patch("sie_sdk.client.sync.httpx.Client") as http_client:+ http_client.return_value.post.return_value = response+ client = SIEClient("http://localhost:8080")+ result = client.system_one(MODEL, "I was charged twice.", QUESTIONS)+ client.close()+ assert result["usage"] == {"input_tokens": 42, "output_tokens": 0}+++async def test_async_system_one_matches_sync() -> None:+ client = SIEAsyncClient("http://localhost:8080")+ post = AsyncMock(return_value=_AioResponse(200, _extract_response(_answers_item()), {}))+ with patch.object(client, "_post", post):+ result = await client.system_one(MODEL, {"subject": "refund"}, QUESTIONS)+ body = msgpack.unpackb(post.call_args.kwargs["data"], raw=False)+ assert body["items"] == [{"metadata": {"state": {"subject": "refund"}}}]+ assert result["answers"]["intent"]["confidence"] == pytest.approx(0.7)+ assert result["answers"]["urgency"]["confidence"] == pytest.approx(0.55)+++def test_state_that_does_not_fit_raises() -> None:+ item = {"id": "item-0", "entities": [], "data": {}, "error": {"code": "INPUT_TOO_LONG", "message": "does not fit"}}+ response = MagicMock(status_code=200, content=_extract_response(item), headers={})+ with patch("sie_sdk.client.sync.httpx.Client") as http_client:+ http_client.return_value.post.return_value = response+ client = SIEClient("http://localhost:8080")+ with pytest.raises(RequestError, match="does not fit") as raised:+ client.system_one(MODEL, "x" * 10, QUESTIONS)+ client.close()+ assert raised.value.code == "INPUT_TOO_LONG"++[email protected]("case", FIXTURE["requests"], ids=lambda case: case["name"])+def test_fixture_requests(case: dict[str, Any]) -> None:+ item, schema = system_one_request(case["request"]["state"], case["request"]["questions"])+ assert item == case["extract"]["item"]+ assert schema == case["extract"]["output_schema"]+++ "case",+ [+ case+ for case in FIXTURE["invalid_requests"]+ if case["name"].startswith(+ ("number", "boolean", "null", "empty q", "questions", "question", "eleven", "null score")+ )+ ],+ ids=lambda case: case["name"],+)+def test_fixture_invalid_requests(case: dict[str, Any]) -> None:+ request = case["request"]+ with pytest.raises(RequestError):+ system_one_request(request.get("state"), request.get("questions", {}))++[email protected]("kind", ["choice", "score"])+def test_fixture_confidence(kind: str) -> None:+ fn = choice_confidence if kind == "choice" else score_confidence+ for case in FIXTURE["confidence"][kind]:+ assert fn(case["probabilities"]) == pytest.approx(case["confidence"])diff --git a/packages/sie_ts_sdk/src/client.ts b/packages/sie_ts_sdk/src/client.tsindex 0efc219ee..23e7fd4bd 100644--- a/packages/sie_ts_sdk/src/client.ts+++ b/packages/sie_ts_sdk/src/client.ts@@ -110,6 +110,14 @@ import {} from "./jobs.js";import { packMessage, unpackMessage } from "./msgpack.js";import { parseSseStream } from "./sse.js";+import {+ SYSTEM_ONE_OPTIONS,+ type SystemOneOptions,+ type SystemOneResult,+ type SystemOneState,+ systemOneRequest,+ systemOneResult,+} from "./systemone.js";import type {AddConnectionOptions,Batch,@@ -177,7 +185,7 @@ type OpenAiCompatModelKeys = Partial<Record<"id" | "object" | "created" | "owned/*** Map a wire `/v1/models` entry to the client-facing shape.*- * Total by construction: every key except the three camelCase renames and the+ * Total by construction: every key except the four camelCase renames and the* OpenAI-compat keys flows through the rest spread, so a field added to the* endpoint reaches callers without a code change here — only `ModelInfo` and* `WireModelInfo` need to declare it. The previous hardcoded allowlist silently@@ -188,6 +196,7 @@ function toModelInfo(wire: WireModelInfo): ModelInfo {max_sequence_length,last_error,pending_generation,+ release_date,aliases,id: _id,object: _object,@@ -205,6 +214,7 @@ function toModelInfo(wire: WireModelInfo): ModelInfo {...(max_sequence_length !== undefined ? { maxSequenceLength: max_sequence_length } : {}),...(last_error !== undefined ? { lastError: last_error } : {}),...(pending_generation !== undefined ? { pendingGeneration: pending_generation } : {}),+ ...(release_date !== undefined ? { releaseDate: release_date } : {}),};}@@ -2105,6 +2115,43 @@ export class SIEClient {return result;}+ /**+ * Answer typed questions about one state (System One).+ *+ * Answers `noul` (yes/no), `choice` (pick one) and `score` (ordinal)+ * questions about a text, a JSON object, or a list of conversation turns with+ * a decision model, in the response shape of SIE's System One-compatible+ * `POST /v1/systemone`. It runs as one `extract` call, so it waits for+ * capacity and model loading like `extract`. A state or question set that+ * does not fit the model's window throws `RequestError` instead of being+ * truncated.+ *+ * @example+ * ```typescript+ * const result = await client.systemOne(+ * "fastino/GLiNER2.5-Decide",+ * "I was charged twice. Please fix this ASAP.",+ * { spam: { type: "noul", instructions: "Is this spam?" } },+ * );+ * console.log(result.answers.spam?.noul);+ * ```+ */+ async systemOne(+ model: string,+ state: SystemOneState,+ questions: Record<string, unknown>,+ options: SystemOneOptions = {},+ ): Promise<SystemOneResult> {+ const { item, outputSchema } = systemOneRequest(state, questions);+ const result = await this.extract(model, item, {+ outputSchema,+ gpu: options.gpu,+ waitForCapacity: options.waitForCapacity,+ adapterOptions: { ...(options.adapterOptions ?? {}), ...SYSTEM_ONE_OPTIONS },+ });+ return systemOneResult(model, result, outputSchema);+ }+/*** Extract entities or structured data from a single item.*diff --git a/packages/sie_ts_sdk/src/index.ts b/packages/sie_ts_sdk/src/index.tsindex 0ad21de17..309bd6d3b 100644--- a/packages/sie_ts_sdk/src/index.ts+++ b/packages/sie_ts_sdk/src/index.ts@@ -209,6 +209,13 @@ export {// Client-side scoring (MaxSim for ColBERT-style models)export { maxsim, maxsimDocuments, maxsimBatch } from "./scoring.js";+export { choiceConfidence, scoreConfidence, MAX_SCORE_LEVELS } from "./systemone.js";+export type {+ SystemOneOptions,+ SystemOneResult,+ SystemOneState,+ SystemOneUsage,+} from "./systemone.js";// Low-level utilities (for advanced users)export { packMessage, unpackMessage } from "./msgpack.js";diff --git a/packages/sie_ts_sdk/src/systemone.ts b/packages/sie_ts_sdk/src/systemone.tsnew file mode 100644index 000000000..e5810c51a--- /dev/null+++ b/packages/sie_ts_sdk/src/systemone.ts@@ -0,0 +1,186 @@+/**+ * System One typed decisions on top of `extract`.+ *+ * `SIEClient.systemOne` answers one state against typed `noul`, `choice` and+ * `score` questions with a decision model, and returns the System One response+ * shape (`{ model, answers, usage }`) that SIE's `POST /v1/systemone` serves. It+ * runs as one `extract` call, so it waits for capacity and model loading like+ * every other SDK call. Mirrors the Python SDK's `sie_sdk.systemone`.+ */++import { RequestError } from "./errors.js";+import type { ExtractItem, ExtractResult } from "./types.js";++/** Score levels per question, as the System One API accepts. */+export const MAX_SCORE_LEVELS = 10;++/** Runtime options every System One call sends: input that does not fit the model's row is refused, not cut. */+export const SYSTEM_ONE_OPTIONS: Readonly<Record<string, unknown>> = { overflow_policy: "error" };++/** A System One state: the text to judge, a JSON object, or a list of conversation turns. */+export type SystemOneState = string | Record<string, unknown> | unknown[];++/** Options for `SIEClient.systemOne`. */+export interface SystemOneOptions {+ /** Runtime options forwarded as `params.options`, as for `extract`. */+ adapterOptions?: Record<string, unknown>;+ /** GPU type for this request */+ gpu?: string;+ /** Whether to wait for capacity */+ waitForCapacity?: boolean;+}++/** Tokens a System One call read; decision models generate none. */+export interface SystemOneUsage {+ /**+ * The metered count the response reported (SIE Serverless meters every+ * request); 0 when the deployment reports no metering.+ */+ input_tokens: number;+ output_tokens: number;+}++/** Answers to typed questions, in the System One response shape. */+export interface SystemOneResult {+ /** The decision model that answered */+ model: string;+ /**+ * One answer per question id. `noul`: `noul`, the probability of yes.+ * `choice`: `choice`, `confidence` and `probabilities` by option. `score`:+ * `score`, `confidence`, and `legend` and `probabilities` by level index.+ */+ answers: Record<string, Record<string, unknown>>;+ usage: SystemOneUsage;+}++function invalid(message: string): RequestError {+ return new RequestError(message, "INVALID_INPUT");+}++/**+ * The extract item and `outputSchema` for a System One call. A question may+ * omit `instructions`; a score question takes 1 to 10 levels, none null.+ */+export function systemOneRequest(+ state: unknown,+ questions: Record<string, unknown>,+): { item: ExtractItem; outputSchema: Record<string, Record<string, unknown>> } {+ let item: ExtractItem;+ if (typeof state === "string") {+ item = { text: state };+ } else if (state !== null && typeof state === "object") {+ item = { metadata: { state } };+ } else {+ throw invalid("state must be a string, an object, or an array");+ }+ const entries =+ questions !== null && typeof questions === "object" && !Array.isArray(questions)+ ? Object.entries(questions)+ : [];+ if (entries.length === 0) {+ throw invalid("questions must be a non-empty object of questions by id");+ }+ const outputSchema: Record<string, Record<string, unknown>> = {};+ for (const [qid, question] of entries) {+ if (question === null || typeof question !== "object" || Array.isArray(question)) {+ throw invalid(`question ${JSON.stringify(qid)} must be an object`);+ }+ const normalized: Record<string, unknown> = { ...(question as Record<string, unknown>) };+ if (normalized.instructions === undefined || normalized.instructions === null) {+ normalized.instructions = "";+ }+ const levels = normalized.criteria;+ if (normalized.type === "score" && Array.isArray(levels)) {+ if (levels.length > MAX_SCORE_LEVELS) {+ throw invalid(+ `score question ${JSON.stringify(qid)} has ${levels.length} levels; at most ${MAX_SCORE_LEVELS} are allowed`,+ );+ }+ if (levels.some((level) => level === null || level === undefined)) {+ throw invalid(`score question ${JSON.stringify(qid)} has a null level`);+ }+ }+ outputSchema[qid] = normalized;+ }+ return { item, outputSchema };+}++/** System One choice confidence: `(p_max - 1/n) / (1 - 1/n)`, within [0, 1]. */+export function choiceConfidence(probabilities: number[]): number {+ const n = probabilities.length;+ if (n <= 1) return 1;+ const floor = 1 / n;+ return Math.min(1, Math.max(0, (Math.max(...probabilities) - floor) / (1 - floor)));+}++/**+ * System One score confidence: `max(0, 1 - spread / even)`, where `spread` is+ * the expected distance from the most likely level and `even` that of a+ * uniform distribution from the middle level.+ */+export function scoreConfidence(probabilities: number[]): number {+ const n = probabilities.length;+ if (n <= 1) return 1;+ let mode = 0;+ probabilities.forEach((p, index) => {+ if (p > (probabilities[mode] ?? 0)) mode = index;+ });+ const spread = probabilities.reduce((sum, p, index) => sum + p * Math.abs(index - mode), 0);+ const middle = (n - 1) / 2;+ let even = 0;+ for (let index = 0; index < n; index++) even += Math.abs(index - middle);+ even /= n;+ return Math.min(1, Math.max(0, 1 - spread / even));+}++function toAnswer(answer: Record<string, unknown>): Record<string, unknown> {+ const result = { ...answer };+ const probabilities = result.probabilities;+ if (probabilities === null || typeof probabilities !== "object") return result;+ const byKey = probabilities as Record<string, number>;+ if (result.type === "choice") {+ result.confidence = choiceConfidence(Object.values(byKey).map(Number));+ } else if (result.type === "score") {+ const ordered = Object.keys(byKey)+ .sort((a, b) => Number(a) - Number(b))+ .map((key) => Number(byKey[key]));+ result.confidence = scoreConfidence(ordered);+ }+ return result;+}++/**+ * An extract result in the System One response shape. Throws `RequestError`+ * when the model refused the state (for example, it does not fit the model's+ * window) or answered no question of the request.+ */+export function systemOneResult(+ model: string,+ result: ExtractResult,+ questions: Record<string, unknown>,+): SystemOneResult {+ if (result.error) {+ throw new RequestError(result.error.message, result.error.code, 422, undefined, "state");+ }+ const data = (result.data ?? {}) as Record<string, unknown>;+ const missing = Object.keys(questions).filter((qid) => {+ const answer = data[qid];+ return answer === null || typeof answer !== "object";+ });+ if (missing.length > 0) {+ throw new RequestError(+ `model ${JSON.stringify(model)} returned no answer for questions ${JSON.stringify(missing)}; use a decision model such as fastino/GLiNER2.5-Decide`,+ "INVALID_RESPONSE",+ );+ }+ const answers: Record<string, Record<string, unknown>> = {};+ for (const qid of Object.keys(questions)) {+ answers[qid] = toAnswer(data[qid] as Record<string, unknown>);+ }+ const inputTokens = result.request?.usage?.inputTokens;+ return {+ model,+ answers,+ usage: { input_tokens: typeof inputTokens === "number" ? inputTokens : 0, output_tokens: 0 },+ };+}diff --git a/packages/sie_ts_sdk/src/types.ts b/packages/sie_ts_sdk/src/types.tsindex da06cda9c..4a7c2dbb4 100644--- a/packages/sie_ts_sdk/src/types.ts+++ b/packages/sie_ts_sdk/src/types.ts@@ -367,6 +367,10 @@ export interface ModelInfo {maxSequenceLength?: number | null;/** Pinned HF commit SHA for the weights; null for unpinned/package-backed models */revision?: string | null;+ /** One line about the model; "" when the catalog sets none */+ description?: string;+ /** Release date of the served weights, YYYY-MM-DD; "" when the catalog sets none */+ releaseDate?: string;/** Servable profiles keyed by name; address one as "model@profile" */profiles?: Record<string, ProfileInfo>;/** Advertised model capabilities; null for models with no `generate` task */@@ -390,7 +394,7 @@ export interface ModelInfo {/*** A `/v1/models` entry exactly as the gateway emits it, before the client- * camelCases the three renamed top-level keys.+ * camelCases the four renamed top-level keys.** Declared once here (rather than inline per call site) so `listModels` and* `getModel` cannot drift apart, and so the emitted key set has a single@@ -406,6 +410,8 @@ export interface WireModelInfo {dims?: ModelDims;max_sequence_length?: number | null;revision?: string | null;+ description?: string;+ release_date?: string;profiles?: Record<string, ProfileInfo>;capabilities?: ModelCapabilities | null;pending_generation?: PendingGeneration;@@ -423,6 +429,7 @@ export interface WireModelInfo {const MODEL_INFO_WIRE_FIELD_SET: Record<keyof WireModelInfo, true> = {aliases: true,capabilities: true,+ description: true,dims: true,inputs: true,last_error: true,@@ -432,6 +439,7 @@ const MODEL_INFO_WIRE_FIELD_SET: Record<keyof WireModelInfo, true> = {outputs: true,pending_generation: true,profiles: true,+ release_date: true,revision: true,routing: true,state: true,diff --git a/packages/sie_ts_sdk/tests/systemOne.test.ts b/packages/sie_ts_sdk/tests/systemOne.test.tsnew file mode 100644index 000000000..164a98cd0--- /dev/null+++ b/packages/sie_ts_sdk/tests/systemOne.test.ts@@ -0,0 +1,124 @@+/**+ * SIEClient.systemOne: System One typed decisions over extract, checked+ * against the shared golden fixture `wire-fixtures/systemone.json`.+ */++import { readFileSync } from "node:fs";+import { fileURLToPath } from "node:url";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { SIEClient } from "../src/client.js";+import { RequestError } from "../src/errors.js";+import { packMessage, unpackMessage } from "../src/msgpack.js";+import { choiceConfidence, scoreConfidence, systemOneRequest } from "../src/systemone.js";++const mockFetch = vi.fn();+vi.stubGlobal("fetch", mockFetch);++const fixturesDir = fileURLToPath(new URL("../../wire-fixtures/", import.meta.url));+// biome-ignore lint/suspicious/noExplicitAny: golden fixture JSON+const FIXTURE: any = JSON.parse(readFileSync(`${fixturesDir}systemone.json`, "utf8"));+const RESPONSE_CASE = FIXTURE.responses[0];+const MODEL: string = RESPONSE_CASE.model;+const QUESTIONS: Record<string, unknown> = Object.fromEntries(+ (RESPONSE_CASE.questions as string[]).map((qid) => [qid, { type: "noul" }]),+);++function extractResponse(+ item: Record<string, unknown>,+ headers: Record<string, string> = {},+): Response {+ return new Response(packMessage({ model: MODEL, items: [item] }), {+ status: 200,+ headers: { "Content-Type": "application/msgpack", ...headers },+ });+}++function expectClose(actual: unknown, expected: unknown, path = "$"): void {+ if (expected !== null && typeof expected === "object") {+ const actualObject = actual as Record<string, unknown>;+ expect(Object.keys(actualObject).sort(), path).toEqual(Object.keys(expected).sort());+ for (const [key, value] of Object.entries(expected)) {+ expectClose(actualObject[key], value, `${path}.${key}`);+ }+ } else if (typeof expected === "number" && !Number.isInteger(expected)) {+ expect(actual as number, path).toBeCloseTo(expected, 9);+ } else {+ expect(actual, path).toEqual(expected);+ }+}++describe("SIEClient.systemOne()", () => {+ let client: SIEClient;++ beforeEach(() => {+ mockFetch.mockReset();+ client = new SIEClient("http://localhost:8080");+ });++ afterEach(async () => {+ await client.close();+ });++ it("sends one strict extract item and reshapes the answers", async () => {+ mockFetch.mockResolvedValueOnce(+ extractResponse(+ { id: "item-0", entities: [], data: RESPONSE_CASE.data },+ { "X-SIE-Units-Input-Tokens": "42" },+ ),+ );++ const result = await client.systemOne(MODEL, "I was charged twice.", QUESTIONS);++ const [url, init] = mockFetch.mock.calls[0] as [string, RequestInit];+ expect(url).toContain("/v1/extract/");+ // biome-ignore lint/suspicious/noExplicitAny: decoded msgpack request body+ const body = unpackMessage(new Uint8Array(init.body as ArrayBuffer)) as Record<string, any>;+ expect(body.items).toEqual([{ text: "I was charged twice." }]);+ expect(body.params.options.overflow_policy).toBe("error");+ expect(Object.keys(body.params.output_schema)).toEqual(RESPONSE_CASE.questions);+ expectClose(result, RESPONSE_CASE.response);+ });++ it("throws RequestError when the state does not fit", async () => {+ mockFetch.mockResolvedValueOnce(+ extractResponse({+ id: "item-0",+ entities: [],+ data: {},+ error: { code: "INPUT_TOO_LONG", message: "does not fit" },+ }),+ );+ await expect(client.systemOne(MODEL, "x", QUESTIONS)).rejects.toBeInstanceOf(RequestError);+ });+});++describe("System One fixture", () => {+ it.each(FIXTURE.requests)("builds the extract call: $name", (testCase) => {+ const { item, outputSchema } = systemOneRequest(+ testCase.request.state,+ testCase.request.questions,+ );+ expect(item).toEqual(testCase.extract.item);+ expect(outputSchema).toEqual(testCase.extract.output_schema);+ });++ it.each(+ // biome-ignore lint/suspicious/noExplicitAny: golden fixture JSON+ FIXTURE.invalid_requests.filter((testCase: any) =>+ /^(number|boolean|null|empty q|questions|question|eleven|null score)/.test(testCase.name),+ ),+ )("refuses: $name", (testCase) => {+ expect(() =>+ systemOneRequest(testCase.request.state, testCase.request.questions ?? {}),+ ).toThrow(RequestError);+ });++ it("matches the confidence goldens", () => {+ for (const testCase of FIXTURE.confidence.choice) {+ expect(choiceConfidence(testCase.probabilities)).toBeCloseTo(testCase.confidence, 9);+ }+ for (const testCase of FIXTURE.confidence.score) {+ expect(scoreConfidence(testCase.probabilities)).toBeCloseTo(testCase.confidence, 9);+ }+ });+});diff --git a/packages/sie_ts_sdk/tests/wireContract.test.ts b/packages/sie_ts_sdk/tests/wireContract.test.tsindex 44d4b4865..b99fb7975 100644--- a/packages/sie_ts_sdk/tests/wireContract.test.ts+++ b/packages/sie_ts_sdk/tests/wireContract.test.ts@@ -33,11 +33,12 @@ function jsonResponse(body: unknown): Response {});}-/** The three top-level keys the client camelCases; everything else passes through. */+/** The four top-level keys the client camelCases; everything else passes through. */const WIRE_TO_CLIENT_KEY: Record<string, string> = {max_sequence_length: "maxSequenceLength",last_error: "lastError",pending_generation: "pendingGeneration",+ release_date: "releaseDate",};/**@@ -71,6 +72,8 @@ const FULL_WIRE_ENTRY = {dims: { dense: 1024, sparse: 250002 },max_sequence_length: 8192,revision: "5617a9f61b028005a4858fdac845db406aefb181",+ description: "BAAI/bge-m3: embedding and reranking model.",+ release_date: "2024-07-03",profiles: { default: { is_default: true }, fp8: { is_default: false } },capabilities: { grammar: ["json_schema"], tools: true, code: false, sql: false, guard: false },pending_generation: { total: 0, groups: [] },@@ -140,6 +143,8 @@ describe("getModel wire mapping", () => {expect(model.outputs).toEqual(FULL_WIRE_ENTRY.outputs);expect(model.dims).toEqual(FULL_WIRE_ENTRY.dims);expect(model.revision).toBe(FULL_WIRE_ENTRY.revision);+ expect(model.description).toBe(FULL_WIRE_ENTRY.description);+ expect(model.releaseDate).toBe(FULL_WIRE_ENTRY.release_date);expect(model.profiles).toEqual(FULL_WIRE_ENTRY.profiles);expect(model.capabilities).toEqual(FULL_WIRE_ENTRY.capabilities);expect(model.pendingGeneration).toEqual(FULL_WIRE_ENTRY.pending_generation);diff --git a/packages/wire-fixtures/model_info.json b/packages/wire-fixtures/model_info.jsonindex 182a8b422..727e9cbdf 100644--- a/packages/wire-fixtures/model_info.json+++ b/packages/wire-fixtures/model_info.json@@ -15,6 +15,7 @@"typed": ["aliases","capabilities",+ "description","dims","inputs","last_error",@@ -24,6 +25,7 @@"outputs","pending_generation","profiles",+ "release_date","revision","routing","state"@@ -37,7 +39,7 @@"notes": {"excluded_scope": "The four excluded keys are merged in by GET /v1/models/{model} for vanilla OpenAI 'retrieve model' clients; on GET /v1/models they live in the sibling `data` array instead, never on a `models` entry.","optionality": "Python marks every typed key optional (`total=False`). TypeScript requires `name`, `loaded`, `inputs` and `outputs` on both `ModelInfo` and `WireModelInfo`; its remaining keys are optional. `pending_generation` is gateway-only. `last_error`/`max_sequence_length`/`revision`/`capabilities` are the four the emitters can send as an explicit null, so the SDK types admit null on each. The fixture pins which keys are declarable, not which are always present.",- "ts_renames": "The TS SDK camelCases three top-level keys \u2014 max_sequence_length -> maxSequenceLength, last_error -> lastError, pending_generation -> pendingGeneration \u2014 and leaves nested objects wire-shaped. Its consumer test checks the wire-side names listed here.",+ "ts_renames": "The TS SDK camelCases four top-level keys \u2014 max_sequence_length -> maxSequenceLength, last_error -> lastError, pending_generation -> pendingGeneration, release_date -> releaseDate \u2014 and leaves nested objects wire-shaped. Its consumer test checks the wire-side names listed here.","aliases": "Short task-tier names resolving to this model. Always emitted, empty when the model has none, so callers can distinguish 'no aliases' from an older gateway. Only catalog- or operator-declared names appear; the gateway's compiled-in routing defaults are not public API and are never listed.","routing": "How the bare model name is served: `policy` (`remote_only`, `fallback`, `threshold`, or null for local only) and `upstream_kind` (`sie`, `openai`, or null). The single server and the gateway emit it on every entry."}