feat: Langzeit-Erinnerungen (#3b) und WebSocket-Streaming-Chat (#4, erster Increment)
#3b Langzeit-Erinnerungen: - Store: memories-Tabelle + add/get/delete_memory (pro Nutzer) - API: GET/POST/DELETE /api/me/memories - chat.py injiziert Nutzer-Erinnerungen als System-Kontext ins LLM (sessionunabhaengig) - ?debug zeigt memories_len #4 Echtzeit (erster Increment): - WS /ws/chat: dauerhafter Kanal, Event-Folge ack -> semantic -> audio (binaer) -> done - Auth (Token-Query), Session-Gedaechtnis und Erinnerungen wie bei POST /api/chat - Fehler als error-Event (422/403/502) - Tests: 38 gruen (Erinnerungs-CRUD/Injektion, WebSocket-Streaming/Auth) - Doku aktualisiert (README, BEDIENUNGSANLEITUNG, Architektur) Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
parent
16a964032e
commit
531b57e08d
12 changed files with 389 additions and 9 deletions
|
|
@ -81,6 +81,32 @@ def test_user_prefs_applied_to_route(monkeypatch):
|
|||
assert resp.headers["X-Output-Endpoint"] == "loopback"
|
||||
|
||||
|
||||
def test_memories_crud(monkeypatch):
|
||||
_enable_auth(monkeypatch)
|
||||
auth = {"Authorization": f"Bearer {_create_user('Mem')}"}
|
||||
|
||||
assert client.get("/api/me/memories", headers=auth).json() == []
|
||||
|
||||
created = client.post("/api/me/memories", headers=auth, json={"content": "mag Tee"})
|
||||
assert created.status_code == 200
|
||||
mid = created.json()["id"]
|
||||
|
||||
listed = client.get("/api/me/memories", headers=auth).json()
|
||||
assert len(listed) == 1 and listed[0]["content"] == "mag Tee"
|
||||
|
||||
assert client.delete(f"/api/me/memories/{mid}", headers=auth).status_code == 200
|
||||
assert client.get("/api/me/memories", headers=auth).json() == []
|
||||
assert client.delete("/api/me/memories/9999", headers=auth).status_code == 404
|
||||
|
||||
|
||||
def test_memories_are_per_user(monkeypatch):
|
||||
_enable_auth(monkeypatch)
|
||||
auth_a = {"Authorization": f"Bearer {_create_user('A')}"}
|
||||
auth_b = {"Authorization": f"Bearer {_create_user('B')}"}
|
||||
client.post("/api/me/memories", headers=auth_a, json={"content": "geheim A"})
|
||||
assert client.get("/api/me/memories", headers=auth_b).json() == []
|
||||
|
||||
|
||||
def test_admin_unconfigured_returns_503(monkeypatch):
|
||||
# Auth an, aber kein Admin-Key gesetzt.
|
||||
monkeypatch.setattr(settings, "auth_enabled", True)
|
||||
|
|
|
|||
|
|
@ -50,6 +50,22 @@ def test_no_session_id_is_stateless(monkeypatch):
|
|||
assert captured["history"] == [] # ohne session_id kein Gedaechtnis
|
||||
|
||||
|
||||
def test_memories_injected_as_context(monkeypatch):
|
||||
captured = {}
|
||||
base = _install_stubs(monkeypatch, captured)
|
||||
|
||||
# Erinnerung fuer den (anonymen) Nutzer ablegen.
|
||||
deps.get_store().ensure_anonymous_user()
|
||||
deps.get_store().add_memory("anonymous", "heisst Anna")
|
||||
|
||||
# Ohne session_id -> kein Verlauf, aber Erinnerung wird trotzdem injiziert.
|
||||
r = client.post("/api/chat?debug=true", json={"text": "Hallo", **base})
|
||||
assert r.status_code == 200
|
||||
assert r.json()["memories_len"] == 1
|
||||
assert captured["history"][0]["role"] == "system"
|
||||
assert "heisst Anna" in captured["history"][0]["content"]
|
||||
|
||||
|
||||
def test_history_limited_by_setting(monkeypatch):
|
||||
from app.config import settings
|
||||
|
||||
|
|
|
|||
68
tests/test_ws.py
Normal file
68
tests/test_ws.py
Normal file
|
|
@ -0,0 +1,68 @@
|
|||
import pytest
|
||||
from fastapi.testclient import TestClient
|
||||
from starlette.websockets import WebSocketDisconnect
|
||||
|
||||
import app.dependencies as deps
|
||||
from app.main import app
|
||||
from app.config import settings
|
||||
|
||||
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"Echo: {text}"
|
||||
|
||||
class StubTTS:
|
||||
async def synthesize(self, text, voice=None, audio_format="pcm"):
|
||||
return b"WSAUDIO"
|
||||
|
||||
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 _drain_turn(ws):
|
||||
assert ws.receive_json()["type"] == "ack"
|
||||
sem = ws.receive_json()
|
||||
assert ws.receive_bytes() == b"WSAUDIO"
|
||||
assert ws.receive_json()["type"] == "done"
|
||||
return sem
|
||||
|
||||
|
||||
def test_ws_streams_events_and_remembers(monkeypatch):
|
||||
captured = {}
|
||||
base = _install_stubs(monkeypatch, captured)
|
||||
|
||||
with client.websocket_connect("/ws/chat?session_id=wsconv") as ws:
|
||||
ws.send_json({"text": "Hallo", **base})
|
||||
sem1 = _drain_turn(ws)
|
||||
assert sem1["type"] == "semantic" and sem1["text"] == "Echo: Hallo"
|
||||
|
||||
ws.send_json({"text": "Weiter", **base})
|
||||
_drain_turn(ws)
|
||||
|
||||
# Zweiter Turn hat den Verlauf des ersten erhalten.
|
||||
assert captured["history"] == [
|
||||
{"role": "user", "content": "Hallo"},
|
||||
{"role": "assistant", "content": "Echo: Hallo"},
|
||||
]
|
||||
|
||||
|
||||
def test_ws_unknown_provider_sends_error_event(monkeypatch):
|
||||
captured = {}
|
||||
_install_stubs(monkeypatch, captured)
|
||||
with client.websocket_connect("/ws/chat") as ws:
|
||||
ws.send_json({"text": "x", "llm_provider": "gibtsnicht"})
|
||||
err = ws.receive_json()
|
||||
assert err["type"] == "error" and err["status"] == 422
|
||||
|
||||
|
||||
def test_ws_requires_token_when_auth_enabled(monkeypatch):
|
||||
monkeypatch.setattr(settings, "auth_enabled", True)
|
||||
monkeypatch.setattr(settings, "admin_api_key", "k")
|
||||
with pytest.raises(WebSocketDisconnect):
|
||||
with client.websocket_connect("/ws/chat"):
|
||||
pass
|
||||
Loading…
Add table
Add a link
Reference in a new issue