mirror of
https://github.com/Alkatrazz24/Funk-lab.git
synced 2026-07-08 05:24:43 +02:00
feat(stt): mode texte + sélection de modèle (client→serveur par requête) (#7)
Serveur : /v1/ask accepte un model optionnel (validé contre STT_ALLOWED_MODELS), nouvel endpoint GET /v1/models (défaut + alias autorisés). Pas de switch global. Client : 'stt --text' (chat texte simple sans micro/HUD), '--model hermes|claude|qwen|opus' (noms courts → alias LiteLLM), commandes /model et /models en mode texte. Le modèle choisi est envoyé au serveur à chaque requête (voix comme texte). Claude-Session: https://claude.ai/code/session_013FmcxGsyXZXogiAHQLjnZT Co-authored-by: Claude <noreply@anthropic.com>
This commit is contained in:
parent
47936b0088
commit
bcdb4f8b2a
10 changed files with 146 additions and 25 deletions
|
|
@ -75,6 +75,12 @@ route lui-même vers Qwen3 (g01) ou Claude selon l'alias `hermes-default` / `her
|
|||
> MVP : l'API `:8080` n'est pas spécifiée, et depuis un pod le SSH vers Hermes est impraticable.
|
||||
> MVP = inférence/chat. L'intégration Hermes est une étape ultérieure.
|
||||
|
||||
**Choix du modèle** : le client envoie un `model` (alias LiteLLM) **par requête** à
|
||||
`/v1/ask` ; le serveur le valide contre `STT_ALLOWED_MODELS` et le passe à LiteLLM. Pas de
|
||||
switch global type `hermes-switch` (pas de restart, chaque client choisit le sien).
|
||||
`GET /v1/models` liste le défaut + les alias autorisés. Noms courts client : `hermes`
|
||||
(=hermes-default), `qwen`, `claude` (=claude-sonnet-4-6), `opus`.
|
||||
|
||||
### La mémoire — côté serveur (futur)
|
||||
|
||||
- **Client** : cache local SQLite (`~/.local/share/stt/`, gitignoré) — historique brut.
|
||||
|
|
@ -89,7 +95,7 @@ route lui-même vers Qwen3 (g01) ou Claude selon l'alias `hermes-default` / `her
|
|||
|
||||
| Composant | Emplacement | Description |
|
||||
|---|---|---|
|
||||
| Client `stt` | `stt/client/` (pipx) | `stt`, `stt --setup`, `stt --server <url>`, `stt --no-tts` |
|
||||
| Client `stt` | `stt/client/` (pipx) | `stt` (voix+HUD), `stt --text` (chat texte), `stt --setup`, `stt --server <url>`, `stt --model <hermes\|claude\|qwen\|opus>` |
|
||||
| — voix | `stt/client/stt/voice/` | wake word, STT faster-whisper, TTS Piper |
|
||||
| — api | `stt/client/stt/api.py` | `ServerClient` → `POST /v1/ask` |
|
||||
| — UI/HUD | `stt/client/stt/ui/` + `hud/` | HTTP statique + websocket d'états ; HUD embarqué dans le package |
|
||||
|
|
|
|||
|
|
@ -27,9 +27,12 @@ Assistant vocal type *Jarvis* pour le homelab Funk, en **architecture client-ser
|
|||
```bash
|
||||
pipx install "git+ssh://git@github.com/Alkatrazz24/Funk-lab.git@<branche>#subdirectory=stt/client"
|
||||
stt --setup # génère ~/.config/stt/stt.toml (dont [server] url)
|
||||
stt # lance la voix + ouvre le HUD ; dis "Ok Hermès …"
|
||||
stt --text # chat texte simple (sans micro ni HUD) — idéal pour tester
|
||||
stt # voix + HUD ; dis "Ok Hermès …"
|
||||
stt --model claude # choisir le modèle : hermes (défaut) | claude | qwen | opus
|
||||
```
|
||||
Prérequis poste : micro, Piper + voix dans `~/.local/share/piper/`, `aplay` (alsa-utils).
|
||||
En mode texte : commandes `/model <nom>`, `/models`, `/quit`.
|
||||
Prérequis voix : micro, Piper + voix dans `~/.local/share/piper/`, `aplay` (alsa-utils).
|
||||
|
||||
## Serveur — déploiement (cluster)
|
||||
|
||||
|
|
|
|||
|
|
@ -5,6 +5,9 @@
|
|||
[server]
|
||||
url = "http://stt.lab.local" # endpoint du STT-server (paramétrable)
|
||||
timeout_sec = 90
|
||||
model = "hermes-default" # modèle demandé au serveur
|
||||
# Noms courts (--model / commande /model) : hermes=hermes-default, qwen=qwen3-8b,
|
||||
# claude=claude-sonnet-4-6, opus=claude-opus-4-7. Sinon mets un alias LiteLLM brut.
|
||||
|
||||
[voice]
|
||||
wake_word = "hermes" # "Ok Hermès"
|
||||
|
|
|
|||
|
|
@ -1,7 +1,8 @@
|
|||
"""Client HTTP vers le STT-server (in-cluster).
|
||||
|
||||
Le client n'a plus de cerveau : il envoie le texte transcrit au serveur, qui
|
||||
orchestre l'inférence (LiteLLM → Qwen3/Claude) et renvoie la réponse.
|
||||
orchestre l'inférence (LiteLLM → Qwen3/Claude) et renvoie la réponse. Le client
|
||||
choisit le modèle (alias LiteLLM) et le passe au serveur par requête.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
|
@ -13,18 +14,29 @@ class ServerClient:
|
|||
def __init__(self, cfg: dict[str, Any]):
|
||||
self.url = cfg["url"].rstrip("/")
|
||||
self.timeout = cfg.get("timeout_sec", 90)
|
||||
self.model = cfg.get("model", "hermes-default")
|
||||
|
||||
def ask(self, text: str) -> str:
|
||||
def ask(self, text: str, model: str | None = None) -> str:
|
||||
import requests
|
||||
|
||||
r = requests.post(
|
||||
f"{self.url}/v1/ask",
|
||||
json={"text": text},
|
||||
json={"text": text, "model": model or self.model},
|
||||
timeout=self.timeout,
|
||||
)
|
||||
if r.status_code == 400:
|
||||
raise RuntimeError(r.json().get("detail", "requête invalide"))
|
||||
r.raise_for_status()
|
||||
return r.json()["reply"].strip()
|
||||
|
||||
def models(self) -> dict:
|
||||
"""{'default': ..., 'available': [...]} depuis le serveur."""
|
||||
import requests
|
||||
|
||||
r = requests.get(f"{self.url}/v1/models", timeout=10)
|
||||
r.raise_for_status()
|
||||
return r.json()
|
||||
|
||||
def healthy(self) -> bool:
|
||||
import requests
|
||||
|
||||
|
|
|
|||
|
|
@ -8,30 +8,80 @@ import sys
|
|||
|
||||
|
||||
def _cmd_setup() -> int:
|
||||
from stt.config import write_default_config
|
||||
from stt.config import MODEL_PRESETS, write_default_config
|
||||
|
||||
path = write_default_config()
|
||||
print(f"✓ Config : {path}")
|
||||
print("\nÀ installer / configurer sur le poste :")
|
||||
print(" • modèle Whisper (téléchargé au 1er lancement par faster-whisper)")
|
||||
print(" • Piper + voix → ~/.local/share/piper/<voix>.onnx")
|
||||
print("\nUtilisation :")
|
||||
print(" stt --text # chat texte simple (sans micro ni HUD)")
|
||||
print(" stt # voix + HUD")
|
||||
print(f" stt --model claude # modèles : {', '.join(MODEL_PRESETS)}")
|
||||
print("\nÀ configurer si besoin :")
|
||||
print(f" • URL du STT-server dans {path} ([server] url)")
|
||||
print(" • Pour la voix : Piper + voix → ~/.local/share/piper/<voix>.onnx")
|
||||
return 0
|
||||
|
||||
|
||||
def _cmd_run(args) -> int:
|
||||
def _make_client(args):
|
||||
from stt.api import ServerClient
|
||||
from stt.config import load_config
|
||||
from stt.memory import LocalMemory
|
||||
from stt.ui import serve
|
||||
from stt.voice import VoiceEngine
|
||||
from stt.config import load_config, resolve_model
|
||||
|
||||
cfg = load_config()
|
||||
if args.server:
|
||||
cfg["server"]["url"] = args.server
|
||||
|
||||
client = ServerClient(cfg["server"])
|
||||
print(f"STT-server : {client.url}")
|
||||
if args.model:
|
||||
client.model = resolve_model(args.model)
|
||||
return cfg, client
|
||||
|
||||
|
||||
def _cmd_text(args) -> int:
|
||||
"""Chat texte simple : tape, le serveur répond. Pas de micro ni HUD."""
|
||||
_, client = _make_client(args)
|
||||
print(f"STT (texte) — serveur {client.url} — modèle '{client.model}'")
|
||||
if not client.healthy():
|
||||
print(" ⚠️ serveur injoignable — vérifie [server] url et le réseau")
|
||||
print(" commandes : /model <nom>, /models, /quit\n")
|
||||
|
||||
from stt.config import resolve_model
|
||||
|
||||
while True:
|
||||
try:
|
||||
line = input("vous> ").strip()
|
||||
except (EOFError, KeyboardInterrupt):
|
||||
print("\n👋")
|
||||
return 0
|
||||
if not line:
|
||||
continue
|
||||
if line in ("/quit", "/exit", "/q"):
|
||||
return 0
|
||||
if line == "/models":
|
||||
try:
|
||||
m = client.models()
|
||||
print(f" défaut: {m['default']} — dispo: {', '.join(m['available'])}\n")
|
||||
except Exception as e: # noqa: BLE001
|
||||
print(f" ❌ {e}\n")
|
||||
continue
|
||||
if line.startswith("/model "):
|
||||
client.model = resolve_model(line.split(maxsplit=1)[1].strip())
|
||||
print(f" → modèle : {client.model}\n")
|
||||
continue
|
||||
try:
|
||||
reply = client.ask(line)
|
||||
except Exception as e: # noqa: BLE001
|
||||
print(f" ❌ {e}\n")
|
||||
continue
|
||||
print(f"hermes [{client.model}]> {reply}\n")
|
||||
|
||||
|
||||
def _cmd_voice(args) -> int:
|
||||
from stt.config import load_config # noqa: F401 (cfg via _make_client)
|
||||
from stt.memory import LocalMemory
|
||||
from stt.ui import serve
|
||||
from stt.voice import VoiceEngine
|
||||
|
||||
cfg, client = _make_client(args)
|
||||
print(f"STT-server : {client.url} — modèle '{client.model}'")
|
||||
if not client.healthy():
|
||||
print(" ⚠️ serveur injoignable — vérifie [server] url et le réseau")
|
||||
|
||||
|
|
@ -57,13 +107,17 @@ def _cmd_run(args) -> int:
|
|||
def main(argv: list[str] | None = None) -> int:
|
||||
p = argparse.ArgumentParser(prog="stt", description="Client vocal Jarvis de Funk")
|
||||
p.add_argument("--setup", action="store_true", help="Écrit la config par défaut")
|
||||
p.add_argument("--text", action="store_true", help="Mode chat texte (sans micro ni HUD)")
|
||||
p.add_argument("--model", help="Modèle : hermes, claude, qwen, opus (ou alias LiteLLM)")
|
||||
p.add_argument("--server", help="Force l'URL du STT-server (sinon config)")
|
||||
p.add_argument("--no-tts", action="store_true", help="Réponses texte seulement")
|
||||
p.add_argument("--no-tts", action="store_true", help="Réponses texte seulement (voix)")
|
||||
args = p.parse_args(argv)
|
||||
|
||||
if args.setup:
|
||||
return _cmd_setup()
|
||||
return _cmd_run(args)
|
||||
if args.text:
|
||||
return _cmd_text(args)
|
||||
return _cmd_voice(args)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
|
|
|||
|
|
@ -16,11 +16,26 @@ CONFIG_DIR = Path.home() / ".config" / "stt"
|
|||
CONFIG_PATH = CONFIG_DIR / "stt.toml"
|
||||
DATA_DIR = Path.home() / ".local" / "share" / "stt"
|
||||
|
||||
# Noms courts → alias LiteLLM (pour --model et la commande /model)
|
||||
MODEL_PRESETS = {
|
||||
"hermes": "hermes-default", # Qwen3-8B local (défaut, gratuit)
|
||||
"qwen": "qwen3-8b",
|
||||
"claude": "claude-sonnet-4-6", # Claude (facturé)
|
||||
"opus": "claude-opus-4-7",
|
||||
}
|
||||
|
||||
|
||||
def resolve_model(name: str) -> str:
|
||||
"""Nom court → alias LiteLLM (ou renvoie tel quel si déjà un alias)."""
|
||||
return MODEL_PRESETS.get(name, name)
|
||||
|
||||
DEFAULT_CONFIG: dict[str, Any] = {
|
||||
"server": {
|
||||
# STT-server (in-cluster) — joignable via Traefik / wildcard *.lab.local
|
||||
"url": "http://stt.lab.local",
|
||||
"timeout_sec": 90,
|
||||
# Modèle demandé au serveur (alias LiteLLM, ou nom court ci-dessous)
|
||||
"model": "hermes-default",
|
||||
},
|
||||
"voice": {
|
||||
"wake_word": "hermes",
|
||||
|
|
|
|||
|
|
@ -8,7 +8,11 @@ STT et route l'inférence vers LiteLLM (s01) → Qwen3 (g01) / Claude.
|
|||
| Méthode | Route | Corps | Réponse |
|
||||
|---|---|---|---|
|
||||
| `GET` | `/healthz` | — | `{status, version}` |
|
||||
| `POST` | `/v1/ask` | `{text}` | `{reply}` |
|
||||
| `GET` | `/v1/models` | — | `{default, available[]}` |
|
||||
| `POST` | `/v1/ask` | `{text, model?}` | `{reply, model}` |
|
||||
|
||||
`model` (optionnel) = alias LiteLLM ; défaut serveur si absent ; rejeté (400) si absent
|
||||
de `STT_ALLOWED_MODELS`. Le client choisit le modèle par requête (pas de switch global).
|
||||
|
||||
## Configuration (variables d'env)
|
||||
|
||||
|
|
@ -16,7 +20,8 @@ STT et route l'inférence vers LiteLLM (s01) → Qwen3 (g01) / Claude.
|
|||
|---|---|---|
|
||||
| `STT_LITELLM_URL` | `http://192.168.10.1:4000/v1/chat/completions` | endpoint LiteLLM (IP directe s01, cf. open-webui) |
|
||||
| `STT_LITELLM_KEY` | `lm-studio` | clé LiteLLM (valeur exacte attendue) |
|
||||
| `STT_MODEL` | `hermes-default` | alias LiteLLM (bascule Qwen/Claude via `hermes-switch`) |
|
||||
| `STT_MODEL` | `hermes-default` | modèle par défaut |
|
||||
| `STT_ALLOWED_MODELS` | `hermes-default,qwen3-8b,claude-sonnet-4-6,claude-opus-4-7` | alias autorisés (demandables par le client) |
|
||||
| `STT_SYSTEM_PROMPT` | prompt vocal FR concis | persona |
|
||||
| `STT_MAX_TOKENS` / `STT_TEMPERATURE` | `200` / `0.7` | génération |
|
||||
|
||||
|
|
|
|||
|
|
@ -13,16 +13,19 @@ from pydantic import BaseModel
|
|||
|
||||
from stt_server import __version__
|
||||
from stt_server.brain import ask as brain_ask
|
||||
from stt_server.config import settings
|
||||
|
||||
app = FastAPI(title="STT-server", version=__version__)
|
||||
|
||||
|
||||
class AskRequest(BaseModel):
|
||||
text: str
|
||||
model: str | None = None # alias LiteLLM ; défaut serveur si absent
|
||||
|
||||
|
||||
class AskReply(BaseModel):
|
||||
reply: str
|
||||
model: str
|
||||
|
||||
|
||||
@app.get("/healthz")
|
||||
|
|
@ -30,16 +33,27 @@ async def healthz() -> dict:
|
|||
return {"status": "ok", "version": __version__}
|
||||
|
||||
|
||||
@app.get("/v1/models")
|
||||
async def v1_models() -> dict:
|
||||
return {"default": settings.model, "available": settings.allowed_models}
|
||||
|
||||
|
||||
@app.post("/v1/ask", response_model=AskReply)
|
||||
async def v1_ask(req: AskRequest) -> AskReply:
|
||||
text = req.text.strip()
|
||||
if not text:
|
||||
raise HTTPException(status_code=400, detail="text vide")
|
||||
model = req.model or settings.model
|
||||
if model not in settings.allowed_models:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=f"modèle '{model}' non autorisé ; dispo : {settings.allowed_models}",
|
||||
)
|
||||
try:
|
||||
reply = await brain_ask(text)
|
||||
reply = await brain_ask(text, model)
|
||||
except httpx.HTTPError as e:
|
||||
raise HTTPException(status_code=502, detail=f"upstream LiteLLM : {e}") from e
|
||||
return AskReply(reply=reply)
|
||||
return AskReply(reply=reply, model=model)
|
||||
|
||||
|
||||
def run() -> None:
|
||||
|
|
|
|||
|
|
@ -12,9 +12,9 @@ import httpx
|
|||
from stt_server.config import settings
|
||||
|
||||
|
||||
async def ask(text: str) -> str:
|
||||
async def ask(text: str, model: str | None = None) -> str:
|
||||
payload = {
|
||||
"model": settings.model,
|
||||
"model": model or settings.model,
|
||||
"messages": [
|
||||
{"role": "system", "content": settings.system_prompt},
|
||||
{"role": "user", "content": text},
|
||||
|
|
|
|||
|
|
@ -11,7 +11,16 @@ class Settings:
|
|||
"STT_LITELLM_URL", "http://192.168.10.1:4000/v1/chat/completions"
|
||||
)
|
||||
litellm_key: str = os.getenv("STT_LITELLM_KEY", "lm-studio")
|
||||
# Modèle par défaut + alias LiteLLM autorisés (le client peut en demander un par requête)
|
||||
model: str = os.getenv("STT_MODEL", "hermes-default")
|
||||
allowed_models: list[str] = [
|
||||
m.strip()
|
||||
for m in os.getenv(
|
||||
"STT_ALLOWED_MODELS",
|
||||
"hermes-default,qwen3-8b,claude-sonnet-4-6,claude-opus-4-7",
|
||||
).split(",")
|
||||
if m.strip()
|
||||
]
|
||||
|
||||
system_prompt: str = os.getenv(
|
||||
"STT_SYSTEM_PROMPT",
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue