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

@ -0,0 +1,323 @@
//! Adapter für das Faster Qwen3-TTS Studio (Sprachausgabe), angehängt an einen
//! **laufenden** Dienst (Modus External).
//!
//! Das Studio (im Container, Port 8862 auf srv04) bietet `POST /v1/audio/speech`
//! im OpenAI-Format. Es lädt und entlädt seine Modelle selbst, auf Anfrage; das
//! Gateway steuert das nicht. Eine Gateway-„Instanz“ ist deshalb nur die
//! Zusage „der Dienst ist erreichbar, dieses Modell wird angefragt“. `start`
//! prüft die Erreichbarkeit (`GET /studio/status`), `stop` vergisst die Instanz.
//! Das Feld `model` der Anfrage wird auf den Modellnamen des Studios umgeschrieben
//! (zum Beispiel `Qwen/Qwen3-TTS-12Hz-1.7B-Base`), der als Pfad im Profil steht.
//!
//! Gelesen und am 17.11.2026 gegen das Studio auf srv04 geprüft: `/studio/status`,
//! `/v1/models` (zeigt auch nicht installierte Modelle) und `POST /v1/audio/speech`.
use std::collections::HashMap;
use std::sync::Mutex;
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::Duration;
use async_trait::async_trait;
use serde::Deserialize;
use serde_json::Value;
use crate::engine::Engine;
use crate::types::{
AdapterError, Capabilities, DiscoveredArtifact, Endpoint, EngineInfo, Health, InstanceHandle,
Mode, ProfileSpec, Protocol, Result, StartInfo, Usage,
};
/// Konfiguration (Abschnitt `[tts]`). Enthält keine Geheimnisse.
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct StudioConfig {
/// Adresse des laufenden Studios.
pub base_url: String,
/// Wie lange die Erreichbarkeitsprüfung beim Start höchstens dauert.
pub ready_timeout_secs: u64,
}
impl Default for StudioConfig {
fn default() -> Self {
Self {
base_url: "http://127.0.0.1:8862".to_string(),
ready_timeout_secs: 15,
}
}
}
pub struct StudioEngine {
config: StudioConfig,
http: reqwest::Client,
next_id: AtomicU64,
/// Instanz-ID -> Modellname im Studio.
models: Mutex<HashMap<u64, String>>,
}
impl StudioEngine {
pub fn new(config: StudioConfig) -> Self {
Self {
config,
http: reqwest::Client::builder()
.connect_timeout(Duration::from_secs(3))
.build()
.expect("HTTP-Client konnte nicht gebaut werden"),
next_id: AtomicU64::new(1),
models: Mutex::new(HashMap::new()),
}
}
fn base(&self) -> &str {
self.config.base_url.trim_end_matches('/')
}
fn models(&self) -> std::sync::MutexGuard<'_, HashMap<u64, String>> {
self.models.lock().unwrap_or_else(|e| e.into_inner())
}
fn port(&self) -> u16 {
self.base()
.rsplit(':')
.next()
.and_then(|p| p.parse().ok())
.unwrap_or(80)
}
async fn reachable(&self, timeout: Duration) -> bool {
matches!(
self.http
.get(format!("{}/studio/status", self.base()))
.timeout(timeout)
.send()
.await,
Ok(r) if r.status().is_success()
)
}
}
/// Aus der Antwort von `/v1/models`: Modellnamen des Studios als Vorschläge.
fn models_from(json: &Value) -> Vec<DiscoveredArtifact> {
json["data"]
.as_array()
.map(|list| {
list.iter()
.filter_map(|m| m["id"].as_str())
.map(|id| DiscoveredArtifact {
name: id.rsplit('/').next().unwrap_or(id).to_string(),
path: id.into(),
quantization: None,
size_bytes: 0,
})
.collect()
})
.unwrap_or_default()
}
#[async_trait]
impl Engine for StudioEngine {
fn describe(&self) -> EngineInfo {
EngineInfo {
name: "tts".to_string(),
mode: Mode::External,
// Gemessen am 17.11.2026: Sprachausgabe über `POST /v1/audio/speech`.
capabilities: Capabilities {
speech: true,
..Capabilities::default()
},
}
}
fn start_info(&self) -> StartInfo {
StartInfo {
executable: None,
command:
"läuft extern (Faster Qwen3-TTS Studio, Container); das Gateway startet nichts"
.to_string(),
env: Vec::new(),
details: vec![("Adresse".to_string(), self.config.base_url.clone())],
}
}
async fn discover(&self) -> Result<Vec<DiscoveredArtifact>> {
let resp = self
.http
.get(format!("{}/v1/models", self.base()))
.timeout(Duration::from_secs(self.config.ready_timeout_secs))
.send()
.await
.map_err(|e| AdapterError::Spawn(format!("Studio nicht erreichbar: {e}")))?;
let bytes = resp
.bytes()
.await
.map_err(|e| AdapterError::Spawn(format!("Studio-Antwort nicht lesbar: {e}")))?;
let json: Value = serde_json::from_slice(&bytes)
.map_err(|e| AdapterError::Spawn(format!("Studio-Antwort kein JSON: {e}")))?;
Ok(models_from(&json))
}
async fn start(&self, profile: &ProfileSpec) -> Result<InstanceHandle> {
let model = profile.model_path.to_string_lossy().trim().to_string();
if model.is_empty() {
return Err(AdapterError::InvalidProfile(
"kein Modellname des Studios angegeben".to_string(),
));
}
let timeout = Duration::from_secs(self.config.ready_timeout_secs);
if !self.reachable(timeout).await {
return Err(AdapterError::NotReady {
seconds: self.config.ready_timeout_secs,
log_tail: format!("{} antwortet nicht", self.base()),
});
}
let id = self.next_id.fetch_add(1, Ordering::SeqCst);
self.models().insert(id, model);
Ok(InstanceHandle {
id,
pid: None,
port: self.port(),
})
}
async fn stop(&self, instance: &InstanceHandle, _grace: Duration) -> Result<()> {
self.models().remove(&instance.id);
Ok(())
}
async fn health(&self, instance: &InstanceHandle) -> Health {
if !self.models().contains_key(&instance.id) {
return Health::Gone;
}
if self.reachable(Duration::from_secs(5)).await {
Health::Ready
} else {
Health::Unhealthy("keine Antwort".to_string())
}
}
fn endpoint(&self, instance: &InstanceHandle) -> Endpoint {
Endpoint {
base_url: self.base().to_string(),
protocol: Protocol::OpenAi,
upstream_model: self.models().get(&instance.id).cloned(),
}
}
async fn measure(&self, _instance: &InstanceHandle) -> Usage {
Usage::default()
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::path::PathBuf;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::TcpListener;
/// Minimaler HTTP-Server: antwortet je Pfad mit fester JSON-Antwort.
async fn fake_studio() -> u16 {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let port = listener.local_addr().unwrap().port();
tokio::spawn(async move {
loop {
let Ok((mut s, _)) = listener.accept().await else {
return;
};
tokio::spawn(async move {
let mut buf = [0u8; 2048];
let n = s.read(&mut buf).await.unwrap_or(0);
let head = String::from_utf8_lossy(&buf[..n]).to_string();
let body = if head.starts_with("GET /studio/status") {
r#"{"state":"idle"}"#
} else if head.starts_with("GET /v1/models") {
r#"{"data":[{"id":"Qwen/Qwen3-TTS-12Hz-1.7B-Base"},{"id":"Qwen/Qwen3-TTS-12Hz-1.7B-CustomVoice"}]}"#
} else {
r#"{}"#
};
let resp = format!(
"HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}",
body.len()
);
let _ = s.write_all(resp.as_bytes()).await;
});
}
});
port
}
fn profile(model: &str) -> ProfileSpec {
ProfileSpec {
start_parameters: Default::default(),
model_alias: "tts-test".to_string(),
model_path: PathBuf::from(model),
gpus: vec![0],
context: None,
extra_args: Vec::new(),
}
}
fn engine(port: u16) -> StudioEngine {
StudioEngine::new(StudioConfig {
base_url: format!("http://127.0.0.1:{port}/"),
ready_timeout_secs: 3,
})
}
#[test]
fn modellliste_wird_zu_vorschlaegen_mit_kurzem_namen() {
let json: Value = serde_json::from_str(
r#"{"data":[{"id":"Qwen/Qwen3-TTS-12Hz-1.7B-Base"},{"object":"x"}]}"#,
)
.unwrap();
let found = models_from(&json);
assert_eq!(found.len(), 1);
assert_eq!(found[0].name, "Qwen3-TTS-12Hz-1.7B-Base");
assert_eq!(
found[0].path,
PathBuf::from("Qwen/Qwen3-TTS-12Hz-1.7B-Base")
);
assert!(models_from(&Value::Null).is_empty());
}
#[test]
fn beschreibt_nur_sprachausgabe() {
let info = engine(1).describe();
assert_eq!(info.name, "tts");
assert!(info.capabilities.speech && !info.capabilities.chat);
}
#[tokio::test]
async fn start_prueft_erreichbarkeit_und_endpunkt_nennt_das_studio_modell() {
let port = fake_studio().await;
let e = engine(port);
let handle = e
.start(&profile("Qwen/Qwen3-TTS-12Hz-1.7B-Base"))
.await
.unwrap();
assert_eq!(handle.port, port);
assert!(matches!(e.health(&handle).await, Health::Ready));
let ep = e.endpoint(&handle);
assert_eq!(ep.base_url, format!("http://127.0.0.1:{port}"));
assert_eq!(
ep.upstream_model.as_deref(),
Some("Qwen/Qwen3-TTS-12Hz-1.7B-Base")
);
assert_eq!(e.discover().await.unwrap().len(), 2);
e.stop(&handle, Duration::from_secs(1)).await.unwrap();
assert!(matches!(e.health(&handle).await, Health::Gone));
}
#[tokio::test]
async fn nicht_erreichbar_und_leerer_modellname_scheitern() {
// Port 1 ist nicht belegt.
let e = engine(1);
assert!(matches!(
e.start(&profile("x")).await,
Err(AdapterError::NotReady { .. })
));
assert!(matches!(
e.start(&profile(" ")).await,
Err(AdapterError::InvalidProfile(_))
));
}
}