Compare commits
4 Commits
v0.1.9-rc5
...
22e349f168
| Author | SHA1 | Date | |
|---|---|---|---|
| 22e349f168 | |||
| 3049d063ca | |||
| d21f8d871f | |||
| 9dd8037b64 |
@ -267,3 +267,28 @@ für einen Block aufweichen; das steht dann im Todo.
|
||||
| browser2faehigkeiten.2 | Ein Ollama-Modell und ein llama.cpp-Modell ohne Bild-Zusatzdatei mit `qwen38-iq3s` vergleichen | Nur Modelle mit Bild-Zusatzdatei oder Vision-Eintrag zeigen das Vision-Symbol; kein Symbol steht als „geprüft“; die Tabelle bleibt filter- und sortierbar | manuell |
|
||||
| browser2faehigkeiten.3 | „Engines“ öffnen und je Karte die Fähigkeiten ansehen | Je Engine stehen die Fähigkeiten als Symbol mit Namen (Chat, Completions, Streaming, Embeddings, Werkzeuge, Bilder, soweit die Engine sie meldet) auf gefüllter Kachel, in denselben Farben wie bei den Modellen; die alten Text-Chips sind weg | manuell |
|
||||
|
||||
## client2sprachausgabe
|
||||
**Zweck:** Ein Client bekommt über das Gateway Sprache aus Text (Todo 1060, Sprachausgabe mit dem Faster Qwen3-TTS Studio).
|
||||
**Deckt ab:** #1003
|
||||
**Voraussetzung:** Gateway ab der Version mit Sprachausgabe auf srv04; das Studio läuft (Podman, `http://192.168.12.4:8862`), im Gateway ist unter `[tts]` die Adresse eingetragen und ein Modell der Engine `tts` registriert (zum Beispiel `nexus model add --name tts-base --engine tts --tts-model Qwen/Qwen3-TTS-12Hz-1.7B-Base --gpus 0 --vram-mb 6000`); gültiger API-Key; kein anderes Modell hält die GPU 0 voll. Verbraucht echte GPU-Zeit.
|
||||
|
||||
| Test | Schritte | Erwartet | Art |
|
||||
| --- | --- | --- | --- |
|
||||
| client2sprachausgabe.1 | `nexus model discover --engine tts` auf srv04 ausführen | Die Modelle des Studios werden aufgelistet (auch solche, die lokal nicht installiert sind: das Studio meldet sie trotzdem) | manuell |
|
||||
| client2sprachausgabe.2 | Mit `curl` `POST /v1/audio/speech` mit `model`, `input`, `voice` (Qwen-Stimmenname oder ID einer gespeicherten Stimme), `language`, `response_format: wav` und dem Key senden | Antwort 200, `Content-Type: audio/wav`, die Datei lässt sich abspielen und spricht den Text | manuell |
|
||||
| client2sprachausgabe.3 | Dieselbe Anfrage ohne Key, danach mit einem unbekannten Modellnamen | 401 beziehungsweise 404 im OpenAI-Fehlerformat, das Studio wird nicht angefragt | auto |
|
||||
| client2sprachausgabe.4 | Auf der Seite „Modelle“ das Tts-Modell ansehen | Spalte „Kann“ zeigt das Symbol „Sprachausgabe“ (Lautsprecher, gestrichelt, Engine, nicht geprüft); auf „Engines“ steht bei der Engine `tts` „Sprachausgabe“ | manuell |
|
||||
| client2sprachausgabe.5 | Während Strata geladen ist (beide GPUs voll), eine Sprachausgabe anfordern | Der Scheduler entlädt Strata, das Studio lädt sein Modell, die Antwort kommt; danach lädt ein Chat an Strata wieder (kein CUDA-Speicherfehler) | manuell |
|
||||
|
||||
## browser2vorlesen
|
||||
**Zweck:** Im Playground lässt man sich eine Antwort vorlesen (Todo 1100, erste Stufe: nur Vorlesen, noch kein Mikrofon).
|
||||
**Deckt ab:** #1006
|
||||
**Voraussetzung:** Wie `client2sprachausgabe`; im Playground angemeldet als Admin oder Nutzer, dessen Key das Sprachmodell freigibt; ein Chat-Modell ist erreichbar.
|
||||
|
||||
| Test | Schritte | Erwartet | Art |
|
||||
| --- | --- | --- | --- |
|
||||
| browser2vorlesen.1 | „Playground“ öffnen und die Modellwahl ansehen | Das Sprachmodell steht nicht in der Modellwahl des Chats; oben gibt es „Sprachausgabe“ (aus oder Sprachmodell) und „Stimme“ (voreingestellt Vivian) | manuell |
|
||||
| browser2vorlesen.2 | Sprachausgabe auf das Sprachmodell stellen, eine kurze Frage senden, bei der Antwort „Vorlesen“ drücken | Der Knopf zeigt „spricht …“, die Antwort wird abgespielt (Ton im Browser), danach steht wieder „Vorlesen“ | manuell |
|
||||
| browser2vorlesen.3 | „Vorlesen“ drücken, ohne dass das Studio läuft (oder mit einer ungültigen Stimme) | Eine Fehlerblase „Sprachausgabe: …“ mit verständlicher Meldung, der Chat bleibt benutzbar | manuell |
|
||||
| browser2vorlesen.4 | In der Browser-Konsole nach Meldungen der Content-Security-Policy suchen | Keine Meldung zu `media-src` oder Blob-Audio | manuell |
|
||||
|
||||
|
||||
File diff suppressed because one or more lines are too long
@ -5,6 +5,7 @@
|
||||
//! - [`OllamaEngine`]: Ollama, verwaltet (`ollama serve` als Prozess) oder angehängt
|
||||
//! (laufender Server).
|
||||
//! - [`MayaEngine`]: Project Maya (`maya.py`) als verwalteter Prozess.
|
||||
//! - [`StudioEngine`]: das Faster Qwen3-TTS Studio (Sprachausgabe) als laufender Dienst.
|
||||
//! - [`MockEngine`]: Attrappe ohne Prozesse für Scheduler- und Vertragstests.
|
||||
//!
|
||||
//! Stand M2.2: Die Weiterleitung von Anfragen (`forward`) kommt mit der API
|
||||
@ -17,6 +18,7 @@ mod maya;
|
||||
mod mock;
|
||||
mod ollama;
|
||||
mod process;
|
||||
mod studio;
|
||||
mod types;
|
||||
// Dieselbe reine Parameterdefinition wie nexus-core, ohne neue Crate-Abhängigkeit.
|
||||
#[path = "../../startparams.rs"]
|
||||
@ -29,6 +31,7 @@ pub use maya::{MayaConfig, MayaEngine};
|
||||
pub use mock::{MockConfig, MockEngine};
|
||||
pub use ollama::{OllamaConfig, OllamaEngine, OllamaMode};
|
||||
pub use process::process_exists;
|
||||
pub use studio::{StudioConfig, StudioEngine};
|
||||
pub use types::{
|
||||
AdapterError, Capabilities, DiscoveredArtifact, Endpoint, EngineInfo, Health, InstanceHandle,
|
||||
Mode, ProfileSpec, Protocol, Result, StartInfo, Usage,
|
||||
|
||||
@ -349,6 +349,7 @@ impl Engine for LlamaCppEngine {
|
||||
streaming: true,
|
||||
tool_calling: false,
|
||||
images: false,
|
||||
speech: false,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
@ -601,6 +601,7 @@ impl Engine for MayaEngine {
|
||||
streaming: true,
|
||||
tool_calling: self.flavor == Flavor::Strata,
|
||||
images: false,
|
||||
speech: false,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
@ -86,6 +86,7 @@ impl Engine for MockEngine {
|
||||
streaming: true,
|
||||
tool_calling: false,
|
||||
images: false,
|
||||
speech: false,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
@ -478,6 +478,7 @@ impl Engine for OllamaEngine {
|
||||
streaming: true,
|
||||
tool_calling: false,
|
||||
images: false,
|
||||
speech: false,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
323
crates/nexus-adapter/src/studio.rs
Normal file
323
crates/nexus-adapter/src/studio.rs
Normal 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(_))
|
||||
));
|
||||
}
|
||||
}
|
||||
@ -28,6 +28,8 @@ pub struct Capabilities {
|
||||
pub streaming: bool,
|
||||
pub tool_calling: bool,
|
||||
pub images: bool,
|
||||
/// Sprachausgabe (`POST /v1/audio/speech`).
|
||||
pub speech: bool,
|
||||
}
|
||||
|
||||
/// Wie das Gateway eine Engine startet, zum Anzeigen in der Oberfläche. Enthält
|
||||
|
||||
@ -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,54 @@ 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
|
||||
}
|
||||
|
||||
/// Sprachausgabe für den Playground der Oberfläche (dieselbe Zuteilung und Protokollierung wie die API).
|
||||
pub(crate) async fn forward_speech(
|
||||
state: Arc<AppState>,
|
||||
key: &ApiKeyRecord,
|
||||
priority: Priority,
|
||||
slot: AccessSlot,
|
||||
correlation: String,
|
||||
started: std::time::Instant,
|
||||
body: Bytes,
|
||||
) -> Result<Response, ApiError> {
|
||||
forward_to(
|
||||
"/v1/audio/speech",
|
||||
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 +169,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 +207,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())?)
|
||||
|
||||
@ -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))
|
||||
|
||||
@ -147,6 +147,7 @@ pub fn routes() -> Router<Arc<AppState>> {
|
||||
.route("/ui/keys/entfernen", post(verwaltung::key_remove))
|
||||
.route("/ui/chat", get(chat::page))
|
||||
.route("/ui/chat/senden", post(chat::send))
|
||||
.route("/ui/chat/sprechen", post(chat::speak))
|
||||
.route("/ui/chat/status", get(chat::load_status))
|
||||
.route("/ui/chat.js", get(chat::script))
|
||||
.route("/ui/auswertung", get(auswertung::page))
|
||||
@ -363,7 +364,7 @@ pub(crate) fn secure(builder: axum::http::response::Builder) -> axum::http::resp
|
||||
.header(
|
||||
"content-security-policy",
|
||||
"default-src 'none'; manifest-src 'self'; script-src 'self'; style-src 'self'; \
|
||||
img-src 'self'; connect-src 'self'; form-action 'self'; frame-ancestors 'none'; \
|
||||
img-src 'self'; media-src blob:; connect-src 'self'; form-action 'self'; frame-ancestors 'none'; \
|
||||
base-uri 'none'",
|
||||
)
|
||||
.header("x-content-type-options", "nosniff")
|
||||
@ -1193,7 +1194,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}
|
||||
|
||||
@ -25,19 +25,32 @@ const MAX_TOKENS_LIMIT: u64 = 16_384;
|
||||
/// Voreinstellung für „Max. Tokens“. Bei Modellen mit Denkphase zählt das Denken mit; 1024 schnitt
|
||||
/// Antworten dort ab, bevor sie sichtbar wurden.
|
||||
const DEFAULT_MAX_TOKENS: u64 = 4096;
|
||||
/// Grenzen für die Sprachausgabe (Zeichen).
|
||||
const MAX_SPEECH_CHARS: usize = 4000;
|
||||
const MAX_VOICE_CHARS: usize = 100;
|
||||
|
||||
pub(super) async fn page(State(state): State<Arc<AppState>>, headers: HeaderMap) -> Response {
|
||||
let Some(viewer) = viewer(&state, &headers) else {
|
||||
return redirect("/ui/login");
|
||||
};
|
||||
let models: Vec<String> = state
|
||||
// Sprachmodelle (Engine `tts`) gehören nicht in die Modellwahl des Chats, sondern zur Sprachausgabe.
|
||||
let mut models: Vec<String> = Vec::new();
|
||||
let mut sprachmodelle: Vec<String> = Vec::new();
|
||||
// Erst die Liste holen und die Sperre auf den Speicher freigeben: `start_plan` sperrt ihn wieder.
|
||||
let candidates: Vec<_> = state
|
||||
.store()
|
||||
.list_models(true)
|
||||
.unwrap_or_default()
|
||||
.into_iter()
|
||||
.filter(|m| m.kind == "llm" && viewer.key.rights.allows(&m.name))
|
||||
.map(|m| m.name)
|
||||
.collect();
|
||||
for m in candidates {
|
||||
let plan = state.store().start_plan(&m.name);
|
||||
match plan {
|
||||
Ok(Some(plan)) if plan.engine_name == "tts" => sprachmodelle.push(m.name),
|
||||
_ => models.push(m.name),
|
||||
}
|
||||
}
|
||||
let body = if models.is_empty() {
|
||||
"<p class=\"leer\">Für diesen Key ist kein Modell freigegeben.</p>".to_string()
|
||||
} else {
|
||||
@ -45,11 +58,23 @@ pub(super) async fn page(State(state): State<Arc<AppState>>, headers: HeaderMap)
|
||||
.iter()
|
||||
.map(|m| format!("<option value=\"{0}\">{0}</option>", esc(m)))
|
||||
.collect();
|
||||
let sprache = if sprachmodelle.is_empty() {
|
||||
String::new()
|
||||
} else {
|
||||
let options: String = sprachmodelle
|
||||
.iter()
|
||||
.map(|m| format!("<option value=\"{0}\">{0}</option>", esc(m)))
|
||||
.collect();
|
||||
format!(
|
||||
"<label>Sprachausgabe <select id=\"chat-sprache\"><option value=\"\">aus</option>{options}</select></label>\
|
||||
<label>Stimme <input id=\"chat-stimme\" value=\"Vivian\" maxlength=\"100\" size=\"14\"></label>"
|
||||
)
|
||||
};
|
||||
format!(
|
||||
"<section class=\"card\" id=\"chat\">\
|
||||
<div class=\"zeile\"><label>Modell <select id=\"chat-modell\">{options}</select></label>\
|
||||
<label>Denkstufe <select id=\"chat-denkstufe\"><option value=\"\">Engine-Voreinstellung</option><option value=\"none\">aus</option><option value=\"low\">niedrig</option><option value=\"medium\" selected>mittel</option><option value=\"high\">hoch</option></select></label>\
|
||||
<label>Max. Tokens <input id=\"chat-max\" type=\"number\" min=\"1\" max=\"{MAX_TOKENS_LIMIT}\" value=\"{DEFAULT_MAX_TOKENS}\"></label>\
|
||||
<label>Max. Tokens <input id=\"chat-max\" type=\"number\" min=\"1\" max=\"{MAX_TOKENS_LIMIT}\" value=\"{DEFAULT_MAX_TOKENS}\"></label>{sprache}\
|
||||
<span class=\"rechts\"><button class=\"sm\" type=\"button\" id=\"chat-neu\">Neuer Chat</button></span></div>\
|
||||
<div class=\"verlauf\" id=\"chat-verlauf\" aria-live=\"polite\"></div>\
|
||||
<form id=\"chat-form\"><textarea id=\"chat-text\" rows=\"3\" required placeholder=\"Nachricht … (Enter sendet, Umschalt+Enter macht eine neue Zeile)\"></textarea>\
|
||||
@ -114,16 +139,15 @@ pub(crate) fn build_request(input: &Value) -> Result<Value, &'static str> {
|
||||
Ok(request)
|
||||
}
|
||||
|
||||
pub(super) async fn send(
|
||||
State(state): State<Arc<AppState>>,
|
||||
Extension(slot): Extension<AccessSlot>,
|
||||
Extension(RequestId(correlation)): Extension<RequestId>,
|
||||
Extension(StartedAt(started)): Extension<StartedAt>,
|
||||
headers: HeaderMap,
|
||||
body: Bytes,
|
||||
) -> Response {
|
||||
/// Prüft Sitzung und CSRF-Token einer JSON-Anfrage des Browsers und trägt den Benutzer ein.
|
||||
#[allow(clippy::result_large_err)]
|
||||
fn json_viewer(
|
||||
state: &Arc<AppState>,
|
||||
headers: &HeaderMap,
|
||||
slot: &AccessSlot,
|
||||
) -> Result<super::Viewer, Response> {
|
||||
let csrf = headers.get("x-csrf-token").and_then(|v| v.to_str().ok());
|
||||
let viewer = match guard(&state, &headers, csrf, false) {
|
||||
let viewer = match guard(state, headers, csrf, false) {
|
||||
Ok(v) => v,
|
||||
// Das Skript erwartet JSON, keine Seite.
|
||||
Err(response) => {
|
||||
@ -138,8 +162,10 @@ pub(super) async fn send(
|
||||
"Abgelehnt. Bitte die Seite neu laden.",
|
||||
)
|
||||
};
|
||||
return ApiError::new(status, "invalid_request_error", "ui_session", message)
|
||||
.into_response();
|
||||
return Err(
|
||||
ApiError::new(status, "invalid_request_error", "ui_session", message)
|
||||
.into_response(),
|
||||
);
|
||||
}
|
||||
};
|
||||
{
|
||||
@ -148,6 +174,21 @@ pub(super) async fn send(
|
||||
info.user = Some(viewer.user.clone());
|
||||
info.key_name = Some(viewer.user.clone());
|
||||
}
|
||||
Ok(viewer)
|
||||
}
|
||||
|
||||
pub(super) async fn send(
|
||||
State(state): State<Arc<AppState>>,
|
||||
Extension(slot): Extension<AccessSlot>,
|
||||
Extension(RequestId(correlation)): Extension<RequestId>,
|
||||
Extension(StartedAt(started)): Extension<StartedAt>,
|
||||
headers: HeaderMap,
|
||||
body: Bytes,
|
||||
) -> Response {
|
||||
let viewer = match json_viewer(&state, &headers, &slot) {
|
||||
Ok(v) => v,
|
||||
Err(response) => return response,
|
||||
};
|
||||
let Ok(input) = serde_json::from_slice::<Value>(&body) else {
|
||||
return bad("Die Anfrage ist kein gültiges JSON.");
|
||||
};
|
||||
@ -175,6 +216,92 @@ pub(super) async fn send(
|
||||
}
|
||||
}
|
||||
|
||||
/// Baut aus der Eingabe des Browsers die Sprachausgabe-Anfrage: nur bekannte Felder, WAV.
|
||||
pub(crate) fn build_speech_request(input: &Value) -> Result<Value, &'static str> {
|
||||
let model = input
|
||||
.get("model")
|
||||
.and_then(Value::as_str)
|
||||
.filter(|m| !m.is_empty())
|
||||
.ok_or("Das Sprachmodell fehlt.")?;
|
||||
let text = input
|
||||
.get("input")
|
||||
.and_then(Value::as_str)
|
||||
.map(str::trim)
|
||||
.filter(|t| !t.is_empty())
|
||||
.ok_or("Der Text fehlt.")?;
|
||||
if text.chars().count() > MAX_SPEECH_CHARS {
|
||||
return Err("Der Text ist zu lang für die Sprachausgabe.");
|
||||
}
|
||||
let voice = input
|
||||
.get("voice")
|
||||
.and_then(Value::as_str)
|
||||
.map(str::trim)
|
||||
.filter(|v| !v.is_empty())
|
||||
.unwrap_or("Vivian");
|
||||
if voice.chars().count() > MAX_VOICE_CHARS || voice.chars().any(char::is_control) {
|
||||
return Err("Die Stimme ist ungültig.");
|
||||
}
|
||||
Ok(json!({
|
||||
"model": model,
|
||||
"input": text,
|
||||
"voice": voice,
|
||||
"language": "Auto",
|
||||
"response_format": "wav",
|
||||
}))
|
||||
}
|
||||
|
||||
/// `POST /ui/chat/sprechen`: Text eines Chats vorlesen lassen. Nur Modelle der Engine `tts`.
|
||||
pub(super) async fn speak(
|
||||
State(state): State<Arc<AppState>>,
|
||||
Extension(slot): Extension<AccessSlot>,
|
||||
Extension(RequestId(correlation)): Extension<RequestId>,
|
||||
Extension(StartedAt(started)): Extension<StartedAt>,
|
||||
headers: HeaderMap,
|
||||
body: Bytes,
|
||||
) -> Response {
|
||||
let viewer = match json_viewer(&state, &headers, &slot) {
|
||||
Ok(v) => v,
|
||||
Err(response) => return response,
|
||||
};
|
||||
let Ok(input) = serde_json::from_slice::<Value>(&body) else {
|
||||
return bad("Die Anfrage ist kein gültiges JSON.");
|
||||
};
|
||||
let request = match build_speech_request(&input) {
|
||||
Ok(request) => request,
|
||||
Err(message) => return bad(message),
|
||||
};
|
||||
let model = request["model"].as_str().unwrap_or_default();
|
||||
let is_speech_model = viewer.key.rights.allows(model)
|
||||
&& matches!(
|
||||
state.store().start_plan(model),
|
||||
Ok(Some(plan)) if plan.engine_name == "tts"
|
||||
);
|
||||
if !is_speech_model {
|
||||
return super::refused(
|
||||
StatusCode::NOT_FOUND,
|
||||
"Das Sprachmodell ist nicht verfügbar.",
|
||||
);
|
||||
}
|
||||
let Ok(bytes) = serde_json::to_vec(&request) else {
|
||||
return ApiError::internal().into_response();
|
||||
};
|
||||
let priority = viewer.key.default_priority;
|
||||
match crate::chat::forward_speech(
|
||||
state,
|
||||
&viewer.key,
|
||||
priority,
|
||||
slot,
|
||||
correlation,
|
||||
started,
|
||||
Bytes::from(bytes),
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(response) => response,
|
||||
Err(error) => error.into_response(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Leichtgewichtiger Statusabruf: keine Health-Abfrage und kein Modellstart.
|
||||
pub(super) async fn load_status(
|
||||
State(state): State<Arc<AppState>>,
|
||||
@ -221,6 +348,8 @@ const CHAT_JS: &str = r#"(function () {
|
||||
var modell = document.getElementById("chat-modell");
|
||||
var max = document.getElementById("chat-max");
|
||||
var denkstufe = document.getElementById("chat-denkstufe");
|
||||
var sprache = document.getElementById("chat-sprache");
|
||||
var stimme = document.getElementById("chat-stimme");
|
||||
var messages = [];
|
||||
var laufend = null;
|
||||
|
||||
@ -246,6 +375,38 @@ const CHAT_JS: &str = r#"(function () {
|
||||
denkstufe.disabled = an;
|
||||
}
|
||||
|
||||
// Vorlesen: Text an die Sprachausgabe schicken, die WAV-Antwort als Blob abspielen.
|
||||
var spielt = null;
|
||||
function vorlesen(knopf, textInhalt) {
|
||||
if (!sprache || !sprache.value) { fehler("Sprachausgabe oben auswählen."); return; }
|
||||
if (spielt) { spielt.pause(); spielt = null; }
|
||||
knopf.disabled = true;
|
||||
var alt = knopf.textContent;
|
||||
knopf.textContent = "spricht …";
|
||||
fetch("/ui/chat/sprechen", {
|
||||
method: "POST",
|
||||
credentials: "same-origin",
|
||||
headers: { "content-type": "application/json", "x-csrf-token": csrf },
|
||||
body: JSON.stringify({ model: sprache.value, voice: stimme ? stimme.value : "", input: textInhalt })
|
||||
}).then(function (r) {
|
||||
if (!r.ok) {
|
||||
return r.text().then(function (t) {
|
||||
var meldung = "Fehler " + r.status;
|
||||
try { meldung = JSON.parse(t).error.message + " (" + r.status + ")"; } catch (e) {}
|
||||
fehler("Sprachausgabe: " + meldung);
|
||||
});
|
||||
}
|
||||
return r.blob().then(function (blob) {
|
||||
var url = URL.createObjectURL(blob);
|
||||
var ton = new Audio(url);
|
||||
spielt = ton;
|
||||
ton.addEventListener("ended", function () { URL.revokeObjectURL(url); });
|
||||
return ton.play();
|
||||
});
|
||||
}).catch(function () { fehler("Sprachausgabe: Die Verbindung ist abgebrochen."); })
|
||||
.finally(function () { knopf.disabled = false; knopf.textContent = alt; });
|
||||
}
|
||||
|
||||
function sekunden(seit) {
|
||||
return ((Date.now() - seit) / 1000).toFixed(1).replace(".", ",") + " s";
|
||||
}
|
||||
@ -307,6 +468,15 @@ const CHAT_JS: &str = r#"(function () {
|
||||
}
|
||||
// Die Antwort wurde an der Grenze „Max. Tokens“ abgeschnitten: sagen, wo man es ändert.
|
||||
var abgeschnitten = endeGrund === "length";
|
||||
if (gesamt && sprache) {
|
||||
var knopf = document.createElement("button");
|
||||
knopf.type = "button";
|
||||
knopf.className = "sm";
|
||||
knopf.textContent = "Vorlesen";
|
||||
var vorgelesen = gesamt;
|
||||
knopf.addEventListener("click", function () { vorlesen(knopf, vorgelesen); });
|
||||
antwort.el.appendChild(knopf);
|
||||
}
|
||||
if (abgeschnitten) {
|
||||
var hinweis = document.createElement("span");
|
||||
hinweis.className = "meta";
|
||||
@ -482,6 +652,31 @@ mod tests {
|
||||
assert!(build_request(&json!({"model": "m", "messages": viele})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sprachanfrage_hat_nur_bekannte_felder_und_grenzen() {
|
||||
let r = build_speech_request(&json!({
|
||||
"model": "tts-base", "input": " Hallo ", "voice": " Ryan ",
|
||||
"response_format": "mp3", "speed": 9, "language": "x"
|
||||
}))
|
||||
.unwrap();
|
||||
assert_eq!(r["input"], "Hallo");
|
||||
assert_eq!(r["voice"], "Ryan");
|
||||
assert_eq!(r["response_format"], "wav");
|
||||
assert_eq!(r["language"], "Auto");
|
||||
assert!(r.get("speed").is_none());
|
||||
assert_eq!(
|
||||
build_speech_request(&json!({"model": "m", "input": "x"})).unwrap()["voice"],
|
||||
"Vivian"
|
||||
);
|
||||
assert!(build_speech_request(&json!({"input": "x"})).is_err());
|
||||
assert!(build_speech_request(&json!({"model": "m", "input": " "})).is_err());
|
||||
let lang = "x".repeat(MAX_SPEECH_CHARS + 1);
|
||||
assert!(build_speech_request(&json!({"model": "m", "input": lang})).is_err());
|
||||
assert!(
|
||||
build_speech_request(&json!({"model": "m", "input": "x", "voice": "a\nb"})).is_err()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn skript_schreibt_nie_html() {
|
||||
assert!(!CHAT_JS.contains("innerHTML"));
|
||||
|
||||
@ -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());
|
||||
|
||||
@ -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
|
||||
}
|
||||
@ -297,6 +310,22 @@ async fn gateway_with(
|
||||
})
|
||||
.unwrap();
|
||||
}
|
||||
// Ein Sprachmodell (Engine `tts`), das wie alle anderen auf die Attrappe zeigt.
|
||||
store
|
||||
.register_llm(&NewLlm {
|
||||
name: "sprecher".to_string(),
|
||||
engine: "tts".to_string(),
|
||||
path: PathBuf::from("Qwen/Qwen3-TTS-12Hz-1.7B-Base"),
|
||||
quantization: None,
|
||||
size_bytes: None,
|
||||
gpus: vec![0],
|
||||
context: None,
|
||||
vram_mb,
|
||||
ram_mb: None,
|
||||
idle_secs: None,
|
||||
enabled: true,
|
||||
})
|
||||
.unwrap();
|
||||
let key = store
|
||||
.create_api_key(
|
||||
"alle",
|
||||
@ -374,6 +403,7 @@ async fn gateway_with(
|
||||
|
||||
let mut engines: HashMap<String, Arc<dyn Engine>> = HashMap::new();
|
||||
engines.insert("llama.cpp".to_string(), engine.clone());
|
||||
engines.insert("tts".to_string(), engine.clone());
|
||||
let state = AppState::new(store, Runtime::with_options(engines, options));
|
||||
let port = serve(nexus_api::router(state.clone())).await;
|
||||
Gateway {
|
||||
@ -451,7 +481,7 @@ async fn modellliste_zeigt_freigegebene_modelle_je_nach_rechten_auch_ungeladene(
|
||||
let (status, _, body) = gw.get("/v1/models", Some(&gw.key)).await;
|
||||
assert_eq!(status, 200);
|
||||
assert_eq!(body["object"], "list");
|
||||
assert_eq!(ids(&body), ["bonsai", "zweit"]);
|
||||
assert_eq!(ids(&body), ["bonsai", "sprecher", "zweit"]);
|
||||
assert_eq!(body["data"][0]["object"], "model");
|
||||
let (_, _, body) = gw.get("/v1/models", Some(&gw.key_bonsai)).await;
|
||||
assert_eq!(ids(&body), ["bonsai"]);
|
||||
@ -496,6 +526,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;
|
||||
@ -2232,6 +2293,61 @@ async fn playground(
|
||||
req.send().await.unwrap()
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn playground_liest_vor_nur_mit_sprachmodell_und_sitzung() {
|
||||
let gw = gateway(0, false).await;
|
||||
let (cookie, csrf) = ui_session(&gw, &gw.key_admin).await;
|
||||
// Das Sprachmodell steht bei der Sprachausgabe, nicht in der Modellwahl des Chats.
|
||||
let (_, _, seite) = ui_get(&gw, "/ui/chat", Some(&cookie)).await;
|
||||
assert!(seite.contains("id=\"chat-sprache\"") && seite.contains("<option value=\"sprecher\">"));
|
||||
let chat_wahl = seite
|
||||
.split("id=\"chat-modell\"")
|
||||
.nth(1)
|
||||
.and_then(|t| t.split("</select>").next())
|
||||
.unwrap();
|
||||
assert!(chat_wahl.contains("bonsai") && !chat_wahl.contains("sprecher"));
|
||||
let sprechen = |cookie: String, csrf: Option<String>, body: Value| {
|
||||
let mut req = gw
|
||||
.client
|
||||
.post(format!("{}/ui/chat/sprechen", gw.base))
|
||||
.header("origin", &gw.base)
|
||||
.header("cookie", cookie)
|
||||
.header(CONTENT_TYPE, "application/json")
|
||||
.body(body.to_string());
|
||||
if let Some(csrf) = csrf {
|
||||
req = req.header("x-csrf-token", csrf);
|
||||
}
|
||||
async move { req.send().await.unwrap() }
|
||||
};
|
||||
let gut = json!({"model": "sprecher", "input": "Hallo", "voice": "Ryan"});
|
||||
let resp = sprechen(cookie.clone(), Some(csrf.clone()), gut.clone()).await;
|
||||
assert_eq!(resp.status(), 200);
|
||||
assert_eq!(resp.headers()[CONTENT_TYPE], "audio/wav");
|
||||
// Die Attrappe gibt zurück, was sie gesehen hat (die Umschreibung des Modellnamens auf den des
|
||||
// Studios macht `StudioEngine::endpoint`, getestet im Adapter, nicht die FixedEngine).
|
||||
assert_eq!(resp.text().await.unwrap(), "RIFF|sprecher|Hallo");
|
||||
// Ohne Token 403, ohne Sitzung 401, ein Chatmodell ist kein Sprachmodell.
|
||||
assert_eq!(
|
||||
sprechen(cookie.clone(), None, gut.clone()).await.status(),
|
||||
403
|
||||
);
|
||||
assert_eq!(
|
||||
sprechen("nexus_ui=falsch".to_string(), Some(csrf.clone()), gut)
|
||||
.await
|
||||
.status(),
|
||||
401
|
||||
);
|
||||
let chatmodell = json!({"model": "bonsai", "input": "Hallo"});
|
||||
assert_eq!(
|
||||
sprechen(cookie.clone(), Some(csrf.clone()), chatmodell)
|
||||
.await
|
||||
.status(),
|
||||
404
|
||||
);
|
||||
let leer = json!({"model": "sprecher", "input": " "});
|
||||
assert_eq!(sprechen(cookie, Some(csrf), leer).await.status(), 400);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn playground_streamt_fuer_benutzer_und_protokolliert_nur_metadaten() {
|
||||
let gw = gateway(0, false).await;
|
||||
|
||||
@ -47,6 +47,8 @@ pub struct Config {
|
||||
pub maya: toml::Table,
|
||||
/// Rohe Einstellungen des Strata-Adapters (Abschnitt `[strata]`).
|
||||
pub strata: toml::Table,
|
||||
/// Rohe Einstellungen des Sprachausgabe-Adapters (Abschnitt `[tts]`).
|
||||
pub tts: toml::Table,
|
||||
}
|
||||
|
||||
/// Einstellungen des Schedulers (Entscheidungen #1051 bis #1056).
|
||||
@ -104,6 +106,7 @@ impl Default for Config {
|
||||
ollama: toml::Table::new(),
|
||||
maya: toml::Table::new(),
|
||||
strata: toml::Table::new(),
|
||||
tts: toml::Table::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -15,6 +15,8 @@ pub const OLLAMA: &str = "ollama";
|
||||
pub const MAYA: &str = "maya";
|
||||
/// Name der Engine-Zeile für Strata.
|
||||
pub const STRATA: &str = "strata";
|
||||
/// Name der Engine-Zeile für die Sprachausgabe (Faster Qwen3-TTS Studio).
|
||||
pub const TTS: &str = "tts";
|
||||
|
||||
/// Eingabe für `register_llm`: ein Sprachmodell mit einem Startprofil.
|
||||
#[derive(Debug, Clone)]
|
||||
@ -105,9 +107,10 @@ impl Store {
|
||||
&& new.engine != OLLAMA
|
||||
&& new.engine != MAYA
|
||||
&& new.engine != STRATA
|
||||
&& new.engine != TTS
|
||||
{
|
||||
return Err(Error::Db(format!(
|
||||
"unbekannte Engine \"{}\" (llama.cpp, ollama, maya oder strata)",
|
||||
"unbekannte Engine \"{}\" (llama.cpp, ollama, maya, strata oder tts)",
|
||||
new.engine
|
||||
)));
|
||||
}
|
||||
|
||||
@ -3,7 +3,7 @@
|
||||
use std::path::PathBuf;
|
||||
use std::process::ExitCode;
|
||||
|
||||
use nexus_adapter::{Engine, LlamaCppEngine, MayaEngine, OllamaEngine};
|
||||
use nexus_adapter::{Engine, LlamaCppEngine, MayaEngine, OllamaEngine, StudioEngine};
|
||||
use nexus_core::Priority;
|
||||
use nexus_store::{NewLlm, Rights};
|
||||
|
||||
@ -281,6 +281,7 @@ fn model_add(args: &[String]) -> Result<(), String> {
|
||||
"tag",
|
||||
"maya-config",
|
||||
"strata-config",
|
||||
"tts-model",
|
||||
"gpus",
|
||||
"context",
|
||||
"vram-mb",
|
||||
@ -321,9 +322,12 @@ fn model_add(args: &[String]) -> Result<(), String> {
|
||||
}
|
||||
(path, None)
|
||||
}
|
||||
// Sprachausgabe: der Modellname im laufenden Studio (zum Beispiel
|
||||
// `Qwen/Qwen3-TTS-12Hz-1.7B-Base`); das Studio lädt ihn selbst.
|
||||
"tts" => (PathBuf::from(flags.require("tts-model")?), None),
|
||||
other => {
|
||||
return Err(format!(
|
||||
"Unbekannte Engine \"{other}\" (llama.cpp, ollama, maya oder strata)."
|
||||
"Unbekannte Engine \"{other}\" (llama.cpp, ollama, maya, strata oder tts)."
|
||||
));
|
||||
}
|
||||
};
|
||||
@ -517,9 +521,14 @@ async fn model_discover(args: &[String]) -> Result<(), String> {
|
||||
.discover()
|
||||
.await
|
||||
}
|
||||
"tts" => {
|
||||
StudioEngine::new(crate::serve::tts_config(&config)?)
|
||||
.discover()
|
||||
.await
|
||||
}
|
||||
other => {
|
||||
return Err(format!(
|
||||
"Unbekannte Engine \"{other}\" (llama.cpp, ollama, maya oder strata)."
|
||||
"Unbekannte Engine \"{other}\" (llama.cpp, ollama, maya, strata oder tts)."
|
||||
));
|
||||
}
|
||||
}
|
||||
@ -544,6 +553,8 @@ async fn model_discover(args: &[String]) -> Result<(), String> {
|
||||
"--engine maya --maya-config <pfad>"
|
||||
} else if engine == "strata" {
|
||||
"--engine strata --strata-config <pfad>"
|
||||
} else if engine == "tts" {
|
||||
"--engine tts --tts-model <Modellname im Studio>"
|
||||
} else {
|
||||
"--path <pfad>"
|
||||
}
|
||||
|
||||
@ -28,8 +28,9 @@ Aufruf:
|
||||
nexus model add --name N --engine ollama --tag MODELLNAME [--gpus 0] [--disabled]
|
||||
nexus model add --name N --engine maya --maya-config PFAD.json [--gpus 0,1] [--disabled]
|
||||
nexus model add --name N --engine strata --strata-config PFAD.json [--gpus 0,1] [--disabled]
|
||||
nexus model add --name N --engine tts --tts-model QWEN-MODELL [--gpus 0] [--vram-mb N] [--disabled] (Sprachausgabe, laufendes Studio)
|
||||
nexus model set --name N [--vram-mb N] [--idle-min MINUTEN (0 = nie) | --idle-default]
|
||||
nexus model list | enable --name N | disable --name N | remove --name N (nur gesperrte Modelle) | discover [--engine llama.cpp|ollama|maya|strata]
|
||||
nexus model list | enable --name N | disable --name N | remove --name N (nur gesperrte Modelle) | discover [--engine llama.cpp|ollama|maya|strata|tts]
|
||||
nexus diag [--out DATEI.tar.gz] [--ohne-engine-logs] Diagnose-Archiv ohne Prompts und Keys
|
||||
nexus backup [--out DATEI.db] Kopie der Datenbank (ohne sie zu migrieren; auch bei laufendem Gateway)
|
||||
nexus help Diese Hilfe
|
||||
|
||||
@ -8,6 +8,7 @@ use std::time::Duration;
|
||||
|
||||
use nexus_adapter::{
|
||||
Engine, LlamaCppConfig, LlamaCppEngine, MayaConfig, MayaEngine, OllamaConfig, OllamaEngine,
|
||||
StudioConfig, StudioEngine,
|
||||
};
|
||||
use nexus_api::{AppState, Runtime, RuntimeOptions, SchedulerSettings};
|
||||
use nexus_core::Config;
|
||||
@ -30,6 +31,15 @@ pub fn llama_config(config: &Config) -> Result<LlamaCppConfig, String> {
|
||||
.map_err(|e| format!("Konfiguration [llama_cpp]: {e}"))
|
||||
}
|
||||
|
||||
/// Liest den Abschnitt `[tts]` (Sprachausgabe, Faster Qwen3-TTS Studio).
|
||||
pub fn tts_config(config: &Config) -> Result<StudioConfig, String> {
|
||||
config
|
||||
.tts
|
||||
.clone()
|
||||
.try_into::<StudioConfig>()
|
||||
.map_err(|e| format!("Konfiguration [tts]: {e}"))
|
||||
}
|
||||
|
||||
/// Liest den Abschnitt `[ollama]`; ohne eigenen `log_dir` landen die Logs im
|
||||
/// Datenverzeichnis.
|
||||
pub fn ollama_config(config: &Config) -> Result<OllamaConfig, String> {
|
||||
@ -148,6 +158,10 @@ async fn run(args: &[String]) -> Result<(), String> {
|
||||
"strata".to_string(),
|
||||
Arc::new(MayaEngine::strata(strata_config(&config)?)),
|
||||
);
|
||||
engines.insert(
|
||||
"tts".to_string(),
|
||||
Arc::new(StudioEngine::new(tts_config(&config)?)),
|
||||
);
|
||||
let state = AppState::new(
|
||||
store,
|
||||
Runtime::with_options(engines, runtime_options(&config)),
|
||||
|
||||
Reference in New Issue
Block a user