Skip to content

armgit / sie

Public Imported from GitHub
0

Open-source inference server and production cluster for all the models your agent needs.

feat(server): add a System One-compatible POST /v1/systemone

Rahul Parundekar3fad998ad759
diff --git a/packages/sie_server/src/sie_server/adapters/laya/adapter.py b/packages/sie_server/src/sie_server/adapters/laya/adapter.py
index dda14a616..c240aa3a1 100644
--- a/packages/sie_server/src/sie_server/adapters/laya/adapter.py
+++ b/packages/sie_server/src/sie_server/adapters/laya/adapter.py
@@ -31,6 +31,9 @@ Request contract:
script. A longer text that averages more bytes per token than its budget over
the cut can keep fewer tokens than the reference would; that takes long runs
of one character, which ModernBERT merges into tokens of up to 512 characters.
+ With ``options.overflow_policy`` ``"error"``, an item whose state does not
+ fit whole in the row of every question returns a per-item ``INPUT_TOO_LONG``
+ error instead of being cut.
Metering counts every row the model encodes: an item's input tokens are the sum
of its (state, question) row lengths, so cost scales with items x questions.
@@ -101,6 +104,7 @@ from sie_server.adapters.laya.questions import (
)
from sie_server.core.inference_output import ExtractItemError, ExtractOutput
from sie_server.types.inputs import InvalidInputError, Item
+from sie_server.types.overflow_policy import DEFAULT_OVERFLOW_POLICY, VALID_OVERFLOW_POLICIES
from sie_server.types.responses import Classification, ErrorCode
if TYPE_CHECKING:
@@ -153,6 +157,11 @@ _ERR_STATE = (
)
_ERR_STATE_JSON = "Laya metadata.state must be JSON-serializable"
_ERR_TOO_MANY_OPTIONS = "Laya accepts at most {limit} {what} per request, got {count}"
+_ERR_DOES_NOT_FIT = (
+ "The state takes {tokens} tokens; with its longest question, this model's {window}-token row has room "
+ "for {room}. Send a shorter state or shorter questions (overflow_policy 'error')"
+)
+_ERR_OVERFLOW_POLICY = "Laya overflow_policy must be one of {choices}"
def graph_token_bound(hidden_size: int) -> int:
@@ -499,22 +508,49 @@ class LayaAdapter(BaseAdapter):
threshold = _threshold_option(opts) if labels_mode else 0.0
max_len, head_max_len = self._token_budget(opts)
self._check_item_tokens(len(questions), max_len)
+ overflow_policy = opts.get("overflow_policy", DEFAULT_OVERFLOW_POLICY)
+ if not isinstance(overflow_policy, str) or overflow_policy not in VALID_OVERFLOW_POLICIES:
+ raise InvalidInputError(_ERR_OVERFLOW_POLICY.format(choices=sorted(VALID_OVERFLOW_POLICIES)))
+ strict = overflow_policy == "error"
state_bytes = self._max_len * STATE_BYTES_PER_TOKEN
states: list[tuple[str, bool] | None] = []
errors: list[ExtractItemError | None] = []
+ clipped: list[bool] = []
for item in items:
try:
- states.append(self._item_state(item, state_bytes))
+ state = self._item_state(item, state_bytes)
+ states.append(state)
errors.append(None)
+ # A state cut to its byte budget is longer than any row: it cannot fit.
+ clipped.append(strict and self._item_state(item)[0] != state[0])
except InvalidInputError as exc:
states.append(None)
errors.append(ExtractItemError(code=ErrorCode.INVALID_INPUT.value, message=str(exc)))
+ clipped.append(False)
valid = [i for i, s in enumerate(states) if s is not None]
+ state_lengths: list[int] = []
prefixes, rows = self._build_rows(
- [s for s in states if s is not None], questions, max_len=max_len, head_max_len=head_max_len
+ [s for s in states if s is not None],
+ questions,
+ max_len=max_len,
+ head_max_len=head_max_len,
+ state_lengths=state_lengths,
)
+ if strict and prefixes:
+ # Rows are state-major: one row per question for each valid state.
+ room = max(0, max_len - max(len(prefix.ids) for prefix in prefixes) - 1)
+ keep: list[int] = []
+ for position, i in enumerate(valid):
+ if clipped[i] or state_lengths[position] > room:
+ message = _ERR_DOES_NOT_FIT.format(tokens=state_lengths[position], window=max_len, room=room)
+ errors[i] = ExtractItemError(code=ErrorCode.INPUT_TOO_LONG.value, message=message)
+ else:
+ keep.append(position)
+ per_state = len(prefixes)
+ rows = [rows[p * per_state + q] for p in keep for q in range(per_state)]
+ valid = [valid[p] for p in keep]
logits = self._run_rows(rows, [prefixes[r % len(prefixes)] for r in range(len(rows))]) if rows else []
data: list[dict[str, Any]] = [{} for _ in items]
@@ -550,11 +586,14 @@ class LayaAdapter(BaseAdapter):
*,
max_len: int,
head_max_len: int,
+ state_lengths: list[int] | None = None,
) -> tuple[list[QuestionPrefix], list[list[int]]]:
"""Tokenize each question once and each state once, then assemble the rows.
Returns the question prefixes and one row per (state, question) pair,
state-major (row ``s * len(questions) + q``), like the reference batch.
+ A ``state_lengths`` list is filled with each state's token count before
+ it is cut to its rows.
"""
tokenizer = self._tokenizer
if tokenizer is None:
@@ -570,6 +609,8 @@ class LayaAdapter(BaseAdapter):
for text, truncate_left in states
]
state_ids = tokenizer(texts, add_special_tokens=False)["input_ids"]
+ if state_lengths is not None:
+ state_lengths.extend(len(ids) for ids in state_ids)
rows = [
assemble_row(
prefix,
diff --git a/packages/sie_server/src/sie_server/api/systemone.py b/packages/sie_server/src/sie_server/api/systemone.py
new file mode 100644
index 000000000..ddb2bdd33
--- /dev/null
+++ b/packages/sie_server/src/sie_server/api/systemone.py
@@ -0,0 +1,407 @@
+"""System One-compatible typed decisions: ``POST /v1/systemone``.
+
+A client written for the System One API (the TypeSafe SDKs, or anything that
+sends the same JSON) points its base URL at SIE and keeps its code. The route
+answers one ``state`` against a mapping of typed ``questions`` (``noul``,
+``choice``, ``score``) with an SIE decision model, through the same worker path
+as ``POST /v1/extract/{model}``:
+
+- request ``{model, state, questions}``; the model is named in the body, and
+ fields the route does not read are ignored;
+- response ``{model, answers, usage: {input_tokens, output_tokens}}``, always
+ JSON;
+- a question may omit ``instructions`` or send ``null``;
+- ``choice`` and ``score`` confidences follow the System One API's published
+ definitions (see :func:`choice_confidence` and :func:`score_confidence`);
+- a state or question set that does not fit the model's row is refused with
+ 422 instead of being truncated, as ``extract`` does by default;
+- validation errors are 422 in FastAPI's ``{"detail": [...]}`` shape, other
+ errors ``{"detail": {"error_type", "code", "message"}}``, and a retryable
+ error's ``Retry-After`` is at most 60 seconds, with ``retry-after-ms``.
+"""
+
+from __future__ import annotations
+
+import logging
+import math
+from collections.abc import Mapping
+from typing import TYPE_CHECKING, Annotated, Any, cast
+
+from fastapi import APIRouter, Depends, Header, HTTPException, Request, status
+from fastapi.responses import JSONResponse
+from pydantic import BaseModel, ConfigDict, Field
+
+from sie_server.adapters.errors import InputTooLongError
+from sie_server.api.extract import _extract_via_worker
+from sie_server.api.helpers import (
+ InferenceErrorHandler,
+ ModelStateChecker,
+ ResponseBuilder,
+ check_sdk_version,
+ oom_retry_after_from_registry,
+ validated_total,
+)
+from sie_server.api.options import resolve_runtime_options
+from sie_server.api.routing import remote_routing, route_request
+from sie_server.api.validation import validate_machine_profile_header
+from sie_server.core.worker import QueueFullError
+from sie_server.core.worker.handlers.extract import ExtractHandler
+from sie_server.observability.tracing import tracer
+from sie_server.observability.worker_telemetry import worker_telemetry, worker_telemetry_enabled
+from sie_server.types.inputs import Item, item_size_error
+from sie_server.types.responses import ErrorCode
+
+if TYPE_CHECKING:
+ from sie_server.config.model import ModelConfig
+ from sie_server.core.inference_output import ExtractOutput
+
+logger = logging.getLogger(__name__)
+
+router = APIRouter(prefix="/v1", tags=["systemone"], dependencies=[Depends(remote_routing)])
+
+# Adapters that answer typed questions (``output_schema`` question mappings).
+DECISION_ADAPTERS = frozenset(
+ {
+ "sie_server.adapters.gliner2.decide:GLiNER2DecideAdapter",
+ "sie_server.adapters.laya.adapter:LayaAdapter",
+ }
+)
+
+# Score levels per question, as the System One API accepts.
+MAX_SCORE_LEVELS = 10
+
+# Longest Retry-After the route sends. Clients built for the System One API
+# (and LiteLLM) wait for at most 60 seconds before falling back.
+MAX_RETRY_AFTER_S = 60
+
+# Request fields for media the decision models cannot read.
+_MEDIA_FIELDS = ("images", "audio", "videos")
+
+_ERROR_TYPES = {
+ status.HTTP_400_BAD_REQUEST: "invalid_request_error",
+ status.HTTP_401_UNAUTHORIZED: "authentication_error",
+ status.HTTP_403_FORBIDDEN: "permission_error",
+ status.HTTP_404_NOT_FOUND: "not_found_error",
+ status.HTTP_413_CONTENT_TOO_LARGE: "invalid_request_error",
+ status.HTTP_422_UNPROCESSABLE_CONTENT: "invalid_request_error",
+ status.HTTP_429_TOO_MANY_REQUESTS: "rate_limit_error",
+}
+
+
+class SystemOneRequest(BaseModel):
+ """A System One request: one state and its typed questions."""
+
+ model_config = ConfigDict(extra="allow")
+
+ model: str = Field(
+ ..., min_length=1, description="SIE model id of a decision model, e.g. fastino/GLiNER2.5-Decide."
+ )
+ state: str | dict[str, Any] | list[Any] = Field(
+ ..., description="The text to judge, or a JSON object, or a list of conversation turns."
+ )
+ questions: dict[str, Any] = Field(
+ ...,
+ min_length=1,
+ description='Typed questions by id: {"type": "noul" | "choice" | "score", "instructions"?, "criteria"?}.',
+ )
+
+
+class SystemOneUsage(BaseModel):
+ """Tokens the model read. Decision models generate no tokens."""
+
+ input_tokens: int
+ output_tokens: int = 0
+
+
+class SystemOneResponse(BaseModel):
+ """Answers by question id, in the System One response shape."""
+
+ model: str
+ answers: dict[str, dict[str, Any]]
+ usage: SystemOneUsage
+
+
+def choice_confidence(probabilities: list[float]) -> float:
+ """System One choice confidence: ``(p_max - 1/n) / (1 - 1/n)``, within [0, 1].
+
+ 0 when every option is equally likely, 1 when one option has all the
+ probability. A single option is certain.
+ """
+ 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 in levels from the most likely level,
+ ``sum(p_i * |i - m|)``, and ``even`` the expected distance of a uniform
+ distribution from the middle level, ``sum(|i - (n - 1) / 2|) / n``. A
+ single level is certain.
+ """
+ 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 _invalid(message: str, loc: list[str | int]) -> HTTPException:
+ """A 422 in FastAPI's validation-error shape, which System One clients parse."""
+ return HTTPException(
+ status_code=status.HTTP_422_UNPROCESSABLE_CONTENT,
+ detail=[{"type": "value_error", "loc": ["body", *loc], "msg": message}],
+ )
+
+
+def _is_decision_model(config: ModelConfig) -> bool:
+ return config.tasks.extract is not None and any(
+ profile.adapter_path in DECISION_ADAPTERS for profile in config.profiles.values()
+ )
+
+
+def normalize_questions(questions: Mapping[str, Any]) -> dict[str, Any]:
+ """The questions as the decision adapters read them.
+
+ A missing or ``null`` ``instructions`` becomes ``""``. A score question
+ must have 1 to 10 levels, none of them ``null``. Everything else is left to
+ the adapter's own validation, which rejects what it cannot answer.
+
+ Raises:
+ HTTPException: 422 naming the question.
+ """
+ normalized: dict[str, Any] = {}
+ for qid, question in questions.items():
+ if not isinstance(question, Mapping):
+ raise _invalid(f"question {qid!r} must be an object", ["questions", qid])
+ question = dict(question)
+ if question.get("instructions") is None:
+ question["instructions"] = ""
+ if question.get("type") == "score":
+ levels = question.get("criteria")
+ if isinstance(levels, list):
+ if len(levels) > MAX_SCORE_LEVELS:
+ raise _invalid(
+ f"score question {qid!r} has {len(levels)} levels; at most {MAX_SCORE_LEVELS} are allowed",
+ ["questions", qid, "criteria"],
+ )
+ if any(level is None for level in levels):
+ raise _invalid(f"score question {qid!r} has a null level", ["questions", qid, "criteria"])
+ normalized[qid] = question
+ return normalized
+
+
+def to_answer(answer: Mapping[str, Any]) -> dict[str, Any]:
+ """One adapter answer in the System One shape, with System One confidences."""
+ result = dict(answer)
+ kind = result.get("type")
+ probabilities = result.get("probabilities")
+ if kind == "choice" and isinstance(probabilities, Mapping):
+ result["confidence"] = choice_confidence([float(p) for p in probabilities.values()])
+ elif kind == "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 _error_message(detail: Any) -> str:
+ if isinstance(detail, Mapping):
+ inner = detail.get("error")
+ if isinstance(inner, Mapping) and isinstance(inner.get("message"), str):
+ return inner["message"]
+ if isinstance(detail.get("message"), str):
+ return detail["message"]
+ if isinstance(detail, str):
+ return detail
+ return "request failed"
+
+
+def _error_code(detail: Any) -> str | None:
+ if isinstance(detail, Mapping):
+ code = detail.get("code")
+ if isinstance(code, str):
+ return code
+ inner = detail.get("error")
+ if isinstance(inner, Mapping) and isinstance(inner.get("code"), str):
+ return inner["code"]
+ return None
+
+
+def _retry_headers(headers: Mapping[str, str] | None) -> dict[str, str]:
+ """The error's headers, with ``Retry-After`` capped and mirrored as ``retry-after-ms``."""
+ out = dict(headers or {})
+ retry_key = next((key for key in out if key.lower() == "retry-after"), None)
+ if retry_key is None:
+ return out
+ try:
+ seconds = float(out.pop(retry_key))
+ except ValueError:
+ return out
+ if not math.isfinite(seconds) or seconds < 0:
+ return out
+ seconds = min(seconds, MAX_RETRY_AFTER_S)
+ out["Retry-After"] = str(max(1, math.ceil(seconds)))
+ out["retry-after-ms"] = str(int(seconds * 1000))
+ return out
+
+
+def error_response(error: HTTPException) -> JSONResponse:
+ """An SIE error in the System One error shapes.
+
+ Input errors (400 ``INVALID_INPUT`` / ``INPUT_TOO_LONG``) become 422 in
+ FastAPI's validation shape, as System One answers a request it cannot
+ validate. Every other status keeps its code, with
+ ``{"detail": {"error_type", "code", "message"}}``.
+ """
+ headers = _retry_headers(error.headers)
+ if isinstance(error.detail, list):
+ return JSONResponse(status_code=error.status_code, content={"detail": error.detail}, headers=headers)
+ message = _error_message(error.detail)
+ code = _error_code(error.detail)
+ if error.status_code == status.HTTP_400_BAD_REQUEST:
+ return JSONResponse(
+ status_code=status.HTTP_422_UNPROCESSABLE_CONTENT,
+ content={"detail": [{"type": "value_error", "loc": ["body"], "msg": message, "code": code}]},
+ headers=headers,
+ )
+ error_type = _ERROR_TYPES.get(error.status_code, "api_error")
+ detail: dict[str, Any] = {"error_type": error_type, "message": message}
+ if code is not None:
+ detail["code"] = code
+ return JSONResponse(status_code=error.status_code, content={"detail": detail}, headers=headers)
+
+
+def _item_error(result: Mapping[str, Any]) -> HTTPException | None:
+ """The 422 for an item the adapter refused (a state that does not fit, an unreadable state)."""
+ error = result.get("error")
+ if not isinstance(error, Mapping):
+ return None
+ return _invalid(str(error.get("message", "the state could not be read")), ["state"])
+
+
+ "/systemone",
+ response_model=SystemOneResponse,
+ responses={
+ 200: {"description": "Every question answered"},
+ 404: {"description": "Model not found"},
+ 422: {
+ "description": (
+ "Invalid request: a malformed question, a model that does not answer typed questions, "
+ "or a state or question set that does not fit the model's window"
+ )
+ },
+ 503: {"description": "Model loading or server busy; retry after Retry-After (at most 60 seconds)"},
+ },
+)
+async def system_one(
+ request: SystemOneRequest,
+ http_request: Request,
+ x_machine_profile: Annotated[str | None, Header(alias="X-SIE-MACHINE-PROFILE")] = None,
+) -> JSONResponse:
+ """Answer typed questions about one state (System One-compatible).
+
+ Clients written for the System One API work by changing their base URL.
+ """
+ try:
+ return await _system_one(request, http_request, x_machine_profile)
+ except HTTPException as error:
+ return error_response(error)
+
+
+async def _system_one(
+ request: SystemOneRequest,
+ http_request: Request,
+ x_machine_profile: str | None,
+) -> JSONResponse:
+ validate_machine_profile_header(x_machine_profile)
+ check_sdk_version(http_request)
+ model = request.model
+
+ with tracer.start_as_current_span("systemone") as span:
+ span.set_attribute("model", model)
+ registry = http_request.app.state.registry
+ ModelStateChecker(registry, model, span).check_exists()
+
+ config = registry.get_config(model)
+ if not _is_decision_model(config):
+ span.set_attribute("error", "unsupported_operation")
+ raise _invalid(
+ f"Model '{model}' does not answer typed questions. Use a decision model such as "
+ "fastino/GLiNER2.5-Decide or convaiinnovations/laya-typed-decisions.",
+ ["model"],
+ )
+
+ extra = request.model_extra or {}
+ for field in _MEDIA_FIELDS:
+ if extra.get(field) is not None:
+ raise _invalid(f"'{field}' is not supported: SIE decision models read text only", [field])
+
+ questions = normalize_questions(request.questions)
+ state = request.state
+ item = Item(text=state) if isinstance(state, str) else Item(metadata={"state": state})
+ if size_error := item_size_error(item, "state"):
+ raise _invalid(size_error, ["state"])
+
+ options = resolve_runtime_options(config, {"overflow_policy": "error"}, span)
+ route = await route_request(http_request, model, span, queued_items=1)
+ error_handler = InferenceErrorHandler(
+ model,
+ "extract",
+ span,
+ oom_retry_after_s=oom_retry_after_from_registry(registry),
+ profile="default",
+ item_count=1,
+ )
+ try:
+ worker_result = await _extract_via_worker(
+ registry, route.key, [item], output_schema=questions, options=options
+ )
+ except QueueFullError as e:
+ raise error_handler.handle_queue_full(e) from e
+ except InputTooLongError as e:
+ raise error_handler.handle_input_too_long(e) from e
+ except ValueError as e:
+ raise error_handler.handle_value_error(e) from e
+ except Exception as e:
+ raise error_handler.handle_inference_error(e, "Decision") from e
+
+ output = cast("ExtractOutput", worker_result.output)
+ result = ExtractHandler.format_output(output)[0]
+ if refusal := _item_error(result):
+ span.set_attribute("error", _error_code(result.get("error")) or ErrorCode.INVALID_INPUT.value)
+ raise refusal
+
+ data = result.get("data") or {}
+ answers = {qid: to_answer(data[qid]) for qid in questions if isinstance(data.get(qid), Mapping)}
+ if len(answers) != len(questions):
+ missing = sorted(set(questions) - set(answers))
+ raise error_handler.handle_inference_error(
+ RuntimeError(f"model returned no answer for questions {missing}"), "Decision"
+ )
+
+ input_tokens = validated_total(output.input_token_counts, 1) or 0
+ timing = worker_result.timing
+ if worker_telemetry_enabled():
+ worker_telemetry().item_completed(
+ operation="extract",
+ outcome="success",
+ model=model,
+ profile="default",
+ duration_s=timing.total_ms / 1000.0,
+ item_count=1,
+ tokenization_s=timing.tokenization_ms / 1000.0,
+ inference_s=timing.inference_ms / 1000.0,
+ postprocessing_s=timing.postprocessing_ms / 1000.0,
+ units={"input_tokens": input_tokens},
+ )
+
+ body = SystemOneResponse(model=model, answers=answers, usage=SystemOneUsage(input_tokens=input_tokens))
+ headers = ResponseBuilder.build_headers(timing)
+ headers.update(route.headers())
+ return JSONResponse(content=body.model_dump(), headers=headers)
diff --git a/packages/sie_server/src/sie_server/app/app_factory.py b/packages/sie_server/src/sie_server/app/app_factory.py
index aaaa01e2a..2645b77bb 100644
--- a/packages/sie_server/src/sie_server/app/app_factory.py
+++ b/packages/sie_server/src/sie_server/app/app_factory.py
@@ -21,6 +21,7 @@ from sie_server.api.openai_responses import router as openai_responses_router
from sie_server.api.openapi import setup_custom_openapi_schema
from sie_server.api.root import router as root_router
from sie_server.api.score import router as score_router
+from sie_server.api.systemone import router as systemone_router
from sie_server.api.ws import init_server_start_time
from sie_server.api.ws import router as ws_router
from sie_server.app.app_state_config import AppStateConfig
@@ -120,6 +121,7 @@ class AppFactory:
app.include_router(openai_router) # OpenAI-compatible /v1/embeddings
app.include_router(openai_completions_router) # OpenAI-compatible /v1/completions
app.include_router(openai_responses_router) # OpenAI-compatible /v1/responses
+ app.include_router(systemone_router) # System One-compatible /v1/systemone
# Local-only convenience (single-node/dev); intentionally NOT in the published
# openapi.json — see cli.openapi_export. The Rust gateway is the prod API authority.
app.include_router(openai_local_router) # local /v1/chat/completions + /v1/rerank
diff --git a/packages/sie_server/tests/adapters/test_laya_bounds.py b/packages/sie_server/tests/adapters/test_laya_bounds.py
index 7963c9c36..159171924 100644
--- a/packages/sie_server/tests/adapters/test_laya_bounds.py
+++ b/packages/sie_server/tests/adapters/test_laya_bounds.py
@@ -397,3 +397,50 @@ def test_cost_hook_is_bounded_for_oversized_requests() -> None:
row_chars = 4 * adapter._max_len
costs = adapter.extract_item_costs([Item(text="abc")], labels=["x" * 10] * 1_000_000)
assert costs == [3 + row_chars]
+
+
+# ---------------------------------------------------------------------------- overflow_policy "error"
+
+
+def _strict_adapter() -> LayaAdapter:
+ adapter = _adapter(WordTokenizer())
+ adapter._run_rows = lambda rows, prefixes: [np.zeros(len(p.markers), dtype=np.float32) for p in prefixes] # ty: ignore[invalid-assignment]
+ return adapter
+
+
+def test_overflow_error_refuses_only_states_that_do_not_fit() -> None:
+ adapter = _strict_adapter()
+ long_words = " ".join(["word"] * MAX_LEN) # about 2 * MAX_LEN tokens: more than any row holds
+ items = [Item(text="short state"), Item(text=long_words), Item(metadata={"state": {"body": long_words}})]
+ output = adapter.extract(items, output_schema=ONE_QUESTION, options={"overflow_policy": "error"})
+ assert output.errors is not None
+ assert output.errors[0] is None
+ assert [error.code for error in output.errors[1:] if error is not None] == ["INPUT_TOO_LONG", "INPUT_TOO_LONG"]
+ assert "row has room" in output.errors[1].message
+ assert output.data is not None
+ assert set(output.data[0]) == {"q"}
+ assert output.data[1] == output.data[2] == {}
+ assert output.input_token_counts is not None
+ assert output.input_token_counts[0] > 0
+ assert output.input_token_counts[1:] == [0, 0]
+
+
+def test_overflow_error_refuses_a_state_cut_to_its_byte_budget() -> None:
+ adapter = _strict_adapter()
+ output = adapter.extract([Item(text=LONG_TEXT)], output_schema=ONE_QUESTION, options={"overflow_policy": "error"})
+ assert output.errors is not None
+ assert output.errors[0] is not None
+ assert output.errors[0].code == "INPUT_TOO_LONG"
+
+
+def test_default_overflow_still_cuts_long_states() -> None:
+ adapter = _strict_adapter()
+ output = adapter.extract([Item(text=" ".join(["word"] * MAX_LEN))], output_schema=ONE_QUESTION)
+ assert output.errors is None
+ assert output.data is not None
+ assert set(output.data[0]) == {"q"}
+
+
+def test_unknown_overflow_policy_is_invalid_input() -> None:
+ with pytest.raises(InvalidInputError, match="overflow_policy"):
+ _strict_adapter().extract([Item(text="x")], output_schema=ONE_QUESTION, options={"overflow_policy": "drop"})
diff --git a/packages/sie_server/tests/api/test_systemone.py b/packages/sie_server/tests/api/test_systemone.py
new file mode 100644
index 000000000..845a7dac9
--- /dev/null
+++ b/packages/sie_server/tests/api/test_systemone.py
@@ -0,0 +1,416 @@
+"""Tests for the System One-compatible POST /v1/systemone."""
+
+import asyncio
+import json
+from pathlib import Path
+from typing import Any
+from unittest.mock import AsyncMock, MagicMock
+
+import pytest
+from fastapi import FastAPI, HTTPException
+from fastapi.testclient import TestClient
+from sie_server.adapters.base import ModelCapabilities, ModelDims
+from sie_server.adapters.errors import InputTooLongError
+from sie_server.api.systemone import (
+ MAX_RETRY_AFTER_S,
+ choice_confidence,
+ error_response,
+ normalize_questions,
+ score_confidence,
+)
+from sie_server.api.systemone import router as systemone_router
+from sie_server.config.model import EncodeTask, ExtractTask, ModelConfig, ProfileConfig, Tasks
+from sie_server.core.inference_output import ExtractItemError, ExtractOutput
+from sie_server.core.registry import ModelRegistry
+from sie_server.core.timing import RequestTiming
+from sie_server.core.worker import WorkerResult
+from sie_server.types.responses import ErrorCode
+
+DECIDE = "fastino/GLiNER2.5-Decide"
+EMBEDDER = "org/embedder"
+DECIDE_ADAPTER = "sie_server.adapters.gliner2.decide:GLiNER2DecideAdapter"
+
+QUESTIONS: dict[str, Any] = {
+ "spam": {"type": "noul", "instructions": "Is this message spam?"},
+ "intent": {
+ "type": "choice",
+ "instructions": "What does the sender want?",
+ "criteria": {"billing": "payments and refunds", "support": None, "other": None},
+ },
+ "urgency": {
+ "type": "score",
+ "instructions": "How urgent is it?",
+ "criteria": ["Can wait", "Needs attention this week", "Needs attention today"],
+ },
+}
+
+
+def _answer(question: dict[str, Any]) -> dict[str, Any]:
+ """An adapter answer in the shape the decision adapters return."""
+ if question["type"] == "noul":
+ return {"type": "noul", "noul": 0.9, "answer": True, "confidence": 0.9}
+ if question["type"] == "choice":
+ keys = list(question["criteria"])
+ probabilities = {key: (0.8 if i == 0 else 0.2 / (len(keys) - 1)) for i, key in enumerate(keys)}
+ # The adapters' own (entropy) confidence, which the route replaces.
+ return {"type": "choice", "choice": keys[0], "probabilities": probabilities, "confidence": 0.123}
+ levels = question["criteria"]
+ probabilities = {str(i): (0.8 if i == len(levels) - 1 else 0.2 / (len(levels) - 1)) for i in range(len(levels))}
+ score = sum(i * p for i, p in enumerate(probabilities.values()))
+ return {
+ "type": "score",
+ "score": score,
+ "legend": {str(i): level for i, level in enumerate(levels)},
+ "probabilities": probabilities,
+ "confidence": 0.123,
+ }
+
+
+def _decide(items: list[Any], *, output_schema: dict[str, Any] | None = None, **_: Any) -> ExtractOutput:
+ data = [{qid: _answer(q) for qid, q in (output_schema or {}).items()} for _ in items]
+ return ExtractOutput(entities=[[] for _ in items], data=data, input_token_counts=[42 for _ in items])
+
+
+def adapter() -> MagicMock:
+ adapter = MagicMock()
+ adapter.extract = MagicMock(side_effect=_decide)
+ adapter.capabilities = ModelCapabilities(inputs=["text"], outputs=[])
+ adapter.dims = ModelDims()
+ return adapter
+
+
+def _worker(adapter: MagicMock) -> MagicMock:
+ worker = MagicMock()
+
+ async def submit_extract(
+ prepared_items, items, *, labels=None, output_schema=None, instruction=None, options=None, timing=None
+ ):
+ future = asyncio.get_running_loop().create_future()
+ try:
+ output = adapter.extract(
+ items, labels=labels, output_schema=output_schema, instruction=instruction, options=options
+ )
+ except Exception as exc: # noqa: BLE001 — the worker hands adapter errors back through the future
+ future.set_exception(exc)
+ return future
+ request_timing = timing or RequestTiming()
+ if request_timing._inference_start is None:
+ request_timing._inference_start = request_timing._queue_start or 0
+ request_timing._inference_end = request_timing._inference_start
+ future.set_result(WorkerResult(output=output, timing=request_timing))
+ return future
+
+ worker.submit_extract = submit_extract
+ return worker
+
+
+def registry(adapter: MagicMock) -> MagicMock:
+ configs = {
+ DECIDE: ModelConfig(
+ sie_id=DECIDE,
+ hf_id=DECIDE,
+ tasks=Tasks(extract=ExtractTask()),
+ profiles={"default": ProfileConfig(adapter_path=DECIDE_ADAPTER, max_batch_tokens=8192)},
+ ),
+ EMBEDDER: ModelConfig(
+ sie_id=EMBEDDER,
+ hf_id=EMBEDDER,
+ tasks=Tasks(encode=EncodeTask()),
+ profiles={"default": ProfileConfig(adapter_path="test:Embedder", max_batch_tokens=8192)},
+ ),
+ }
+ registry = MagicMock(spec=ModelRegistry)
+ registry.has_model.side_effect = lambda name: name in configs
+ registry.get_config.side_effect = lambda name: configs[name]
+ registry.is_loaded.return_value = True
+ registry.is_loading.return_value = False
+ registry.is_unloading.return_value = False
+ registry.is_failed.return_value = False
+ registry.get_failure.return_value = None
+ registry.get.return_value = adapter
+ registry.model_names = list(configs)
+ registry.device = "cpu"
+ registry.start_worker = AsyncMock(return_value=_worker(adapter))
+ return registry
+
+
+def client(registry: MagicMock) -> TestClient:
+ app = FastAPI()
+ app.include_router(systemone_router)
+ app.state.registry = registry
+ return TestClient(app)
+
+
+def _post(client: TestClient, **body: Any) -> Any:
+ payload = {"model": DECIDE, "state": "I was charged twice. Please fix this ASAP.", "questions": QUESTIONS, **body}
+ return client.post("/v1/systemone", json=payload)
+
+
+class TestAnswers:
+ def test_envelope(self, client: TestClient) -> None:
+ response = _post(client)
+ assert response.status_code == 200
+ assert response.headers["content-type"].startswith("application/json")
+ body = response.json()
+ assert set(body) == {"model", "answers", "usage"}
+ assert body["model"] == DECIDE
+ assert list(body["answers"]) == ["spam", "intent", "urgency"]
+ assert body["usage"] == {"input_tokens": 42, "output_tokens": 0}
+ assert all(type(v) is int for v in body["usage"].values())
+
+ def test_json_even_when_msgpack_is_accepted(self, client: TestClient) -> None:
+ payload = {"model": DECIDE, "state": "hi", "questions": QUESTIONS}
+ response = client.post("/v1/systemone", json=payload, headers={"Accept": "application/msgpack"})
+ assert response.headers["content-type"].startswith("application/json")
+
+ def test_answer_shapes(self, client: TestClient) -> None:
+ answers = _post(client).json()["answers"]
+ assert answers["spam"]["type"] == "noul"
+ assert answers["spam"]["noul"] == pytest.approx(0.9)
+ assert answers["intent"]["choice"] == "billing"
+ assert set(answers["intent"]["probabilities"]) == {"billing", "support", "other"}
+ urgency = answers["urgency"]
+ assert set(urgency["legend"]) == set(urgency["probabilities"]) == {"0", "1", "2"}
+ assert urgency["legend"]["2"] == "Needs attention today"
+ assert all(value is not None for value in urgency["legend"].values())
+
+ def test_confidences_follow_system_one(self, client: TestClient) -> None:
+ answers = _post(client).json()["answers"]
+ # p_max 0.8 over 3 options: (0.8 - 1/3) / (1 - 1/3) = 0.7
+ assert answers["intent"]["confidence"] == pytest.approx(0.7)
+ # probabilities (0.1, 0.1, 0.8): spread 0.3, even 2/3, 1 - 0.45 = 0.55
+ assert answers["urgency"]["confidence"] == pytest.approx(0.55)
+
+ @pytest.mark.parametrize(
+ ("state", "text", "metadata"),
+ [
+ ("plain text", "plain text", None),
+ (
+ {"subject": "refund", "body": "charged twice"},
+ None,
+ {"state": {"subject": "refund", "body": "charged twice"}},
+ ),
+ (["hi", "I was charged twice"], None, {"state": ["hi", "I was charged twice"]}),
+ ],
+ )
+ def test_state_shapes(self, client: TestClient, adapter: MagicMock, state: Any, text: Any, metadata: Any) -> None:
+ assert _post(client, state=state).status_code == 200
+ item = adapter.extract.call_args.args[0][0]
+ assert item.text == text
+ assert item.metadata == metadata
+
+ def test_strict_overflow_and_questions_reach_the_adapter(self, client: TestClient, adapter: MagicMock) -> None:
+ _post(client)
+ kwargs = adapter.extract.call_args.kwargs
+ assert kwargs["options"]["overflow_policy"] == "error"
+ assert list(kwargs["output_schema"]) == ["spam", "intent", "urgency"]
+
+ @pytest.mark.parametrize("question", [{"type": "noul"}, {"type": "noul", "instructions": None}])
+ def test_instructions_optional(self, client: TestClient, adapter: MagicMock, question: dict[str, Any]) -> None:
+ assert _post(client, questions={"spam": question}).status_code == 200
+ assert adapter.extract.call_args.kwargs["output_schema"]["spam"]["instructions"] == ""
+
+ def test_unknown_fields_ignored(self, client: TestClient) -> None:
+ questions = {"spam": {"type": "noul", "instructions": "spam?", "weight": 2}}
+ response = _post(client, questions=questions, metadata={"user": "u1"}, temperature=0)
+ assert response.status_code == 200
+
+
+class TestValidation:
+ def _assert_422(self, response: Any) -> list[dict[str, Any]]:
+ assert response.status_code == 422
+ detail = response.json()["detail"]
+ assert isinstance(detail, list)
+ assert detail
+ assert all("msg" in entry and "loc" in entry for entry in detail)
+ return detail
+
+ @pytest.mark.parametrize(
+ "body",
+ [
+ {"state": "hi", "questions": QUESTIONS},
+ {"model": DECIDE, "questions": QUESTIONS},
+ {"model": DECIDE, "state": "hi"},
+ {"model": DECIDE, "state": "hi", "questions": {}},
+ {"model": DECIDE, "state": 3, "questions": QUESTIONS},
+ {"model": DECIDE, "state": None, "questions": QUESTIONS},
+ ],
+ )
+ def test_malformed_request(self, client: TestClient, body: dict[str, Any]) -> None:
+ self._assert_422(client.post("/v1/systemone", json=body))
+
+ def test_malformed_json(self, client: TestClient) -> None:
+ response = client.post("/v1/systemone", content=b"{", headers={"Content-Type": "application/json"})
+ self._assert_422(response)
+
+ @pytest.mark.parametrize("field", ["images", "audio", "videos"])
+ def test_media_rejected(self, client: TestClient, field: str) -> None:
+ self._assert_422(_post(client, **{field: ["https://example.com/x.png"]}))
+
+ def test_score_level_limit(self, client: TestClient) -> None:
+ questions = {"q": {"type": "score", "instructions": "?", "criteria": [str(i) for i in range(11)]}}
+ detail = self._assert_422(_post(client, questions=questions))
+ assert "at most 10" in detail[0]["msg"]
+
+ def test_score_null_level(self, client: TestClient) -> None:
+ questions = {"q": {"type": "score", "instructions": "?", "criteria": ["low", None]}}
+ self._assert_422(_post(client, questions=questions))
+
+ def test_question_not_an_object(self, client: TestClient) -> None:
+ self._assert_422(_post(client, questions={"q": "spam?"}))
+
+ def test_model_without_typed_questions(self, client: TestClient) -> None:
+ detail = self._assert_422(_post(client, model=EMBEDDER))
+ assert "does not answer typed questions" in detail[0]["msg"]
+
+ def test_adapter_rejects_question(self, client: TestClient, adapter: MagicMock) -> None:
+ adapter.extract.side_effect = ValueError("question 'q': unknown type 'maybe'")
+ detail = self._assert_422(_post(client))
+ assert "unknown type" in detail[0]["msg"]
+
+ def test_questions_over_token_budget(self, client: TestClient, adapter: MagicMock) -> None:
+ adapter.extract.side_effect = InputTooLongError("questions and labels take 300 tokens; at most 256")
+ detail = self._assert_422(_post(client))
+ assert "300 tokens" in detail[0]["msg"]
+
+ def test_state_does_not_fit(self, client: TestClient, adapter: MagicMock) -> None:
+ def too_long(items: list[Any], **_: Any) -> ExtractOutput:
+ error = ExtractItemError(code=ErrorCode.INPUT_TOO_LONG.value, message="The document does not fit")
+ return ExtractOutput(entities=[[]], data=[{}], errors=[error], input_token_counts=[0])
+
+ adapter.extract.side_effect = too_long
+ detail = self._assert_422(_post(client))
+ assert detail[0]["loc"] == ["body", "state"]
+
+
+class TestErrors:
+ def test_unknown_model(self, client: TestClient) -> None:
+ response = _post(client, model="org/missing")
+ assert response.status_code == 404
+ detail = response.json()["detail"]
+ assert detail["error_type"] == "not_found_error"
+ assert "org/missing" in detail["message"]
+
+ def test_missing_answer_is_a_server_error(self, client: TestClient, adapter: MagicMock) -> None:
+ adapter.extract.side_effect = lambda items, **_: ExtractOutput(entities=[[]], data=[{}], input_token_counts=[1])
+ assert _post(client).status_code == 500
+
+ def test_retry_after_capped_and_mirrored(self) -> None:
+ error = HTTPException(
+ status_code=503,
+ detail={"code": "MODEL_LOADING", "message": "loading"},
+ headers={"Retry-After": "270"},
+ )
+ response = error_response(error)
+ assert response.status_code == 503
+ assert response.headers["Retry-After"] == str(MAX_RETRY_AFTER_S)
+ assert response.headers["retry-after-ms"] == str(MAX_RETRY_AFTER_S * 1000)
+
+ def test_short_retry_after_kept(self) -> None:
+ error = HTTPException(
+ status_code=503, detail={"code": "QUEUE_FULL", "message": "busy"}, headers={"Retry-After": "5"}
+ )
+ response = error_response(error)
+ assert response.headers["Retry-After"] == "5"
+ assert response.headers["retry-after-ms"] == "5000"
+
+ def test_bad_request_becomes_422(self) -> None:
+ response = error_response(HTTPException(status_code=400, detail={"code": "INVALID_INPUT", "message": "bad"}))
+ assert response.status_code == 422
+
+
+class TestConfidence:
+ @pytest.mark.parametrize(
+ ("probabilities", "expected"),
+ [([1.0, 0.0], 1.0), ([0.5, 0.5], 0.0), ([0.8, 0.1, 0.1], 0.7), ([1.0], 1.0)],
+ )
+ def test_choice(self, probabilities: list[float], expected: float) -> None:
+ assert choice_confidence(probabilities) == pytest.approx(expected)
+
+ @pytest.mark.parametrize(
+ ("probabilities", "expected"),
+ [([0.0, 0.0, 1.0], 1.0), ([0.1, 0.1, 0.8], 0.55), ([0.5, 0.0, 0.5], 0.0), ([1.0], 1.0)],
+ )
+ def test_score(self, probabilities: list[float], expected: float) -> None:
+ assert score_confidence(probabilities) == pytest.approx(expected)
+
+
+def test_normalize_questions_keeps_other_fields() -> None:
+ questions = {"q": {"type": "noul", "criteria": {"true": "yes"}, "labels": {"false": "ham", "true": "spam"}}}
+ assert normalize_questions(questions)["q"] == {
+ "type": "noul",
+ "criteria": {"true": "yes"},
+ "labels": {"false": "ham", "true": "spam"},
+ "instructions": "",
+ }
+
+
+# ---------------------------------------------------------------------------- shared wire fixture
+
+FIXTURE = json.loads(
+ (Path(__file__).resolve().parents[3] / "wire-fixtures" / "systemone.json").read_text(encoding="utf-8")
+)
+
+
[email protected]("case", FIXTURE["requests"], ids=lambda case: case["name"])
+def test_fixture_requests(client: TestClient, adapter: MagicMock, case: dict[str, Any]) -> None:
+ assert client.post("/v1/systemone", json=case["request"]).status_code == 200
+ expected = case["extract"]
+ items = adapter.extract.call_args.args[0]
+ kwargs = adapter.extract.call_args.kwargs
+ assert len(items) == 1
+ assert items[0].text == expected["item"].get("text")
+ assert items[0].metadata == expected["item"].get("metadata")
+ assert kwargs["output_schema"] == expected["output_schema"]
+ assert kwargs["options"]["overflow_policy"] == expected["options"]["overflow_policy"]
+
+
[email protected]("case", FIXTURE["invalid_requests"], ids=lambda case: case["name"])
+def test_fixture_invalid_requests(client: TestClient, adapter: MagicMock, case: dict[str, Any]) -> None:
+ response = client.post("/v1/systemone", json=case["request"])
+ assert response.status_code == 422
+ assert isinstance(response.json()["detail"], list)
+ adapter.extract.assert_not_called()
+
+
[email protected]("case", FIXTURE["responses"], ids=lambda case: case["name"])
+def test_fixture_responses(client: TestClient, adapter: MagicMock, case: dict[str, Any]) -> None:
+ adapter.extract.side_effect = lambda items, **_: ExtractOutput(
+ entities=[[]], data=[case["data"]], input_token_counts=[case["input_tokens"]]
+ )
+ questions = {qid: {"type": "noul"} for qid in case["questions"]}
+ body = client.post("/v1/systemone", json={"model": case["model"], "state": "x", "questions": questions}).json()
+ assert _approx_equal(body, case["response"])
+
+
+def _approx_equal(actual: Any, expected: Any) -> bool:
+ if isinstance(expected, dict):
+ assert isinstance(actual, dict)
+ assert set(actual) == set(expected)
+ return all(_approx_equal(actual[key], value) for key, value in expected.items())
+ if isinstance(expected, float):
+ assert actual == pytest.approx(expected)
+ return True
+ assert actual == expected
+ assert type(actual) is type(expected)
+ return True
+
+
[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"])
+
+
[email protected]("case", FIXTURE["retry_after"], ids=lambda case: case["retry_after"])
+def test_fixture_retry_after(case: dict[str, str]) -> None:
+ error = HTTPException(
+ status_code=503, detail={"code": "MODEL_LOADING", "message": "x"}, headers={"Retry-After": case["retry_after"]}
+ )
+ response = error_response(error)
+ assert response.headers["Retry-After"] == case["expected"]
+ assert response.headers["retry-after-ms"] == case["expected_ms"]
diff --git a/packages/wire-fixtures/systemone.json b/packages/wire-fixtures/systemone.json
new file mode 100644
index 000000000..7788ea541
--- /dev/null
+++ b/packages/wire-fixtures/systemone.json
@@ -0,0 +1,176 @@
+{
+ "_comment": [
+ "Golden contract of the System One-compatible POST /v1/systemone, served by",
+ "the single server (packages/sie_server/src/sie_server/api/systemone.py) and",
+ "the gateway (packages/sie_gateway/src/handlers/proxy.rs::proxy_systemone).",
+ "Both translate a System One request into one extract item and the extract",
+ "result back into the System One response; both load this file in tests.",
+ "`requests`: a valid request and the extract call it becomes (one item,",
+ "the normalized questions as output_schema, overflow_policy 'error').",
+ "`invalid_requests`: requests both answer with 422 in FastAPI's",
+ "{\"detail\": [{\"loc\", \"msg\", \"type\"}]} shape before any model runs.",
+ "`responses`: an extract item's data and usage, and the System One response",
+ "body they become. Choice and score confidences are recomputed with the",
+ "System One definitions; every other answer field passes through.",
+ "`confidence`: choice (p_max - 1/n) / (1 - 1/n); score max(0, 1 - spread / even).",
+ "`retry_after`: a retryable error's Retry-After, capped at 60 s and mirrored",
+ "in milliseconds as retry-after-ms."
+ ],
+ "max_score_levels": 10,
+ "max_retry_after_s": 60,
+ "requests": [
+ {
+ "name": "text state, all three question types",
+ "request": {
+ "model": "fastino/GLiNER2.5-Decide",
+ "state": "I was charged twice. Please fix this ASAP.",
+ "questions": {
+ "spam": {"type": "noul", "instructions": "Is this message spam?"},
+ "intent": {
+ "type": "choice",
+ "instructions": "What does the sender want?",
+ "criteria": {"billing": "payments and refunds", "support": null}
+ },
+ "urgency": {"type": "score", "instructions": "How urgent?", "criteria": ["Can wait", "Today"]}
+ }
+ },
+ "extract": {
+ "model": "fastino/GLiNER2.5-Decide",
+ "item": {"text": "I was charged twice. Please fix this ASAP."},
+ "output_schema": {
+ "spam": {"type": "noul", "instructions": "Is this message spam?"},
+ "intent": {
+ "type": "choice",
+ "instructions": "What does the sender want?",
+ "criteria": {"billing": "payments and refunds", "support": null}
+ },
+ "urgency": {"type": "score", "instructions": "How urgent?", "criteria": ["Can wait", "Today"]}
+ },
+ "options": {"overflow_policy": "error"}
+ }
+ },
+ {
+ "name": "object state, missing and null instructions, unknown fields ignored",
+ "request": {
+ "model": "fastino/GLiNER2.5-Decide",
+ "state": {"subject": "refund", "body": "charged twice"},
+ "questions": {
+ "a": {"type": "noul", "criteria": {"true": "asks for money back"}},
+ "b": {"type": "noul", "instructions": null, "weight": 2}
+ },
+ "metadata": {"user": "u1"},
+ "temperature": 0
+ },
+ "extract": {
+ "model": "fastino/GLiNER2.5-Decide",
+ "item": {"metadata": {"state": {"subject": "refund", "body": "charged twice"}}},
+ "output_schema": {
+ "a": {"type": "noul", "criteria": {"true": "asks for money back"}, "instructions": ""},
+ "b": {"type": "noul", "instructions": "", "weight": 2}
+ },
+ "options": {"overflow_policy": "error"}
+ }
+ },
+ {
+ "name": "conversation state",
+ "request": {
+ "model": "fastino/GLiNER2.5-Decide",
+ "state": [{"role": "user", "content": "hi"}, {"role": "user", "content": "refund please"}],
+ "questions": {"refund": {"type": "noul", "instructions": "Asks for a refund?"}}
+ },
+ "extract": {
+ "model": "fastino/GLiNER2.5-Decide",
+ "item": {"metadata": {"state": [{"role": "user", "content": "hi"}, {"role": "user", "content": "refund please"}]}},
+ "output_schema": {"refund": {"type": "noul", "instructions": "Asks for a refund?"}},
+ "options": {"overflow_policy": "error"}
+ }
+ }
+ ],
+ "invalid_requests": [
+ {"name": "missing model", "request": {"state": "hi", "questions": {"q": {"type": "noul"}}}},
+ {"name": "empty model", "request": {"model": "", "state": "hi", "questions": {"q": {"type": "noul"}}}},
+ {"name": "missing state", "request": {"model": "fastino/GLiNER2.5-Decide", "questions": {"q": {"type": "noul"}}}},
+ {"name": "null state", "request": {"model": "fastino/GLiNER2.5-Decide", "state": null, "questions": {"q": {"type": "noul"}}}},
+ {"name": "number state", "request": {"model": "fastino/GLiNER2.5-Decide", "state": 3, "questions": {"q": {"type": "noul"}}}},
+ {"name": "boolean state", "request": {"model": "fastino/GLiNER2.5-Decide", "state": true, "questions": {"q": {"type": "noul"}}}},
+ {"name": "missing questions", "request": {"model": "fastino/GLiNER2.5-Decide", "state": "hi"}},
+ {"name": "empty questions", "request": {"model": "fastino/GLiNER2.5-Decide", "state": "hi", "questions": {}}},
+ {"name": "questions not an object", "request": {"model": "fastino/GLiNER2.5-Decide", "state": "hi", "questions": [{"type": "noul"}]}},
+ {"name": "question not an object", "request": {"model": "fastino/GLiNER2.5-Decide", "state": "hi", "questions": {"q": "spam?"}}},
+ {
+ "name": "eleven score levels",
+ "request": {
+ "model": "fastino/GLiNER2.5-Decide",
+ "state": "hi",
+ "questions": {"q": {"type": "score", "criteria": ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10"]}}
+ }
+ },
+ {"name": "null score level", "request": {"model": "fastino/GLiNER2.5-Decide", "state": "hi", "questions": {"q": {"type": "score", "criteria": ["low", null]}}}},
+ {"name": "images", "request": {"model": "fastino/GLiNER2.5-Decide", "state": "hi", "questions": {"q": {"type": "noul"}}, "images": ["https://example.com/a.png"]}},
+ {"name": "audio", "request": {"model": "fastino/GLiNER2.5-Decide", "state": "hi", "questions": {"q": {"type": "noul"}}, "audio": ["https://example.com/a.wav"]}},
+ {"name": "videos", "request": {"model": "fastino/GLiNER2.5-Decide", "state": "hi", "questions": {"q": {"type": "noul"}}, "videos": ["https://example.com/a.mp4"]}}
+ ],
+ "responses": [
+ {
+ "name": "noul, choice and score",
+ "model": "fastino/GLiNER2.5-Decide",
+ "questions": ["spam", "intent", "urgency"],
+ "data": {
+ "spam": {"type": "noul", "noul": 0.9, "answer": true, "confidence": 0.9},
+ "intent": {
+ "type": "choice",
+ "choice": "billing",
+ "probabilities": {"billing": 0.8, "support": 0.1, "other": 0.1},
+ "confidence": 0.123
+ },
+ "urgency": {
+ "type": "score",
+ "score": 1.7,
+ "legend": {"0": "Can wait", "1": "This week", "2": "Today"},
+ "probabilities": {"0": 0.1, "1": 0.1, "2": 0.8},
+ "confidence": 0.123
+ }
+ },
+ "input_tokens": 42,
+ "response": {
+ "model": "fastino/GLiNER2.5-Decide",
+ "answers": {
+ "spam": {"type": "noul", "noul": 0.9, "answer": true, "confidence": 0.9},
+ "intent": {
+ "type": "choice",
+ "choice": "billing",
+ "probabilities": {"billing": 0.8, "support": 0.1, "other": 0.1},
+ "confidence": 0.7
+ },
+ "urgency": {
+ "type": "score",
+ "score": 1.7,
+ "legend": {"0": "Can wait", "1": "This week", "2": "Today"},
+ "probabilities": {"0": 0.1, "1": 0.1, "2": 0.8},
+ "confidence": 0.55
+ }
+ },
+ "usage": {"input_tokens": 42, "output_tokens": 0}
+ }
+ }
+ ],
+ "confidence": {
+ "choice": [
+ {"probabilities": [1.0, 0.0], "confidence": 1.0},
+ {"probabilities": [0.5, 0.5], "confidence": 0.0},
+ {"probabilities": [0.8, 0.1, 0.1], "confidence": 0.7},
+ {"probabilities": [1.0], "confidence": 1.0}
+ ],
+ "score": [
+ {"probabilities": [0.0, 0.0, 1.0], "confidence": 1.0},
+ {"probabilities": [0.1, 0.1, 0.8], "confidence": 0.55},
+ {"probabilities": [0.5, 0.0, 0.5], "confidence": 0.0},
+ {"probabilities": [1.0], "confidence": 1.0}
+ ]
+ },
+ "retry_after": [
+ {"retry_after": "270", "expected": "60", "expected_ms": "60000"},
+ {"retry_after": "60", "expected": "60", "expected_ms": "60000"},
+ {"retry_after": "5", "expected": "5", "expected_ms": "5000"}
+ ]
+}