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 OpenAI Decisions compatibility for text models

svonava5cebd8791d25
diff --git a/packages/sie_server/openapi.json b/packages/sie_server/openapi.json
index 283056a69..9c4610fb9 100644
--- a/packages/sie_server/openapi.json
+++ b/packages/sie_server/openapi.json
@@ -1217,6 +1217,145 @@
}
}
}
+ },
+ "/v1/decisions": {
+ "post": {
+ "tags": [
+ "openai-compat"
+ ],
+ "summary": "Decisions",
+ "description": "Answer ordered predicate, choice, and score questions with a text decision model.",
+ "operationId": "decisions_v1_decisions_post",
+ "parameters": [
+ {
+ "name": "X-SIE-MACHINE-PROFILE",
+ "in": "header",
+ "required": false,
+ "schema": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "X-Sie-Machine-Profile"
+ }
+ },
+ {
+ "name": "X-SIE-Remote",
+ "in": "header",
+ "required": false,
+ "schema": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "The only accepted value is `forbid`. It keeps the request off remote upstreams: local capacity serves or refuses it, and a model served only by an upstream answers 400. Any other value answers 400.",
+ "title": "X-Sie-Remote"
+ },
+ "description": "The only accepted value is `forbid`. It keeps the request off remote upstreams: local capacity serves or refuses it, and a model served only by an upstream answers 400. Any other value answers 400."
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/DecisionResponse"
+ }
+ }
+ }
+ },
+ "400": {
+ "description": "Invalid or unsupported input"
+ },
+ "404": {
+ "description": "Model not found"
+ },
+ "503": {
+ "description": "Model loading or capacity exhausted"
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ }
+ }
+ },
+ "requestBody": {
+ "required": true,
+ "content": {
+ "application/json": {
+ "schema": {
+ "properties": {
+ "model": {
+ "description": "SIE decision model id, for example fastino/GLiNER2.5-Decide.",
+ "title": "Model",
+ "type": "string"
+ },
+ "input": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "items": {
+ "additionalProperties": true,
+ "type": "object"
+ },
+ "type": "array"
+ }
+ ],
+ "description": "Text or text-only messages, in conversation order.",
+ "title": "Input"
+ },
+ "questions": {
+ "description": "Predicate, choice, or score questions, in answer order.",
+ "items": {
+ "additionalProperties": true,
+ "type": "object"
+ },
+ "maxItems": 200,
+ "minItems": 1,
+ "title": "Questions",
+ "type": "array"
+ },
+ "safety_identifier": {
+ "anyOf": [
+ {
+ "maxLength": 128,
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Safety Identifier"
+ }
+ },
+ "required": [
+ "model",
+ "input",
+ "questions"
+ ],
+ "title": "DecisionRequest",
+ "type": "object"
+ }
+ }
+ }
+ }
+ }
}
},
"components": {
@@ -1242,6 +1381,71 @@
"title": "ClassificationModel",
"description": "Classification result."
},
+ "DecisionResponse": {
+ "properties": {
+ "model": {
+ "type": "string",
+ "title": "Model"
+ },
+ "answers": {
+ "items": {
+ "additionalProperties": true,
+ "type": "object"
+ },
+ "type": "array",
+ "title": "Answers"
+ },
+ "usage": {
+ "$ref": "#/components/schemas/DecisionUsage"
+ }
+ },
+ "type": "object",
+ "required": [
+ "model",
+ "answers",
+ "usage"
+ ],
+ "title": "DecisionResponse"
+ },
+ "DecisionUsage": {
+ "properties": {
+ "input_tokens": {
+ "type": "integer",
+ "title": "Input Tokens"
+ },
+ "input_tokens_details": {
+ "additionalProperties": {
+ "type": "integer"
+ },
+ "type": "object",
+ "title": "Input Tokens Details"
+ },
+ "output_tokens": {
+ "type": "integer",
+ "title": "Output Tokens",
+ "default": 0
+ },
+ "output_tokens_details": {
+ "additionalProperties": {
+ "type": "integer"
+ },
+ "type": "object",
+ "title": "Output Tokens Details"
+ },
+ "total_tokens": {
+ "type": "integer",
+ "title": "Total Tokens"
+ }
+ },
+ "type": "object",
+ "required": [
+ "input_tokens",
+ "input_tokens_details",
+ "output_tokens_details",
+ "total_tokens"
+ ],
+ "title": "DecisionUsage"
+ },
"DenseVectorModel": {
"properties": {
"dims": {
diff --git a/packages/sie_server/src/sie_server/api/decisions.py b/packages/sie_server/src/sie_server/api/decisions.py
new file mode 100644
index 000000000..520b6d793
--- /dev/null
+++ b/packages/sie_server/src/sie_server/api/decisions.py
@@ -0,0 +1,314 @@
+"""OpenAI-compatible text decisions over SIE's typed decision models."""
+
+from __future__ import annotations
+
+import json
+import math
+import re
+from typing import Annotated, Any, cast
+
+from fastapi import APIRouter, Depends, Header, HTTPException, Request, status
+from fastapi.responses import JSONResponse
+from pydantic import BaseModel, Field
+
+from sie_server.api import systemone
+from sie_server.api.helpers import openai_error_response, read_bounded_request_body
+from sie_server.api.routing import error_code, fallback_refusal, remote_routing
+
+router = APIRouter(prefix="/v1", tags=["openai-compat"], dependencies=[Depends(remote_routing)])
+
+MAX_BODY_BYTES = 16 * 1024 * 1024
+MAX_QUESTIONS = 200
+MAX_CHOICES = 255
+MAX_MESSAGES = 4096
+MAX_FIELD_CHARS = 1_048_576
+MAX_SAFETY_IDENTIFIER_CHARS = 128
+PROBABILITY_TOLERANCE = 1e-4
+
+
+class DecisionRequest(BaseModel):
+ model: str = Field(description="SIE decision model id, for example fastino/GLiNER2.5-Decide.")
+ input: str | list[dict[str, Any]] = Field(description="Text or text-only messages, in conversation order.")
+ questions: list[dict[str, Any]] = Field(
+ min_length=1, max_length=MAX_QUESTIONS, description="Predicate, choice, or score questions, in answer order."
+ )
+ safety_identifier: str | None = Field(default=None, max_length=128)
+
+
+class DecisionUsage(BaseModel):
+ input_tokens: int
+ input_tokens_details: dict[str, int]
+ output_tokens: int = 0
+ output_tokens_details: dict[str, int]
+ total_tokens: int
+
+
+class DecisionResponse(BaseModel):
+ model: str
+ answers: list[dict[str, Any]]
+ usage: DecisionUsage
+
+
+def invalid(message: str, param: str | None = None, *, code: str = "invalid_request") -> HTTPException:
+ return HTTPException(400, {"message": message, "type": "invalid_request_error", "param": param, "code": code})
+
+
+def _text(value: Any, param: str) -> str:
+ if not isinstance(value, str):
+ raise invalid("must be a string", param)
+ if len(value) > MAX_FIELD_CHARS:
+ raise invalid(f"must contain at most {MAX_FIELD_CHARS} characters", param)
+ return value
+
+
+def _fields(value: dict[str, Any], allowed: set[str], param: str) -> None:
+ for key in value:
+ if key not in allowed:
+ raise invalid("unsupported field", f"{param}.{key}" if param else key, code="unsupported_field")
+
+
+def _input(value: Any) -> str | list[dict[str, Any]]:
+ if isinstance(value, str):
+ return value
+ if not isinstance(value, list) or not 1 <= len(value) <= MAX_MESSAGES:
+ raise invalid(f"must be text or 1 to {MAX_MESSAGES} text messages", "input")
+ for index, message in enumerate(value):
+ param = f"input[{index}]"
+ if not isinstance(message, dict):
+ raise invalid("must be a message object", param)
+ message = cast("dict[str, Any]", message)
+ _fields(message, {"type", "role", "content", "phase"}, param)
+ if message.get("type", "message") != "message":
+ raise invalid("SIE decision models support text messages, not tool calls or media", f"{param}.type")
+ role = message.get("role")
+ if role not in ("user", "developer", "system", "assistant"):
+ raise invalid("unsupported message role", f"{param}.role")
+ if message.get("phase") not in (None, "commentary", "final_answer"):
+ raise invalid("unsupported message phase", f"{param}.phase")
+ content = message.get("content")
+ if isinstance(content, str):
+ continue
+ if not isinstance(content, list) or not content:
+ raise invalid("must be text or a non-empty list of text parts", f"{param}.content")
+ for part_index, part in enumerate(content):
+ part_param = f"{param}.content[{part_index}]"
+ if not isinstance(part, dict):
+ raise invalid("must be a text part", part_param)
+ part = cast("dict[str, Any]", part)
+ kind = part.get("type")
+ allowed = ("output_text", "refusal") if role == "assistant" else ("input_text",)
+ if kind not in allowed:
+ raise invalid("SIE decision models read text only; unsupported content part", f"{part_param}.type")
+ field = "refusal" if kind == "refusal" else "text"
+ _fields(part, {"type", field}, part_param)
+ if not isinstance(part.get(field), str):
+ raise invalid("must be a string", f"{part_param}.{field}")
+ return cast("list[dict[str, Any]]", value)
+
+
+def _description(value: str | bool, description: str | None, *, typed: bool = False) -> str:
+ label = json.dumps(value, ensure_ascii=False) if typed else str(value)
+ return f"{label}: {description}" if description else label
+
+
+def normalize_request(body: Any) -> tuple[systemone.SystemOneRequest, list[dict[str, Any]]]:
+ """Validate the public contract and preserve ordered, typed option identities.
+
+ Raises:
+ HTTPException: An unsupported or invalid request field.
+ """
+ if not isinstance(body, dict):
+ raise invalid("request body must be a JSON object")
+ _fields(body, {"model", "input", "questions", "safety_identifier"}, "")
+ model = _text(body.get("model"), "model")
+ if re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9._/-]*", model) is None or ".." in model:
+ raise invalid("invalid model id", "model")
+ if body.get("safety_identifier") is not None:
+ identifier = _text(body["safety_identifier"], "safety_identifier")
+ if len(identifier) > MAX_SAFETY_IDENTIFIER_CHARS:
+ raise invalid("must contain at most 128 characters", "safety_identifier")
+ state = _input(body.get("input"))
+ questions = body.get("questions")
+ if not isinstance(questions, list) or not 1 <= len(questions) <= MAX_QUESTIONS:
+ raise invalid(f"must contain 1 to {MAX_QUESTIONS} questions", "questions")
+ native: dict[str, Any] = {}
+ for index, question in enumerate(questions):
+ param = f"questions[{index}]"
+ if not isinstance(question, dict):
+ raise invalid("must be a question object", param)
+ question = cast("dict[str, Any]", question)
+ kind = question.get("type")
+ if kind not in ("predicate", "choice", "score"):
+ raise invalid("must be predicate, choice, or score", f"{param}.type")
+ extra = {"choices"} if kind == "choice" else ({"levels"} if kind == "score" else set())
+ _fields(question, {"type", "name", "instructions"} | extra, param)
+ instructions = _text(question.get("instructions"), f"{param}.instructions")
+ if "name" in question:
+ _text(question["name"], f"{param}.name")
+ normalized: dict[str, Any] = {"type": "noul" if kind == "predicate" else kind, "instructions": instructions}
+ if kind in ("choice", "score"):
+ field = "choices" if kind == "choice" else "levels"
+ options = question.get(field)
+ minimum, maximum = (2, MAX_CHOICES) if kind == "choice" else (1, systemone.MAX_SCORE_LEVELS)
+ if not isinstance(options, list) or not minimum <= len(options) <= maximum:
+ raise invalid(f"must contain {minimum} to {maximum} entries", f"{param}.{field}")
+ descriptions: list[str] = []
+ seen: set[tuple[type, str | bool]] = set()
+ for option_index, option in enumerate(options):
+ option_param = f"{param}.{field}[{option_index}]"
+ if not isinstance(option, dict):
+ raise invalid("must be an object", option_param)
+ option = cast("dict[str, Any]", option)
+ value_field = "value" if kind == "choice" else "label"
+ _fields(option, {value_field, "description"}, option_param)
+ value = option.get(value_field)
+ if kind == "choice" and type(value) not in (str, bool):
+ raise invalid("must be a string or boolean", f"{option_param}.value")
+ if kind == "score" or isinstance(value, str):
+ _text(value, f"{option_param}.{value_field}")
+ value = cast("str | bool", value)
+ if kind == "choice":
+ identity = (type(value), value)
+ if identity in seen:
+ raise invalid("choice values must be unique", f"{option_param}.value")
+ seen.add(identity)
+ description = (
+ _text(option["description"], f"{option_param}.description") if "description" in option else None
+ )
+ descriptions.append(_description(value, description, typed=kind == "choice"))
+ normalized["criteria"] = (
+ {f"option_{i}": description for i, description in enumerate(descriptions)}
+ if kind == "choice"
+ else descriptions
+ )
+ native[f"question_{index}"] = normalized
+ return systemone.SystemOneRequest(model=model, state=state, questions=native), questions
+
+
+def _probability(value: Any) -> float:
+ if isinstance(value, bool) or not isinstance(value, int | float) or not math.isfinite(value) or not 0 <= value <= 1:
+ raise ValueError("invalid decision probability")
+ return float(value)
+
+
+def response_from_systemone(body: dict[str, Any], questions: list[dict[str, Any]]) -> dict[str, Any]:
+ """Render answers without losing question order or boolean choice values.
+
+ Raises:
+ ValueError: The model returned an invalid answer distribution.
+ KeyError: A required answer field is absent.
+ TypeError: The model returned an invalid answer shape.
+ """
+ answers = []
+ for index, question in enumerate(questions):
+ answer = body["answers"][f"question_{index}"]
+ kind = question["type"]
+ output: dict[str, Any] = {"type": kind, "name": question.get("name")}
+ if answer.get("type") == "refusal":
+ output["type"] = "refusal"
+ elif kind == "predicate":
+ if answer.get("type") != "noul":
+ raise ValueError("unexpected predicate answer type")
+ output["probability"] = _probability(answer["noul"])
+ else:
+ if answer.get("type") != kind:
+ raise ValueError("unexpected decision answer type")
+ options = question["choices" if kind == "choice" else "levels"]
+ keys = [f"option_{i}" if kind == "choice" else str(i) for i in range(len(options))]
+ probabilities = answer["probabilities"]
+ if not isinstance(probabilities, dict) or set(probabilities) != set(keys):
+ raise ValueError("decision probability keys do not match the options")
+ values = [_probability(probabilities[key]) for key in keys]
+ if abs(sum(values) - 1.0) > PROBABILITY_TOLERANCE:
+ raise ValueError("decision probabilities must sum to one")
+ if kind == "choice":
+ choice = answer["choice"]
+ if choice not in keys:
+ raise ValueError("decision choice is not an allowed option")
+ output["choice"] = options[keys.index(choice)]["value"]
+ output["probabilities"] = [
+ {"value": option["value"], "probability": p} for option, p in zip(options, values, strict=True)
+ ]
+ output["confidence"] = systemone.choice_confidence(values)
+ else:
+ output["score"] = sum(i * p for i, p in enumerate(values))
+ output["probabilities"] = [
+ {"value": i, "label": option["label"], "probability": p}
+ for i, (option, p) in enumerate(zip(options, values, strict=True))
+ ]
+ output["confidence"] = systemone.score_confidence(values)
+ answers.append(output)
+ tokens = body["usage"]["input_tokens"]
+ if type(tokens) is not int or tokens < 0:
+ raise ValueError("invalid input token count")
+ return {
+ "model": body["model"],
+ "answers": answers,
+ "usage": {
+ "input_tokens": tokens,
+ "input_tokens_details": {"cached_tokens": 0, "cache_write_tokens": 0},
+ "output_tokens": 0,
+ "output_tokens_details": {"reasoning_tokens": 0},
+ "total_tokens": tokens,
+ },
+ }
+
+
+def _translate_error(error: HTTPException) -> HTTPException:
+ detail = error.detail
+ if isinstance(detail, list) and detail:
+ first = detail[0]
+ loc = first.get("loc", [])[1:]
+ param = ".".join("input" if part == "state" else str(part) for part in loc) or None
+ detail = {
+ "message": first.get("msg", "invalid request"),
+ "param": param,
+ "code": first.get("code", "invalid_request"),
+ }
+ response_status = (
+ status.HTTP_400_BAD_REQUEST if error.status_code == status.HTTP_422_UNPROCESSABLE_CONTENT else error.status_code
+ )
+ return HTTPException(response_status, detail, headers=systemone._retry_headers(error.headers))
+
+
+ "/decisions",
+ response_model=DecisionResponse,
+ openapi_extra={
+ "requestBody": {
+ "required": True,
+ "content": {"application/json": {"schema": DecisionRequest.model_json_schema()}},
+ }
+ },
+ responses={
+ 400: {"description": "Invalid or unsupported input"},
+ 404: {"description": "Model not found"},
+ 503: {"description": "Model loading or capacity exhausted"},
+ },
+)
+async def decisions(
+ http_request: Request,
+ x_machine_profile: Annotated[str | None, Header(alias="X-SIE-MACHINE-PROFILE")] = None,
+) -> JSONResponse:
+ """Answer ordered predicate, choice, and score questions with a text decision model."""
+ try:
+ raw = await read_bounded_request_body(http_request, MAX_BODY_BYTES)
+ try:
+ parsed = json.loads(raw)
+ except (ValueError, UnicodeDecodeError, RecursionError) as exc:
+ raise invalid("request body must be valid JSON") from exc
+ request, questions = normalize_request(parsed)
+ try:
+ response = await systemone._system_one(request, http_request, x_machine_profile)
+ body = response_from_systemone(json.loads(bytes(response.body)), questions)
+ except (KeyError, TypeError, ValueError, AttributeError) as exc:
+ raise HTTPException(
+ 500, {"message": "model returned an invalid decision result", "code": "INTERNAL_ERROR"}
+ ) from exc
+ headers = {
+ key: value for key, value in response.headers.items() if key not in ("content-length", "content-type")
+ }
+ return JSONResponse(body, headers=headers)
+ except HTTPException as exc:
+ refusal = fallback_refusal(http_request, exc.status_code, error_code(exc))
+ return openai_error_response(_translate_error(refusal or exc))
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 ec719b99c..494687320 100644
--- a/packages/sie_server/src/sie_server/app/app_factory.py
+++ b/packages/sie_server/src/sie_server/app/app_factory.py
@@ -9,6 +9,7 @@ import torch
from fastapi import FastAPI
from sie_server import __version__
+from sie_server.api.decisions import router as decisions_router
from sie_server.api.encode import router as encode_router
from sie_server.api.extract import router as extract_router
from sie_server.api.generate import router as generate_router
@@ -134,6 +135,7 @@ class AppFactory:
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
+ app.include_router(decisions_router)
# 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/src/sie_server/cli.py b/packages/sie_server/src/sie_server/cli.py
index 9ae236f21..ab7987419 100644
--- a/packages/sie_server/src/sie_server/cli.py
+++ b/packages/sie_server/src/sie_server/cli.py
@@ -42,6 +42,7 @@ from sie_sdk.bundle_utils import (
)
import sie_server
+from sie_server.api.decisions import router as decisions_router
from sie_server.api.generate import router as generate_router
from sie_server.api.openai_audio import router as openai_audio_router
from sie_server.app.app_state_config import (
@@ -431,6 +432,7 @@ def openapi_export(
app_.include_router(openai_completions_router)
app_.include_router(openai_responses_router)
app_.include_router(systemone_router)
+ app_.include_router(decisions_router)
setup_custom_openapi_schema(app_)
spec = app_.openapi()
diff --git a/packages/sie_server/tests/api/test_decisions.py b/packages/sie_server/tests/api/test_decisions.py
new file mode 100644
index 000000000..1fd71b585
--- /dev/null
+++ b/packages/sie_server/tests/api/test_decisions.py
@@ -0,0 +1,165 @@
+"""OpenAI Decisions wire contract and the direct worker dispatch boundary."""
+
+import copy
+import json
+from pathlib import Path
+from types import SimpleNamespace
+from unittest.mock import AsyncMock, MagicMock
+
+import pytest
+from fastapi import FastAPI, HTTPException
+from fastapi.testclient import TestClient
+from sie_server.api import decisions, systemone
+from sie_server.config.model import 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
+
+FIXTURE = json.loads((Path(__file__).resolve().parents[3] / "wire-fixtures" / "decisions.json").read_text())
+
+
+def assert_contract(actual, expected):
+ if isinstance(expected, dict):
+ assert set(actual) == set(expected)
+ for key, value in expected.items():
+ assert_contract(actual[key], value)
+ elif isinstance(expected, list):
+ assert len(actual) == len(expected)
+ for left, right in zip(actual, expected, strict=True):
+ assert_contract(left, right)
+ elif isinstance(expected, float):
+ assert actual == pytest.approx(expected)
+ else:
+ assert type(actual) is type(expected)
+ assert actual == expected
+
+
[email protected]("case", FIXTURE["requests"], ids=lambda case: case["name"])
+def test_shared_contract(case):
+ request, questions = decisions.normalize_request(case["request"])
+ assert request.model_dump() == case["systemone"]
+ response = decisions.response_from_systemone(
+ {"model": request.model, "answers": case["native_answers"], "usage": {"input_tokens": 42}}, questions
+ )
+ assert_contract(response, case["response"])
+
+
[email protected]("case", FIXTURE["invalid_requests"], ids=lambda case: case["name"])
+def test_shared_invalid_contract(case):
+ with pytest.raises(HTTPException) as caught:
+ decisions.normalize_request(case["request"])
+ assert caught.value.status_code == 400
+ assert caught.value.detail["param"] == case["param"]
+
+
+def dispatch(monkeypatch):
+ case = FIXTURE["requests"][0]
+ config = ModelConfig(
+ sie_id=case["request"]["model"],
+ hf_id=case["request"]["model"],
+ tasks=Tasks(extract=ExtractTask()),
+ profiles={
+ "default": ProfileConfig(
+ adapter_path="sie_server.adapters.gliner2.decide:GLiNER2DecideAdapter", max_batch_tokens=8192
+ )
+ },
+ )
+ registry = MagicMock(spec=ModelRegistry)
+ registry.has_model.return_value = True
+ registry.get_config.return_value = config
+ route = SimpleNamespace(key="route", headers=lambda: {"X-SIE-Served-By": "local"})
+ route_mock = AsyncMock(return_value=route)
+ monkeypatch.setattr(systemone, "route_request", route_mock)
+ timing = RequestTiming()
+ output = ExtractOutput(entities=[[]], data=[copy.deepcopy(case["native_answers"])], input_token_counts=[42])
+ worker = AsyncMock(return_value=WorkerResult(output=output, timing=timing))
+ monkeypatch.setattr(systemone, "_extract_via_worker", worker)
+ app = FastAPI()
+ app.include_router(decisions.router)
+ app.include_router(systemone.router)
+ app.state.registry = registry
+ return SimpleNamespace(client=TestClient(app), worker=worker, route=route_mock, registry=registry, output=output)
+
+
+def test_route_uses_native_worker_and_preserves_headers(dispatch):
+ case = FIXTURE["requests"][0]
+ response = dispatch.client.post("/v1/decisions", json=case["request"])
+ assert response.status_code == 200
+ assert_contract(response.json(), case["response"])
+ assert response.headers["x-sie-served-by"] == "local"
+ assert int(response.headers["content-length"]) == len(response.content)
+ args = dispatch.worker.call_args
+ assert args.args[2][0].text == case["request"]["input"]
+ assert args.kwargs["output_schema"] == case["systemone"]["questions"]
+ assert args.kwargs["options"]["overflow_policy"] == "error"
+
+
[email protected]("case", FIXTURE["invalid_requests"], ids=lambda case: case["name"])
+def test_invalid_request_does_not_dispatch(dispatch, case):
+ response = dispatch.client.post("/v1/decisions", json=case["request"])
+ assert response.status_code == 400
+ assert response.json()["error"]["param"] == case["param"]
+ dispatch.worker.assert_not_awaited()
+ dispatch.route.assert_not_awaited()
+
+
+def test_unknown_model_error_is_openai_shaped(dispatch):
+ dispatch.registry.has_model.return_value = False
+ dispatch.registry.model_names = []
+ response = dispatch.client.post("/v1/decisions", json=FIXTURE["requests"][0]["request"])
+ assert response.status_code == 404
+ assert response.json()["error"]["code"] == "MODEL_NOT_FOUND"
+ dispatch.worker.assert_not_awaited()
+
+
+def test_retry_headers_survive(dispatch):
+ dispatch.route.side_effect = HTTPException(
+ 503, {"code": "MODEL_LOADING", "message": "loading"}, headers={"Retry-After": "30"}
+ )
+ response = dispatch.client.post("/v1/decisions", json=FIXTURE["requests"][0]["request"])
+ assert response.status_code == 503
+ assert response.headers["retry-after"] == "30"
+ assert response.json()["error"]["code"] == "MODEL_LOADING"
+
+
[email protected]("invalid_probability", [-0.1, 1.1, True, "0.9", None, float("nan"), float("inf")])
+def test_invalid_predicate_output_is_server_error(dispatch, invalid_probability):
+ dispatch.output.data[0]["question_0"]["noul"] = invalid_probability
+ response = dispatch.client.post("/v1/decisions", json=FIXTURE["requests"][0]["request"])
+ assert response.status_code == 500
+ assert response.json()["error"]["type"] == "server_error"
+
+
+ "probabilities", [{"option_0": 0.9}, {"option_0": 0.9, "option_1": 0.9}, {"option_0": -0.1, "option_1": 1.1}]
+)
+def test_invalid_distribution_is_server_error(dispatch, probabilities):
+ dispatch.output.data[0]["question_1"]["probabilities"] = probabilities
+ response = dispatch.client.post("/v1/decisions", json=FIXTURE["requests"][0]["request"])
+ assert response.status_code == 500
+
+
+def test_body_limit_precedes_model_work(dispatch, monkeypatch):
+ monkeypatch.setattr(decisions, "MAX_BODY_BYTES", 16)
+ response = dispatch.client.post("/v1/decisions", json=FIXTURE["requests"][0]["request"])
+ assert response.status_code == 413
+ assert "error" in response.json()
+ dispatch.worker.assert_not_awaited()
+
+
[email protected]("raw", ["{", "[]", "null"])
+def test_malformed_body_is_openai_shaped(dispatch, raw):
+ response = dispatch.client.post("/v1/decisions", content=raw)
+ assert response.status_code == 400
+ assert response.json()["error"]["type"] == "invalid_request_error"
+
+
+def test_model_refusal_preserves_code_and_names_input(dispatch):
+ dispatch.output.errors = [ExtractItemError(code=ErrorCode.INPUT_TOO_LONG.value, message="too long")]
+ response = dispatch.client.post("/v1/decisions", json=FIXTURE["requests"][0]["request"])
+ assert response.status_code == 400
+ assert response.json()["error"]["code"] == "INPUT_TOO_LONG"
+ assert response.json()["error"]["param"] == "input"
diff --git a/packages/wire-fixtures/decisions.json b/packages/wire-fixtures/decisions.json
new file mode 100644
index 000000000..a4097ed2b
--- /dev/null
+++ b/packages/wire-fixtures/decisions.json
@@ -0,0 +1,476 @@
+{
+ "requests": [
+ {
+ "name": "ordered_typed_answers",
+ "request": {
+ "model": "fastino/GLiNER2.5-Decide",
+ "input": "I was charged twice and need a refund.",
+ "questions": [
+ {
+ "type": "predicate",
+ "name": "refund",
+ "instructions": "Is the customer asking for a refund?"
+ },
+ {
+ "type": "choice",
+ "name": "department",
+ "instructions": "Which department should respond?",
+ "choices": [
+ {
+ "value": "billing",
+ "description": "Payments and refunds"
+ },
+ {
+ "value": "technical"
+ }
+ ]
+ },
+ {
+ "type": "score",
+ "name": "urgency",
+ "instructions": "How urgent is this?",
+ "levels": [
+ {
+ "label": "Low"
+ },
+ {
+ "label": "Medium",
+ "description": "Needs attention this week"
+ },
+ {
+ "label": "High"
+ }
+ ]
+ }
+ ]
+ },
+ "systemone": {
+ "model": "fastino/GLiNER2.5-Decide",
+ "state": "I was charged twice and need a refund.",
+ "questions": {
+ "question_0": {
+ "type": "noul",
+ "instructions": "Is the customer asking for a refund?"
+ },
+ "question_1": {
+ "type": "choice",
+ "instructions": "Which department should respond?",
+ "criteria": {
+ "option_0": "\"billing\": Payments and refunds",
+ "option_1": "\"technical\""
+ }
+ },
+ "question_2": {
+ "type": "score",
+ "instructions": "How urgent is this?",
+ "criteria": [
+ "Low",
+ "Medium: Needs attention this week",
+ "High"
+ ]
+ }
+ }
+ },
+ "native_answers": {
+ "question_0": {
+ "type": "noul",
+ "noul": 0.9
+ },
+ "question_1": {
+ "type": "choice",
+ "choice": "option_0",
+ "probabilities": {
+ "option_1": 0.1,
+ "option_0": 0.9
+ }
+ },
+ "question_2": {
+ "type": "score",
+ "score": 1.1,
+ "probabilities": {
+ "2": 0.2,
+ "0": 0.1,
+ "1": 0.7
+ }
+ }
+ },
+ "response": {
+ "model": "fastino/GLiNER2.5-Decide",
+ "answers": [
+ {
+ "type": "predicate",
+ "name": "refund",
+ "probability": 0.9
+ },
+ {
+ "type": "choice",
+ "name": "department",
+ "choice": "billing",
+ "probabilities": [
+ {
+ "value": "billing",
+ "probability": 0.9
+ },
+ {
+ "value": "technical",
+ "probability": 0.1
+ }
+ ],
+ "confidence": 0.8
+ },
+ {
+ "type": "score",
+ "name": "urgency",
+ "score": 1.1,
+ "probabilities": [
+ {
+ "value": 0,
+ "label": "Low",
+ "probability": 0.1
+ },
+ {
+ "value": 1,
+ "label": "Medium",
+ "probability": 0.7
+ },
+ {
+ "value": 2,
+ "label": "High",
+ "probability": 0.2
+ }
+ ],
+ "confidence": 0.55
+ }
+ ],
+ "usage": {
+ "input_tokens": 42,
+ "input_tokens_details": {
+ "cached_tokens": 0,
+ "cache_write_tokens": 0
+ },
+ "output_tokens": 0,
+ "output_tokens_details": {
+ "reasoning_tokens": 0
+ },
+ "total_tokens": 42
+ }
+ }
+ },
+ {
+ "name": "boolean_and_string_choices_unnamed_and_repeated_names",
+ "request": {
+ "model": "convaiinnovations/laya-typed-decisions",
+ "input": [
+ {
+ "role": "user",
+ "content": [
+ {
+ "type": "input_text",
+ "text": "Please continue."
+ }
+ ]
+ }
+ ],
+ "questions": [
+ {
+ "type": "choice",
+ "instructions": "Choose whether to continue",
+ "choices": [
+ {
+ "value": true
+ },
+ {
+ "value": "true"
+ },
+ {
+ "value": false
+ }
+ ]
+ },
+ {
+ "type": "predicate",
+ "name": "same",
+ "instructions": "Continue?"
+ },
+ {
+ "type": "predicate",
+ "name": "same",
+ "instructions": "Stop?"
+ }
+ ]
+ },
+ "systemone": {
+ "model": "convaiinnovations/laya-typed-decisions",
+ "state": [
+ {
+ "role": "user",
+ "content": [
+ {
+ "type": "input_text",
+ "text": "Please continue."
+ }
+ ]
+ }
+ ],
+ "questions": {
+ "question_0": {
+ "type": "choice",
+ "instructions": "Choose whether to continue",
+ "criteria": {
+ "option_0": "true",
+ "option_1": "\"true\"",
+ "option_2": "false"
+ }
+ },
+ "question_1": {
+ "type": "noul",
+ "instructions": "Continue?"
+ },
+ "question_2": {
+ "type": "noul",
+ "instructions": "Stop?"
+ }
+ }
+ },
+ "native_answers": {
+ "question_0": {
+ "type": "choice",
+ "choice": "option_0",
+ "probabilities": {
+ "option_0": 1.0,
+ "option_1": 0.0,
+ "option_2": 0.0
+ }
+ },
+ "question_1": {
+ "type": "noul",
+ "noul": 1.0
+ },
+ "question_2": {
+ "type": "refusal"
+ }
+ },
+ "response": {
+ "model": "convaiinnovations/laya-typed-decisions",
+ "answers": [
+ {
+ "type": "choice",
+ "name": null,
+ "choice": true,
+ "probabilities": [
+ {
+ "value": true,
+ "probability": 1.0
+ },
+ {
+ "value": "true",
+ "probability": 0.0
+ },
+ {
+ "value": false,
+ "probability": 0.0
+ }
+ ],
+ "confidence": 1.0
+ },
+ {
+ "type": "predicate",
+ "name": "same",
+ "probability": 1.0
+ },
+ {
+ "type": "refusal",
+ "name": "same"
+ }
+ ],
+ "usage": {
+ "input_tokens": 42,
+ "input_tokens_details": {
+ "cached_tokens": 0,
+ "cache_write_tokens": 0
+ },
+ "output_tokens": 0,
+ "output_tokens_details": {
+ "reasoning_tokens": 0
+ },
+ "total_tokens": 42
+ }
+ }
+ }
+ ],
+ "invalid_requests": [
+ {
+ "name": "empty_questions",
+ "request": {
+ "model": "m",
+ "input": "hello",
+ "questions": []
+ },
+ "param": "questions"
+ },
+ {
+ "name": "missing_instructions",
+ "request": {
+ "model": "m",
+ "input": "hello",
+ "questions": [
+ {
+ "type": "predicate"
+ }
+ ]
+ },
+ "param": "questions[0].instructions"
+ },
+ {
+ "name": "unknown_type",
+ "request": {
+ "model": "m",
+ "input": "hello",
+ "questions": [
+ {
+ "type": "noul",
+ "instructions": "hello"
+ }
+ ]
+ },
+ "param": "questions[0].type"
+ },
+ {
+ "name": "duplicate_choice",
+ "request": {
+ "model": "m",
+ "input": "hello",
+ "questions": [
+ {
+ "type": "choice",
+ "instructions": "Pick",
+ "choices": [
+ {
+ "value": "a"
+ },
+ {
+ "value": "a"
+ }
+ ]
+ }
+ ]
+ },
+ "param": "questions[0].choices[1].value"
+ },
+ {
+ "name": "numeric_choice",
+ "request": {
+ "model": "m",
+ "input": "hello",
+ "questions": [
+ {
+ "type": "choice",
+ "instructions": "Pick",
+ "choices": [
+ {
+ "value": 1
+ },
+ {
+ "value": 2
+ }
+ ]
+ }
+ ]
+ },
+ "param": "questions[0].choices[0].value"
+ },
+ {
+ "name": "no_levels",
+ "request": {
+ "model": "m",
+ "input": "hello",
+ "questions": [
+ {
+ "type": "score",
+ "instructions": "Rate",
+ "levels": []
+ }
+ ]
+ },
+ "param": "questions[0].levels"
+ },
+ {
+ "name": "image_not_ignored",
+ "request": {
+ "model": "m",
+ "input": [
+ {
+ "role": "user",
+ "content": [
+ {
+ "type": "input_text",
+ "text": "Inspect"
+ },
+ {
+ "type": "input_image",
+ "image_url": "https://example.com/a.png"
+ }
+ ]
+ }
+ ],
+ "questions": [
+ {
+ "type": "predicate",
+ "instructions": "Damaged?"
+ }
+ ]
+ },
+ "param": "input[0].content[1].type"
+ },
+ {
+ "name": "tool_call_not_ignored",
+ "request": {
+ "model": "m",
+ "input": [
+ {
+ "type": "function_call",
+ "name": "lookup",
+ "call_id": "call1",
+ "arguments": "{}"
+ }
+ ],
+ "questions": [
+ {
+ "type": "predicate",
+ "instructions": "Done?"
+ }
+ ]
+ },
+ "param": "input[0].name"
+ },
+ {
+ "name": "backend_field_not_forwarded",
+ "request": {
+ "model": "m",
+ "input": "hi",
+ "questions": [
+ {
+ "type": "predicate",
+ "instructions": "OK?"
+ }
+ ],
+ "lora_path": "/tmp/weights"
+ },
+ "param": "lora_path"
+ },
+ {
+ "name": "model_path_traversal",
+ "request": {
+ "model": "../m",
+ "input": "hi",
+ "questions": [
+ {
+ "type": "predicate",
+ "instructions": "OK?"
+ }
+ ]
+ },
+ "param": "model"
+ }
+ ]
+}