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
fix(systemone): keep refusal codes and surface unreadable results
Rahul Parundekarb1bc9a527d09
diff --git a/examples/systemone-local/README.md b/examples/systemone-local/README.mdindex 1bf8213dc..482d9e10b 100644--- a/examples/systemone-local/README.md+++ b/examples/systemone-local/README.md@@ -65,8 +65,9 @@ uv run conformance.py --check-authA Serverless model that has gone cold takes minutes to load. SIE answers`503` with a `Retry-After` of at most 60 seconds while it loads, and the-TypeSafe SDK gives up after about 30 seconds of retries. Warm the model first,-for example with one call from the console playground.+TypeSafe SDK retries twice by default (`max_retries=2` in `typesafe-sdk`+0.7.4), so a cold load outlasts its retries. Warm the model first, for example+with one call from the console playground.## Limits@@ -76,10 +77,12 @@ never truncates the text silently:| Model | Row | What shares the row ||---|---|---|-| `fastino/GLiNER2.5-Decide` | 512 tokens | All of the request's questions (at most half the row) and the state |-| `fastino/GLiNER2.5-Decide-1B` | 2,048 tokens | Same; use it for longer text |-| `fastino/GLiNER2.5-multi-Decide` | 2,048 tokens | Same; multilingual |+| `fastino/GLiNER2.5-Decide` | 512 tokens | All of the request's questions (at most 256 tokens, half the row) and the state |+| `fastino/GLiNER2.5-Decide-1B` | 2,048 tokens | All of the questions (at most 512 tokens) and the state; use it for longer text |+| `fastino/GLiNER2.5-multi-Decide` | 2,048 tokens | Same as Decide-1B; multilingual || `convaiinnovations/laya-typed-decisions` | 1,024 tokens | One question and the state, per question |+| `convaiinnovations/laya-multilingual` | 1,024 tokens | Same; multilingual |+| `convaiinnovations/laya` | 512 tokens | Same |Other differences from TypeSafe's hosted API:diff --git a/packages/sie_gateway/openapi.json b/packages/sie_gateway/openapi.jsonindex af1504cdc..95a285735 100644--- a/packages/sie_gateway/openapi.json+++ b/packages/sie_gateway/openapi.json@@ -4098,12 +4098,11 @@"type": "string"},"questions": {- "description": "Typed questions by id: `{\"type\": \"noul\" | \"choice\" | \"score\",\n\"instructions\"?, \"criteria\"?}`. A score question takes at most 10 levels.",+ "description": "Typed questions by id: `{\"type\": \"noul\" | \"choice\" | \"score\",\n\"instructions\"?, \"criteria\"?}`. A score question takes 1 to 10 levels.","type": "object"},"state": {- "description": "The text to judge, a JSON object, or a list of conversation turns.",- "type": "object"+ "description": "The text to judge (a string), a JSON object, or a list of conversation\nturns."}},"required": [@@ -4117,7 +4116,7 @@"description": "Answers by question id, in the System One response shape.","properties": {"answers": {- "description": "One answer per question: `noul` (`noul`, the probability of yes),\n`choice` (`choice`, `confidence`, `probabilities` by option) or `score`\n(`score`, `confidence`, `legend` and `probabilities` by level index).",+ "description": "One answer per question: `noul` (`noul`, the probability of yes,\n`answer` and `confidence`),\n`choice` (`choice`, `confidence`, `probabilities` by option) or `score`\n(`score`, `confidence`, `legend` and `probabilities` by level index).","type": "object"},"model": {diff --git a/packages/sie_gateway/src/handlers/systemone.rs b/packages/sie_gateway/src/handlers/systemone.rsindex ac83d938d..e212fdfbf 100644--- a/packages/sie_gateway/src/handlers/systemone.rs+++ b/packages/sie_gateway/src/handlers/systemone.rs@@ -8,8 +8,8 @@//! check `packages/wire-fixtures/systemone.json`.//!//! - Request `{model, state, questions}`. Unknown fields are ignored; a-//! question may omit `instructions` or send `null`; media fields and more-//! than 10 score levels are refused.+//! question may omit `instructions` or send `null`; media fields and a+//! score question without 1 to 10 levels are refused.//! - Response `{model, answers, usage: {input_tokens, output_tokens}}`, JSON.//! Choice and score confidences follow the System One definitions.//! - The extract call sets `overflow_policy: "error"`, so a state or question@@ -28,6 +28,7 @@ use axum::http::{HeaderMap, HeaderName, HeaderValue, Method, StatusCode};use axum::response::{IntoResponse, Response};use axum::Json;use serde_json::{json, Map, Value};+use tracing::warn;use crate::http_error::GatewayOwnedFault;use crate::server::AppState;@@ -41,14 +42,17 @@ use super::proxy::{/// Request body cap. A System One request is one text state and its/// questions; 16 MiB is the text-route cap the chat and embeddings routes use.const MAX_REQUEST_BYTES: usize = 16 * 1024 * 1024;-/// Native extract reply cap. One item's answers: a probability per option.+/// Native extract reply cap, the same 16 MiB as the other compatibility+/// routes' native replies; one item's answers are far smaller.const MAX_RESPONSE_BYTES: usize = 16 * 1024 * 1024;/// Score levels per question, as the System One API accepts.pub(crate) const MAX_SCORE_LEVELS: usize = 10;/// Longest `Retry-After` the route sends. System One clients (and LiteLLM)/// wait at most 60 seconds before falling back.pub(crate) const MAX_RETRY_AFTER_S: u64 = 60;-/// Adapter modules that answer typed questions.+/// Adapter modules that answer typed questions: the modules of the single+/// server's `DECISION_ADAPTERS` (`sie_server.api.systemone`), which names+/// their classes.const DECISION_ADAPTER_MODULES: [&str; 2] = ["sie_server.adapters.gliner2.decide","sie_server.adapters.laya.adapter",@@ -138,6 +142,12 @@ pub(crate) fn normalize_request(parsed: &Value) -> Result<SystemOneRequest, Inva}if question.get("type").and_then(Value::as_str) == Some("score") {if let Some(levels) = question.get("criteria").and_then(Value::as_array) {+ if levels.is_empty() {+ return Err(invalid(+ &["questions", qid, "criteria"],+ format!("score question {qid:?} has no levels"),+ ));+ }if levels.len() > MAX_SCORE_LEVELS {return Err(invalid(&["questions", qid, "criteria"],@@ -202,23 +212,40 @@ pub(crate) fn score_confidence(probabilities: &[f64]) -> f64 {(1.0 - spread / even).clamp(0.0, 1.0)}+fn probability(value: &Value) -> Result<f64, String> {+ value+ .as_f64()+ .ok_or_else(|| format!("probability {value} is not a number"))+}+/// One adapter answer in the System One shape, with System One confidences.-pub(crate) fn to_answer(answer: &Map<String, Value>) -> Map<String, Value> {+///+/// `Err` for a probability that is not a number or a score level key that is+/// not an integer, as the single server refuses them.+pub(crate) fn to_answer(answer: &Map<String, Value>) -> Result<Map<String, Value>, String> {let mut result = answer.clone();let kind = answer.get("type").and_then(Value::as_str);let Some(probabilities) = answer.get("probabilities").and_then(Value::as_object) else {- return result;+ return Ok(result);};let confidence = match kind {Some("choice") => {- let values: Vec<f64> = probabilities.values().filter_map(Value::as_f64).collect();+ let values = probabilities+ .values()+ .map(probability)+ .collect::<Result<Vec<f64>, String>>()?;Some(choice_confidence(&values))}Some("score") => {- let mut levels: Vec<(u64, f64)> = probabilities+ let mut levels = probabilities.iter()- .filter_map(|(key, value)| Some((key.parse().ok()?, value.as_f64()?)))- .collect();+ .map(|(key, value)| {+ let level: u64 = key+ .parse()+ .map_err(|_| format!("score level {key:?} is not an integer"))?;+ Ok((level, probability(value)?))+ })+ .collect::<Result<Vec<(u64, f64)>, String>>()?;levels.sort_by_key(|(level, _)| *level);let values: Vec<f64> = levels.into_iter().map(|(_, p)| p).collect();Some(score_confidence(&values))@@ -228,15 +255,16 @@ pub(crate) fn to_answer(answer: &Map<String, Value>) -> Map<String, Value> {if let Some(confidence) = confidence {result.insert("confidence".to_string(), json!(confidence));}- result+ Ok(result)}/// What an extract reply becomes: the System One body, or the 422 for an item-/// the adapter refused (a state that does not fit, an unreadable state).+/// the adapter refused (a state that does not fit, an unreadable state) with+/// the adapter's error code.#[derive(Debug, PartialEq)]pub(crate) enum Translated {Answers(Value),- Refused(Invalid),+ Refused(Invalid, String),}/// Translate a native extract reply into the System One response body.@@ -259,7 +287,14 @@ pub(crate) fn response_from_extract(.get("message").and_then(Value::as_str).unwrap_or("the state could not be read");- return Ok(Translated::Refused(invalid(&["state"], message)));+ let code = error+ .get("code")+ .and_then(Value::as_str)+ .unwrap_or("INVALID_INPUT");+ return Ok(Translated::Refused(+ invalid(&["state"], message),+ code.to_string(),+ ));}let data = item.get("data")@@ -271,8 +306,11 @@ pub(crate) fn response_from_extract(.get(qid).and_then(Value::as_object).ok_or_else(|| format!("model returned no answer for question {qid:?}"))?;- answers.insert(qid.clone(), Value::Object(to_answer(answer)));+ let answer = to_answer(answer).map_err(|error| format!("question {qid:?}: {error}"))?;+ answers.insert(qid.clone(), Value::Object(answer));}+ // The queued extract reply carries no `usage`, so this is 0 on a cluster;+ // metered deployments report units in `X-SIE-Units-*` headers instead.let input_tokens = native.get("usage").and_then(|usage| usage.get("input_tokens"))@@ -375,6 +413,40 @@ fn copy_error_headers(from: &HeaderMap, to: &mut HeaderMap) {}}+/// The code and message of a native error body. Reads the native and OpenAI+/// envelopes (`{"detail" | "error": {code, message}}`), the batch failure+/// `{"error": "all_items_failed", "details": [{code, error}]}`, and a FastAPI+/// validation list (`{"detail": [{msg}]}`).+pub(crate) fn error_parts(parsed: &Value) -> (Option<&str>, Option<&str>) {+ let envelope = parsed.get("detail").or_else(|| parsed.get("error"));+ if let Some(envelope @ Value::Object(_)) = envelope {+ return (+ envelope.get("code").and_then(Value::as_str),+ envelope.get("message").and_then(Value::as_str),+ );+ }+ if let Some(first) = parsed+ .get("details")+ .and_then(Value::as_array)+ .and_then(|details| details.first())+ {+ return (+ first.get("code").and_then(Value::as_str),+ first.get("error").and_then(Value::as_str),+ );+ }+ if let Some(first) = envelope+ .and_then(Value::as_array)+ .and_then(|detail| detail.first())+ {+ return (+ first.get("code").and_then(Value::as_str),+ first.get("msg").and_then(Value::as_str),+ );+ }+ (None, None)+}+/// Re-surface a native error in the System One shapes. A 400 (invalid input,/// input too long) becomes 422; other statuses keep their code. The extensions/// (a gateway-owned-fault marker) and the retry headers survive.@@ -386,14 +458,14 @@ async fn translate_error(response: Response) -> Response {Ok(bytes) => serde_json::from_slice(&bytes).unwrap_or(Value::Null),Err(_) => Value::Null,};- let envelope = parsed.get("detail").or_else(|| parsed.get("error"));- let code = envelope- .and_then(|detail| detail.get("code"))- .and_then(Value::as_str);- let message = envelope- .and_then(|detail| detail.get("message"))- .and_then(Value::as_str)- .unwrap_or("request failed");+ let (code, message) = error_parts(&parsed);+ if message.is_none() {+ warn!(+ status = parts.status.as_u16(),+ "System One: native error without a readable message"+ );+ }+ let message = message.unwrap_or("request failed");let mut out = if parts.status == StatusCode::BAD_REQUEST {validation_error(&invalid(&[], message), code)} else {@@ -404,7 +476,9 @@ async fn translate_error(response: Response) -> Response {out}-fn translation_fault(stage: &'static str, message: impl Into<String>) -> Response {+fn translation_fault(model: &str, stage: &'static str, message: impl Into<String>) -> Response {+ let message = message.into();+ warn!(model = %model, stage, error = %message, "System One: undelivered extract result");GatewayOwnedFault::new(stage).mark(api_error(StatusCode::INTERNAL_SERVER_ERROR,Some("INTERNAL_ERROR"),@@ -545,6 +619,7 @@ pub async fn proxy_systemone(State(state): State<Arc<AppState>>, req: Request) -Ok(value) => value,Err(error) => {return translation_fault(+ &request.model,"decode_extract_response",format!("extract response is not valid JSON: {error}"),)@@ -552,6 +627,7 @@ pub async fn proxy_systemone(State(state): State<Arc<AppState>>, req: Request) -},Err(_) => {return translation_fault(+ &request.model,"read_extract_response","failed to read extract response body",)@@ -559,8 +635,8 @@ pub async fn proxy_systemone(State(state): State<Arc<AppState>>, req: Request) -};let mut output = match response_from_extract(&native, &request.model, &request.questions) {Ok(Translated::Answers(body)) => (StatusCode::OK, Json(body)).into_response(),- Ok(Translated::Refused(error)) => validation_error(&error, Some("INPUT_TOO_LONG")),- Err(message) => return translation_fault("format_systemone", message),+ Ok(Translated::Refused(error, code)) => validation_error(&error, Some(&code)),+ Err(message) => return translation_fault(&request.model, "format_systemone", message),};for (name, value) in response_headers.iter() {if is_openai_compat_forwarded_header(name.as_str()) {@@ -708,8 +784,66 @@ mod tests {.collect();assert_eq!(response_from_extract(&native, "m", &questions).unwrap(),- Translated::Refused(invalid(&["state"], "does not fit"))+ Translated::Refused(+ invalid(&["state"], "does not fit"),+ "INPUT_TOO_LONG".to_string()+ ));+ let unreadable = json!({+ "items": [{"id": "item-0", "data": {}, "error": {"code": "INVALID_INPUT", "message": "not JSON"}}],+ });+ assert_eq!(+ response_from_extract(&unreadable, "m", &questions).unwrap(),+ Translated::Refused(invalid(&["state"], "not JSON"), "INVALID_INPUT".to_string())+ );+ }++ #[test]+ fn unreadable_probabilities_are_a_translation_failure() {+ let questions: Map<String, Value> = [("q".to_string(), json!({"type": "score"}))]+ .into_iter()+ .collect();+ for probabilities in [+ json!({"0": 0.5, "high": 0.5}),+ json!({"0": 0.5, "1": "half"}),+ ] {+ let native = json!({"items": [{"id": "item-0", "data": {+ "q": {"type": "score", "score": 0.5, "probabilities": probabilities}+ }}]});+ assert!(+ response_from_extract(&native, "m", &questions).is_err(),+ "{probabilities}"+ );+ }+ }++ #[test]+ fn error_parts_reads_every_native_error_shape() {+ for (body, code, message) in [+ (+ json!({"detail": {"code": "MODEL_LOADING", "message": "loading"}}),+ Some("MODEL_LOADING"),+ Some("loading"),+ ),+ (+ json!({"error": {"code": "INVALID_INPUT", "message": "bad"}}),+ Some("INVALID_INPUT"),+ Some("bad"),+ ),+ (+ json!({"error": "all_items_failed", "details": [{"item_index": 0, "error": "boom", "code": "INFERENCE_ERROR"}]}),+ Some("INFERENCE_ERROR"),+ Some("boom"),+ ),+ (+ json!({"detail": [{"loc": ["body"], "msg": "field required"}]}),+ None,+ Some("field required"),+ ),+ (Value::Null, None, None),+ ] {+ assert_eq!(error_parts(&body), (code, message), "{body}");+ }}#[test]@@ -810,6 +944,44 @@ mod tests {assert_eq!(dispatched[0].model, "acme/decide");}+ #[tokio::test]+ async fn an_undelivered_result_is_a_gateway_owned_fault() {+ let gateway = TestGateway::new(&[LOCAL_DECISION_MODEL]).await;+ gateway+ .add_verified_worker("local-1", LOCAL_LANE, &["acme/decide"])+ .await;+ gateway+ .dispatcher+ .return_extract_data(json!({"other": {"type": "noul", "noul": 0.5}}));+ let request = systemone_request(json!({+ "model": "acme/decide", "state": "hi", "questions": {"q": {"type": "noul"}}+ }));+ let response = proxy_systemone(State(Arc::clone(&gateway.state)), request).await;+ assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);+ assert_eq!(+ response.extensions().get::<GatewayOwnedFault>(),+ Some(&GatewayOwnedFault::new("format_systemone"))+ );+ assert_eq!(+ body_json(response).await["detail"]["code"],+ "INTERNAL_ERROR"+ );+ }++ #[tokio::test]+ async fn translated_errors_keep_the_fault_marker() {+ let marked = GatewayOwnedFault::new("upstream").mark(api_error(+ StatusCode::INTERNAL_SERVER_ERROR,+ Some("INTERNAL_ERROR"),+ "boom",+ ));+ let translated = translate_error(marked).await;+ assert_eq!(+ translated.extensions().get::<GatewayOwnedFault>(),+ Some(&GatewayOwnedFault::new("upstream"))+ );+ }+#[tokio::test]async fn refuses_a_model_that_does_not_answer_typed_questions() {let gateway = TestGateway::new(&[LOCAL_DECISION_MODEL, LOCAL_ENCODE_MODEL]).await;diff --git a/packages/sie_gateway/src/openapi.rs b/packages/sie_gateway/src/openapi.rsindex e1b154a84..87bac0ded 100644--- a/packages/sie_gateway/src/openapi.rs+++ b/packages/sie_gateway/src/openapi.rs@@ -3100,11 +3100,11 @@ pub struct ScoreRequest {pub struct SystemOneRequest {/// SIE model id of a decision model, e.g. `fastino/GLiNER2.5-Decide`.pub model: String,- /// The text to judge, a JSON object, or a list of conversation turns.- #[schema(value_type = Object)]+ /// The text to judge (a string), a JSON object, or a list of conversation+ /// turns.pub state: Value,/// Typed questions by id: `{"type": "noul" | "choice" | "score",- /// "instructions"?, "criteria"?}`. A score question takes at most 10 levels.+ /// "instructions"?, "criteria"?}`. A score question takes 1 to 10 levels.#[schema(value_type = Object)]pub questions: Value,}@@ -3120,7 +3120,8 @@ pub struct SystemOneUsage {#[derive(Debug, Serialize, Deserialize, ToSchema)]pub struct SystemOneResponse {pub model: String,- /// One answer per question: `noul` (`noul`, the probability of yes),+ /// One answer per question: `noul` (`noul`, the probability of yes,+ /// `answer` and `confidence`),/// `choice` (`choice`, `confidence`, `probabilities` by option) or `score`/// (`score`, `confidence`, `legend` and `probabilities` by level index).#[schema(value_type = Object)]diff --git a/packages/sie_sdk/src/sie_sdk/client/async_.py b/packages/sie_sdk/src/sie_sdk/client/async_.pyindex b80ae5465..7a3e4d866 100644--- a/packages/sie_sdk/src/sie_sdk/client/async_.py+++ b/packages/sie_sdk/src/sie_sdk/client/async_.py@@ -71,7 +71,6 @@ from sie_sdk.types import (CostEstimate,EncodeResult,ExtractResult,- SystemOneResult,File,FileDeleted,FileList,@@ -94,6 +93,7 @@ from sie_sdk.types import (ResponseResult,ScoreResult,StatusMessage,+ SystemOneResult,WorkerInfo,)diff --git a/packages/sie_sdk/src/sie_sdk/client/sync.py b/packages/sie_sdk/src/sie_sdk/client/sync.pyindex 7be4bc3fc..3a2448f00 100644--- a/packages/sie_sdk/src/sie_sdk/client/sync.py+++ b/packages/sie_sdk/src/sie_sdk/client/sync.py@@ -79,7 +79,6 @@ from sie_sdk.types import (CostEstimate,EncodeResult,ExtractResult,- SystemOneResult,File,FileDeleted,FileList,@@ -102,6 +101,7 @@ from sie_sdk.types import (ResponseResult,ScoreResult,StatusMessage,+ SystemOneResult,WorkerInfo,)diff --git a/packages/sie_sdk/src/sie_sdk/systemone.py b/packages/sie_sdk/src/sie_sdk/systemone.pyindex 85a1c410e..5ecd9c7ee 100644--- a/packages/sie_sdk/src/sie_sdk/systemone.py+++ b/packages/sie_sdk/src/sie_sdk/systemone.py@@ -51,6 +51,8 @@ def system_one_request(state: Any, questions: Mapping[str, Any]) -> tuple[Item,normalized["instructions"] = ""levels = normalized.get("criteria")if normalized.get("type") == "score" and isinstance(levels, list):+ if not levels:+ raise RequestError(f"score question {qid!r} has no levels", code="INVALID_INPUT")if len(levels) > MAX_SCORE_LEVELS:raise RequestError(f"score question {qid!r} has {len(levels)} levels; at most {MAX_SCORE_LEVELS} are allowed",@@ -86,14 +88,17 @@ def score_confidence(probabilities: list[float]) -> float:return min(1.0, max(0.0, 1.0 - spread / even))-def _answer(answer: Mapping[str, Any]) -> dict[str, Any]:+def _answer(qid: str, 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)+ try:+ 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=int)]+ result["confidence"] = score_confidence(ordered)+ except (TypeError, ValueError) as e:+ raise RequestError(f"unreadable answer to question {qid!r}: {e}", code="INVALID_RESPONSE") from ereturn result@@ -106,7 +111,12 @@ def system_one_result(model: str, result: ExtractResult, questions: Mapping[str,"""error = result.get("error")if error:- raise RequestError(error["message"], code=error["code"], status_code=422, param="state")+ raise RequestError(+ str(error.get("message", "the state could not be read")),+ code=str(error.get("code", "INVALID_INPUT")),+ 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:@@ -119,6 +129,6 @@ def system_one_result(model: str, result: ExtractResult, questions: Mapping[str,input_tokens = usage.get("input_tokens", 0)return {"model": model,- "answers": {qid: _answer(data[qid]) for qid in questions},+ "answers": {qid: _answer(qid, 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/tests/client/test_system_one.py b/packages/sie_sdk/tests/client/test_system_one.pyindex 8cf824ebf..fe933d254 100644--- a/packages/sie_sdk/tests/client/test_system_one.py+++ b/packages/sie_sdk/tests/client/test_system_one.py@@ -10,7 +10,7 @@ import pytestfrom sie_sdk import SIEAsyncClient, SIEClientfrom sie_sdk.client.async_ import _AioResponsefrom sie_sdk.client.errors import RequestError-from sie_sdk.systemone import choice_confidence, score_confidence, system_one_request+from sie_sdk.systemone import choice_confidence, score_confidence, system_one_request, system_one_resultFIXTURE = json.loads((Path(__file__).resolve().parents[3] / "wire-fixtures" / "systemone.json").read_text(encoding="utf-8")@@ -18,6 +18,9 @@ FIXTURE = json.loads(RESPONSE_CASE = FIXTURE["responses"][0]MODEL = RESPONSE_CASE["model"]QUESTIONS = {qid: {"type": "noul"} for qid in RESPONSE_CASE["questions"]}+# Invalid requests only the HTTP route can see: the SDK takes the model as an+# argument and sends no media fields.+ROUTE_ONLY_INVALID_REQUESTS = {"missing model", "empty model", "images", "audio", "videos"}def _extract_response(item: dict[str, Any]) -> bytes:@@ -108,13 +111,7 @@ def test_fixture_requests(case: dict[str, Any]) -> None:@pytest.mark.parametrize("case",- [- case- for case in FIXTURE["invalid_requests"]- if case["name"].startswith(- ("number", "boolean", "null", "empty q", "questions", "question", "eleven", "null score")- )- ],+ [case for case in FIXTURE["invalid_requests"] if case["name"] not in ROUTE_ONLY_INVALID_REQUESTS],ids=lambda case: case["name"],)def test_fixture_invalid_requests(case: dict[str, Any]) -> None:@@ -128,3 +125,30 @@ def test_fixture_confidence(kind: str) -> None:fn = choice_confidence if kind == "choice" else score_confidencefor case in FIXTURE["confidence"][kind]:assert fn(case["probabilities"]) == pytest.approx(case["confidence"])++[email protected]("case", FIXTURE["responses"], ids=lambda case: case["name"])+def test_fixture_responses(case: dict[str, Any]) -> None:+ questions = {qid: {"type": "noul"} for qid in case["questions"]}+ extract = {+ "id": "item-0",+ "entities": [],+ "data": case["data"],+ "request": {"usage": {"input_tokens": case["input_tokens"]}},+ }+ _assert_close(system_one_result(case["model"], extract, questions), case["response"]) # type: ignore[arg-type]+++def test_missing_answer_raises_invalid_response() -> None:+ extract = {"id": "item-0", "entities": [], "data": {}}+ with pytest.raises(RequestError) as raised:+ system_one_result(MODEL, extract, {"q": {"type": "noul"}}) # type: ignore[arg-type]+ assert raised.value.code == "INVALID_RESPONSE"++[email protected]("probabilities", [{"0": 0.5, "high": 0.5}, {"0": 0.5, "1": "half"}])+def test_unreadable_probabilities_raise_invalid_response(probabilities: dict[str, Any]) -> None:+ extract = {"id": "item-0", "entities": [], "data": {"q": {"type": "score", "probabilities": probabilities}}}+ with pytest.raises(RequestError) as raised:+ system_one_result(MODEL, extract, {"q": {"type": "score"}}) # type: ignore[arg-type]+ assert raised.value.code == "INVALID_RESPONSE"diff --git a/packages/sie_server/scripts/fill_model_metadata.py b/packages/sie_server/scripts/fill_model_metadata.pyindex 6c1511beb..1c8ce961b 100644--- a/packages/sie_server/scripts/fill_model_metadata.py+++ b/packages/sie_server/scripts/fill_model_metadata.py@@ -10,7 +10,7 @@ once, so serving never calls Hugging Face:- ``description``: a hand-written line for the typed-decision models below;otherwise ``"<hf_id or sie_id>: <task> model."`` from the config's tasks.-The two lines are inserted after ``sie_id:``; the rest of each file is left as+The missing lines are inserted after ``sie_id:``; the rest of each file is left asit is. Configs that already set a field keep it. Run from the repository root:mise exec -- uv run --frozen python packages/sie_server/scripts/fill_model_metadata.pydiff --git a/packages/sie_server/src/sie_server/api/systemone.py b/packages/sie_server/src/sie_server/api/systemone.pyindex ddb2bdd33..401311bf5 100644--- a/packages/sie_server/src/sie_server/api/systemone.py+++ b/packages/sie_server/src/sie_server/api/systemone.py@@ -14,7 +14,7 @@ as ``POST /v1/extract/{model}``:- ``choice`` and ``score`` confidences follow the System One API's publisheddefinitions (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;+ 422 instead of being truncated (``extract``'s default);- validation errors are 422 in FastAPI's ``{"detail": [...]}`` shape, othererrors ``{"detail": {"error_type", "code", "message"}}``, and a retryableerror's ``Retry-After`` is at most 60 seconds, with ``retry-after-ms``.@@ -42,7 +42,7 @@ from sie_server.api.helpers import (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.routing import error_code, fallback_refusal, remote_routing, route_requestfrom sie_server.api.validation import validate_machine_profile_headerfrom sie_server.core.worker import QueueFullErrorfrom sie_server.core.worker.handlers.extract import ExtractHandler@@ -169,7 +169,7 @@ 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+ with a list of levels must have 1 to 10 of them, none ``null``. Everything else is left tothe adapter's own validation, which rejects what it cannot answer.Raises:@@ -185,6 +185,8 @@ def normalize_questions(questions: Mapping[str, Any]) -> dict[str, Any]:if question.get("type") == "score":levels = question.get("criteria")if isinstance(levels, list):+ if not levels:+ raise _invalid(f"score question {qid!r} has no levels", ["questions", qid, "criteria"])if len(levels) > MAX_SCORE_LEVELS:raise _invalid(f"score question {qid!r} has {len(levels)} levels; at most {MAX_SCORE_LEVELS} are allowed",@@ -197,14 +199,18 @@ def normalize_questions(questions: Mapping[str, Any]) -> dict[str, Any]:def to_answer(answer: Mapping[str, Any]) -> dict[str, Any]:- """One adapter answer in the System One shape, with System One confidences."""+ """One adapter answer in the System One shape, with System One confidences.++ Raises:+ ValueError: A probability is not a number, or a score level key is not an integer.+ """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))]+ ordered = [float(probabilities[key]) for key in sorted(probabilities, key=int)]result["confidence"] = score_confidence(ordered)return result@@ -239,11 +245,12 @@ def _retry_headers(headers: Mapping[str, str] | None) -> dict[str, str]:if retry_key is None:return outtry:- seconds = float(out.pop(retry_key))+ seconds = float(out[retry_key])except ValueError:return outif not math.isfinite(seconds) or seconds < 0:return out+ del out[retry_key]seconds = min(seconds, MAX_RETRY_AFTER_S)out["Retry-After"] = str(max(1, math.ceil(seconds)))out["retry-after-ms"] = str(int(seconds * 1000))@@ -253,7 +260,7 @@ def _retry_headers(headers: Mapping[str, str] | None) -> dict[str, str]: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+ Any 400 (for example ``INVALID_INPUT`` or ``INPUT_TOO_LONG``) becomes 422 inFastAPI's validation shape, as System One answers a request it cannotvalidate. Every other status keeps its code, with``{"detail": {"error_type", "code", "message"}}``.@@ -264,10 +271,11 @@ def error_response(error: HTTPException) -> JSONResponse:message = _error_message(error.detail)code = _error_code(error.detail)if error.status_code == status.HTTP_400_BAD_REQUEST:+ entry: dict[str, Any] = {"type": "value_error", "loc": ["body"], "msg": message}+ if code is not None:+ entry["code"] = codereturn JSONResponse(- status_code=status.HTTP_422_UNPROCESSABLE_CONTENT,- content={"detail": [{"type": "value_error", "loc": ["body"], "msg": message, "code": code}]},- headers=headers,+ status_code=status.HTTP_422_UNPROCESSABLE_CONTENT, content={"detail": [entry]}, headers=headers)error_type = _ERROR_TYPES.get(error.status_code, "api_error")detail: dict[str, Any] = {"error_type": error_type, "message": message}@@ -277,11 +285,19 @@ def error_response(error: HTTPException) -> JSONResponse: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)."""+ """The 422 for an item the adapter refused (a state that does not fit, an unreadable state).++ The entry carries the adapter's code (``INPUT_TOO_LONG``, ``INVALID_INPUT``).+ """error = result.get("error")if not isinstance(error, Mapping):return None- return _invalid(str(error.get("message", "the state could not be read")), ["state"])+ code = _error_code(error) or ErrorCode.INVALID_INPUT.value+ message = str(error.get("message", "the state could not be read"))+ return HTTPException(+ status_code=status.HTTP_422_UNPROCESSABLE_CONTENT,+ detail=[{"type": "value_error", "loc": ["body", "state"], "msg": message, "code": code}],+ )@router.post(@@ -311,7 +327,7 @@ async def system_one(try:return await _system_one(request, http_request, x_machine_profile)except HTTPException as error:- return error_response(error)+ return error_response(fallback_refusal(http_request, error.status_code, error_code(error)) or error)async def _system_one(@@ -374,18 +390,24 @@ async def _system_one(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)+ span.set_attribute("error", refusal.detail[0]["code"])raise refusaldata = result.get("data") or {}- answers = {qid: to_answer(data[qid]) for qid in questions if isinstance(data.get(qid), Mapping)}+ try:+ answers = {qid: to_answer(data[qid]) for qid in questions if isinstance(data.get(qid), Mapping)}+ except (TypeError, ValueError) as e:+ raise error_handler.handle_inference_error(RuntimeError(f"unreadable answer: {e}"), "Decision") from eif 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+ counted_tokens = validated_total(output.input_token_counts, 1)+ if counted_tokens is None:+ logger.warning("Model %s reported no input token count for a System One request", model)+ input_tokens = counted_tokens or 0timing = worker_result.timingif worker_telemetry_enabled():worker_telemetry().item_completed(@@ -398,7 +420,7 @@ async def _system_one(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},+ units={} if counted_tokens is None else {"input_tokens": counted_tokens},)body = SystemOneResponse(model=model, answers=answers, usage=SystemOneUsage(input_tokens=input_tokens))diff --git a/packages/sie_server/tests/api/test_systemone.py b/packages/sie_server/tests/api/test_systemone.pyindex 845a7dac9..1b09606d5 100644--- a/packages/sie_server/tests/api/test_systemone.py+++ b/packages/sie_server/tests/api/test_systemone.py@@ -23,7 +23,7 @@ from sie_server.config.model import EncodeTask, ExtractTask, ModelConfig, Profilfrom sie_server.core.inference_output import ExtractItemError, ExtractOutputfrom sie_server.core.registry import ModelRegistryfrom sie_server.core.timing import RequestTiming-from sie_server.core.worker import WorkerResult+from sie_server.core.worker import QueueFullError, WorkerResultfrom sie_server.types.responses import ErrorCodeDECIDE = "fastino/GLiNER2.5-Decide"@@ -284,6 +284,16 @@ class TestValidation:adapter.extract.side_effect = too_longdetail = self._assert_422(_post(client))assert detail[0]["loc"] == ["body", "state"]+ assert detail[0]["code"] == ErrorCode.INPUT_TOO_LONG.value++ def test_unreadable_state_keeps_its_code(self, client: TestClient, adapter: MagicMock) -> None:+ def unreadable(items: list[Any], **_: Any) -> ExtractOutput:+ error = ExtractItemError(code=ErrorCode.INVALID_INPUT.value, message="state is not valid JSON")+ return ExtractOutput(entities=[[]], data=[{}], errors=[error], input_token_counts=[0])++ adapter.extract.side_effect = unreadable+ detail = self._assert_422(_post(client))+ assert detail[0]["code"] == ErrorCode.INVALID_INPUT.valueclass TestErrors:@@ -296,7 +306,29 @@ class TestErrors: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+ response = _post(client)+ assert response.status_code == 500+ assert response.json()["detail"]["error_type"] == "api_error"++ @pytest.mark.parametrize("probabilities", [{"0": 0.5, "high": 0.5}, {"0": 0.5, "1": "half"}])+ def test_unreadable_answer_is_a_server_error(+ self, client: TestClient, adapter: MagicMock, probabilities: dict[str, Any]+ ) -> None:+ answer = {"type": "score", "score": 0.5, "probabilities": probabilities}+ adapter.extract.side_effect = lambda items, **_: ExtractOutput(+ entities=[[]], data=[{"q": answer}], input_token_counts=[1]+ )+ response = _post(client, questions={"q": {"type": "score", "criteria": ["low", "high"]}})+ assert response.status_code == 500+ assert response.json()["detail"]["error_type"] == "api_error"++ def test_queue_full_is_retryable(self, client: TestClient, adapter: MagicMock) -> None:+ adapter.extract.side_effect = QueueFullError("queue full")+ response = _post(client)+ assert response.status_code == 503+ assert int(response.headers["Retry-After"]) <= MAX_RETRY_AFTER_S+ assert response.headers["retry-after-ms"] == str(int(float(response.headers["Retry-After"]) * 1000))+ assert set(response.json()["detail"]) >= {"error_type", "message"}def test_retry_after_capped_and_mirrored(self) -> None:error = HTTPException(@@ -320,6 +352,20 @@ class TestErrors: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+ assert json.loads(response.body)["detail"][0]["code"] == "INVALID_INPUT"++ def test_bad_request_without_a_code_has_no_code(self) -> None:+ response = error_response(HTTPException(status_code=400, detail="bad"))+ assert "code" not in json.loads(response.body)["detail"][0]++ def test_unparseable_retry_after_passes_through(self) -> None:+ date = "Wed, 21 Oct 2026 07:28:00 GMT"+ error = HTTPException(+ status_code=503, detail={"code": "QUEUE_FULL", "message": "busy"}, headers={"Retry-After": date}+ )+ response = error_response(error)+ assert response.headers["Retry-After"] == date+ assert "retry-after-ms" not in response.headersclass TestConfidence:diff --git a/packages/sie_ts_sdk/src/systemone.ts b/packages/sie_ts_sdk/src/systemone.tsindex e5810c51a..618544b6b 100644--- a/packages/sie_ts_sdk/src/systemone.ts+++ b/packages/sie_ts_sdk/src/systemone.ts@@ -45,7 +45,8 @@ export interface SystemOneResult {/** The decision model that answered */model: string;/**- * One answer per question id. `noul`: `noul`, the probability of yes.+ * One answer per question id. `noul`: `noul`, the probability of yes,+ * `answer` and `confidence`.* `choice`: `choice`, `confidence` and `probabilities` by option. `score`:* `score`, `confidence`, and `legend` and `probabilities` by level index.*/@@ -91,6 +92,9 @@ export function systemOneRequest(}const levels = normalized.criteria;if (normalized.type === "score" && Array.isArray(levels)) {+ if (levels.length === 0) {+ throw invalid(`score question ${JSON.stringify(qid)} has no 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`,@@ -133,17 +137,35 @@ export function scoreConfidence(probabilities: number[]): number {return Math.min(1, Math.max(0, 1 - spread / even));}-function toAnswer(answer: Record<string, unknown>): Record<string, unknown> {+function probability(qid: string, value: unknown): number {+ if (typeof value !== "number" || !Number.isFinite(value)) {+ throw new RequestError(+ `unreadable answer to question ${JSON.stringify(qid)}: probability ${JSON.stringify(value)} is not a number`,+ "INVALID_RESPONSE",+ );+ }+ return value;+}++function toAnswer(qid: string, 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>;+ const byKey = probabilities as Record<string, unknown>;if (result.type === "choice") {- result.confidence = choiceConfidence(Object.values(byKey).map(Number));+ result.confidence = choiceConfidence(Object.values(byKey).map((p) => probability(qid, p)));} else if (result.type === "score") {- const ordered = Object.keys(byKey)+ const keys = Object.keys(byKey);+ const badKey = keys.find((key) => !/^\d+$/.test(key));+ if (badKey !== undefined) {+ throw new RequestError(+ `unreadable answer to question ${JSON.stringify(qid)}: score level ${JSON.stringify(badKey)} is not an integer`,+ "INVALID_RESPONSE",+ );+ }+ const ordered = keys.sort((a, b) => Number(a) - Number(b))- .map((key) => Number(byKey[key]));+ .map((key) => probability(qid, byKey[key]));result.confidence = scoreConfidence(ordered);}return result;@@ -175,7 +197,7 @@ export function systemOneResult(}const answers: Record<string, Record<string, unknown>> = {};for (const qid of Object.keys(questions)) {- answers[qid] = toAnswer(data[qid] as Record<string, unknown>);+ answers[qid] = toAnswer(qid, data[qid] as Record<string, unknown>);}const inputTokens = result.request?.usage?.inputTokens;return {diff --git a/packages/sie_ts_sdk/tests/systemOne.test.ts b/packages/sie_ts_sdk/tests/systemOne.test.tsindex 164a98cd0..1a0ff6682 100644--- a/packages/sie_ts_sdk/tests/systemOne.test.ts+++ b/packages/sie_ts_sdk/tests/systemOne.test.ts@@ -9,7 +9,12 @@ 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";+import {+ choiceConfidence,+ scoreConfidence,+ systemOneRequest,+ systemOneResult,+} from "../src/systemone.js";const mockFetch = vi.fn();vi.stubGlobal("fetch", mockFetch);@@ -19,6 +24,15 @@ const fixturesDir = fileURLToPath(new URL("../../wire-fixtures/", import.meta.urconst FIXTURE: any = JSON.parse(readFileSync(`${fixturesDir}systemone.json`, "utf8"));const RESPONSE_CASE = FIXTURE.responses[0];const MODEL: string = RESPONSE_CASE.model;+// Invalid requests only the HTTP route can see: the SDK takes the model as an+// argument and sends no media fields.+const ROUTE_ONLY_INVALID_REQUESTS = new Set([+ "missing model",+ "empty model",+ "images",+ "audio",+ "videos",+]);const QUESTIONS: Record<string, unknown> = Object.fromEntries((RESPONSE_CASE.questions as string[]).map((qid) => [qid, { type: "noul" }]),);@@ -103,9 +117,9 @@ describe("System One fixture", () => {});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),+ FIXTURE.invalid_requests.filter(+ // biome-ignore lint/suspicious/noExplicitAny: golden fixture JSON+ (testCase: any) => !ROUTE_ONLY_INVALID_REQUESTS.has(testCase.name),),)("refuses: $name", (testCase) => {expect(() =>@@ -113,6 +127,31 @@ describe("System One fixture", () => {).toThrow(RequestError);});+ it.each(FIXTURE.responses)("renders the response: $name", (testCase) => {+ const questions = Object.fromEntries(+ (testCase.questions as string[]).map((qid) => [qid, { type: "noul" }]),+ );+ const result = systemOneResult(+ testCase.model,+ {+ id: "item-0",+ entities: [],+ data: testCase.data,+ request: { usage: { inputTokens: testCase.input_tokens } },+ },+ questions,+ );+ expectClose(result, testCase.response);+ });++ it.each([+ { "0": 0.5, high: 0.5 },+ { "0": 0.5, "1": "half" },+ ])("refuses unreadable probabilities: %o", (probabilities) => {+ const result = { id: "item-0", entities: [], data: { q: { type: "score", probabilities } } };+ expect(() => systemOneResult(MODEL, result, { q: { type: "score" } })).toThrow(RequestError);+ });+it("matches the confidence goldens", () => {for (const testCase of FIXTURE.confidence.choice) {expect(choiceConfidence(testCase.probabilities)).toBeCloseTo(testCase.confidence, 9);diff --git a/packages/wire-fixtures/systemone.json b/packages/wire-fixtures/systemone.jsonindex 7788ea541..491b3d4cb 100644--- a/packages/wire-fixtures/systemone.json+++ b/packages/wire-fixtures/systemone.json@@ -2,7 +2,7 @@"_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).",+ "the gateway (packages/sie_gateway/src/handlers/systemone.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,",@@ -105,6 +105,7 @@"questions": {"q": {"type": "score", "criteria": ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10"]}}}},+ {"name": "no score levels", "request": {"model": "fastino/GLiNER2.5-Decide", "state": "hi", "questions": {"q": {"type": "score", "criteria": []}}}},{"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"]}},