feat: Sprachausgabe über das Gateway (POST /v1/audio/speech, Adapter tts für das Qwen3-TTS Studio) (#1060)

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01GmHhg3Td16J38kAyDLzb39
This commit is contained in:
2026-11-17 19:44:56 +01:00
parent bdca8e0054
commit 9dd8037b64
17 changed files with 493 additions and 12 deletions

View File

@ -37,6 +37,31 @@ pub async fn completions(
forward(state, &key, priority, slot, correlation, started, body).await
}
/// `POST /v1/audio/speech`: Sprachausgabe. Derselbe Weg wie beim Chat (Rechte, Zuteilung,
/// Durchreichen, Protokoll); die Antwort ist Audio, kein JSON.
pub async fn speech(
State(state): State<Arc<AppState>>,
Authed(key): Authed,
Extension(slot): Extension<AccessSlot>,
Extension(RequestId(correlation)): Extension<RequestId>,
Extension(StartedAt(started)): Extension<StartedAt>,
headers: HeaderMap,
body: Bytes,
) -> Result<Response, ApiError> {
let priority = requested_priority(&headers, &key)?;
forward_to(
"/v1/audio/speech",
state,
&key,
priority,
slot,
correlation,
started,
body,
)
.await
}
/// Der gemeinsame Weg einer Chat-Anfrage, für die API und den Playground der
/// Oberfläche: Rechte prüfen, Instanz zuteilen lassen, durchreichen.
pub(crate) async fn forward(
@ -47,6 +72,31 @@ pub(crate) async fn forward(
correlation: String,
started: std::time::Instant,
body: Bytes,
) -> Result<Response, ApiError> {
forward_to(
"/v1/chat/completions",
state,
key,
priority,
slot,
correlation,
started,
body,
)
.await
}
/// Wie `forward`, an einen anderen Pfad der Engine (Chat oder Sprachausgabe).
#[allow(clippy::too_many_arguments)]
async fn forward_to(
path: &'static str,
state: Arc<AppState>,
key: &ApiKeyRecord,
priority: Priority,
slot: AccessSlot,
correlation: String,
started: std::time::Instant,
body: Bytes,
) -> Result<Response, ApiError> {
let mut request: Value = serde_json::from_slice(&body)
.map_err(|e| ApiError::bad_request(format!("Der Body ist kein gültiges JSON: {e}")))?;
@ -96,7 +146,7 @@ pub(crate) async fn forward(
let upstream = state
.http
.post(format!("{}/v1/chat/completions", endpoint.base_url))
.post(format!("{}{path}", endpoint.base_url))
.header(CONTENT_TYPE, "application/json")
.header("x-request-id", &correlation)
.body(body)
@ -134,7 +184,7 @@ pub(crate) async fn forward(
.remove("reasoning_effort");
let retry = state
.http
.post(format!("{}/v1/chat/completions", endpoint.base_url))
.post(format!("{}{path}", endpoint.base_url))
.header(CONTENT_TYPE, "application/json")
.header("x-request-id", &correlation)
.body(serde_json::to_vec(&request).map_err(|_| ApiError::internal())?)

View File

@ -1,7 +1,7 @@
//! OpenAI-kompatible HTTP-API und Gateway-Endpunkte (Spezifikation, Abschnitt 7).
//!
//! Stand M2.3: `GET /v1/models`, `GET /v1/models/{id}`,
//! `POST /v1/chat/completions` (mit SSE-Streaming), `GET /gateway/v1/health`,
//! `POST /v1/chat/completions` (mit SSE-Streaming), `POST /v1/audio/speech` (Sprachausgabe), `GET /gateway/v1/health`,
//! API-Key-Authentifizierung und das OpenAI-Fehlerformat. Weitere Endpunkte
//! (Completions, Embeddings, Bilder) und die Gateway-Verwaltung folgen später.
//!
@ -49,6 +49,7 @@ pub fn router(state: Arc<AppState>) -> Router {
.route("/v1/models", get(models::list))
.route("/v1/models/{id}", get(models::retrieve))
.route("/v1/chat/completions", post(chat::completions))
.route("/v1/audio/speech", post(chat::speech))
.route("/gateway/v1/health", get(health))
.route("/gateway/v1/metrics", get(metrics_endpoint))
.route("/gateway/v1/status", get(status_endpoint))

View File

@ -1193,7 +1193,7 @@ pre.befehl{margin:0;padding:.6rem .8rem;background:var(--bg);border:1px solid va
.engine h2{margin:0}.chips{display:flex;flex-wrap:wrap;gap:.35rem;margin:.7rem 0 .2rem}
.engine .zeile{gap:.5rem .7rem}
.fsym{--k:var(--muted);width:1.7rem;height:1.7rem;box-sizing:border-box;padding:.27rem;margin-right:.3rem;vertical-align:middle;border-radius:.45rem;fill:none;stroke:var(--k);stroke-width:2;stroke-linecap:round;stroke-linejoin:round}
td.faehig{white-space:nowrap}.fkann{display:inline-flex;align-items:center;gap:.1rem;margin:0 .6rem .3rem 0;white-space:nowrap}.fsym.k-chat{--k:var(--info)}.fsym.k-vision{--k:var(--accent-strong)}.fsym.k-tools{--k:var(--cat-2)}.fsym.k-embed{--k:var(--ok)}.fsym.k-stream{--k:var(--cat-1)}.fsym.k-completion{--k:var(--cat-3)}
td.faehig{white-space:nowrap}.fkann{display:inline-flex;align-items:center;gap:.1rem;margin:0 .6rem .3rem 0;white-space:nowrap}.fsym.k-chat{--k:var(--info)}.fsym.k-vision{--k:var(--accent-strong)}.fsym.k-tools{--k:var(--cat-2)}.fsym.k-embed{--k:var(--ok)}.fsym.k-stream{--k:var(--cat-1)}.fsym.k-completion{--k:var(--cat-3)}.fsym.k-speech{--k:var(--warn)}
.fsym.gemeldet,.fsym.datei{background:color-mix(in srgb,var(--k) 22%,transparent);border:1px solid color-mix(in srgb,var(--k) 55%,transparent)}
.fsym.engine{background:transparent;border:1px dashed color-mix(in srgb,var(--k) 55%,transparent);opacity:.75}
footer label{display:inline-flex;gap:.35rem;align-items:center}footer select{padding:.15rem .4rem;font-size:.8rem}

View File

@ -5,7 +5,7 @@
//! ein `mmproj` neben der Modelldatei). Ein Test am Modell selbst gibt es noch nicht; bis dahin
//! steht in keinem Symbol „geprüft“.
//!
//! Je Modell nur, was vom Modell abhängt (Bilder, Werkzeuge, Embeddings). Chat, Streaming und
//! Je Modell nur, was vom Modell abhängt (Bilder, Werkzeuge, Embeddings, Sprachausgabe). Chat, Streaming und
//! Completions sind Fähigkeiten der Engine und stehen auf der Seite „Engines“.
//!
//! Darstellung: je Fähigkeit eine eigene Farbe (Klasse `k-…`); gefüllte Kachel = aus den Dateien
@ -22,7 +22,7 @@ pub(super) enum Herkunft {
Datei,
}
/// Symbole in fester Reihenfolge: Chat, Bilder (Vision), Werkzeuge, Embeddings, Streaming, Completions.
/// Symbole in fester Reihenfolge: Chat, Bilder (Vision), Werkzeuge, Embeddings, Streaming, Completions, Sprachausgabe.
pub(super) fn capability_icons(caps: &Capabilities) -> Vec<&'static str> {
let mut icons = Vec::new();
if caps.chat {
@ -43,6 +43,9 @@ pub(super) fn capability_icons(caps: &Capabilities) -> Vec<&'static str> {
if caps.completions {
icons.push("completion");
}
if caps.speech {
icons.push("speech");
}
icons
}
@ -104,7 +107,7 @@ pub(super) fn symbole(
let engine_icons = caps.map(capability_icons).unwrap_or_default();
// Chat, Streaming und Completions hängen an der Engine, nicht am Modell: Sie stehen auf der
// Seite „Engines“ (`engine_faehigkeiten`), nicht in der Spalte „Kann“ je Modell.
for key in ["vision", "tools", "embed"] {
for key in ["vision", "tools", "embed", "speech"] {
if datei.contains(&key) {
out.push((key, Herkunft::Datei));
} else if engine_icons.contains(&key) {
@ -138,6 +141,10 @@ fn svg(key: &str) -> &'static str {
"stream" => {
"<path d=\"M2 10v3\"/><path d=\"M6 6v11\"/><path d=\"M10 3v18\"/><path d=\"M14 8v7\"/><path d=\"M18 5v13\"/><path d=\"M22 10v3\"/>"
}
// volume-2
"speech" => {
"<path d=\"M11 4.702a.705.705 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298z\"/><path d=\"M16 9a5 5 0 0 1 0 6\"/><path d=\"M19.364 18.364a9 9 0 0 0 0-12.728\"/>"
}
// braces
_ => {
"<path d=\"M8 3H7a2 2 0 0 0-2 2v5a2 2 0 0 1-2 2 2 2 0 0 1 2 2v5c0 1.1.9 2 2 2h1\"/><path d=\"M16 21h1a2 2 0 0 0 2-2v-5c0-1.1.9-2 2-2a2 2 0 0 1-2-2V5a2 2 0 0 0-2-2h-1\"/>"
@ -152,6 +159,7 @@ fn titel(key: &str) -> &'static str {
"tools" => "Werkzeuge aufrufen (Tool Calling)",
"embed" => "Embeddings",
"stream" => "Streaming",
"speech" => "Sprachausgabe",
_ => "Completions",
}
}
@ -217,9 +225,23 @@ mod tests {
streaming: stream,
tool_calling: tools,
images,
speech: false,
}
}
#[test]
fn sprachausgabe_ist_ein_eigenes_symbol_je_modell() {
let c = Capabilities {
speech: true,
..Capabilities::default()
};
assert_eq!(capability_icons(&c), ["speech"]);
let s = symbole(Some(&c), "tts", "Qwen/Qwen3-TTS-12Hz-1.7B-Base");
assert_eq!(s, vec![("speech", Herkunft::Engine)]);
assert!(zelle(&s).contains("k-speech") && zelle(&s).contains("Sprachausgabe"));
assert!(engine_faehigkeiten(&c).contains("Sprachausgabe"));
}
#[test]
fn icons_in_fester_reihenfolge() {
assert!(capability_icons(&caps(false, false, false, false, false, false)).is_empty());

View File

@ -178,7 +178,20 @@ async fn fake_backend() -> u16 {
.unwrap()
}
}
// Sprachausgabe: liefert ein winziges „Audio“ und gibt die gesehenen Felder im Kopf zurück.
async fn speech(body: Bytes) -> Response {
let req: Value = serde_json::from_slice(&body).unwrap();
Response::builder()
.header(CONTENT_TYPE, "audio/wav")
.body(Body::from(format!(
"RIFF|{}|{}",
req["model"].as_str().unwrap_or(""),
req["input"].as_str().unwrap_or("")
)))
.unwrap()
}
serve(Router::new()
.route("/v1/audio/speech", post(speech))
.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
}
@ -496,6 +509,37 @@ async fn chat_ohne_streaming_startet_die_instanz_und_reicht_die_antwort_durch()
assert_eq!(gw.engine.starts.load(Ordering::SeqCst), 1);
}
#[tokio::test]
async fn sprachausgabe_reicht_audio_durch_und_verlangt_key_und_modell() {
let gw = gateway(0, false).await;
let body = json!({"model": "bonsai", "input": "Hallo", "voice": "Vivian"}).to_string();
let post = |key: Option<&str>, body: String| {
let mut req = gw
.client
.post(format!("{}/v1/audio/speech", gw.base))
.header(CONTENT_TYPE, "application/json")
.body(body);
if let Some(k) = key {
req = req.bearer_auth(k);
}
async move { req.send().await.unwrap() }
};
let resp = post(Some(&gw.key), body.clone()).await;
assert_eq!(resp.status(), 200);
assert_eq!(resp.headers()[CONTENT_TYPE], "audio/wav");
// Die Attrappe gibt zurück, was sie gesehen hat: Modellname und Text unverändert.
assert_eq!(resp.text().await.unwrap(), "RIFF|bonsai|Hallo");
assert_eq!(gw.engine.starts.load(Ordering::SeqCst), 1);
assert_eq!(post(None, body.clone()).await.status(), 401);
let unbekannt = json!({"model": "gibt-es-nicht", "input": "x", "voice": "v"}).to_string();
assert_eq!(post(Some(&gw.key), unbekannt).await.status(), 404);
assert_eq!(
post(Some(&gw.key), "kein json".to_string()).await.status(),
400
);
}
#[tokio::test]
async fn streaming_wird_stueckweise_durchgereicht_und_nicht_gepuffert() {
let gw = gateway(0, false).await;