feat: stream speech audio in supported formats

This commit is contained in:
2026-11-18 16:18:29 +01:00
parent 7b3ee57580
commit be7bc5adb8
2 changed files with 168 additions and 14 deletions

View File

@ -58,6 +58,7 @@ pub async fn speech(
correlation,
started,
body,
false,
)
.await
}
@ -82,6 +83,7 @@ pub(crate) async fn forward(
correlation,
started,
body,
false,
)
.await
}
@ -105,6 +107,7 @@ pub(crate) async fn forward_speech(
correlation,
started,
body,
true,
)
.await
}
@ -120,9 +123,37 @@ async fn forward_to(
correlation: String,
started: std::time::Instant,
body: Bytes,
playground_pcm: bool,
) -> 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}")))?;
// Das Studio unterstützt mehr Formate als die öffentliche Schnittstelle. Vor dem
// Start validieren und den Standard explizit senden. Der Playground fordert
// intern PCM an; das ist kein öffentlich unterstütztes Format. Wer eine
// Datei braucht, liest denselben Strom bis zum Ende.
let audio_type = if path == "/v1/audio/speech" {
let format = match request.get("response_format") {
None => "mp3",
Some(Value::String(format)) => format.as_str(),
Some(_) => "",
};
let content_type = match format {
"mp3" => "audio/mpeg",
"wav" => "audio/wav",
"opus" => "audio/ogg", // Das Studio liefert Opus im Ogg-Container.
"flac" => "audio/flac",
"pcm" if playground_pcm => "audio/pcm",
_ => {
return Err(ApiError::bad_request(
"Unbekanntes Audioformat. Unterstützt werden mp3, wav, opus und flac.",
));
}
};
request["response_format"] = Value::String(format.to_string());
Some(content_type)
} else {
None
};
let model = request
.get("model")
.and_then(Value::as_str)
@ -164,6 +195,9 @@ async fn forward_to(
request["model"] = Value::String(name.clone());
Bytes::from(serde_json::to_vec(&request).map_err(|_| ApiError::internal())?)
}
None if audio_type.is_some() => {
Bytes::from(serde_json::to_vec(&request).map_err(|_| ApiError::internal())?)
}
None => body,
};
@ -238,10 +272,17 @@ async fn forward_to(
};
}
let mut response = Response::builder().status(status);
for name in [CONTENT_TYPE, CACHE_CONTROL] {
if let Some(value) = response_headers.get(&name) {
response = response.header(name, value);
if status.is_success() {
if let Some(content_type) = audio_type {
response = response.header(CONTENT_TYPE, content_type);
} else if let Some(value) = response_headers.get(CONTENT_TYPE) {
response = response.header(CONTENT_TYPE, value);
}
} else if let Some(value) = response_headers.get(CONTENT_TYPE) {
response = response.header(CONTENT_TYPE, value);
}
if let Some(value) = response_headers.get(CACHE_CONTROL) {
response = response.header(CACHE_CONTROL, value);
}
if effort_ignored {
response = response.header("x-nexus-reasoning-effort", "ignored");
@ -281,11 +322,17 @@ type ResponseStream = BoxStream<'static, Result<Bytes, reqwest::Error>>;
/// Grund zurück; sonst der Strom samt erstem Stück. Kommt nach 60 s noch nichts (langsames Laden des
/// Modells), wird die Antwort trotzdem weitergereicht: Das ist kein Fehler.
async fn first_chunk(mut upstream: ResponseStream) -> Result<ResponseStream, &'static str> {
match tokio::time::timeout(std::time::Duration::from_secs(60), upstream.next()).await {
Ok(Some(Ok(chunk))) => Ok(stream::once(async { Ok(chunk) }).chain(upstream).boxed()),
Ok(Some(Err(_))) => Err("abgebrochen"),
Ok(None) => Err("leer"),
Err(_) => Ok(upstream),
let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(60);
loop {
match tokio::time::timeout_at(deadline, upstream.next()).await {
Ok(Some(Ok(chunk))) if chunk.is_empty() => continue,
Ok(Some(Ok(chunk))) => {
return Ok(stream::once(async { Ok(chunk) }).chain(upstream).boxed());
}
Ok(Some(Err(_))) => return Err("abgebrochen"),
Ok(None) => return Err("leer"),
Err(_) => return Ok(upstream),
}
}
}