feat: select playground reasoning effort with compatible fallback (#1096)
This commit is contained in:
@ -34,6 +34,7 @@ struct FixedEngine {
|
||||
starts: AtomicUsize,
|
||||
stops: AtomicUsize,
|
||||
health_checks: AtomicUsize,
|
||||
health_timeout: std::sync::atomic::AtomicBool,
|
||||
delay: Duration,
|
||||
fail: bool,
|
||||
}
|
||||
@ -77,6 +78,9 @@ impl Engine for FixedEngine {
|
||||
}
|
||||
async fn health(&self, _i: &InstanceHandle) -> Health {
|
||||
self.health_checks.fetch_add(1, Ordering::SeqCst);
|
||||
if self.health_timeout.load(Ordering::SeqCst) {
|
||||
std::future::pending::<()>().await;
|
||||
}
|
||||
Health::Ready
|
||||
}
|
||||
fn endpoint(&self, i: &InstanceHandle) -> Endpoint {
|
||||
@ -104,31 +108,52 @@ async fn serve(app: Router) -> u16 {
|
||||
async fn fake_backend() -> u16 {
|
||||
async fn chat(body: Bytes) -> Response {
|
||||
let req: Value = serde_json::from_slice(&body).unwrap();
|
||||
if req["messages"][0]["content"] == "reject-reasoning"
|
||||
&& req.get("reasoning_effort").is_some()
|
||||
{
|
||||
return Response::builder().status(400).header(CONTENT_TYPE, "application/json")
|
||||
.body(Body::from(json!({"error":{"param":"reasoning_effort", "code":"unsupported_parameter", "message":"Unknown parameter reasoning_effort"}}).to_string())).unwrap();
|
||||
}
|
||||
if req["messages"][0]["content"] == "reject-reasoning-422"
|
||||
&& req.get("reasoning_effort").is_some()
|
||||
{
|
||||
return Response::builder().status(422).header(CONTENT_TYPE, "application/json")
|
||||
.body(Body::from(json!({"detail":[{"type":"extra_forbidden", "loc":["body", "reasoning_effort"], "msg":"Extra inputs are not permitted"}]}).to_string())).unwrap();
|
||||
}
|
||||
if req["messages"][0]["content"] == "other-error" {
|
||||
return Response::builder().status(400).header(CONTENT_TYPE, "application/json")
|
||||
.body(Body::from(json!({"error":{"param":"max_tokens", "code":"invalid_value", "message":"Testfehler"}}).to_string())).unwrap();
|
||||
}
|
||||
if req["stream"] == true {
|
||||
// Mit `stream_options.include_usage` kommt wie bei den echten Engines
|
||||
// ein letzter Block mit der Token-Zählung vor `[DONE]`.
|
||||
let with_usage = req["stream_options"]["include_usage"] == true;
|
||||
let effort = req.get("reasoning_effort").cloned().unwrap_or(Value::Null);
|
||||
let reasoning = req["messages"][0]["content"] == "with-reasoning";
|
||||
let parts = ["Hal", "lo", " Welt", "[USAGE]", "[DONE]"];
|
||||
let stream = stream::unfold(0usize, move |i| async move {
|
||||
let part = parts.get(i)?;
|
||||
if *part == "[USAGE]" && !with_usage {
|
||||
return Some((Ok::<_, Infallible>(Bytes::new()), i + 1));
|
||||
let stream = stream::unfold(0usize, move |i| {
|
||||
let effort = effort.clone();
|
||||
async move {
|
||||
let part = parts.get(i)?;
|
||||
if *part == "[USAGE]" && !with_usage {
|
||||
return Some((Ok::<_, Infallible>(Bytes::new()), i + 1));
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(200)).await;
|
||||
let text = if *part == "[DONE]" {
|
||||
"data: [DONE]\n\n".to_string()
|
||||
} else if *part == "[USAGE]" {
|
||||
format!(
|
||||
"data: {}\n\n",
|
||||
json!({"choices":[],"usage":{"prompt_tokens":7,"completion_tokens":9,"total_tokens":16}})
|
||||
)
|
||||
} else {
|
||||
format!(
|
||||
"data: {}\n\n",
|
||||
json!({"choices":[{"index":0,"delta": if reasoning && i == 0 { json!({"content":part,"reasoning_content":"kurzer Gedanke"}) } else { json!({"content":part}) }}],"reasoning_effort":effort})
|
||||
)
|
||||
};
|
||||
Some((Ok::<_, Infallible>(Bytes::from(text)), i + 1))
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(200)).await;
|
||||
let text = if *part == "[DONE]" {
|
||||
"data: [DONE]\n\n".to_string()
|
||||
} else if *part == "[USAGE]" {
|
||||
format!(
|
||||
"data: {}\n\n",
|
||||
json!({"choices":[],"usage":{"prompt_tokens":7,"completion_tokens":9,"total_tokens":16}})
|
||||
)
|
||||
} else {
|
||||
format!(
|
||||
"data: {}\n\n",
|
||||
json!({"choices":[{"index":0,"delta":{"content":part}}]})
|
||||
)
|
||||
};
|
||||
Some((Ok::<_, Infallible>(Bytes::from(text)), i + 1))
|
||||
});
|
||||
Response::builder()
|
||||
.header(CONTENT_TYPE, "text/event-stream")
|
||||
@ -148,7 +173,9 @@ async fn fake_backend() -> u16 {
|
||||
.unwrap()
|
||||
}
|
||||
}
|
||||
serve(Router::new().route("/v1/chat/completions", post(chat))).await
|
||||
serve(Router::new()
|
||||
.route("/", axum::routing::get(|| async { axum::response::Html("<html><script src='/app.js'></script>ENGINE-INHALT-NICHT-AUSLIEFERN</html>") }))
|
||||
.route("/v1/chat/completions", post(chat))).await
|
||||
}
|
||||
|
||||
struct Gateway {
|
||||
@ -241,6 +268,7 @@ async fn gateway_with(
|
||||
starts: AtomicUsize::new(0),
|
||||
stops: AtomicUsize::new(0),
|
||||
health_checks: AtomicUsize::new(0),
|
||||
health_timeout: std::sync::atomic::AtomicBool::new(false),
|
||||
delay: Duration::from_millis(delay_ms),
|
||||
fail,
|
||||
});
|
||||
@ -2993,6 +3021,7 @@ async fn engine_oberflaeche_braucht_admin_und_bleibt_bei_unsicherem_praefix_gesc
|
||||
let (status, headers, body) = ui_get(&gw, path, Some(&admin)).await;
|
||||
assert_eq!(status, 502);
|
||||
assert!(body.contains("Präfix"));
|
||||
assert!(!body.contains("ENGINE-INHALT-NICHT-AUSLIEFERN"));
|
||||
assert!(!body.contains("127.0.0.1"));
|
||||
assert_eq!(
|
||||
headers["content-security-policy"],
|
||||
@ -3071,3 +3100,102 @@ async fn ladephase_meldet_fehlstart_ohne_engine_fehlertext() {
|
||||
assert!(phase["last_load_ms"].is_null());
|
||||
assert!(!body.contains("geheimes-detail"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn playground_reicht_alle_denkstufen_weiter_und_faellt_nur_bei_feldablehnung_zurueck() {
|
||||
let gw = gateway(0, false).await;
|
||||
let (cookie, csrf) = ui_session(&gw, &gw.key_ui).await;
|
||||
for effort in ["none", "low", "medium", "high"] {
|
||||
let resp = playground(&gw, &cookie, Some(&csrf), json!({"model":"bonsai", "messages":[{"role":"user", "content":"x"}], "reasoning_effort":effort})).await;
|
||||
assert_eq!(resp.status(), 200);
|
||||
let body = resp.text().await.unwrap();
|
||||
assert!(
|
||||
body.contains(&format!("\"reasoning_effort\":\"{effort}\"")),
|
||||
"{body}"
|
||||
);
|
||||
}
|
||||
let base = json!({"model":"bonsai", "messages":[{"role":"user", "content":"x"}]});
|
||||
let resp = playground(&gw, &cookie, Some(&csrf), base).await;
|
||||
assert!(
|
||||
resp.text()
|
||||
.await
|
||||
.unwrap()
|
||||
.contains("\"reasoning_effort\":null")
|
||||
);
|
||||
let resp = playground(&gw, &cookie, Some(&csrf), json!({"model":"bonsai", "messages":[{"role":"user", "content":"reject-reasoning"}], "reasoning_effort":"medium"})).await;
|
||||
assert_eq!(resp.status(), 200);
|
||||
assert_eq!(resp.headers()["x-nexus-reasoning-effort"], "ignored");
|
||||
assert!(
|
||||
resp.text()
|
||||
.await
|
||||
.unwrap()
|
||||
.contains("\"reasoning_effort\":null")
|
||||
);
|
||||
let resp = playground(&gw, &cookie, Some(&csrf), json!({"model":"bonsai", "messages":[{"role":"user", "content":"other-error"}], "reasoning_effort":"high"})).await;
|
||||
assert_eq!(resp.status(), 400);
|
||||
assert!(!resp.headers().contains_key("x-nexus-reasoning-effort"));
|
||||
assert!(resp.text().await.unwrap().contains("max_tokens"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[ignore = "Benötigt Chromium und Node.js; separat ausführen."]
|
||||
async fn playground_im_chromium_prueft_denkstufen_ladephase_und_eingeklapptes_denken() {
|
||||
let gw = gateway(1800, false).await;
|
||||
let (cookie, _) = ui_session(&gw, &gw.key_ui).await;
|
||||
let output = tokio::process::Command::new("node")
|
||||
.arg(concat!(
|
||||
env!("CARGO_MANIFEST_DIR"),
|
||||
"/tests/chat_browser.mjs"
|
||||
))
|
||||
.env("NEXUS_TEST_BASE", &gw.base)
|
||||
.env("NEXUS_TEST_COOKIE", cookie)
|
||||
.output()
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"{}{}",
|
||||
String::from_utf8_lossy(&output.stdout),
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
println!("{}", String::from_utf8_lossy(&output.stdout));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn health_timeout_gibt_nicht_erreichbar_ohne_zweite_abfrage() {
|
||||
let gw = gateway(0, false).await;
|
||||
let _ = gw
|
||||
.chat(Some(&gw.key), None, &chat_body("bonsai", false))
|
||||
.await
|
||||
.text()
|
||||
.await;
|
||||
gw.engine.health_timeout.store(true, Ordering::SeqCst);
|
||||
let before = gw.engine.health_checks.load(Ordering::SeqCst);
|
||||
let rows = gw.state.runtime.engine_status().await;
|
||||
assert_eq!(rows[0].loaded, 1);
|
||||
assert_eq!(rows[0].reachable, 0);
|
||||
let (admin, _) = ui_session(&gw, &gw.key_admin).await;
|
||||
let (_, _, body) = ui_get(&gw, "/ui/engines", Some(&admin)).await;
|
||||
assert!(body.contains("nicht vollständig erreichbar (0/1)"));
|
||||
assert!(!body.contains("href=\"/ui/engine/"));
|
||||
assert_eq!(
|
||||
ui_get(&gw, "/ui/engine/llama.cpp/", Some(&admin)).await.0,
|
||||
503
|
||||
);
|
||||
assert_eq!(gw.engine.health_checks.load(Ordering::SeqCst), before + 1);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn playground_vertraegt_fastapi_422_bei_unbekannter_denkstufe() {
|
||||
let gw = gateway(0, false).await;
|
||||
let (cookie, csrf) = ui_session(&gw, &gw.key_ui).await;
|
||||
let resp = playground(&gw, &cookie, Some(&csrf), json!({"model":"bonsai", "messages":[{"role":"user", "content":"reject-reasoning-422"}], "reasoning_effort":"low"})).await;
|
||||
assert_eq!(resp.status(), 200);
|
||||
assert_eq!(resp.headers()["x-nexus-reasoning-effort"], "ignored");
|
||||
assert!(
|
||||
resp.text()
|
||||
.await
|
||||
.unwrap()
|
||||
.contains("\"reasoning_effort\":null")
|
||||
);
|
||||
}
|
||||
|
||||
91
crates/nexus-api/tests/chat_browser.mjs
Normal file
91
crates/nexus-api/tests/chat_browser.mjs
Normal file
@ -0,0 +1,91 @@
|
||||
// Echter Chromium-Test ohne zusätzliche npm-Abhängigkeiten. Aufgerufen vom
|
||||
// ignorierten Rust-Integrationstest, der Gateway und Engine-Attrappe bereitstellt.
|
||||
import { spawn } from 'node:child_process';
|
||||
import { mkdtemp, rm } from 'node:fs/promises';
|
||||
import { join } from 'node:path';
|
||||
import assert from 'node:assert/strict';
|
||||
|
||||
const profile = await mkdtemp(join(process.cwd(), '.nexus-browser-'));
|
||||
const chrome = spawn('chromium', ['--headless', '--no-sandbox', '--disable-gpu',
|
||||
'--remote-debugging-port=0', `--user-data-dir=${profile}`, 'about:blank'],
|
||||
{ stdio: ['ignore', 'ignore', 'pipe'] });
|
||||
let socket;
|
||||
try {
|
||||
const endpoint = await new Promise((resolve, reject) => {
|
||||
let buffer = '';
|
||||
const timer = setTimeout(() => reject(new Error('Chromium startet nicht')), 15000);
|
||||
chrome.on('error', reject);
|
||||
chrome.stderr.on('data', chunk => {
|
||||
buffer += chunk;
|
||||
const found = buffer.match(/DevTools listening on (ws:\/\/[^\s]+)/);
|
||||
if (found) { clearTimeout(timer); resolve(found[1]); }
|
||||
});
|
||||
});
|
||||
socket = new WebSocket(endpoint);
|
||||
await new Promise((resolve, reject) => { socket.onopen = resolve; socket.onerror = reject; });
|
||||
let id = 0;
|
||||
const pending = new Map();
|
||||
const requests = [];
|
||||
socket.onmessage = event => {
|
||||
const data = JSON.parse(event.data);
|
||||
if (data.id) {
|
||||
const call = pending.get(data.id);
|
||||
pending.delete(data.id);
|
||||
if (data.error) { call.reject(new Error(data.error.message)); } else { call.resolve(data.result); }
|
||||
} else if (data.method === 'Network.requestWillBeSent' && data.params.request.url.endsWith('/ui/chat/senden')) {
|
||||
requests.push(JSON.parse(data.params.request.postData));
|
||||
}
|
||||
};
|
||||
function call(method, params = {}, sessionId) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const next = ++id;
|
||||
pending.set(next, { resolve, reject });
|
||||
socket.send(JSON.stringify({ id: next, method, params, sessionId }));
|
||||
});
|
||||
}
|
||||
const { targetId } = await call('Target.createTarget', { url: 'about:blank' });
|
||||
const { sessionId } = await call('Target.attachToTarget', { targetId, flatten: true });
|
||||
const page = (method, params) => call(method, params, sessionId);
|
||||
const evaluate = async expression => {
|
||||
const result = await page('Runtime.evaluate', { expression, returnByValue: true });
|
||||
if (result.exceptionDetails) { throw new Error(result.exceptionDetails.text); }
|
||||
return result.result.value;
|
||||
};
|
||||
async function until(expression) {
|
||||
const deadline = Date.now() + 15000;
|
||||
while (Date.now() < deadline) {
|
||||
if (await evaluate(expression)) { return; }
|
||||
await new Promise(resolve => setTimeout(resolve, 50));
|
||||
}
|
||||
throw new Error(`Browser-Bedingung nicht erfüllt: ${expression}`);
|
||||
}
|
||||
await page('Network.enable');
|
||||
await page('Page.enable');
|
||||
const cookie = process.env.NEXUS_TEST_COOKIE.split('=');
|
||||
await page('Network.setCookie', { name: cookie[0], value: cookie.slice(1).join('='),
|
||||
url: `${process.env.NEXUS_TEST_BASE}/ui`, path: '/ui', httpOnly: true, sameSite: 'Strict' });
|
||||
await page('Page.navigate', { url: `${process.env.NEXUS_TEST_BASE}/ui/chat` });
|
||||
await until('!!document.getElementById("chat-denkstufe")');
|
||||
assert.equal(await evaluate('document.getElementById("chat-denkstufe").value'), 'medium');
|
||||
for (const effort of ['medium', 'none', 'low', 'high', '']) {
|
||||
await evaluate(`document.getElementById('chat-neu').click(); document.getElementById('chat-denkstufe').value=${JSON.stringify(effort)}; document.getElementById('chat-text').value='with-reasoning'; document.getElementById('chat-form').requestSubmit()`);
|
||||
if (effort === 'medium') {
|
||||
await until('document.getElementById("chat-status").textContent.includes("Engine startet")');
|
||||
}
|
||||
await until('!document.getElementById("chat-senden").disabled && document.getElementById("chat-verlauf").textContent.includes("Hallo Welt")');
|
||||
assert.equal(requests.at(-1).reasoning_effort, effort || undefined);
|
||||
assert.equal(await evaluate('document.querySelector("#chat-verlauf details").open'), false);
|
||||
}
|
||||
await evaluate(`document.getElementById('chat-neu').click(); document.getElementById('chat-text').value='reject-reasoning'; document.getElementById('chat-form').requestSubmit()`);
|
||||
await until('!document.getElementById("chat-senden").disabled && document.getElementById("chat-status").textContent.includes("Denkstufe nicht unterstützt")');
|
||||
assert.equal(requests.at(-1).reasoning_effort, 'medium');
|
||||
console.log('Chromium: Ladephase, alle Denkstufen, fehlendes Feld, eingeklappte Denkphase und Fallback geprüft.');
|
||||
} finally {
|
||||
socket?.close();
|
||||
if (chrome.pid && chrome.exitCode === null && chrome.signalCode === null) {
|
||||
const ended = new Promise(resolve => chrome.once('exit', resolve));
|
||||
chrome.kill('SIGTERM');
|
||||
await ended;
|
||||
}
|
||||
await rm(profile, { recursive: true, force: true });
|
||||
}
|
||||
Reference in New Issue
Block a user