diff --git a/BEDIENUNGSANLEITUNG.md b/BEDIENUNGSANLEITUNG.md index 20082c6..599eedb 100644 --- a/BEDIENUNGSANLEITUNG.md +++ b/BEDIENUNGSANLEITUNG.md @@ -136,6 +136,19 @@ python chat_client.py "Erzähl mir einen guten Morgen-Spruch" > `chat_client.py` erwartet den Dienst auf Port **8003** — bei Bedarf im Skript > `GATEWAY_URL` anpassen oder den Dienst mit `PORT=8003 make run` starten. +**Fortlaufendes Gespräch (Gedächtnis):** Wird eine `session_id` mitgegeben, merkt +sich der Assistent den Verlauf und bezieht ihn in die nächste Antwort ein: + +```bash +curl -X POST "http://localhost:8080/api/chat?session_id=oma-anna&debug=true" \ + -H 'Content-Type: application/json' -d '{"text":"Ich heiße Anna."}' +curl -X POST "http://localhost:8080/api/chat?session_id=oma-anna&debug=true" \ + -H 'Content-Type: application/json' -d '{"text":"Wie war noch mein Name?"}' +``` + +Ohne `session_id` ist jeder Aufruf eigenständig (kein Gedächtnis). Wie viele +zurückliegende Nachrichten einfließen, steuert `HISTORY_MAX_MESSAGES` (Standard 10). + ### c) Audio transkribieren (`/api/transcribe`) ```bash diff --git a/Docs/voice-assistant-architecture.md b/Docs/voice-assistant-architecture.md index f4eef5b..ab153a2 100644 --- a/Docs/voice-assistant-architecture.md +++ b/Docs/voice-assistant-architecture.md @@ -143,10 +143,15 @@ Normalizer überwiegend regelbasiert (so heute umgesetzt), Adapter promptbasiert `app/core/orchestrator.py` verbindet Provider, Pipeline und Output-Endpunkt. -- `chat_text(text, language, voice, output)` → `(trace, audio_bytes)` +- `chat_text(text, language, voice, output, history)` → `(trace, audio_bytes)` - `speak_only(text, voice, language, output)` → `audio_bytes` - `transcribe_only(audio_bytes, fmt, language, input)` → `trace` +Bei `/api/chat` mit `session_id` lädt die API-Schicht den letzten Gesprächsverlauf +aus dem Store (`messages`-Tabelle, letzte `HISTORY_MAX_MESSAGES`), gibt ihn als +`history` an das LLM und speichert nach der Antwort User- und Assistant-Turn. +Ohne `session_id` bleibt der Aufruf zustandslos. + Das synthetisierte Audio wird **zusätzlich** durch den gewählten Output-Endpunkt geschrieben (`open → write_chunk → flush → close`) und **gleichzeitig** als HTTP-Stream zurückgegeben (additiv). Bei lokalen Geräten ist `write_chunk` heute @@ -177,7 +182,8 @@ STT (multipart), LLM und TTS; lokaler OpenAI-kompatibler LLM-Adapter; regelbasie Pipeline; geschichtete Config + Profile; Registry + einheitliche Route-Auflösung; Device Router (strikt, Singleton); Output-Lifecycle; **Authentifizierung (Bearer-Token) + persistenter SQLite-Store für Nutzer/Sessions + Mandanten-Trennung -+ dauerhafte Nutzer-Präferenzen**; automatisierte Tests. ++ dauerhafte Nutzer-Präferenzen**; **Gesprächsgedächtnis pro Session (Verlauf im +Store, fließt ins LLM)**; automatisierte Tests. **Platzhalter (Gerüst):** Audio-Endpunkte (`local-default`, `bluetooth`, `mobile-ws`, `mobile-webrtc`) liefern leere Chunks — nur Auswahl/Lifecycle sind @@ -191,7 +197,7 @@ Reihenfolge der Weiterentwicklung: 1. **(erledigt)** Konfig- & Routing-Fundament: Profile, Device Router, Registry, Pro-Request-Override. 2. **(erledigt)** Cloud-Fundament: Bearer-Token-Auth, Mehrbenutzer, persistenter SQLite-Store, Mandanten-Trennung, dauerhafte Nutzer-Präferenzen. Offen: Skalierung auf gemeinsamen Store (Postgres/Redis) für mehrere Instanzen. -3. **Konversationsgedächtnis:** Verlauf + Langzeit-Erinnerungen (heute ist `llm.complete` zustandslos; Nutzer-Präferenzen sind als Basis vorhanden). +3. **(teilweise erledigt)** Konversationsgedächtnis: Kurzzeit-Gesprächsverlauf pro Session ist umgesetzt (Store + ans LLM). Offen: **Langzeit-Erinnerungen** über Sessions hinweg (Fakten/Vorlieben, ggf. LLM-gestützt extrahiert und zusammengefasst). 4. **Echtzeit:** Streaming-STT/TTS, WebSocket/WebRTC-Endpunkte real, Barge-in, Turn-Manager. 5. **Resilienz:** Fallback-Policy (remote KI fällt aus → lokaler/alternativer Provider), Metriken/Tracing. 6. **Betrieb:** Kosten-/Quota-Kontrolle pro Nutzer; Notfall-/Eskalationskonzept (Senioren-Kontext). @@ -209,7 +215,7 @@ voice-assistant-scaffold/ │ ├── main.py # FastAPI-App + Router-Registrierung │ ├── config.py # Settings, TOML-Profile, Präzedenz │ ├── dependencies.py # Registries, ResolvedRoute, resolve_route, Store-/Router-Singleton -│ ├── store.py # Persistenz: Store-Interface + SQLiteStore (Nutzer/Sessions) +│ ├── store.py # Persistenz: Store-Interface + SQLiteStore (Nutzer/Sessions/Verlauf) │ ├── auth.py # Bearer-Token-Auth (require_user) + Admin-Schutz │ ├── errors.py # RoutingError -> HTTP 422 │ ├── schemas.py # Pydantic-Modelle diff --git a/README.md b/README.md index a7e9471..26ad6ec 100644 --- a/README.md +++ b/README.md @@ -16,6 +16,7 @@ Praktische Bedienung: [`BEDIENUNGSANLEITUNG.md`](BEDIENUNGSANLEITUNG.md). - **Geschichtete Konfiguration** mit Profilen (`local-dev` / `hybrid` / `cloud`) - **Routing auf jeder Ebene:** Default → Profil → Nutzer → Session → Request - **Authentifizierung** (Bearer-Token) + persistente Nutzer/Sessions (SQLite) +- **Gesprächsgedächtnis pro Session:** Verlauf wird gespeichert und fließt ins LLM - **REST-API** für Chat, Transkription, Sprachausgabe, Geräte, Sessions, Config - **Ohne Secrets im Code** — API-Keys nur über die Umgebung @@ -95,6 +96,20 @@ curl -X POST http://localhost:8080/api/speak \ Unbekannter Endpunkt/Provider → `HTTP 422` mit Klartext-Hinweis. +## Gesprächsgedächtnis + +Wird bei `/api/chat` eine `session_id` mitgegeben, merkt sich der Assistent den +Verlauf: vergangene Turns werden gespeichert und beim nächsten Aufruf ans LLM +gegeben (begrenzt auf die letzten `HISTORY_MAX_MESSAGES` Nachrichten, Default 10). +Ohne `session_id` bleibt der Aufruf zustandslos. + +```bash +curl -X POST "http://localhost:8080/api/chat?session_id=oma-anna&debug=true" \ + -H 'Content-Type: application/json' -d '{"text":"Ich heiße Anna."}' +curl -X POST "http://localhost:8080/api/chat?session_id=oma-anna&debug=true" \ + -H 'Content-Type: application/json' -d '{"text":"Wie war noch mein Name?"}' +``` + ## Authentifizierung Standardmäßig (`AUTH_ENABLED=true`) sind `chat`/`speak`/`transcribe`/`sessions`/`me` diff --git a/app/api/chat.py b/app/api/chat.py index be40b2a..38009ea 100644 --- a/app/api/chat.py +++ b/app/api/chat.py @@ -11,6 +11,7 @@ from app.dependencies import ( resolve_route, build_orchestrator, resolve_output_endpoint, + get_store, ) from app.schemas import ChatRequest @@ -50,10 +51,18 @@ async def chat( } voice = payload.voice or settings.openrouter_tts_voice + store = get_store() + try: route = resolve_route(user, session_id, overrides) orchestrator = build_orchestrator(route) output = await resolve_output_endpoint(route) + # Gespraechsverlauf laden (nur bei gesetzter session_id -> sonst zustandslos). + history = ( + store.get_recent_messages(session_id, settings.history_max_messages) + if session_id + else [] + ) except SessionOwnershipError as exc: raise HTTPException(status_code=403, detail=str(exc)) except RoutingError as exc: @@ -65,33 +74,39 @@ async def chat( language=route.language, voice=voice, output=output, + history=history, ) - - if debug: - return JSONResponse( - content={ - "ok": True, - "voice": voice, - "route": route.as_dict(), - "trace": { - "raw_transcript": trace.raw_transcript, - "cleaned_transcript": trace.cleaned_transcript, - "semantic_response": trace.semantic_response, - "spoken_response": trace.spoken_response, - "tts_ready_text": trace.tts_ready_text, - }, - } - ) - - headers = { - "Content-Language": route.language, - "X-Audio-Format": "pcm", - "X-Audio-Sample-Rate": "24000", - "X-Audio-Channels": "1", - "X-Audio-Sample-Width": "16", - **_route_headers(route), - } - return StreamingResponse(BytesIO(audio), media_type="audio/pcm", headers=headers) - except Exception as exc: raise HTTPException(status_code=502, detail=str(exc)) + + # Turn persistieren (User-Eingabe + semantische Antwort) fuer das Gedaechtnis. + if session_id: + store.append_message(session_id, user.id, "user", payload.text) + store.append_message(session_id, user.id, "assistant", trace.semantic_response) + + if debug: + return JSONResponse( + content={ + "ok": True, + "voice": voice, + "route": route.as_dict(), + "history_len": len(history), + "trace": { + "raw_transcript": trace.raw_transcript, + "cleaned_transcript": trace.cleaned_transcript, + "semantic_response": trace.semantic_response, + "spoken_response": trace.spoken_response, + "tts_ready_text": trace.tts_ready_text, + }, + } + ) + + headers = { + "Content-Language": route.language, + "X-Audio-Format": "pcm", + "X-Audio-Sample-Rate": "24000", + "X-Audio-Channels": "1", + "X-Audio-Sample-Width": "16", + **_route_headers(route), + } + return StreamingResponse(BytesIO(audio), media_type="audio/pcm", headers=headers) diff --git a/app/config.py b/app/config.py index 64dbcbc..58b8926 100644 --- a/app/config.py +++ b/app/config.py @@ -123,6 +123,7 @@ class Settings(BaseSettings): db_path: str = str(BASE_DIR / "data" / "voice-assistant.db") admin_api_key: str = "" auth_enabled: bool = True + history_max_messages: int = 10 model_config = SettingsConfigDict( env_file=ENV_FILE, case_sensitive=False, extra="ignore" ) diff --git a/app/core/orchestrator.py b/app/core/orchestrator.py index 4ab6322..213fe3f 100644 --- a/app/core/orchestrator.py +++ b/app/core/orchestrator.py @@ -76,6 +76,7 @@ class Orchestrator: language: str | None = None, voice: str | None = None, output=None, + history: list[dict] | None = None, ): trace = PipelineTrace() @@ -83,7 +84,8 @@ class Orchestrator: trace.cleaned_transcript = await self.input_cleaner.run(text or "") trace.semantic_response = await self.llm.complete( - trace.cleaned_transcript or "" + trace.cleaned_transcript or "", + history=history, ) if not trace.semantic_response: raise RuntimeError("LLM returned an empty response") diff --git a/app/providers/llm/base.py b/app/providers/llm/base.py index 2e3517c..5a72add 100644 --- a/app/providers/llm/base.py +++ b/app/providers/llm/base.py @@ -2,4 +2,9 @@ from abc import ABC, abstractmethod class LLMProvider(ABC): @abstractmethod - async def complete(self, text: str, session_id: str | None = None) -> str: ... + async def complete( + self, + text: str, + history: list[dict] | None = None, + session_id: str | None = None, + ) -> str: ... diff --git a/app/providers/llm/local_openai_compatible.py b/app/providers/llm/local_openai_compatible.py index 147a404..99d946b 100644 --- a/app/providers/llm/local_openai_compatible.py +++ b/app/providers/llm/local_openai_compatible.py @@ -7,10 +7,17 @@ class LocalOpenAICompatibleLLM(LLMProvider): self.api_key = api_key self.model = model - async def complete(self, text: str, session_id: str | None = None) -> str: + async def complete( + self, + text: str, + history: list[dict] | None = None, + session_id: str | None = None, + ) -> str: + messages = list(history) if history else [] + messages.append({"role": "user", "content": text}) payload = { "model": self.model, - "messages": [{"role": "user", "content": text}], + "messages": messages, "temperature": 0.3, } async with httpx.AsyncClient(timeout=120) as client: diff --git a/app/providers/llm/openrouter.py b/app/providers/llm/openrouter.py index 66f507f..c4143dd 100644 --- a/app/providers/llm/openrouter.py +++ b/app/providers/llm/openrouter.py @@ -49,7 +49,12 @@ class OpenRouterLLMProvider(LLMProvider): self.api_key = (api_key or "").strip() self.model = (model or "").strip() - async def complete(self, text: str, session_id: str | None = None) -> str: + async def complete( + self, + text: str, + history: list[dict] | None = None, + session_id: str | None = None, + ) -> str: if not self.api_key: raise ValueError("OPENROUTER_API_KEY is empty") if not self.model: @@ -57,12 +62,14 @@ class OpenRouterLLMProvider(LLMProvider): if not text or not text.strip(): raise ValueError("LLM input text is empty") + messages = [{"role": "system", "content": SYSTEM_PROMPT}] + if history: + messages.extend(history) + messages.append({"role": "user", "content": text.strip()}) + payload = { "model": self.model, - "messages": [ - {"role": "system", "content": SYSTEM_PROMPT}, - {"role": "user", "content": text.strip()}, - ], + "messages": messages, } timeout = httpx.Timeout(connect=10.0, read=120.0, write=30.0, pool=10.0) diff --git a/app/store.py b/app/store.py index 98d61fb..15421d9 100644 --- a/app/store.py +++ b/app/store.py @@ -70,6 +70,14 @@ class Store(ABC): def update_session(self, session_id: str, user_id: str, values: dict) -> Session: """Erstellt/aktualisiert eine Session des Nutzers. Fremde Session -> SessionOwnershipError.""" + @abstractmethod + def append_message(self, session_id: str, user_id: str, role: str, content: str) -> None: + """Haengt eine Nachricht an die Session an. Fremde Session -> SessionOwnershipError.""" + + @abstractmethod + def get_recent_messages(self, session_id: str, limit: int) -> list[dict]: + """Liefert die letzten `limit` Nachrichten chronologisch ([{'role','content'}, ...]).""" + class SQLiteStore(Store): def __init__(self, db_path: str): @@ -102,6 +110,15 @@ class SQLiteStore(Store): created_at TEXT NOT NULL, updated_at TEXT NOT NULL ); + CREATE TABLE IF NOT EXISTS messages ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + session_id TEXT NOT NULL, + role TEXT NOT NULL, + content TEXT NOT NULL, + created_at TEXT NOT NULL + ); + CREATE INDEX IF NOT EXISTS idx_messages_session + ON messages(session_id, id); """ ) @@ -195,3 +212,35 @@ class SQLiteStore(Store): (session_id, user_id, payload, now, now), ) return Session(id=session_id, user_id=user_id, data=data) + + # ----- Nachrichten / Gespraechsverlauf ---------------------------------- + def append_message(self, session_id: str, user_id: str, role: str, content: str) -> None: + existing = self.get_session(session_id) + if existing and existing.user_id != user_id: + raise SessionOwnershipError( + f"Session {session_id!r} gehoert einem anderen Nutzer" + ) + now = _now() + with self._connect() as conn: + if not existing: + conn.execute( + "INSERT INTO sessions (id, user_id, data_json, created_at, updated_at)" + " VALUES (?, ?, ?, ?, ?)", + (session_id, user_id, "{}", now, now), + ) + conn.execute( + "INSERT INTO messages (session_id, role, content, created_at)" + " VALUES (?, ?, ?, ?)", + (session_id, role, content, now), + ) + + def get_recent_messages(self, session_id: str, limit: int) -> list[dict]: + if limit <= 0: + return [] + with self._connect() as conn: + rows = conn.execute( + "SELECT role, content FROM messages WHERE session_id = ?" + " ORDER BY id DESC LIMIT ?", + (session_id, limit), + ).fetchall() + return [{"role": row["role"], "content": row["content"]} for row in reversed(rows)] diff --git a/tests/test_endpoints_e2e.py b/tests/test_endpoints_e2e.py index 17949da..a8efd5b 100644 --- a/tests/test_endpoints_e2e.py +++ b/tests/test_endpoints_e2e.py @@ -48,7 +48,7 @@ def test_session_route_applies(): def test_chat_per_request_override_and_loopback(monkeypatch): class StubLLM: - async def complete(self, text, session_id=None): + async def complete(self, text, history=None, session_id=None): return "Mir geht es gut, danke." class StubTTS: diff --git a/tests/test_memory.py b/tests/test_memory.py new file mode 100644 index 0000000..73a824b --- /dev/null +++ b/tests/test_memory.py @@ -0,0 +1,65 @@ +from fastapi.testclient import TestClient + +import app.dependencies as deps +from app.main import app + +client = TestClient(app) + + +def _install_stubs(monkeypatch, captured): + class MemLLM: + async def complete(self, text, history=None, session_id=None): + captured["history"] = list(history or []) + return f"Antwort auf: {text}" + + class StubTTS: + async def synthesize(self, text, voice=None, audio_format="pcm"): + return b"AUDIO" + + monkeypatch.setitem(deps.LLM_REGISTRY, "mem", lambda s: MemLLM()) + monkeypatch.setitem(deps.TTS_REGISTRY, "stub", lambda s: StubTTS()) + return {"llm_provider": "mem", "tts_provider": "stub", "output_endpoint": "loopback"} + + +def test_history_accumulates_and_flows_to_llm(monkeypatch): + captured = {} + base = _install_stubs(monkeypatch, captured) + + # Turn 1: noch kein Verlauf. + r1 = client.post("/api/chat?debug=true&session_id=conv1", json={"text": "Hallo", **base}) + assert r1.status_code == 200 + assert r1.json()["history_len"] == 0 + assert captured["history"] == [] + + # Turn 2: Verlauf enthaelt User+Assistant aus Turn 1. + r2 = client.post("/api/chat?debug=true&session_id=conv1", json={"text": "Und weiter?", **base}) + assert r2.status_code == 200 + assert r2.json()["history_len"] == 2 + assert captured["history"] == [ + {"role": "user", "content": "Hallo"}, + {"role": "assistant", "content": "Antwort auf: Hallo"}, + ] + + +def test_no_session_id_is_stateless(monkeypatch): + captured = {} + base = _install_stubs(monkeypatch, captured) + + client.post("/api/chat?debug=true", json={"text": "A", **base}) + client.post("/api/chat?debug=true", json={"text": "B", **base}) + assert captured["history"] == [] # ohne session_id kein Gedaechtnis + + +def test_history_limited_by_setting(monkeypatch): + from app.config import settings + + captured = {} + base = _install_stubs(monkeypatch, captured) + monkeypatch.setattr(settings, "history_max_messages", 2) + + for text in ("eins", "zwei", "drei"): + client.post("/api/chat?debug=true&session_id=limit", json={"text": text, **base}) + + # Vor dem 3. Turn liegen 4 Nachrichten vor; geladen werden nur die letzten 2. + assert len(captured["history"]) == 2 + assert captured["history"][-1] == {"role": "assistant", "content": "Antwort auf: zwei"}