diff --git a/Cargo.lock b/Cargo.lock index 2497cb5..e2689e9 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -734,6 +734,7 @@ version = "0.1.34" dependencies = [ "async-trait", "axum", + "base64 0.22.1", "futures-util", "nexus-adapter", "nexus-core", diff --git a/KLICKTESTS.md b/KLICKTESTS.md index 29026fd..b95a69d 100644 --- a/KLICKTESTS.md +++ b/KLICKTESTS.md @@ -370,7 +370,7 @@ für einen Block aufweichen; das steht dann im Todo. | --- | --- | --- | --- | | client2embeddings.1 | `curl -s -H "Authorization: Bearer $NX_KEY" -H "Content-Type: application/json" -d '{"model":"","input":"Hallo Welt"}' https://nexus.srv04.lab.wlkns.org/v1/embeddings` | Status 200; `data` hat einen Eintrag mit `object` `embedding`, `index` 0 und einer Zahlenliste in `embedding` (bge-m3: 1024 Werte); `usage` hat `prompt_tokens` und `total_tokens` | auto | | client2embeddings.2 | Dieselbe Anfrage mit `input` als Liste von zwei Texten | `data` hat zwei Einträge mit `index` 0 und 1 | auto | -| client2embeddings.3 | Anfrage mit `encoding_format` `base64`, danach mit leerem `input` (leerer Text und leere Liste) | je Status 400 mit deutscher Meldung im OpenAI-Fehlerformat | auto | +| client2embeddings.3 | Anfrage mit `encoding_format` `int8`, danach mit leerem `input` (leerer Text und leere Liste); Anpassung vom 02.12.2026: `base64` ist seit #1265 erlaubt, siehe `.7` | je Status 400 mit deutscher Meldung im OpenAI-Fehlerformat | auto | | client2embeddings.4 | `POST /v1/embeddings` mit dem Namen eines Chat-Modells, danach `POST /v1/chat/completions` mit dem Embedding-Modell | je Status 400, Meldung nennt, dass das Modell dafür nicht gedacht ist | auto | | client2embeddings.5 | Anfrage mit einem Key ohne Recht für das Modell; Anfrage ohne Key | 403 beziehungsweise 401 im OpenAI-Fehlerformat | auto | | client2embeddings.6 | Auf „Modelle“ und „Engines“ das Embedding-Modell ansehen | Die Fähigkeit „Embeddings“ ist als Symbol sichtbar | manuell | diff --git a/crates/nexus-api/Cargo.toml b/crates/nexus-api/Cargo.toml index e57e344..9b18661 100644 --- a/crates/nexus-api/Cargo.toml +++ b/crates/nexus-api/Cargo.toml @@ -7,6 +7,7 @@ license.workspace = true [dependencies] axum.workspace = true +base64 = "0.22" futures-util = "0.3" nexus-adapter.workspace = true nexus-core.workspace = true diff --git a/crates/nexus-api/src/antwort.rs b/crates/nexus-api/src/antwort.rs new file mode 100644 index 0000000..0891c07 --- /dev/null +++ b/crates/nexus-api/src/antwort.rs @@ -0,0 +1,192 @@ +//! Passt Antworten der Engines an die öffentliche Schnittstelle an: Das Feld `model` nennt die Modell-ID von +//! Nexus, nicht den Namen der Engine (#1266), und Embeddings gibt es auch als `base64` (#1265). Was schon passt, +//! geht Byte für Byte durch. Nie Inhalte loggen. + +use axum::body::Bytes; +use base64::Engine as _; +use futures_util::{ + StreamExt, + stream::{self, BoxStream}, +}; +use serde_json::Value; + +type ResponseStream = BoxStream<'static, Result>; + +/// Größer wird nicht gepuffert; dann geht der Rest unverändert durch. +const MAX_BODY: usize = 32 * 1024 * 1024; +const MAX_LINE: usize = 1024 * 1024; + +#[derive(Clone)] +pub(crate) struct Anpassung { + pub model: String, + pub base64: bool, +} + +impl Anpassung { + /// Ändert die Antwort, falls nötig. `None`: nichts zu tun oder kein passendes JSON. + fn json(&self, bytes: &[u8]) -> Option> { + let mut value: Value = serde_json::from_slice(bytes).ok()?; + let object = value.as_object_mut()?; + let mut changed = false; + if let Some(name) = object.get_mut("model") + && name.is_string() + && name.as_str() != Some(&self.model) + { + *name = Value::String(self.model.clone()); + changed = true; + } + if self.base64 + && let Some(data) = object.get_mut("data").and_then(Value::as_array_mut) + { + for item in data { + let Some(numbers) = item.get("embedding").and_then(Value::as_array) else { + continue; + }; + let floats: Option> = numbers + .iter() + .map(|n| n.as_f64().map(|f| (f as f32).to_le_bytes())) + .collect::>>() + .map(|v| v.concat()); + if let Some(floats) = floats { + item["embedding"] = + Value::String(base64::engine::general_purpose::STANDARD.encode(floats)); + changed = true; + } + } + } + if changed { + serde_json::to_vec(&value).ok() + } else { + None + } + } + + /// Eine Zeile eines SSE-Stroms samt Zeilenende. + fn line(&self, line: &[u8], out: &mut Vec) { + let text = line.strip_suffix(b"\n").unwrap_or(line); + let text = text.strip_suffix(b"\r").unwrap_or(text); + if let Some(data) = text.strip_prefix(b"data:") + && let Some(changed) = self.json(data.trim_ascii()) + { + out.extend_from_slice(b"data: "); + out.extend_from_slice(&changed); + out.extend_from_slice(&line[text.len()..]); + } else { + out.extend_from_slice(line); + } + } + + /// SSE: zeilenweise, ohne auf mehr als das Zeilenende zu warten. + pub(crate) fn strom(self, upstream: ResponseStream) -> ResponseStream { + stream::unfold( + (Some(upstream), Vec::new(), self), + |(upstream, mut buffer, me)| async move { + let mut upstream = upstream?; + loop { + match upstream.next().await { + Some(Ok(chunk)) => { + buffer.extend_from_slice(&chunk); + let mut out = Vec::new(); + if let Some(end) = buffer.iter().rposition(|b| *b == b'\n') { + let rest = buffer.split_off(end + 1); + for line in buffer.split_inclusive(|b| *b == b'\n') { + me.line(line, &mut out); + } + buffer = rest; + } else if buffer.len() > MAX_LINE { + out = std::mem::take(&mut buffer); + } + if !out.is_empty() { + return Some((Ok(Bytes::from(out)), (Some(upstream), buffer, me))); + } + } + Some(Err(e)) => return Some((Err(e), (None, Vec::new(), me))), + None => { + if buffer.is_empty() { + return None; + } + let mut out = Vec::new(); + me.line(&buffer, &mut out); + return Some((Ok(Bytes::from(out)), (None, Vec::new(), me))); + } + } + } + }, + ) + .boxed() + } + + /// Eine vollständige JSON-Antwort: sammeln, anpassen, in einem Stück weitergeben. + pub(crate) fn ganz(self, mut upstream: ResponseStream) -> ResponseStream { + stream::once(async move { + let mut body = Vec::new(); + while let Some(part) = upstream.next().await { + match part { + Ok(chunk) => body.extend_from_slice(&chunk), + Err(e) => { + return stream::iter([Ok(Bytes::from(body)), Err(e)]).boxed(); + } + } + if body.len() > MAX_BODY { + return stream::once(async { Ok(Bytes::from(body)) }) + .chain(upstream) + .boxed(); + } + } + let body = self.json(&body).unwrap_or(body); + stream::iter([Ok(Bytes::from(body))]).boxed() + }) + .flatten() + .boxed() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn nexus() -> Anpassung { + Anpassung { + model: "klein".to_string(), + base64: false, + } + } + + async fn alles(s: ResponseStream) -> String { + let parts: Vec<_> = s.map(|c| c.unwrap()).collect().await; + String::from_utf8(parts.concat()).unwrap() + } + + fn teile(parts: &[&'static str]) -> ResponseStream { + let parts: Vec> = parts + .iter() + .map(|p| Ok(Bytes::from_static(p.as_bytes()))) + .collect(); + stream::iter(parts).boxed() + } + + #[tokio::test] + async fn modellname_im_strom_auch_ueber_stueckgrenzen() { + let got = alles(nexus().strom(teile(&[ + ": keep-alive\n\ndata: {\"model\":\"qw", + "en3:0.6b\",\"n\":1}\r\n\ndata: [DONE]", + "\n\n", + ]))) + .await; + assert_eq!( + got, + ": keep-alive\n\ndata: {\"model\":\"klein\",\"n\":1}\r\n\ndata: [DONE]\n\n" + ); + } + + #[tokio::test] + async fn passende_und_fremde_antworten_bleiben_byte_fuer_byte() { + for body in ["{ \"model\" : \"klein\" }", "kein json", "{\"error\":{}}"] { + assert_eq!(alles(nexus().ganz(teile(&[body]))).await, body); + } + assert_eq!( + alles(nexus().strom(teile(&["data: {\"model\" : \"klein\"}\n", "ohne Ende"]))).await, + "data: {\"model\" : \"klein\"}\nohne Ende" + ); + } +} diff --git a/crates/nexus-api/src/chat.rs b/crates/nexus-api/src/chat.rs index 4bb897f..cfa6740 100644 --- a/crates/nexus-api/src/chat.rs +++ b/crates/nexus-api/src/chat.rs @@ -16,6 +16,7 @@ use futures_util::{ use serde_json::Value; use crate::access::{AccessSlot, RequestId, StartedAt, clip}; +use crate::antwort::Anpassung; use crate::auth::{Authed, requested_priority}; use crate::error::ApiError; use crate::runtime::RuntimeError; @@ -201,11 +202,33 @@ async fn forward_to( } else { None }; + // #1267: Ungültige Chat-Anfragen hier abweisen; nicht jede Engine tut es (Maya rechnete ohne Nachrichten). + if path == "/v1/chat/completions" + && !request + .get("messages") + .and_then(Value::as_array) + .is_some_and(|m| !m.is_empty() && m.iter().all(|n| n["role"].is_string())) + { + return Err(ApiError::bad_request( + "messages muss eine nichtleere Liste von Nachrichten mit dem Feld role sein.", + )); + } + let mut base64 = false; if path == "/v1/embeddings" { - if !request.get("encoding_format").is_none_or(|v| v == "float") { - return Err(ApiError::bad_request( - "Nur encoding_format \"float\" wird unterstützt.", - )); + // #1265: Das offizielle Python-SDK fordert von sich aus base64 an. Die Engine liefert immer float, + // die Umwandlung macht das Gateway. + match request.get("encoding_format") { + None => {} + Some(v) if v == "float" => {} + Some(v) if v == "base64" => { + base64 = true; + request["encoding_format"] = Value::String("float".to_string()); + } + Some(_) => { + return Err(ApiError::bad_request( + "Unbekanntes encoding_format. Unterstützt werden float und base64.", + )); + } } let valid = match request.get("input") { Some(Value::String(s)) => !s.trim().is_empty(), @@ -402,6 +425,22 @@ async fn forward_to( } }; } + // #1266: Die Antwort nennt die Modell-ID von Nexus, nicht den Namen der Engine. + if status.is_success() && path != "/v1/audio/speech" { + let anpassung = Anpassung { + model: model.clone(), + base64, + }; + let sse = response_headers + .get(CONTENT_TYPE) + .and_then(|v| v.to_str().ok()) + .is_some_and(|v| v.starts_with("text/event-stream")); + response_stream = if sse { + anpassung.strom(response_stream) + } else { + anpassung.ganz(response_stream) + }; + } let mut response = Response::builder().status(status); if status.is_success() { if let Some(content_type) = audio_type { diff --git a/crates/nexus-api/src/lib.rs b/crates/nexus-api/src/lib.rs index 61b2f15..416467a 100644 --- a/crates/nexus-api/src/lib.rs +++ b/crates/nexus-api/src/lib.rs @@ -11,6 +11,7 @@ mod access; mod alarm; +mod antwort; mod auth; mod chat; mod error; diff --git a/crates/nexus-api/tests/api.rs b/crates/nexus-api/tests/api.rs index 356d09b..51db501 100644 --- a/crates/nexus-api/tests/api.rs +++ b/crates/nexus-api/tests/api.rs @@ -661,8 +661,21 @@ async fn embeddings_format_rechte_und_faehigkeiten_gegen_attrappe() { assert_eq!(body["usage"]["prompt_tokens"], n * 3); assert_eq!(body["usage"]["total_tokens"], n * 3); } + // #1265: Das offizielle Python-SDK fordert von sich aus base64 an. [0.25, -0.5] als f32, Little Endian. + let resp = g + .client + .post(format!("{}/v1/embeddings", g.base)) + .bearer_auth(&g.key) + .body(json!({"model":"vektor", "input":["a", "b"], "encoding_format":"base64"}).to_string()) + .send() + .await + .unwrap(); + assert_eq!(resp.status(), 200); + let body: Value = serde_json::from_str(&resp.text().await.unwrap()).unwrap(); + assert_eq!(body["data"][1]["embedding"], "AACAPgAAAL8="); + assert_eq!(body["usage"]["total_tokens"], 6); for (model, input, format, status) in [ - ("vektor", json!("Hallo"), "base64", 400), + ("vektor", json!("Hallo"), "int8", 400), ("vektor", json!(""), "float", 400), ("vektor", json!([]), "float", 400), ("vektor", json!(["ok", ""]), "float", 400), @@ -695,6 +708,24 @@ async fn embeddings_format_rechte_und_faehigkeiten_gegen_attrappe() { assert_eq!(resp.status(), 400); } +/// #1267: Ohne Nachrichten darf keine Engine anfangen zu rechnen (Maya tat es). +#[tokio::test] +async fn chat_ohne_nachrichten_wird_abgewiesen_ohne_modellstart() { + let g = gateway(0, false).await; + for body in [ + json!({"model":"bonsai"}), + json!({"model":"bonsai", "messages":[]}), + json!({"model":"bonsai", "messages":"Hallo"}), + json!({"model":"bonsai", "messages":[{"content":"ohne Rolle"}]}), + ] { + let resp = g.chat(Some(&g.key), None, &body.to_string()).await; + assert_eq!(resp.status(), 400, "{body}"); + let answer: Value = serde_json::from_str(&resp.text().await.unwrap()).unwrap(); + assert_eq!(error_code(&answer), "invalid_request"); + } + assert!(g.state.runtime.scheduler_view().instances.is_empty()); +} + fn error_code(body: &Value) -> &str { body["error"]["code"].as_str().unwrap_or("") } diff --git a/scripts/srv04-kern-test/block_cdg.py b/scripts/srv04-kern-test/block_cdg.py index 0369f52..8e93a4a 100644 --- a/scripts/srv04-kern-test/block_cdg.py +++ b/scripts/srv04-kern-test/block_cdg.py @@ -127,10 +127,10 @@ def block_c(emit): rs = last(600, [lambda: call(random.choice(modelle), stream=random.random() < .5, max_tokens=random.randint(30, 300)) for _ in range(10)]) emit({"fall": "c_dauerlast", "anfragen": len(rs), "summe": summe(rs), "monitor": mon.end(), "ruhe": ruhe(), "log": logzahlen()}) -def block_vergleich(emit): +def block_vergleich(emit, fristen=(60, 0)): """Dieselbe Mischlast je 600 s mit Schonfrist 60 (Standard) und 0, mit GPU-Auslastung.""" modelle = ["bonsai", "darkidol", "ollama-gemma3-4b", "erebus", "cydonia"] - for frist in (60, 0): + for frist in fristen: restart("idle_secs = 600", f"evict_min_idle_secs = {frist}") smi = subprocess.Popen(["ssh", "-o", "BatchMode=yes", "srv04", "timeout 600 nvidia-smi --query-gpu=utilization.gpu --format=csv,noheader,nounits -l 2"], stdout=subprocess.PIPE, text=True) werte = [] @@ -143,6 +143,10 @@ def block_vergleich(emit): "gpu_proben": len(werte), "anteil_proben_ohne_gpu_last": round(sum(w == 0 for w in werte) / max(len(werte), 1), 2), "monitor": mon.end(), "ruhe": ruhe(), "log": logzahlen()}) +def block_nachmessung(emit): + """Nach #1269: gleiche Mischlast mit der neuen Standard-Schonfrist von 5 s.""" + block_vergleich(emit, (5,)) + def block_g(emit): restart("idle_secs = 600", "maya_idle_secs = 600") mon = Monitor() diff --git a/tests/sdk/test_gateway.py b/tests/sdk/test_gateway.py index bc11813..fabbf4a 100644 --- a/tests/sdk/test_gateway.py +++ b/tests/sdk/test_gateway.py @@ -264,6 +264,7 @@ class GatewayTest(unittest.TestCase): ) # Die Attrappe nennt das Modell, das tatsächlich in der Anfrage stand. self.assertTrue(antwort.choices[0].message.content.endswith(OLLAMA_TAG), antwort.choices[0].message.content) + self.assertEqual(antwort.model, OLLAMA_MODEL) # #1266 self.assertTrue(self.ollama_log().exists(), "ollama serve muss gestartet worden sein.") def test_11_ollama_streaming(self): @@ -271,6 +272,7 @@ class GatewayTest(unittest.TestCase): for chunk in self.client.chat.completions.create( model=OLLAMA_MODEL, messages=[{"role": "user", "content": "Hallo"}], stream=True ): + self.assertEqual(chunk.model, OLLAMA_MODEL) # #1266 if chunk.choices and chunk.choices[0].delta.content: stuecke.append(chunk.choices[0].delta.content) self.assertGreater(len(stuecke), 1) @@ -284,6 +286,7 @@ class GatewayTest(unittest.TestCase): model=MAYA_MODEL, messages=[{"role": "user", "content": "Hallo"}] ) nachricht = antwort.choices[0].message + self.assertEqual(antwort.model, MAYA_MODEL) # #1266 self.assertEqual(nachricht.content, "Hallo vom Maya-Modell.") self.assertEqual((nachricht.model_extra or {}).get("reasoning_content"), "denke") self.assertTrue(self.maya_log().exists(), "Maya muss gestartet worden sein.")