Open-source inference server and production cluster for all the models your agent needs.
Python bgecolbertdata-pipelinedeep-learningembeddingsinferenceinference-serverinformation-retrievalllmmlmlopsnatural-language-processingnlppythonrerankingretrievalretrieval-augmented-generationsemantic-searchspladevector-search
feat(gateway): serve the System One-compatible /v1/systemone
Rahul Parundekar562b8e6b9db1
diff --git a/packages/sie_gateway/openapi.json b/packages/sie_gateway/openapi.jsonindex 46701fdf8..af1504cdc 100644--- a/packages/sie_gateway/openapi.json+++ b/packages/sie_gateway/openapi.json@@ -2393,6 +2393,10 @@}]},+ "description": {+ "description": "One line about the model; `\"\"` when the catalog sets none. Reported for\nSystem One model-list clients (the TypeSafe SDKs).",+ "type": "string"+ },"dims": {"additionalProperties": {"format": "int64",@@ -2442,6 +2446,10 @@},"type": "object"},+ "release_date": {+ "description": "Release date of the served weights, `YYYY-MM-DD`; `\"\"` when the catalog\nsets none. Reported for System One model-list clients.",+ "type": "string"+ },"revision": {"description": "Immutable model weights revision, when the catalog pins one.","type": [@@ -2471,6 +2479,8 @@"dims","loaded","state",+ "description",+ "release_date","profiles","aliases"],@@ -4080,6 +4090,70 @@],"type": "object"},+ "SystemOneRequest": {+ "description": "A System One request: one state and its typed questions. Fields the route\ndoes not read are ignored.",+ "properties": {+ "model": {+ "description": "SIE model id of a decision model, e.g. `fastino/GLiNER2.5-Decide`.",+ "type": "string"+ },+ "questions": {+ "description": "Typed questions by id: `{\"type\": \"noul\" | \"choice\" | \"score\",\n\"instructions\"?, \"criteria\"?}`. A score question takes at most 10 levels.",+ "type": "object"+ },+ "state": {+ "description": "The text to judge, a JSON object, or a list of conversation turns.",+ "type": "object"+ }+ },+ "required": [+ "model",+ "state",+ "questions"+ ],+ "type": "object"+ },+ "SystemOneResponse": {+ "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).",+ "type": "object"+ },+ "model": {+ "type": "string"+ },+ "usage": {+ "$ref": "#/components/schemas/SystemOneUsage"+ }+ },+ "required": [+ "model",+ "answers",+ "usage"+ ],+ "type": "object"+ },+ "SystemOneUsage": {+ "description": "Tokens the decision model read; it generates none.",+ "properties": {+ "input_tokens": {+ "format": "int64",+ "minimum": 0,+ "type": "integer"+ },+ "output_tokens": {+ "format": "int64",+ "minimum": 0,+ "type": "integer"+ }+ },+ "required": [+ "input_tokens",+ "output_tokens"+ ],+ "type": "object"+ },"TimingInfo": {"properties": {"inference_ms": {@@ -8280,6 +8354,103 @@"x-sie-axum-catch-all": "/v1/score/{*model}"}},+ "/v1/systemone": {+ "post": {+ "description": "System One-compatible typed decisions over SIE's native extract primitive. Answers one state (a string, an object, or a list of conversation turns) against typed noul, choice and score questions with a decision model. Clients written for the System One API work by changing their base URL. A state or question set that does not fit the model's window is refused with 422.",+ "operationId": "proxy_systemone",+ "parameters": [+ {+ "description": "Preferred GPU or machine profile",+ "in": "header",+ "name": "X-SIE-MACHINE-PROFILE",+ "required": false,+ "schema": {+ "type": [+ "string",+ "null"+ ]+ }+ },+ {+ "description": "Explicit pool routing override",+ "in": "header",+ "name": "X-SIE-Pool",+ "required": false,+ "schema": {+ "type": [+ "string",+ "null"+ ]+ }+ },+ {+ "description": "Client SDK version for skew warnings",+ "in": "header",+ "name": "X-SIE-SDK-Version",+ "required": false,+ "schema": {+ "type": [+ "string",+ "null"+ ]+ }+ }+ ],+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/SystemOneRequest"+ }+ }+ },+ "required": true+ },+ "responses": {+ "200": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/SystemOneResponse"+ }+ }+ },+ "description": "Every question answered"+ },+ "401": {+ "description": "Missing or invalid bearer token"+ },+ "404": {+ "description": "Model not found"+ },+ "413": {+ "description": "Request body too large"+ },+ "422": {+ "description": "Invalid request, a model that does not answer typed questions, or input that does not fit the model's window"+ },+ "500": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/StandardApiError"+ }+ }+ },+ "description": "Malformed native extract result; gateway auth enabled but no tokens configured"+ },+ "502": {+ "description": "MODEL_LOAD_FAILED"+ },+ "503": {+ "description": "Provisioning, model loading, or capacity exhausted; Retry-After at most 60 seconds"+ }+ },+ "tags": [+ "inference"+ ]+ }+ },"/v2/rerank": {"post": {"description": "Cohere v2-compatible text-only subset over SIE's native score primitive. Supported request fields are model, query, string documents, top_n, and the documented SIE options extension. max_tokens_per_doc and priority must be omitted or null; unknown or unsupported fields reject with 400. The adapter rejects partial native results and forwards only authoritative worker-emitted usage.",diff --git a/packages/sie_gateway/src/handlers/config_api.rs b/packages/sie_gateway/src/handlers/config_api.rsindex 19e756a21..1dddf60fe 100644--- a/packages/sie_gateway/src/handlers/config_api.rs+++ b/packages/sie_gateway/src/handlers/config_api.rs@@ -826,6 +826,8 @@ mod tests {.add_model_config(ModelConfig {name: model_id.to_string(),hf_revision: None,+ description: None,+ release_date: None,routing: None,adapter_module: None,default_bundle: None,@@ -1131,6 +1133,8 @@ mod tests {let _ = state.model_registry.add_model_config(ModelConfig {name: "empty/model".to_string(),hf_revision: None,+ description: None,+ release_date: None,routing: None,adapter_module: None,default_bundle: None,diff --git a/packages/sie_gateway/src/handlers/mod.rs b/packages/sie_gateway/src/handlers/mod.rsindex a4f52cd2c..3c7fdb424 100644--- a/packages/sie_gateway/src/handlers/mod.rs+++ b/packages/sie_gateway/src/handlers/mod.rs@@ -7,5 +7,6 @@ pub mod pools;pub mod proxy;pub mod serving_disclosure;pub mod sse;+pub mod systemone;#[cfg(test)]pub(crate) mod test_support;diff --git a/packages/sie_gateway/src/handlers/models.rs b/packages/sie_gateway/src/handlers/models.rsindex dc530445b..6b9b42a1b 100644--- a/packages/sie_gateway/src/handlers/models.rs+++ b/packages/sie_gateway/src/handlers/models.rs@@ -351,6 +351,8 @@ fn worker_only_model_info(name: &str, loaded: bool) -> Value {dims: HashMap::new(),max_sequence_length: None,revision: None,+ description: None,+ release_date: None,routing: None,max_output_tokens: None,profile_max_output_tokens: HashMap::new(),@@ -514,6 +516,8 @@ mod route_tests {.add_model_config(ModelConfig {name: model_id.to_string(),hf_revision: None,+ description: None,+ release_date: None,routing: None,adapter_module: None,default_bundle: None,@@ -563,6 +567,8 @@ mod route_tests {.add_model_config(ModelConfig {name: model_id.to_string(),hf_revision: None,+ description: None,+ release_date: None,routing: None,adapter_module: None,default_bundle: None,@@ -598,6 +604,8 @@ mod route_tests {.add_model_config(ModelConfig {name: model_id.to_string(),hf_revision: None,+ description: None,+ release_date: None,routing: None,adapter_module: None,default_bundle: None,@@ -735,6 +743,8 @@ mod route_tests {.add_model_config(ModelConfig {name: model_id.to_string(),hf_revision: None,+ description: None,+ release_date: None,routing: None,adapter_module: None,default_bundle: None,@@ -1350,6 +1360,8 @@ mod route_tests {.add_model_config(ModelConfig {name: model_id.to_string(),hf_revision: None,+ description: None,+ release_date: None,routing: None,adapter_module: None,default_bundle: None,diff --git a/packages/sie_gateway/src/handlers/pools.rs b/packages/sie_gateway/src/handlers/pools.rsindex 432f7279c..52a46ec24 100644--- a/packages/sie_gateway/src/handlers/pools.rs+++ b/packages/sie_gateway/src/handlers/pools.rs@@ -372,6 +372,8 @@ mod tests {.add_model_config(ModelConfig {name: "test/model".to_string(),hf_revision: None,+ description: None,+ release_date: None,routing: None,adapter_module: None,default_bundle: None,diff --git a/packages/sie_gateway/src/handlers/proxy.rs b/packages/sie_gateway/src/handlers/proxy.rsindex 663817258..c78b4036f 100644--- a/packages/sie_gateway/src/handlers/proxy.rs+++ b/packages/sie_gateway/src/handlers/proxy.rs@@ -278,7 +278,10 @@ pub fn is_length_limit_error(error: &axum::Error) -> bool {false}-fn request_body_error(error: &axum::Error, limit: usize) -> (StatusCode, &'static str, String) {+pub(crate) fn request_body_error(+ error: &axum::Error,+ limit: usize,+) -> (StatusCode, &'static str, String) {if is_length_limit_error(error) {(StatusCode::PAYLOAD_TOO_LARGE,@@ -12477,7 +12480,7 @@ fn build_generate_success_body(/// Check client SDK version skew./// Warns once per minor version if client SDK differs by >1 minor version.-fn check_sdk_version(headers: &HeaderMap) {+pub(crate) fn check_sdk_version(headers: &HeaderMap) {let Some(sdk_version) = headers.get("x-sie-sdk-version").and_then(|v| v.to_str().ok())@@ -15830,7 +15833,10 @@ fn normalize_rerank_request(})}-fn compatibility_model_uri(endpoint: &str, model: &str) -> Result<axum::http::Uri, String> {+pub(crate) fn compatibility_model_uri(+ endpoint: &str,+ model: &str,+) -> Result<axum::http::Uri, String> {let model = model.trim_start_matches('/');if model.is_empty() {return Err("'model' must contain a model id".to_string());@@ -17821,6 +17827,8 @@ mod tests {.add_model_config(ModelConfig {name: "org/h".to_string(),hf_revision: None,+ description: None,+ release_date: None,routing: None,adapter_module: None,default_bundle: None,@@ -22173,6 +22181,8 @@ mod tests {.add_model_config(ModelConfig {name: "org/slow".to_string(),hf_revision: None,+ description: None,+ release_date: None,routing: None,adapter_module: None,default_bundle: None,@@ -25529,6 +25539,8 @@ mod tests {.add_model_config(ModelConfig {name: "org/buffered".to_string(),hf_revision: None,+ description: None,+ release_date: None,routing: None,adapter_module: None,default_bundle: None,@@ -25592,6 +25604,8 @@ mod tests {.add_model_config(ModelConfig {name: "org/g".to_string(),hf_revision: None,+ description: None,+ release_date: None,routing: None,adapter_module: None,default_bundle: None,@@ -25675,6 +25689,8 @@ mod tests {.add_model_config(ModelConfig {name: "org/plain".to_string(),hf_revision: None,+ description: None,+ release_date: None,routing: None,adapter_module: None,default_bundle: None,@@ -25742,6 +25758,8 @@ mod tests {.add_model_config(ModelConfig {name: "org/g2".to_string(),hf_revision: None,+ description: None,+ release_date: None,routing: None,adapter_module: None,default_bundle: None,@@ -25805,6 +25823,8 @@ mod tests {.add_model_config(ModelConfig {name: "org/g3".to_string(),hf_revision: None,+ description: None,+ release_date: None,routing: None,adapter_module: None,default_bundle: None,@@ -29471,6 +29491,8 @@ mod tests {dims: std::collections::HashMap::new(),max_sequence_length: None,revision: None,+ description: None,+ release_date: None,routing: None,max_output_tokens: None,profile_max_output_tokens: std::collections::HashMap::new(),diff --git a/packages/sie_gateway/src/handlers/systemone.rs b/packages/sie_gateway/src/handlers/systemone.rsnew file mode 100644index 000000000..ac83d938d--- /dev/null+++ b/packages/sie_gateway/src/handlers/systemone.rs@@ -0,0 +1,852 @@+//! 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+//! gateway rewrites the request into one native `extract` item for a decision+//! model (GLiNER2.5-Decide or Laya) and the extract result back into the System+//! One response, as the single server's `sie_server.api.systemone` does. Both+//! 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.+//! - 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+//! set that does not fit the model's row is refused with 422 instead of+//! being truncated.+//! - Input errors are 422 in FastAPI's `{"detail": [{loc, msg, type}]}` shape;+//! other errors `{"detail": {"error_type", "code", "message"}}`. A+//! retryable error's `Retry-After` is at most 60 seconds, mirrored in+//! milliseconds as `retry-after-ms`.++use std::sync::Arc;++use axum::body::{to_bytes, Body};+use axum::extract::{Request, State};+use axum::http::{HeaderMap, HeaderName, HeaderValue, Method, StatusCode};+use axum::response::{IntoResponse, Response};+use axum::Json;+use serde_json::{json, Map, Value};++use crate::http_error::GatewayOwnedFault;+use crate::server::AppState;++use super::proxy::{+ check_sdk_version, compatibility_model_uri, is_openai_compat_forwarded_header,+ is_openai_compat_inner_request_header, is_valid_compat_model_id, proxy_request,+ request_body_error, CompatibilityRoute,+};++/// 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.+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.+const DECISION_ADAPTER_MODULES: [&str; 2] = [+ "sie_server.adapters.gliner2.decide",+ "sie_server.adapters.laya.adapter",+];+/// Request fields for media the decision models cannot read.+const MEDIA_FIELDS: [&str; 3] = ["images", "audio", "videos"];++/// A validated System One request: the model, the extract item, and the+/// questions as the decision adapters read them.+#[derive(Debug, Clone, PartialEq)]+pub(crate) struct SystemOneRequest {+ pub model: String,+ pub item: Value,+ pub questions: Map<String, Value>,+}++/// Where a request failed validation (after `body`) and why.+#[derive(Debug, Clone, PartialEq)]+pub(crate) struct Invalid {+ pub loc: Vec<String>,+ pub msg: String,+}++fn invalid(loc: &[&str], msg: impl Into<String>) -> Invalid {+ Invalid {+ loc: loc.iter().map(|part| (*part).to_string()).collect(),+ msg: msg.into(),+ }+}++/// Validate a System One request and normalize its questions.+pub(crate) fn normalize_request(parsed: &Value) -> Result<SystemOneRequest, Invalid> {+ let body = parsed+ .as_object()+ .ok_or_else(|| invalid(&[], "the request body must be a JSON object"))?;+ let model = match body.get("model") {+ Some(Value::String(model)) if !model.is_empty() => model.clone(),+ Some(Value::String(_)) => return Err(invalid(&["model"], "'model' must not be empty")),+ Some(_) => return Err(invalid(&["model"], "'model' must be a string")),+ None => return Err(invalid(&["model"], "field required")),+ };+ let item = match body.get("state") {+ Some(Value::String(text)) => json!({ "text": text }),+ Some(state @ (Value::Object(_) | Value::Array(_))) => {+ json!({ "metadata": { "state": state } })+ }+ Some(_) => {+ return Err(invalid(+ &["state"],+ "'state' must be a string, an object, or an array",+ ))+ }+ None => return Err(invalid(&["state"], "field required")),+ };+ let questions = match body.get("questions") {+ Some(Value::Object(questions)) if !questions.is_empty() => questions,+ Some(Value::Object(_)) => {+ return Err(invalid(&["questions"], "'questions' must not be empty"))+ }+ Some(_) => {+ return Err(invalid(+ &["questions"],+ "'questions' must be an object of questions by id",+ ))+ }+ None => return Err(invalid(&["questions"], "field required")),+ };+ for field in MEDIA_FIELDS {+ if body.get(field).is_some_and(|value| !value.is_null()) {+ return Err(invalid(+ &[field],+ format!("'{field}' is not supported: SIE decision models read text only"),+ ));+ }+ }+ let mut normalized = Map::new();+ for (qid, question) in questions {+ let Some(question) = question.as_object() else {+ return Err(invalid(+ &["questions", qid],+ format!("question {qid:?} must be an object"),+ ));+ };+ let mut question = question.clone();+ if question.get("instructions").is_none_or(Value::is_null) {+ question.insert("instructions".to_string(), json!(""));+ }+ 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.len() > MAX_SCORE_LEVELS {+ return Err(invalid(+ &["questions", qid, "criteria"],+ format!(+ "score question {qid:?} has {} levels; at most {MAX_SCORE_LEVELS} are allowed",+ levels.len()+ ),+ ));+ }+ if levels.iter().any(Value::is_null) {+ return Err(invalid(+ &["questions", qid, "criteria"],+ format!("score question {qid:?} has a null level"),+ ));+ }+ }+ }+ normalized.insert(qid.clone(), Value::Object(question));+ }+ Ok(SystemOneRequest {+ model,+ item,+ questions: normalized,+ })+}++/// System One choice confidence: `(p_max - 1/n) / (1 - 1/n)`, within [0, 1].+pub(crate) fn choice_confidence(probabilities: &[f64]) -> f64 {+ let n = probabilities.len();+ if n <= 1 {+ return 1.0;+ }+ let floor = 1.0 / n as f64;+ let p_max = probabilities.iter().copied().fold(f64::MIN, f64::max);+ ((p_max - floor) / (1.0 - floor)).clamp(0.0, 1.0)+}++/// System One score confidence: `max(0, 1 - spread / even)`, where `spread`+/// is the expected distance from the most likely level and `even` that of a+/// uniform distribution from the middle level.+pub(crate) fn score_confidence(probabilities: &[f64]) -> f64 {+ let n = probabilities.len();+ if n <= 1 {+ return 1.0;+ }+ let mut mode = 0;+ for (index, p) in probabilities.iter().enumerate() {+ if *p > probabilities[mode] {+ mode = index;+ }+ }+ let spread: f64 = probabilities+ .iter()+ .enumerate()+ .map(|(index, p)| p * (index as f64 - mode as f64).abs())+ .sum();+ let middle = (n as f64 - 1.0) / 2.0;+ let even: f64 = (0..n)+ .map(|index| (index as f64 - middle).abs())+ .sum::<f64>()+ / n as f64;+ (1.0 - spread / even).clamp(0.0, 1.0)+}++/// One adapter answer in the System One shape, with System One confidences.+pub(crate) fn to_answer(answer: &Map<String, Value>) -> Map<String, Value> {+ 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;+ };+ let confidence = match kind {+ Some("choice") => {+ let values: Vec<f64> = probabilities.values().filter_map(Value::as_f64).collect();+ Some(choice_confidence(&values))+ }+ Some("score") => {+ let mut levels: Vec<(u64, f64)> = probabilities+ .iter()+ .filter_map(|(key, value)| Some((key.parse().ok()?, value.as_f64()?)))+ .collect();+ levels.sort_by_key(|(level, _)| *level);+ let values: Vec<f64> = levels.into_iter().map(|(_, p)| p).collect();+ Some(score_confidence(&values))+ }+ _ => None,+ };+ if let Some(confidence) = confidence {+ result.insert("confidence".to_string(), json!(confidence));+ }+ 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).+#[derive(Debug, PartialEq)]+pub(crate) enum Translated {+ Answers(Value),+ Refused(Invalid),+}++/// Translate a native extract reply into the System One response body.+///+/// `Err` is a reply this route cannot render: the worker ran, and the gateway+/// failed to deliver its result.+pub(crate) fn response_from_extract(+ native: &Value,+ model: &str,+ questions: &Map<String, Value>,+) -> Result<Translated, String> {+ let item = native+ .get("items")+ .and_then(Value::as_array)+ .filter(|items| items.len() == 1)+ .map(|items| &items[0])+ .ok_or_else(|| "extract response is missing its one item".to_string())?;+ if let Some(error) = item.get("error").filter(|error| !error.is_null()) {+ let message = error+ .get("message")+ .and_then(Value::as_str)+ .unwrap_or("the state could not be read");+ return Ok(Translated::Refused(invalid(&["state"], message)));+ }+ let data = item+ .get("data")+ .and_then(Value::as_object)+ .ok_or_else(|| "extract response item has no data".to_string())?;+ let mut answers = Map::new();+ for qid in questions.keys() {+ let answer = data+ .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 input_tokens = native+ .get("usage")+ .and_then(|usage| usage.get("input_tokens"))+ .and_then(Value::as_u64)+ .unwrap_or(0);+ Ok(Translated::Answers(json!({+ "model": model,+ "answers": answers,+ "usage": {"input_tokens": input_tokens, "output_tokens": 0},+ })))+}++/// The native extract body for a System One request: its one item, the+/// questions as `output_schema`, and `overflow_policy: "error"` so input that+/// does not fit the model's row is refused rather than cut.+pub(crate) fn extract_body(request: &SystemOneRequest) -> Value {+ json!({+ "items": [request.item],+ "params": {+ "output_schema": request.questions,+ "options": {"overflow_policy": "error"},+ },+ })+}++fn error_type(status: StatusCode) -> &'static str {+ match status {+ StatusCode::BAD_REQUEST+ | StatusCode::PAYLOAD_TOO_LARGE+ | StatusCode::UNPROCESSABLE_ENTITY => "invalid_request_error",+ StatusCode::UNAUTHORIZED => "authentication_error",+ StatusCode::FORBIDDEN => "permission_error",+ StatusCode::NOT_FOUND => "not_found_error",+ StatusCode::TOO_MANY_REQUESTS => "rate_limit_error",+ _ => "api_error",+ }+}++/// A 422 in FastAPI's validation-error shape, which System One clients parse.+pub(crate) fn validation_error(error: &Invalid, code: Option<&str>) -> Response {+ let mut loc = vec![json!("body")];+ loc.extend(error.loc.iter().map(|part| json!(part)));+ let mut entry = json!({"type": "value_error", "loc": loc, "msg": error.msg});+ if let Some(code) = code {+ entry["code"] = json!(code);+ }+ (+ StatusCode::UNPROCESSABLE_ENTITY,+ Json(json!({ "detail": [entry] })),+ )+ .into_response()+}++/// A non-validation error: `{"detail": {"error_type", "code", "message"}}`.+pub(crate) fn api_error(+ status: StatusCode,+ code: Option<&str>,+ message: impl Into<String>,+) -> Response {+ let mut detail = json!({"error_type": error_type(status), "message": message.into()});+ if let Some(code) = code {+ detail["code"] = json!(code);+ }+ (status, Json(json!({ "detail": detail }))).into_response()+}++/// The `Retry-After` to send for an upstream value: capped at 60 seconds, as+/// whole seconds and as milliseconds. `None` for a value that is not a+/// non-negative number of seconds.+pub(crate) fn capped_retry_after(value: &str) -> Option<(String, String)> {+ let seconds: f64 = value.trim().parse().ok()?;+ if !seconds.is_finite() || seconds < 0.0 {+ return None;+ }+ let seconds = seconds.min(MAX_RETRY_AFTER_S as f64);+ Some((+ (seconds.ceil() as u64).max(1).to_string(),+ ((seconds * 1000.0) as u64).to_string(),+ ))+}++fn copy_error_headers(from: &HeaderMap, to: &mut HeaderMap) {+ for (name, value) in from {+ let key = name.as_str();+ if key.eq_ignore_ascii_case("retry-after") {+ if let Some((seconds, millis)) = value.to_str().ok().and_then(capped_retry_after) {+ if let (Ok(seconds), Ok(millis)) = (+ HeaderValue::from_str(&seconds),+ HeaderValue::from_str(&millis),+ ) {+ to.insert(axum::http::header::RETRY_AFTER, seconds);+ to.insert(HeaderName::from_static("retry-after-ms"), millis);+ }+ }+ } else if is_openai_compat_forwarded_header(key)+ || key.eq_ignore_ascii_case("x-sie-error-code")+ {+ to.insert(name.clone(), value.clone());+ }+ }+}++/// 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.+async fn translate_error(response: Response) -> Response {+ // An error envelope: a code and a sanitized message.+ const MAX: usize = 1024 * 1024;+ let (parts, body) = response.into_parts();+ let parsed: Value = match to_bytes(body, MAX).await {+ 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 mut out = if parts.status == StatusCode::BAD_REQUEST {+ validation_error(&invalid(&[], message), code)+ } else {+ api_error(parts.status, code, message)+ };+ *out.extensions_mut() = parts.extensions;+ copy_error_headers(&parts.headers, out.headers_mut());+ out+}++fn translation_fault(stage: &'static str, message: impl Into<String>) -> Response {+ GatewayOwnedFault::new(stage).mark(api_error(+ StatusCode::INTERNAL_SERVER_ERROR,+ Some("INTERNAL_ERROR"),+ message,+ ))+}++fn is_decision_model(state: &AppState, model: &str) -> Option<bool> {+ let entry = state.model_registry.get_model_info(model)?;+ Some(+ entry+ .adapter_modules+ .iter()+ .any(|module| DECISION_ADAPTER_MODULES.contains(&module.as_str())),+ )+}++#[utoipa::path(+ post,+ path = "/v1/systemone",+ tag = "inference",+ description = "System One-compatible typed decisions over SIE's native extract primitive. Answers one state (a string, an object, or a list of conversation turns) against typed noul, choice and score questions with a decision model. Clients written for the System One API work by changing their base URL. A state or question set that does not fit the model's window is refused with 422.",+ request_body = crate::openapi::SystemOneRequest,+ params(+ ("X-SIE-MACHINE-PROFILE" = Option<String>, Header, description = "Preferred GPU or machine profile"),+ ("X-SIE-Pool" = Option<String>, Header, description = "Explicit pool routing override"),+ ("X-SIE-SDK-Version" = Option<String>, Header, description = "Client SDK version for skew warnings")+ ),+ responses(+ (status = 200, description = "Every question answered", body = crate::openapi::SystemOneResponse),+ (status = 401, description = "Missing or invalid bearer token"),+ (status = 404, description = "Model not found"),+ (status = 413, description = "Request body too large"),+ (status = 422, description = "Invalid request, a model that does not answer typed questions, or input that does not fit the model's window"),+ (status = 500, description = "Malformed native extract result"),+ (status = 502, description = "MODEL_LOAD_FAILED"),+ (status = 503, description = "Provisioning, model loading, or capacity exhausted; Retry-After at most 60 seconds")+ )+)]+pub async fn proxy_systemone(State(state): State<Arc<AppState>>, req: Request) -> Response {+ check_sdk_version(req.headers());+ let headers = req.headers().clone();+ let (parts, body) = req.into_parts();+ let body = match to_bytes(body, MAX_REQUEST_BYTES).await {+ Ok(body) => body,+ Err(error) => {+ let (status, code, message) = request_body_error(&error, MAX_REQUEST_BYTES);+ return api_error(status, Some(code), message);+ }+ };+ let parsed: Value = match serde_json::from_slice(&body) {+ Ok(value) => value,+ Err(error) => {+ return validation_error(&invalid(&[], format!("invalid JSON: {error}")), None);+ }+ };+ let request = match normalize_request(&parsed) {+ Ok(request) => request,+ Err(error) => return validation_error(&error, None),+ };+ if !is_valid_compat_model_id(&request.model) {+ return validation_error(&invalid(&["model"], "invalid model id"), None);+ }+ match is_decision_model(&state, &request.model) {+ None => {+ return api_error(+ StatusCode::NOT_FOUND,+ Some("MODEL_NOT_FOUND"),+ format!("Model '{}' not found", request.model),+ )+ }+ Some(false) => {+ return validation_error(+ &invalid(+ &["model"],+ format!(+ "Model '{}' does not answer typed questions. Use a decision model such as \+ fastino/GLiNER2.5-Decide or convaiinnovations/laya-typed-decisions.",+ request.model+ ),+ ),+ None,+ )+ }+ Some(true) => {}+ }++ let extract_body = extract_body(&request);+ let uri = match compatibility_model_uri("extract", &request.model) {+ Ok(uri) => uri,+ Err(message) => return validation_error(&invalid(&["model"], message), None),+ };+ let extract_bytes = match serde_json::to_vec(&extract_body) {+ Ok(bytes) => bytes,+ Err(error) => {+ return api_error(+ StatusCode::INTERNAL_SERVER_ERROR,+ Some("INTERNAL_ERROR"),+ format!("extract body: {error}"),+ )+ }+ };+ let mut builder = Request::builder()+ .method(Method::POST)+ .uri(uri)+ .version(parts.version);+ for (name, value) in headers.iter() {+ if is_openai_compat_inner_request_header(name.as_str()) {+ builder = builder.header(name, value);+ }+ }+ builder = builder+ .header(axum::http::header::CONTENT_TYPE, "application/json")+ .header(axum::http::header::ACCEPT, "application/json");+ let mut inner = match builder.body(Body::from(extract_bytes)) {+ Ok(request) => request,+ Err(_) => {+ return api_error(+ StatusCode::INTERNAL_SERVER_ERROR,+ Some("INTERNAL_ERROR"),+ "failed to build internal extract request",+ )+ }+ };+ *inner.extensions_mut() = parts.extensions;+ inner.extensions_mut().insert(CompatibilityRoute);+ let response = proxy_request(State(state), inner, "extract").await;+ if response.status() != StatusCode::OK {+ return translate_error(response).await;+ }++ // From here the worker has run and reported its units, so a failure to+ // render its result is the gateway's: the caller receives no answers and+ // must not be charged for them. Each arm is marked [`GatewayOwnedFault`].+ let response_headers = response.headers().clone();+ let native: Value = match to_bytes(response.into_body(), MAX_RESPONSE_BYTES).await {+ Ok(bytes) => match serde_json::from_slice(&bytes) {+ Ok(value) => value,+ Err(error) => {+ return translation_fault(+ "decode_extract_response",+ format!("extract response is not valid JSON: {error}"),+ )+ }+ },+ Err(_) => {+ return translation_fault(+ "read_extract_response",+ "failed to read extract response body",+ )+ }+ };+ 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),+ };+ for (name, value) in response_headers.iter() {+ if is_openai_compat_forwarded_header(name.as_str()) {+ output.headers_mut().insert(name.clone(), value.clone());+ }+ }+ output+}++#[cfg(test)]+mod tests {+ use super::*;++ fn fixture() -> Value {+ serde_json::from_str(include_str!("../../../wire-fixtures/systemone.json"))+ .expect("systemone fixture")+ }++ #[test]+ fn fixture_requests_become_their_extract_calls() {+ for case in fixture()["requests"].as_array().unwrap() {+ let name = case["name"].as_str().unwrap();+ let request = normalize_request(&case["request"]).unwrap_or_else(|error| {+ panic!("{name}: {error:?}");+ });+ let expected = &case["extract"];+ assert_eq!(request.model, expected["model"], "{name}");+ assert_eq!(request.item, expected["item"], "{name}");+ let body = extract_body(&request);+ assert_eq!(body["items"], json!([expected["item"]]), "{name}");+ assert_eq!(+ body["params"]["output_schema"], expected["output_schema"],+ "{name}"+ );+ assert_eq!(body["params"]["options"], expected["options"], "{name}");+ }+ }++ #[test]+ fn fixture_invalid_requests_are_refused() {+ for case in fixture()["invalid_requests"].as_array().unwrap() {+ let name = case["name"].as_str().unwrap();+ assert!(+ normalize_request(&case["request"]).is_err(),+ "{name} was accepted"+ );+ }+ }++ fn assert_close(actual: &Value, expected: &Value, path: &str) {+ match expected {+ Value::Object(expected) => {+ let actual = actual+ .as_object()+ .unwrap_or_else(|| panic!("{path}: not an object"));+ let mut actual_keys: Vec<_> = actual.keys().collect();+ let mut expected_keys: Vec<_> = expected.keys().collect();+ actual_keys.sort();+ expected_keys.sort();+ assert_eq!(actual_keys, expected_keys, "{path}");+ for (key, value) in expected {+ assert_close(&actual[key], value, &format!("{path}.{key}"));+ }+ }+ Value::Number(number) if number.is_f64() => {+ let actual = actual+ .as_f64()+ .unwrap_or_else(|| panic!("{path}: not a number"));+ assert!(+ (actual - number.as_f64().unwrap()).abs() < 1e-9,+ "{path}: {actual} != {number}"+ );+ }+ _ => assert_eq!(actual, expected, "{path}"),+ }+ }++ #[test]+ fn fixture_responses_are_rendered() {+ for case in fixture()["responses"].as_array().unwrap() {+ let name = case["name"].as_str().unwrap();+ let questions: Map<String, Value> = case["questions"]+ .as_array()+ .unwrap()+ .iter()+ .map(|qid| (qid.as_str().unwrap().to_string(), json!({"type": "noul"})))+ .collect();+ let native = json!({+ "model": case["model"],+ "items": [{"id": "item-0", "data": case["data"]}],+ "usage": {"input_tokens": case["input_tokens"]},+ });+ let model = case["model"].as_str().unwrap();+ let Translated::Answers(body) =+ response_from_extract(&native, model, &questions).unwrap()+ else {+ panic!("{name}: refused");+ };+ assert_close(&body, &case["response"], name);+ assert!(body["usage"]["input_tokens"].is_u64(), "{name}");+ assert!(body["usage"]["output_tokens"].is_u64(), "{name}");+ }+ }++ #[test]+ fn fixture_confidences() {+ let fixture = fixture();+ for (kind, function) in [+ ("choice", choice_confidence as fn(&[f64]) -> f64),+ ("score", score_confidence),+ ] {+ for case in fixture["confidence"][kind].as_array().unwrap() {+ let probabilities: Vec<f64> = case["probabilities"]+ .as_array()+ .unwrap()+ .iter()+ .map(|p| p.as_f64().unwrap())+ .collect();+ let expected = case["confidence"].as_f64().unwrap();+ assert!(+ (function(&probabilities) - expected).abs() < 1e-9,+ "{kind} {probabilities:?}"+ );+ }+ }+ }++ #[test]+ fn fixture_retry_after() {+ for case in fixture()["retry_after"].as_array().unwrap() {+ let (seconds, millis) =+ capped_retry_after(case["retry_after"].as_str().unwrap()).unwrap();+ assert_eq!(seconds, case["expected"].as_str().unwrap());+ assert_eq!(millis, case["expected_ms"].as_str().unwrap());+ }+ }++ #[test]+ fn refused_item_is_a_validation_error() {+ let native = json!({+ "items": [{"id": "item-0", "data": {}, "error": {"code": "INPUT_TOO_LONG", "message": "does not fit"}}],+ });+ let questions: Map<String, Value> = [("q".to_string(), json!({"type": "noul"}))]+ .into_iter()+ .collect();+ assert_eq!(+ response_from_extract(&native, "m", &questions).unwrap(),+ Translated::Refused(invalid(&["state"], "does not fit"))+ );+ }++ #[test]+ fn missing_answer_is_a_translation_failure() {+ let native = json!({"items": [{"id": "item-0", "data": {}}]});+ let questions: Map<String, Value> = [("q".to_string(), json!({"type": "noul"}))]+ .into_iter()+ .collect();+ assert!(response_from_extract(&native, "m", &questions).is_err());+ }++ #[tokio::test]+ async fn native_errors_take_the_system_one_shapes() {+ let bad = api_error(+ StatusCode::BAD_REQUEST,+ Some("INVALID_INPUT"),+ "bad question",+ );+ let translated = translate_error(bad).await;+ assert_eq!(translated.status(), StatusCode::UNPROCESSABLE_ENTITY);+ let body: Value =+ serde_json::from_slice(&to_bytes(translated.into_body(), 1 << 20).await.unwrap())+ .unwrap();+ assert_eq!(body["detail"][0]["msg"], "bad question");++ let mut loading = (+ StatusCode::SERVICE_UNAVAILABLE,+ Json(json!({"detail": {"code": "MODEL_LOADING", "message": "loading"}})),+ )+ .into_response();+ loading.headers_mut().insert(+ axum::http::header::RETRY_AFTER,+ HeaderValue::from_static("270"),+ );+ let translated = translate_error(loading).await;+ assert_eq!(translated.status(), StatusCode::SERVICE_UNAVAILABLE);+ assert_eq!(translated.headers()["retry-after"], "60");+ assert_eq!(translated.headers()["retry-after-ms"], "60000");+ let body: Value =+ serde_json::from_slice(&to_bytes(translated.into_body(), 1 << 20).await.unwrap())+ .unwrap();+ assert_eq!(body["detail"]["error_type"], "api_error");+ assert_eq!(body["detail"]["code"], "MODEL_LOADING");+ }++ use crate::handlers::test_support::{+ TestGateway, LOCAL_DECISION_MODEL, LOCAL_ENCODE_MODEL, LOCAL_LANE,+ };++ fn systemone_request(body: Value) -> Request {+ Request::builder()+ .method(Method::POST)+ .uri("/v1/systemone")+ .header(axum::http::header::CONTENT_TYPE, "application/json")+ .body(Body::from(serde_json::to_vec(&body).unwrap()))+ .unwrap()+ }++ async fn body_json(response: Response) -> Value {+ serde_json::from_slice(&to_bytes(response.into_body(), 1 << 20).await.unwrap()).unwrap()+ }++ #[tokio::test]+ async fn answers_through_the_extract_queue() {+ 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!({+ "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.1+ }+ }));+ let request = systemone_request(json!({+ "model": "acme/decide",+ "state": "I was charged twice.",+ "questions": {+ "spam": {"type": "noul"},+ "intent": {"type": "choice", "criteria": {"billing": null, "support": null, "other": null}}+ },+ "temperature": 0+ }));+ let response = proxy_systemone(State(Arc::clone(&gateway.state)), request).await;+ assert_eq!(response.status(), StatusCode::OK);+ let body = body_json(response).await;+ assert_eq!(body["model"], "acme/decide");+ assert_eq!(body["answers"]["spam"]["noul"], 0.9);+ assert!((body["answers"]["intent"]["confidence"].as_f64().unwrap() - 0.7).abs() < 1e-9);+ assert_eq!(body["usage"]["output_tokens"], 0);+ assert!(body["usage"]["input_tokens"].is_u64());+ let dispatched = gateway.dispatcher.dispatched();+ assert_eq!(dispatched.len(), 1);+ assert_eq!(dispatched[0].endpoint, "extract");+ assert_eq!(dispatched[0].model, "acme/decide");+ }++ #[tokio::test]+ async fn refuses_a_model_that_does_not_answer_typed_questions() {+ let gateway = TestGateway::new(&[LOCAL_DECISION_MODEL, LOCAL_ENCODE_MODEL]).await;+ let request = systemone_request(json!({+ "model": "acme/local", "state": "hi", "questions": {"q": {"type": "noul"}}+ }));+ let response = proxy_systemone(State(Arc::clone(&gateway.state)), request).await;+ assert_eq!(response.status(), StatusCode::UNPROCESSABLE_ENTITY);+ let body = body_json(response).await;+ assert_eq!(body["detail"][0]["loc"], json!(["body", "model"]));+ assert!(gateway.dispatcher.dispatched().is_empty());+ }++ #[tokio::test]+ async fn unknown_model_is_not_found() {+ let gateway = TestGateway::new(&[LOCAL_DECISION_MODEL]).await;+ let request = systemone_request(json!({+ "model": "acme/missing", "state": "hi", "questions": {"q": {"type": "noul"}}+ }));+ let response = proxy_systemone(State(Arc::clone(&gateway.state)), request).await;+ assert_eq!(response.status(), StatusCode::NOT_FOUND);+ assert_eq!(+ body_json(response).await["detail"]["error_type"],+ "not_found_error"+ );+ }++ #[tokio::test]+ async fn malformed_json_is_a_validation_error() {+ let gateway = TestGateway::new(&[LOCAL_DECISION_MODEL]).await;+ let request = Request::builder()+ .method(Method::POST)+ .uri("/v1/systemone")+ .body(Body::from("{"))+ .unwrap();+ let response = proxy_systemone(State(Arc::clone(&gateway.state)), request).await;+ assert_eq!(response.status(), StatusCode::UNPROCESSABLE_ENTITY);+ assert!(body_json(response).await["detail"].is_array());+ }+}diff --git a/packages/sie_gateway/src/handlers/test_support.rs b/packages/sie_gateway/src/handlers/test_support.rsindex c807ac33d..e4a15f8bb 100644--- a/packages/sie_gateway/src/handlers/test_support.rs+++ b/packages/sie_gateway/src/handlers/test_support.rs@@ -32,7 +32,7 @@ pub(crate) const LOCAL_LANE: (&str, &str, &str) = ("default", "l4", "default");/// The remote lane's `(pool, machine_profile, bundle)`.pub(crate) const REMOTE_LANE: (&str, &str, &str) = ("default", "cpu", "remote");-const DEFAULT_BUNDLE: &str = "name: default\ndefault: true\nadapters:\n - sie_server.adapters.bert_flash\n - sie_server.adapters.sglang\n - sie_server.adapters.whisper.adapter\n - sie_server.adapters.remote.sie\n";+const DEFAULT_BUNDLE: &str = "name: default\ndefault: true\nadapters:\n - sie_server.adapters.bert_flash\n - sie_server.adapters.sglang\n - sie_server.adapters.whisper.adapter\n - sie_server.adapters.gliner2.decide\n - sie_server.adapters.remote.sie\n";const REMOTE_BUNDLE: &str ="name: remote\npriority: 1\ndefault: false\nadapters:\n - sie_server.adapters.remote.sie\n";@@ -129,6 +129,18 @@ profiles:upstream_model: acme/extract";+/// A local typed-decision model (GLiNER2.5-Decide) for `/v1/systemone`.+pub(crate) const LOCAL_DECISION_MODEL: &str = "\+sie_id: acme/decide+hf_id: acme/decide+tasks:+ extract: {}+profiles:+ default:+ adapter_path: sie_server.adapters.gliner2.decide:GLiNER2DecideAdapter+ max_batch_tokens: 8192+";+/// One request as the transport received it.#[derive(Clone, Debug, PartialEq, Eq)]pub(crate) struct Dispatched {diff --git a/packages/sie_gateway/src/nats/manager.rs b/packages/sie_gateway/src/nats/manager.rsindex 007aca93f..1d228341d 100644--- a/packages/sie_gateway/src/nats/manager.rs+++ b/packages/sie_gateway/src/nats/manager.rs@@ -786,6 +786,8 @@ adapters:let seed = ModelConfig {name: "test/model".to_string(),hf_revision: None,+ description: None,+ release_date: None,routing: None,adapter_module: None,default_bundle: None,diff --git a/packages/sie_gateway/src/openapi.rs b/packages/sie_gateway/src/openapi.rsindex 8700fc382..e1b154a84 100644--- a/packages/sie_gateway/src/openapi.rs+++ b/packages/sie_gateway/src/openapi.rs@@ -54,6 +54,7 @@ static OPENAPI_JSON: LazyLock<String> = LazyLock::new(|| {crate::handlers::audio::proxy_openai_transcription,crate::handlers::proxy::proxy_rerank,crate::handlers::proxy::proxy_rerank_v2,+ crate::handlers::systemone::proxy_systemone,crate::handlers::proxy::proxy_score,crate::handlers::proxy::proxy_extract,crate::handlers::proxy::proxy_generate,@@ -165,6 +166,9 @@ static OPENAPI_JSON: LazyLock<String> = LazyLock::new(|| {RerankV2Request,RerankResponse,RerankResult,+ SystemOneRequest,+ SystemOneResponse,+ SystemOneUsage,ScoreUsage,ScoreEntry,crate::handlers::config_api::ResolveRequest,@@ -2712,6 +2716,12 @@ pub struct ModelInfoWire {pub max_sequence_length: Option<u64>,/// Immutable model weights revision, when the catalog pins one.pub revision: Option<String>,+ /// One line about the model; `""` when the catalog sets none. Reported for+ /// System One model-list clients (the TypeSafe SDKs).+ pub description: String,+ /// Release date of the served weights, `YYYY-MM-DD`; `""` when the catalog+ /// sets none. Reported for System One model-list clients.+ pub release_date: String,pub profiles: std::collections::HashMap<String, ProfileInfoWire>,/// Advertised model capabilities. Consumers use this to discover/// which features the model supports before composing a request.@@ -3084,6 +3094,40 @@ pub struct ScoreRequest {pub options: Option<Value>,}+/// A System One request: one state and its typed questions. Fields the route+/// does not read are ignored.+#[derive(Debug, Serialize, Deserialize, ToSchema)]+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)]+ pub state: Value,+ /// Typed questions by id: `{"type": "noul" | "choice" | "score",+ /// "instructions"?, "criteria"?}`. A score question takes at most 10 levels.+ #[schema(value_type = Object)]+ pub questions: Value,+}++/// Tokens the decision model read; it generates none.+#[derive(Debug, Serialize, Deserialize, ToSchema)]+pub struct SystemOneUsage {+ pub input_tokens: u64,+ pub output_tokens: u64,+}++/// Answers by question id, in the System One response shape.+#[derive(Debug, Serialize, Deserialize, ToSchema)]+pub struct SystemOneResponse {+ pub model: String,+ /// One answer per question: `noul` (`noul`, the probability of yes),+ /// `choice` (`choice`, `confidence`, `probabilities` by option) or `score`+ /// (`score`, `confidence`, `legend` and `probabilities` by level index).+ #[schema(value_type = Object)]+ pub answers: Value,+ pub usage: SystemOneUsage,+}+#[derive(Debug, Serialize, Deserialize, ToSchema)]#[serde(deny_unknown_fields)]pub struct RerankRequest {@@ -3865,6 +3909,7 @@ mod tests {("/v1/moderations", &["post"][..]),("/v1/rerank", &["post"][..]),("/v2/rerank", &["post"][..]),+ ("/v1/systemone", &["post"][..]),("/ws/cluster-status", &["get"][..]),("/v1/encode/{model}", &["post"][..]),("/v1/score/{model}", &["post"][..]),diff --git a/packages/sie_gateway/src/server.rs b/packages/sie_gateway/src/server.rsindex c5cebd3f5..574371206 100644--- a/packages/sie_gateway/src/server.rs+++ b/packages/sie_gateway/src/server.rs@@ -6,7 +6,7 @@ use std::sync::Arc;use std::time::{Duration, SystemTime, UNIX_EPOCH};use crate::config::Config;-use crate::handlers::{audio, config_api, health, models, pools, proxy};+use crate::handlers::{audio, config_api, health, models, pools, proxy, systemone};use crate::middleware::audit::AuditLayer;use crate::middleware::auth::AuthLayer;use crate::middleware::metrics::apply_request_telemetry;@@ -635,6 +635,8 @@ pub fn create_router_core(.route("/v1/embeddings", post(proxy::proxy_openai_embeddings)).route("/v1/rerank", post(proxy::proxy_rerank)).route("/v2/rerank", post(proxy::proxy_rerank_v2))+ // System One-compatible typed decisions over the native extract primitive.+ .route("/v1/systemone", post(systemone::proxy_systemone)).route("/v1/chat/completions", post(proxy::proxy_chat))// OpenAI legacy Completions — raw-prompt continuation (non-streaming)..route("/v1/completions", post(proxy::proxy_completions))diff --git a/packages/sie_gateway/src/state/config_bootstrap.rs b/packages/sie_gateway/src/state/config_bootstrap.rsindex 17535b279..436e2bd3e 100644--- a/packages/sie_gateway/src/state/config_bootstrap.rs+++ b/packages/sie_gateway/src/state/config_bootstrap.rs@@ -903,6 +903,8 @@ mod tests {ModelConfig {name: name.to_string(),hf_revision: None,+ description: None,+ release_date: None,routing: None,adapter_module: None,default_bundle: None,diff --git a/packages/sie_gateway/src/state/model_registry.rs b/packages/sie_gateway/src/state/model_registry.rsindex 1261414ca..88467446a 100644--- a/packages/sie_gateway/src/state/model_registry.rs+++ b/packages/sie_gateway/src/state/model_registry.rs@@ -3567,6 +3567,8 @@ mod tests {.add_model_config(ModelConfig {name: "org/x".to_string(),hf_revision: None,+ description: None,+ release_date: None,routing: None,adapter_module: None,default_bundle: None,@@ -3681,6 +3683,8 @@ mod tests {.add_model_config(ModelConfig {name: "org/g".to_string(),hf_revision: None,+ description: None,+ release_date: None,routing: None,adapter_module: None,default_bundle: None,@@ -3775,6 +3779,8 @@ mod tests {.add_model_config(ModelConfig {name: "org/scoped-only".to_string(),hf_revision: None,+ description: None,+ release_date: None,routing: None,adapter_module: None,default_bundle: None,@@ -4307,6 +4313,8 @@ profiles:.add_model_config(ModelConfig {name: "org/n".to_string(),hf_revision: None,+ description: None,+ release_date: None,routing: None,adapter_module: None,default_bundle: None,@@ -4359,6 +4367,8 @@ profiles:.add_model_config(ModelConfig {name: "org/unsafe-global-target".to_string(),hf_revision: None,+ description: None,+ release_date: None,routing: None,adapter_module: None,default_bundle: None,@@ -4383,6 +4393,8 @@ profiles:.add_model_config(ModelConfig {name: "org/mismatch".to_string(),hf_revision: None,+ description: None,+ release_date: None,routing: None,adapter_module: None,default_bundle: None,@@ -4409,6 +4421,8 @@ profiles:.add_model_config(ModelConfig {name: "org/mode-mismatch".to_string(),hf_revision: None,+ description: None,+ release_date: None,routing: None,adapter_module: None,default_bundle: None,@@ -4436,6 +4450,8 @@ profiles:.add_model_config(ModelConfig {name: "org/output-cap-mismatch".to_string(),hf_revision: None,+ description: None,+ release_date: None,routing: None,adapter_module: None,default_bundle: None,@@ -4463,6 +4479,8 @@ profiles:.add_model_config(ModelConfig {name: "org/kv-budget-mismatch".to_string(),hf_revision: None,+ description: None,+ release_date: None,routing: None,adapter_module: None,default_bundle: None,@@ -4490,6 +4508,8 @@ profiles:.add_model_config(ModelConfig {name: "org/chained-fallback".to_string(),hf_revision: None,+ description: None,+ release_date: None,routing: None,adapter_module: None,default_bundle: None,@@ -4581,6 +4601,8 @@ profiles:.add_model_config(ModelConfig {name: "org/g".to_string(),hf_revision: None,+ description: None,+ release_date: None,routing: None,adapter_module: None,default_bundle: None,@@ -4652,6 +4674,8 @@ profiles:.add_model_config(ModelConfig {name: "org/x".to_string(),hf_revision: None,+ description: None,+ release_date: None,routing: None,adapter_module: None,default_bundle: None,@@ -4819,6 +4843,8 @@ profiles:.add_model_config(ModelConfig {name: "org/profile-only".to_string(),hf_revision: Some("0123456789abcdef0123456789abcdef01234567".to_string()),+ description: None,+ release_date: None,routing: None,adapter_module: None,default_bundle: None,@@ -5240,6 +5266,8 @@ profiles:.add_model_config(ModelConfig {name: "org/broken".to_string(),hf_revision: None,+ description: None,+ release_date: None,routing: None,adapter_module: None,default_bundle: None,@@ -5303,6 +5331,8 @@ profiles:let cfg = ModelConfig {name: name.clone(),hf_revision: None,+ description: None,+ release_date: None,routing: None,adapter_module: None,default_bundle: None,@@ -5556,6 +5586,8 @@ adapters:let config = ModelConfig {name: "test/model".to_string(),hf_revision: None,+ description: None,+ release_date: None,routing: None,adapter_module: None,default_bundle: None,@@ -5631,6 +5663,8 @@ adapters:.add_model_config(ModelConfig {name: "test/model".to_string(),hf_revision: None,+ description: None,+ release_date: None,routing: None,adapter_module: None,default_bundle: None,@@ -5690,6 +5724,8 @@ encode:.add_model_config(ModelConfig {name: "test/model".to_string(),hf_revision: None,+ description: None,+ release_date: None,routing: None,adapter_module: None,default_bundle: None,@@ -5741,6 +5777,8 @@ encode:.add_model_config(ModelConfig {name: "test/generator".to_string(),hf_revision: None,+ description: None,+ release_date: None,routing: None,adapter_module: None,default_bundle: None,@@ -5775,6 +5813,8 @@ encode:.add_model_config(ModelConfig {name: "test/generator".to_string(),hf_revision: None,+ description: None,+ release_date: None,routing: None,adapter_module: None,default_bundle: None,@@ -5848,6 +5888,8 @@ adapters:.add_model_config(ModelConfig {name: "test/model".to_string(),hf_revision: None,+ description: None,+ release_date: None,routing: None,adapter_module: None,default_bundle: None,@@ -5902,6 +5944,8 @@ encode:.add_model_config(ModelConfig {name: "test/model".to_string(),hf_revision: None,+ description: None,+ release_date: None,routing: None,adapter_module: None,default_bundle: None,@@ -5927,6 +5971,8 @@ encode:ModelConfig {name: "test/model".to_string(),hf_revision: None,+ description: None,+ release_date: None,routing: None,adapter_module: None,default_bundle: None,@@ -6529,6 +6575,8 @@ adapters:let seed = ModelConfig {name: "test/model".to_string(),hf_revision: None,+ description: None,+ release_date: None,routing: None,adapter_module: None,default_bundle: None,@@ -6592,6 +6640,8 @@ adapters:let delta = ModelConfig {name: "test/model".to_string(),hf_revision: None,+ description: None,+ release_date: None,routing: None,adapter_module: None,default_bundle: None,@@ -7076,6 +7126,8 @@ profiles:.add_model_config(ModelConfig {name: "org/revisioned".to_string(),hf_revision: Some("89abcdef0123456789abcdef0123456789abcdef".to_string()),+ description: None,+ release_date: None,routing: None,adapter_module: None,default_bundle: None,@@ -7396,6 +7448,8 @@ adapters:let config = ModelConfig {name: format!("race/model-{i}"),hf_revision: None,+ description: None,+ release_date: None,routing: None,adapter_module: None,default_bundle: None,@@ -7630,6 +7684,8 @@ profiles:ModelConfig {name: name.to_string(),hf_revision: None,+ description: None,+ release_date: None,routing: None,adapter_module: None,default_bundle: None,diff --git a/packages/sie_gateway/src/types/model.rs b/packages/sie_gateway/src/types/model.rsindex fc54a41de..883d1fec2 100644--- a/packages/sie_gateway/src/types/model.rs+++ b/packages/sie_gateway/src/types/model.rs@@ -14,6 +14,12 @@ pub struct ModelInfoExtras {/// of worker/gateway parity and is absent for unpinned or package-backed/// models.pub revision: Option<String>,+ /// One line about the model and the release date of its served weights+ /// (``YYYY-MM-DD``), from the model YAML. ``/v1/models`` reports both, ``""``+ /// when unset, because the System One model list (the TypeSafe SDKs) reads+ /// them as strings from every entry.+ pub description: Option<String>,+ pub release_date: Option<String>,/// Bare-model policy; explicit profile variants never apply it.pub routing: Option<RoutingConfig>,/// Per-request hard cap on ``max_new_tokens``. Mirrors@@ -124,6 +130,15 @@ impl ModelInfoExtras {.filter(|value| !value.is_empty()).map(str::to_owned);+ extras.description = raw+ .get("description")+ .and_then(|value| value.as_str())+ .map(str::to_owned);+ extras.release_date = raw+ .get("release_date")+ .and_then(|value| value.as_str())+ .map(str::to_owned);+extras.routing = raw.get("routing").and_then(|value| serde_json::from_value(value.clone()).ok());@@ -347,6 +362,8 @@ impl ModelInfoExtras {dims: HashMap::new(),max_sequence_length: config.max_sequence_length,revision: None,+ description: config.description.clone(),+ release_date: config.release_date.clone(),routing: None,max_output_tokens: None,profile_max_output_tokens: HashMap::new(),@@ -553,6 +570,12 @@ pub struct ModelConfig {pub name: String,#[serde(default)]pub hf_revision: Option<String>,+ /// One line about the model, reported by ``/v1/models``.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub description: Option<String>,+ /// Release date of the served weights (``YYYY-MM-DD``), reported by ``/v1/models``.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub release_date: Option<String>,#[serde(default, skip_serializing_if = "Option::is_none")]pub routing: Option<RoutingConfig>,#[serde(default)]@@ -674,6 +697,8 @@ impl ModelEntry {"last_error": Value::Null,"max_sequence_length": self.info_extras.max_sequence_length,"revision": self.info_extras.revision,+ "description": self.info_extras.description.as_deref().unwrap_or(""),+ "release_date": self.info_extras.release_date.as_deref().unwrap_or(""),"profiles": Value::Object(profiles),// Advertised model capabilities. ``lora_adapters`` lists the// public served-names of declared LoRA adapters (union across@@ -1272,6 +1297,8 @@ profiles: {}let config = ModelConfig {name: "test/model".into(),hf_revision: Some("0123456789abcdef0123456789abcdef01234567".into()),+ description: None,+ release_date: None,routing: None,adapter_module: Some("mod".into()),default_bundle: None,