Compare commits
115
Commits
V2.3.1-WP06
...
V2.6.0
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d2e0b48aa5 | ||
|
|
302e2a3d24 | ||
|
|
faaa3ef55f | ||
|
|
70ffa5cd4e | ||
|
|
65bcea71ee | ||
|
|
16af07dd21 | ||
|
|
fc4c868eaa | ||
|
|
1fe9582cbe | ||
|
|
d34f388ee1 | ||
|
|
4cd82d1d2b | ||
|
|
fb6e35ed01 | ||
|
|
0ba8ae8d1e | ||
|
|
1121d63383 | ||
|
|
0b8f0a6c22 | ||
|
|
30047f8e00 | ||
|
|
7b6cc8da7c | ||
|
|
c5e613d2b1 | ||
|
|
d965d96cde | ||
|
|
65bc7622f8 | ||
|
|
844d13316a | ||
|
|
a403d8baf6 | ||
|
|
d25d623b9c | ||
|
|
1e3fcc1633 | ||
|
|
0d28a6c1a7 | ||
|
|
87083355ee | ||
|
|
7e9e496d86 | ||
|
|
d93b9b30ae | ||
|
|
7fc316d284 | ||
|
|
e27b1f4621 | ||
|
|
3c19e192bc | ||
|
|
df971f9c56 | ||
|
|
ecc2b60427 | ||
|
|
2826cbadbc | ||
|
|
a2856bfe87 | ||
|
|
69617802c3 | ||
|
|
135c02bc9a | ||
|
|
cd28a9d35c | ||
|
|
49cdc9a13f | ||
|
|
3629bc3fb9 | ||
|
|
37c0f526ec | ||
|
|
bf40169662 | ||
|
|
9fbf0b7c91 | ||
|
|
652d22e8e8 | ||
|
|
94dbaafc72 | ||
|
|
69ad7bc823 | ||
|
|
d59bd1885d | ||
|
|
f6d8751f23 | ||
|
|
9a38daafc0 | ||
|
|
e5bc77b93e | ||
|
|
2bcf1930fe | ||
|
|
2d58220a3c | ||
|
|
8436f4192d | ||
|
|
13ab2b7d68 | ||
|
|
714763f92f | ||
|
|
a1cd0741c9 | ||
|
|
c741cc7d1b | ||
|
|
e8b8c9a350 | ||
|
|
f016a16c68 | ||
|
|
5bf91d51da | ||
|
|
00aecf692d | ||
|
|
b815f6235f | ||
|
|
a1a58727fd | ||
|
|
b1cf89982b | ||
|
|
5fa02aed2d | ||
|
|
1fde4ed72a | ||
|
|
52210a91fd | ||
|
|
9d792e11ce | ||
|
|
2677ad7269 | ||
|
|
98c395b5de | ||
|
|
b4ebbe5c28 | ||
|
|
88e2cbf254 | ||
|
|
b153571933 | ||
|
|
aba6f0c38b | ||
|
|
f4299db347 | ||
|
|
06f77fe8b7 | ||
|
|
54e38d58c3 | ||
|
|
fd47a954bd | ||
|
|
5aae33f578 | ||
|
|
4ed04039e5 | ||
|
|
e7cec6acc6 | ||
|
|
a7cda3f51c | ||
|
|
d2ee48555a | ||
|
|
8639791914 | ||
|
|
765fad6a8d | ||
|
|
408c4ace93 | ||
|
|
565d34fb7b | ||
|
|
0170d9291f | ||
|
|
865b261294 | ||
|
|
62aa24a4bc | ||
|
|
f2de556c16 | ||
|
|
67d865d373 | ||
|
|
5c0a36c9ea | ||
|
|
f50ae4c934 | ||
|
|
1fefc538ac | ||
|
|
a520b62d08 | ||
|
|
1063c94f5d | ||
|
|
954e21ca81 | ||
|
|
fd39211801 | ||
|
|
ff23ce6f00 | ||
|
|
86464cec11 | ||
|
|
ba57e8b43f | ||
|
|
be406d230f | ||
|
|
38abde8516 | ||
|
|
9bb6566419 | ||
|
|
2acaf3c060 | ||
|
|
ec33163d98 | ||
|
|
2d0913cf3b | ||
|
|
76ea8e3350 | ||
|
|
bbc1e589f5 | ||
|
|
987e297c07 | ||
|
|
046aa2cf48 | ||
|
|
0bc0e66a85 | ||
|
|
2310633de3 | ||
|
|
bd36d78025 | ||
|
|
d2270fafdd |
No files matched your search
@@ -1,10 +1,10 @@
|
|||||||
# mindnet v2.2 — Programmplan
|
# mindnet v2.4 — Programmplan
|
||||||
**Version:** 2.3.1 (Post-WP06 Decision Engine)
|
**Version:** 2.6.0 (Inkl. WP-15 Smart Edge Allocation)
|
||||||
**Stand:** 2025-12-09
|
**Stand:** 2025-12-12
|
||||||
**Status:** Aktiv
|
**Status:** Aktiv
|
||||||
|
|
||||||
---
|
---
|
||||||
- [mindnet v2.2 — Programmplan](#mindnet-v22--programmplan)
|
- [mindnet v2.4 — Programmplan](#mindnet-v24--programmplan)
|
||||||
- [1. Programmauftrag](#1-programmauftrag)
|
- [1. Programmauftrag](#1-programmauftrag)
|
||||||
- [2. Vision](#2-vision)
|
- [2. Vision](#2-vision)
|
||||||
- [3. Programmziele](#3-programmziele)
|
- [3. Programmziele](#3-programmziele)
|
||||||
@@ -24,27 +24,29 @@
|
|||||||
- [WP-05 – Persönlichkeitsmodell \& RAG-Chat (abgeschlossen)](#wp-05--persönlichkeitsmodell--rag-chat-abgeschlossen)
|
- [WP-05 – Persönlichkeitsmodell \& RAG-Chat (abgeschlossen)](#wp-05--persönlichkeitsmodell--rag-chat-abgeschlossen)
|
||||||
- [WP-05b – Advanced Chat (Optional)](#wp-05b--advanced-chat-optional)
|
- [WP-05b – Advanced Chat (Optional)](#wp-05b--advanced-chat-optional)
|
||||||
- [WP-06 – Decision Engine \& Hybrid Router (abgeschlossen)](#wp-06--decision-engine--hybrid-router-abgeschlossen)
|
- [WP-06 – Decision Engine \& Hybrid Router (abgeschlossen)](#wp-06--decision-engine--hybrid-router-abgeschlossen)
|
||||||
- [WP-07 – Interview-Assistent (geplant)](#wp-07--interview-assistent-geplant)
|
- [WP-07 – Interview-Assistent (abgeschlossen)](#wp-07--interview-assistent-abgeschlossen)
|
||||||
- [WP-08 – Self-Tuning v1/v2 (geplant)](#wp-08--self-tuning-v1v2-geplant)
|
- [WP-08 – Self-Tuning v1/v2 (geplant)](#wp-08--self-tuning-v1v2-geplant)
|
||||||
- [WP-09 – Vault-Onboarding \& Migration (geplant)](#wp-09--vault-onboarding--migration-geplant)
|
- [WP-09 – Vault-Onboarding \& Migration (geplant)](#wp-09--vault-onboarding--migration-geplant)
|
||||||
- [WP-10 – Chat-Interface \& Writeback (geplant)](#wp-10--chat-interface--writeback-geplant)
|
- [WP-10 – Chat-Interface \& Writeback (abgeschlossen)](#wp-10--chat-interface--writeback-abgeschlossen)
|
||||||
- [WP-11 – Knowledge-Builder \& Vernetzungs-Assistent (geplant)](#wp-11--knowledge-builder--vernetzungs-assistent-geplant)
|
- [WP-10a – GUI Evolution: Draft Editor (abgeschlossen)](#wp-10a--gui-evolution-draft-editor-abgeschlossen)
|
||||||
|
- [WP-11 – Backend Intelligence \& Persistence (abgeschlossen)](#wp-11--backend-intelligence--persistence-abgeschlossen)
|
||||||
- [WP-12 – Knowledge Rewriter (Soft Mode, geplant)](#wp-12--knowledge-rewriter-soft-mode-geplant)
|
- [WP-12 – Knowledge Rewriter (Soft Mode, geplant)](#wp-12--knowledge-rewriter-soft-mode-geplant)
|
||||||
- [WP-13 – MCP-Integration \& Agenten-Layer (geplant)](#wp-13--mcp-integration--agenten-layer-geplant)
|
- [WP-13 – MCP-Integration \& Agenten-Layer (geplant)](#wp-13--mcp-integration--agenten-layer-geplant)
|
||||||
- [WP-14 – Review / Refactoring / Dokumentation (geplant)](#wp-14--review--refactoring--dokumentation-geplant)
|
- [WP-14 – Review / Refactoring / Dokumentation (geplant)](#wp-14--review--refactoring--dokumentation-geplant)
|
||||||
|
- [WP-15 – Smart Edge Allocation \& Chunking Strategies (abgeschlossen)](#wp-15--smart-edge-allocation--chunking-strategies-abgeschlossen)
|
||||||
|
- [WP-16 – Auto-Discovery \& Enrichment (geplant)](#wp-16--auto-discovery--enrichment-geplant)
|
||||||
|
- [WP-17 – Conversational Memory (Dialog-Gedächtnis) (geplant)](#wp-17--conversational-memory-dialog-gedächtnis-geplant)
|
||||||
- [7. Abhängigkeiten (vereinfacht, aktualisiert)](#7-abhängigkeiten-vereinfacht-aktualisiert)
|
- [7. Abhängigkeiten (vereinfacht, aktualisiert)](#7-abhängigkeiten-vereinfacht-aktualisiert)
|
||||||
- [8. Laufzeit- \& Komplexitätsindikatoren (aktualisiert)](#8-laufzeit---komplexitätsindikatoren-aktualisiert)
|
- [8. Laufzeit- \& Komplexitätsindikatoren (aktualisiert)](#8-laufzeit---komplexitätsindikatoren-aktualisiert)
|
||||||
- [9. Programmfortschritt (Ampel, aktualisiert)](#9-programmfortschritt-ampel-aktualisiert)
|
- [9. Programmfortschritt (Ampel, aktualisiert)](#9-programmfortschritt-ampel-aktualisiert)
|
||||||
- [10. Governance \& Versionierung](#10-governance--versionierung)
|
- [10. Governance \& Versionierung](#10-governance--versionierung)
|
||||||
- [11. Executive Summary](#11-executive-summary)
|
- [11. Executive Summary](#11-executive-summary)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 1. Programmauftrag
|
## 1. Programmauftrag
|
||||||
|
|
||||||
mindnet v2.2 entwickelt ein persönliches, wachsendes KI-Gedächtnis, das:
|
mindnet v2.4 entwickelt ein persönliches, wachsendes KI-Gedächtnis, das:
|
||||||
|
|
||||||
- Wissen, Erfahrungen, Werte und Entscheidungen speichert,
|
- Wissen, Erfahrungen, Werte und Entscheidungen speichert,
|
||||||
- diese Informationen semantisch verknüpft und rekonstruierbar macht,
|
- diese Informationen semantisch verknüpft und rekonstruierbar macht,
|
||||||
@@ -52,7 +54,8 @@ mindnet v2.2 entwickelt ein persönliches, wachsendes KI-Gedächtnis, das:
|
|||||||
- über mehrere Kanäle gefüttert wird:
|
- über mehrere Kanäle gefüttert wird:
|
||||||
- Obsidian-Markdown (primäre Quelle),
|
- Obsidian-Markdown (primäre Quelle),
|
||||||
- Chat-basierter Agent (Decision Engine & RAG-Chat aktiv),
|
- Chat-basierter Agent (Decision Engine & RAG-Chat aktiv),
|
||||||
- später: Interview-Assistent (strukturierte Dialogerfassung),
|
- Interview-Assistent (One-Shot Extraction aktiv),
|
||||||
|
- **Draft Editor (Active Intelligence aktiv)**,
|
||||||
- automatisch neue Zusammenhänge erkennt und vernetzt (Edges, Typen, Hinweise),
|
- automatisch neue Zusammenhänge erkennt und vernetzt (Edges, Typen, Hinweise),
|
||||||
- sich durch Rückmeldungen (Feedback) selbst verbessert (Self-Tuning).
|
- sich durch Rückmeldungen (Feedback) selbst verbessert (Self-Tuning).
|
||||||
|
|
||||||
@@ -87,7 +90,7 @@ Kernprinzipien der Vision:
|
|||||||
Das System arbeitet von Anfang an mit unvollständigen Daten, kann aber schrittweise dichter werden, ohne dass alte Notizen massenhaft manuell angepasst werden müssen.
|
Das System arbeitet von Anfang an mit unvollständigen Daten, kann aber schrittweise dichter werden, ohne dass alte Notizen massenhaft manuell angepasst werden müssen.
|
||||||
|
|
||||||
- **Flexibilität (Late Binding):**
|
- **Flexibilität (Late Binding):**
|
||||||
Semantik wird überwiegend in Konfiguration (z. B. `types.yaml`, `prompts.yaml`, `decision_engine.yaml`, Policies) festgelegt. Die Persönlichkeit entsteht durch das Config-Design, nicht durch Hardcoding.
|
Semantik wird überwiegend in Konfiguration (z. B. `types.yaml`, `prompts.yaml`, `decision_engine.yaml`) festgelegt. Die Persönlichkeit entsteht durch das Config-Design, nicht durch Hardcoding.
|
||||||
|
|
||||||
- **Autonomie & Self-Healing:**
|
- **Autonomie & Self-Healing:**
|
||||||
mindnet schlägt fehlende Typen, Relationen und Edges vor (z. B. aus Inline-Relationen, Edge-Defaults, Ähnlichkeitsbeziehungen) und baut damit einen „self-healing graph“ auf.
|
mindnet schlägt fehlende Typen, Relationen und Edges vor (z. B. aus Inline-Relationen, Edge-Defaults, Ähnlichkeitsbeziehungen) und baut damit einen „self-healing graph“ auf.
|
||||||
@@ -115,7 +118,10 @@ Kernprinzipien der Vision:
|
|||||||
- **RAG-Chat:** KI antwortet in natürlicher Sprache auf Basis von Wissen und Persönlichkeit (WP-05 abgeschlossen).
|
- **RAG-Chat:** KI antwortet in natürlicher Sprache auf Basis von Wissen und Persönlichkeit (WP-05 abgeschlossen).
|
||||||
- **Decision Engine:** System erkennt Intent (Fakt vs. Entscheidung) und wägt Werte ab (WP-06 abgeschlossen).
|
- **Decision Engine:** System erkennt Intent (Fakt vs. Entscheidung) und wägt Werte ab (WP-06 abgeschlossen).
|
||||||
- **Multi-Persona:** System wechselt den Tonfall (Empathisch vs. Analytisch) situativ (WP-06 abgeschlossen).
|
- **Multi-Persona:** System wechselt den Tonfall (Empathisch vs. Analytisch) situativ (WP-06 abgeschlossen).
|
||||||
- Technische Basis: FastAPI, Qdrant, Ollama (Local LLM).
|
- **Chat Interface:** Web-basiertes Frontend (Streamlit) für einfache Interaktion und Feedback-Gabe (WP-10 abgeschlossen).
|
||||||
|
- **Interview-Assistent (WP-07):** One-Shot Extraction von Notizen ("Neues Projekt anlegen") ist live.
|
||||||
|
- **Active Intelligence (WP-11):** Automatische Link-Vorschläge (Matrix-Logik) während des Schreibens.
|
||||||
|
- Technische Basis: FastAPI (Async), Qdrant (768 Dim), Ollama (Phi-3/Nomic), Streamlit.
|
||||||
- Automatisierte Erkennung von Beziehungen:
|
- Automatisierte Erkennung von Beziehungen:
|
||||||
- Wikilinks, Inline-Relationen, Callout-Edges, Typ-Defaults.
|
- Wikilinks, Inline-Relationen, Callout-Edges, Typ-Defaults.
|
||||||
- „Mitwachsendes“ Schema ohne Obsidian-Umstrukturierungen:
|
- „Mitwachsendes“ Schema ohne Obsidian-Umstrukturierungen:
|
||||||
@@ -124,10 +130,8 @@ Kernprinzipien der Vision:
|
|||||||
|
|
||||||
### 3.2 Mittelfristig (Nächste Schritte)
|
### 3.2 Mittelfristig (Nächste Schritte)
|
||||||
|
|
||||||
- **Chat Interface (WP-10):** Ablösung der Terminal-Interaktion durch ein Web-Frontend (Streamlit/React) für bessere UX und einfacheres Feedback-Geben.
|
- **Self-Tuning (WP-08):** Optimierung der Gewichte in `retriever.yaml` basierend auf dem gesammelten Feedback.
|
||||||
- Interview-Assistent erstellt neue Notes automatisch (strukturierte Dialoge → Markdown).
|
- Agenten können über MCP-Tools (`mindnet_query`, `mindnet_chat`) auf mindnet zugreifen (WP-13).
|
||||||
- mindnet erzeugt Vorschläge für neue Notes & Edges und bietet einen „Vernetzungs-Assistenten“ für manuell angelegte Notizen.
|
|
||||||
- Agenten können über MCP-Tools (`mindnet_query`, `mindnet_chat`) auf mindnet zugreifen.
|
|
||||||
|
|
||||||
### 3.3 Langfristig
|
### 3.3 Langfristig
|
||||||
|
|
||||||
@@ -180,7 +184,7 @@ Die folgenden Prinzipien steuern alle Workpackages und Entscheidungen:
|
|||||||
- Jeder Importlauf, jede Retriever-Anfrage und jede Policy-Änderung soll prüfbar sein.
|
- Jeder Importlauf, jede Retriever-Anfrage und jede Policy-Änderung soll prüfbar sein.
|
||||||
|
|
||||||
10. **Local First & Privacy**
|
10. **Local First & Privacy**
|
||||||
- Nutzung lokaler LLMs (Ollama/Phi-3) für Inference. Keine Daten verlassen den Server.
|
- Nutzung lokaler LLMs (Ollama) für Inference. Keine Daten verlassen den Server.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -189,10 +193,10 @@ Die folgenden Prinzipien steuern alle Workpackages und Entscheidungen:
|
|||||||
Phase A – Fundament & Import (Fertig)
|
Phase A – Fundament & Import (Fertig)
|
||||||
Phase B – Semantik, Graph & Lernen (Fertig)
|
Phase B – Semantik, Graph & Lernen (Fertig)
|
||||||
Phase C – Persönlichkeitsmodell & KI-Zwilling (Fertig)
|
Phase C – Persönlichkeitsmodell & KI-Zwilling (Fertig)
|
||||||
Phase D – Agenten, MCP & Interaktion (Startend)
|
Phase D – Agenten, MCP & Interaktion (Aktiv)
|
||||||
Phase E – Review, Refactoring, Dokumentation
|
Phase E – Review, Refactoring, Dokumentation
|
||||||
|
|
||||||
Alle Workpackages sind einer Phase zugeordnet. WP-01 bis WP-06 sind bereits erfolgreich abgeschlossen.
|
Alle Workpackages sind einer Phase zugeordnet. WP-01 bis WP-07 und WP-10/10a/11 sind erfolgreich abgeschlossen.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -352,17 +356,18 @@ Transformation vom reinen Wissens-Abrufer zum strategischen Entscheidungspartner
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
### WP-07 – Interview-Assistent (geplant)
|
### WP-07 – Interview-Assistent (abgeschlossen)
|
||||||
|
|
||||||
**Phase:** C
|
**Phase:** C/D
|
||||||
**Status:** 🟡 geplant
|
**Status:** 🟢 abgeschlossen
|
||||||
|
|
||||||
**Ziel:**
|
**Ziel:**
|
||||||
Dialogbasierter Erfassungs-Assistent, der strukturierte Interviews führt und daraus konsistente Markdown-Notizen generiert.
|
Dialogbasierter Erfassungs-Assistent, der strukturierte Interviews führt und daraus konsistente Markdown-Notizen generiert.
|
||||||
|
|
||||||
**Umfang:**
|
**Erreichte Ergebnisse:**
|
||||||
- Design von Interview-Flows.
|
- **One-Shot Extractor:** Extrahiert Notiz-Inhalte aus einem Prompt.
|
||||||
- Konvertierung von Dialogtranskripten in typisierte Notes.
|
- **Schema Injection:** Typspezifische Pflichtfelder (Late Binding).
|
||||||
|
- **Draft Generator:** Liefert validen Markdown-Codeblock mit `status: draft`.
|
||||||
|
|
||||||
**Aufwand / Komplexität:**
|
**Aufwand / Komplexität:**
|
||||||
- Aufwand: Niedrig/Mittel
|
- Aufwand: Niedrig/Mittel
|
||||||
@@ -373,7 +378,7 @@ Dialogbasierter Erfassungs-Assistent, der strukturierte Interviews führt und da
|
|||||||
### WP-08 – Self-Tuning v1/v2 (geplant)
|
### WP-08 – Self-Tuning v1/v2 (geplant)
|
||||||
|
|
||||||
**Phase:** B/C
|
**Phase:** B/C
|
||||||
**Status:** 🟡 geplant
|
**Status:** 🟡 geplant (Nächster Fokus)
|
||||||
|
|
||||||
**Ziel:**
|
**Ziel:**
|
||||||
Aufbau eines Self-Tuning-Mechanismus, der auf Basis von Feedback-Daten (WP-04c) Vorschläge für Retriever- und Policy-Anpassungen macht.
|
Aufbau eines Self-Tuning-Mechanismus, der auf Basis von Feedback-Daten (WP-04c) Vorschläge für Retriever- und Policy-Anpassungen macht.
|
||||||
@@ -406,32 +411,60 @@ Sicherstellen, dass bestehende und neue Obsidian-Vaults schrittweise in mindnet
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
### WP-10 – Chat-Interface & Writeback (geplant)
|
### WP-10 – Chat-Interface & Writeback (abgeschlossen)
|
||||||
|
|
||||||
**Phase:** D
|
**Phase:** D
|
||||||
**Status:** 🟡 geplant (Priorität B - "Quick Win")
|
**Status:** 🟢 abgeschlossen
|
||||||
|
|
||||||
**Ziel:**
|
**Ziel:**
|
||||||
Ablösung der Terminal-Interaktion durch ein grafisches Interface.
|
Ablösung der Terminal-Interaktion durch ein grafisches Interface.
|
||||||
|
|
||||||
**Umfang:**
|
**Erreichte Ergebnisse:**
|
||||||
- Technologie: Streamlit oder einfaches HTML/JS Frontend.
|
- **Tech-Stack:** Streamlit Frontend (`app/frontend/ui.py`).
|
||||||
- Funktionen: Chat-Verlauf, Anzeige der Quellen (mit Scores), Daumen-hoch/runter für WP-04c Feedback.
|
- **Funktionen:** Chat-Verlauf, Visualisierung von Intents und Quellen (Expander).
|
||||||
- Funktionen für Q&A sowie Vorschlag neuer Notes/Edges.
|
- **Feedback:** Globales Rating (Sterne) und granulare Quellen-Bewertung (Faces).
|
||||||
|
- **Writeback:** Mockup-Interface für neue Einträge (Vorbereitung WP-07).
|
||||||
|
- **Deployment:** Systemd-Services für Prod (8501) und Dev (8502).
|
||||||
|
|
||||||
**Aufwand / Komplexität:**
|
**Aufwand / Komplexität:**
|
||||||
- Aufwand: Hoch (durch Writeback) / Mittel (für reines Frontend)
|
- Aufwand: Hoch
|
||||||
- Komplexität: Hoch
|
- Komplexität: Hoch
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
### WP-11 – Knowledge-Builder & Vernetzungs-Assistent (geplant)
|
### WP-10a – GUI Evolution: Draft Editor (abgeschlossen)
|
||||||
|
|
||||||
**Phase:** D
|
**Phase:** D
|
||||||
**Status:** 🟡 geplant
|
**Status:** 🟢 abgeschlossen
|
||||||
|
|
||||||
**Ziel:**
|
**Ziel:**
|
||||||
Assistent, der manuell erstellte oder importierte Notizen analysiert und Vorschläge für Typen, Edges und Einordnung macht.
|
Anpassung der GUI an komplexe Interaktionsmuster, die durch den Interview-Assistenten und Knowledge-Builder entstehen.
|
||||||
|
|
||||||
|
**Erreichte Ergebnisse:**
|
||||||
|
- **Draft Editor:** Interaktive `st.text_area` für generierte Entwürfe.
|
||||||
|
- **Sanitizer:** `normalize_meta_and_body` zur Korrektur von LLM-Fehlern.
|
||||||
|
- **Download/Copy:** Export-Funktionen für Markdown.
|
||||||
|
|
||||||
|
**Aufwand / Komplexität:**
|
||||||
|
- Aufwand: Mittel
|
||||||
|
- Komplexität: Mittel
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### WP-11 – Backend Intelligence & Persistence (abgeschlossen)
|
||||||
|
|
||||||
|
**Phase:** D
|
||||||
|
**Status:** 🟢 abgeschlossen
|
||||||
|
|
||||||
|
**Ziel:**
|
||||||
|
Ermöglichung von "Active Intelligence" durch asynchrone Verarbeitung und semantische Analyse im Hintergrund.
|
||||||
|
|
||||||
|
**Erreichte Ergebnisse:**
|
||||||
|
- **Async Core:** Umstellung der Pipeline auf `asyncio` und `httpx` (Vermeidung von Blockaden).
|
||||||
|
- **Nomic Embeddings:** Integration von `nomic-embed-text` (768 Dim) für State-of-the-Art Semantik.
|
||||||
|
- **Matrix Logic:** Regelwerk für kontextsensitive Kanten (`experience` + `value` -> `based_on`).
|
||||||
|
- **Sliding Window:** Analyse langer Texte für Link-Vorschläge.
|
||||||
|
- **Persistence API:** Neuer Endpunkt `/ingest/save` für atomares Speichern & Indizieren.
|
||||||
|
|
||||||
**Aufwand / Komplexität:**
|
**Aufwand / Komplexität:**
|
||||||
- Aufwand: Hoch
|
- Aufwand: Hoch
|
||||||
@@ -484,13 +517,73 @@ Aufräumen, dokumentieren, stabilisieren – insbesondere für Onboarding Dritte
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
### WP-15 – Smart Edge Allocation & Chunking Strategies (abgeschlossen)
|
||||||
|
|
||||||
|
**Phase:** D
|
||||||
|
**Status:** 🟢 abgeschlossen
|
||||||
|
|
||||||
|
**Ziel:**
|
||||||
|
Einführung einer intelligenten Verteilung von Wissenskanten an spezifische Text-Chunks, um die Präzision des Retrievals zu erhöhen, ohne die Stabilität des Systems durch lange LLM-Verarbeitungszeiten zu gefährden.
|
||||||
|
|
||||||
|
**Erreichte Ergebnisse:**
|
||||||
|
- **5-Stufen-Workflow:** Implementierung von "Smart Edge Allocation" (Global Scan -> Deterministic Split -> LLM Filter -> Injection -> Fallback).
|
||||||
|
- **Neue Chunking-Strategien:** Einführung von `by_heading` (für strukturierte Daten) und verbessertem `sliding_window` als deterministische Basis.
|
||||||
|
- **Robustheit:** Trennung von Zerlegung (Code) und Analyse (LLM). Bei LLM-Fehlern oder Timeouts greift ein Fallback-Mechanismus (Datenverlust ausgeschlossen).
|
||||||
|
- **Architektur:** Trennung der Orchestrierung (`chunker.py`) von der KI-Logik (`semantic_analyzer.py`).
|
||||||
|
- **Konfiguration:** Steuerung über `types.yaml` (`enable_smart_edge_allocation`) ermöglicht granulare Anpassung pro Notiztyp.
|
||||||
|
|
||||||
|
**Aufwand / Komplexität:**
|
||||||
|
- Aufwand: Mittel
|
||||||
|
- Komplexität: Hoch
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### WP-16 – Auto-Discovery & Enrichment (geplant)
|
||||||
|
|
||||||
|
**Phase:** D
|
||||||
|
**Status:** 🟡 geplant
|
||||||
|
|
||||||
|
**Ziel:**
|
||||||
|
Automatisches Erkennen und Vorschlagen von fehlenden Kanten in "dummem" Text (ohne explizite Wikilinks) vor der Speicherung. Umwandlung von Text in "smarten Text" durch Nutzung des `DiscoveryService`.
|
||||||
|
|
||||||
|
**Umfang:**
|
||||||
|
- Integration eines "Enrichers" in die Ingestion-Pipeline (Schritt 0).
|
||||||
|
- Unterscheidung zwischen "Hard Candidates" (explizite Links) und "Soft Candidates" (Vektor-basierte Vorschläge).
|
||||||
|
- LLM-basierte Verifikation der Vorschläge zur Vermeidung von Halluzinationen.
|
||||||
|
|
||||||
|
**Aufwand / Komplexität:**
|
||||||
|
- Aufwand: Mittel
|
||||||
|
- Komplexität: Hoch
|
||||||
|
|
||||||
|
---
|
||||||
|
### WP-17 – Conversational Memory (Dialog-Gedächtnis) (geplant)
|
||||||
|
|
||||||
|
**Phase:** D
|
||||||
|
**Status:** 🟡 geplant
|
||||||
|
|
||||||
|
**Ziel:**
|
||||||
|
Erweiterung des Chat-Backends von einem statischen Request-Response-Modell zu einem zustandsbehafteten Dialogsystem ("Multi-Turn Conversation"). Das System soll sich an vorherige Aussagen im aktuellen Gesprächsverlauf erinnern, um Rückfragen ("Was meinst du damit?") korrekt zu interpretieren.
|
||||||
|
|
||||||
|
**Umfang:**
|
||||||
|
- **API-Erweiterung:** `ChatRequest` DTO erhält ein `history`-Feld (Liste von Nachrichten).
|
||||||
|
- **Context Management:** Implementierung einer Token-Budget-Logik, die dynamisch zwischen RAG-Kontext (Dokumente) und Dialog-Verlauf (History) balanciert, um das Kontextfenster (8k) optimal zu nutzen.
|
||||||
|
- **Prompt Engineering:** Integration eines `{chat_history}` Platzhalters in den System-Prompt.
|
||||||
|
- **Frontend-Update:** Die `ui.py` muss die letzten N Nachrichtenpaare (User/AI) bei jedem Request mitsenden.
|
||||||
|
|
||||||
|
**Aufwand / Komplexität:**
|
||||||
|
- Aufwand: Mittel
|
||||||
|
- Komplexität: Mittel
|
||||||
|
---
|
||||||
## 7. Abhängigkeiten (vereinfacht, aktualisiert)
|
## 7. Abhängigkeiten (vereinfacht, aktualisiert)
|
||||||
|
|
||||||
WP01 → WP02 → WP03 → WP04a
|
WP01 → WP02 → WP03 → WP04a
|
||||||
WP04a → WP04b → WP04c → WP08
|
WP04a → WP04b → WP04c → WP08
|
||||||
WP03 → WP05 → WP06 → WP07
|
WP03 → WP05 → WP06 → WP07
|
||||||
|
WP07 → WP10a
|
||||||
WP03 → WP09
|
WP03 → WP09
|
||||||
WP01/WP03 → WP10 → WP11 → WP12
|
WP01/WP03 → WP10 → WP11 → WP12
|
||||||
|
WP10 → WP17
|
||||||
|
WP11 → WP15 → WP16
|
||||||
WP03/WP04 → WP13
|
WP03/WP04 → WP13
|
||||||
Alles → WP14
|
Alles → WP14
|
||||||
|
|
||||||
@@ -508,10 +601,14 @@ Aufräumen, dokumentieren, stabilisieren – insbesondere für Onboarding Dritte
|
|||||||
| WP08 | Hoch | Hoch |
|
| WP08 | Hoch | Hoch |
|
||||||
| WP09 | Mittel | Niedrig/Mittel |
|
| WP09 | Mittel | Niedrig/Mittel |
|
||||||
| WP10 | Hoch | Hoch |
|
| WP10 | Hoch | Hoch |
|
||||||
|
| WP10a | Mittel | Mittel |
|
||||||
| WP11 | Hoch | Hoch |
|
| WP11 | Hoch | Hoch |
|
||||||
| WP12 | Niedrig/Mittel | Mittel |
|
| WP12 | Niedrig/Mittel | Mittel |
|
||||||
| WP13 | Mittel | Mittel |
|
| WP13 | Mittel | Mittel |
|
||||||
| WP14 | Mittel | Niedrig/Mittel |
|
| WP14 | Mittel | Niedrig/Mittel |
|
||||||
|
| WP15 | Mittel | Hoch |
|
||||||
|
| WP16 | Mittel | Hoch |
|
||||||
|
| WP17 | Mittel | Mittel |
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -528,14 +625,18 @@ Aufräumen, dokumentieren, stabilisieren – insbesondere für Onboarding Dritte
|
|||||||
| WP05 | 🟢 |
|
| WP05 | 🟢 |
|
||||||
| WP05b | ⚪ |
|
| WP05b | ⚪ |
|
||||||
| WP06 | 🟢 |
|
| WP06 | 🟢 |
|
||||||
| WP07 | 🟡 |
|
| WP07 | 🟢 |
|
||||||
| WP08 | 🟡 |
|
| WP08 | 🟡 |
|
||||||
| WP09 | 🟡 |
|
| WP09 | 🟡 |
|
||||||
| WP10 | 🟡 |
|
| WP10 | 🟢 |
|
||||||
| WP11 | 🟡 |
|
| WP10a | 🟢 |
|
||||||
|
| WP11 | 🟢 |
|
||||||
| WP12 | 🟡 |
|
| WP12 | 🟡 |
|
||||||
| WP13 | 🟡 |
|
| WP13 | 🟡 |
|
||||||
| WP14 | 🟡 |
|
| WP14 | 🟡 |
|
||||||
|
| WP15 | 🟢 |
|
||||||
|
| WP16 | 🟡 |
|
||||||
|
| WP17 | 🟡 |
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -552,14 +653,16 @@ Aufräumen, dokumentieren, stabilisieren – insbesondere für Onboarding Dritte
|
|||||||
|
|
||||||
## 11. Executive Summary
|
## 11. Executive Summary
|
||||||
|
|
||||||
mindnet v2.2 ist so aufgesetzt, dass:
|
mindnet v2.4 ist so aufgesetzt, dass:
|
||||||
|
|
||||||
- du **schrittweise** Wissen erfassen kannst (Obsidian + Chat + später Interview-Assistent),
|
- du **schrittweise** Wissen erfassen kannst (Obsidian + Chat + Interview-Drafts),
|
||||||
- die Struktur **mitwächst**, ohne Retro-Massenarbeit im Vault,
|
- die Struktur **mitwächst**, ohne Retro-Massenarbeit im Vault,
|
||||||
- ein **hybrider Retriever** qualitativ hochwertige, erklärbare Antworten liefert,
|
- ein **hybrider Retriever** qualitativ hochwertige, erklärbare Antworten liefert,
|
||||||
- ein **Self-Healing- und Self-Tuning-Mechanismus** vorbereitet ist (durch WP-04c Feedback-Daten),
|
- ein **Self-Healing- und Self-Tuning-Mechanismus** vorbereitet ist (durch WP-04c Feedback-Daten),
|
||||||
- ein **Persönlichkeitsmodell** (Decision Engine, Empathie) existiert und den Tonfall situativ anpasst,
|
- ein **Persönlichkeitsmodell** (Decision Engine, Empathie) existiert und den Tonfall situativ anpasst,
|
||||||
|
- eine **grafische Oberfläche** (WP-10/10a) existiert, die komplexe Zusammenhänge visualisiert und Co-Creation ermöglicht,
|
||||||
|
- **Active Intelligence** (WP-11) dich beim Schreiben unterstützt, indem es automatisch Verknüpfungen vorschlägt,
|
||||||
- langfristig ein **KI-Zwilling** aufgebaut wird, der deine Werte, Erfahrungen und Denkweise spiegelt,
|
- langfristig ein **KI-Zwilling** aufgebaut wird, der deine Werte, Erfahrungen und Denkweise spiegelt,
|
||||||
- die technische Architektur (FastAPI, Qdrant, YAML-Policies, MCP-Integration) lokal, nachvollziehbar und erweiterbar bleibt.
|
- die technische Architektur (AsyncIO, Qdrant 768d, YAML-Policies) lokal, nachvollziehbar und performant bleibt.
|
||||||
|
|
||||||
Dieser Programmplan bildet die konsolidierte Grundlage (v2.3.1) für alle weiteren Arbeiten.
|
Dieser Programmplan bildet die konsolidierte Grundlage (v2.4.0) für alle weiteren Arbeiten.
|
||||||
@@ -1,13 +0,0 @@
|
|||||||
TYPE_SIZES = {
|
|
||||||
"thought": {"target": (150, 250), "max": 300, "overlap": (30, 40)},
|
|
||||||
"experience":{"target": (250, 350), "max": 450, "overlap": (40, 60)},
|
|
||||||
"journal": {"target": (200, 300), "max": 400, "overlap": (30, 50)},
|
|
||||||
"task": {"target": (120, 200), "max": 250, "overlap": (20, 30)},
|
|
||||||
"project": {"target": (300, 450), "max": 600, "overlap": (50, 70)},
|
|
||||||
"concept": {"target": (250, 400), "max": 550, "overlap": (40, 60)},
|
|
||||||
"source": {"target": (200, 350), "max": 500, "overlap": (30, 50)},
|
|
||||||
}
|
|
||||||
DEFAULT = {"target": (250, 350), "max": 500, "overlap": (40, 60)}
|
|
||||||
|
|
||||||
def get_sizes(note_type: str):
|
|
||||||
return TYPE_SIZES.get(str(note_type).lower(), DEFAULT)
|
|
||||||
@@ -5,6 +5,7 @@ app/core/chunk_payload.py (Mindnet V2 — types.yaml authoritative)
|
|||||||
- neighbors_prev / neighbors_next sind Listen ([], [id]).
|
- neighbors_prev / neighbors_next sind Listen ([], [id]).
|
||||||
- retriever_weight / chunk_profile kommen aus types.yaml (Frontmatter wird ignoriert).
|
- retriever_weight / chunk_profile kommen aus types.yaml (Frontmatter wird ignoriert).
|
||||||
- Fallbacks: defaults.* in types.yaml; sonst 1.0 / "default".
|
- Fallbacks: defaults.* in types.yaml; sonst 1.0 / "default".
|
||||||
|
- WP-11 Update: Injects 'title' into chunk payload for Discovery Service.
|
||||||
"""
|
"""
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
from typing import Any, Dict, List, Optional
|
from typing import Any, Dict, List, Optional
|
||||||
@@ -82,6 +83,11 @@ def make_chunk_payloads(note: Dict[str, Any],
|
|||||||
file_path: Optional[str] = None) -> List[Dict[str, Any]]:
|
file_path: Optional[str] = None) -> List[Dict[str, Any]]:
|
||||||
fm = (note or {}).get("frontmatter", {}) or {}
|
fm = (note or {}).get("frontmatter", {}) or {}
|
||||||
note_type = fm.get("type") or note.get("type") or "concept"
|
note_type = fm.get("type") or note.get("type") or "concept"
|
||||||
|
|
||||||
|
# WP-11 FIX: Title Extraction für Discovery Service
|
||||||
|
# Wir holen den Titel aus Frontmatter oder Fallback ID/Untitled
|
||||||
|
title = fm.get("title") or note.get("title") or fm.get("id") or "Untitled"
|
||||||
|
|
||||||
reg = types_cfg if isinstance(types_cfg, dict) else _load_types()
|
reg = types_cfg if isinstance(types_cfg, dict) else _load_types()
|
||||||
|
|
||||||
# types.yaml authoritative
|
# types.yaml authoritative
|
||||||
@@ -106,6 +112,7 @@ def make_chunk_payloads(note: Dict[str, Any],
|
|||||||
pl: Dict[str, Any] = {
|
pl: Dict[str, Any] = {
|
||||||
"note_id": nid,
|
"note_id": nid,
|
||||||
"chunk_id": cid,
|
"chunk_id": cid,
|
||||||
|
"title": title, # <--- HIER: Titel in Payload einfügen
|
||||||
"index": int(index),
|
"index": int(index),
|
||||||
"ord": int(index) + 1,
|
"ord": int(index) + 1,
|
||||||
"type": note_type,
|
"type": note_type,
|
||||||
@@ -126,4 +133,4 @@ def make_chunk_payloads(note: Dict[str, Any],
|
|||||||
|
|
||||||
out.append(pl)
|
out.append(pl)
|
||||||
|
|
||||||
return out
|
return out
|
||||||
+294
-190
@@ -1,226 +1,330 @@
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
from dataclasses import dataclass
|
from dataclasses import dataclass
|
||||||
from typing import List, Dict, Optional, Tuple
|
from typing import List, Dict, Optional, Tuple, Any, Set
|
||||||
import re
|
import re
|
||||||
import math
|
import math
|
||||||
|
import yaml
|
||||||
|
from pathlib import Path
|
||||||
from markdown_it import MarkdownIt
|
from markdown_it import MarkdownIt
|
||||||
from markdown_it.token import Token
|
from markdown_it.token import Token
|
||||||
from .chunk_config import get_sizes
|
import asyncio
|
||||||
|
import logging
|
||||||
|
|
||||||
# --- Hilfen ---
|
# Services
|
||||||
_SENT_SPLIT = re.compile(r'(?<=[.!?])\s+(?=[A-ZÄÖÜ0-9„(])')
|
from app.services.semantic_analyzer import get_semantic_analyzer
|
||||||
_WS = re.compile(r'\s+')
|
|
||||||
|
# Core Imports
|
||||||
|
try:
|
||||||
|
from app.core.derive_edges import build_edges_for_note
|
||||||
|
except ImportError:
|
||||||
|
# Mock für Tests
|
||||||
|
def build_edges_for_note(note_id, chunks, note_level_references=None, include_note_scope_refs=False): return []
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
# ==========================================
|
||||||
|
# 1. HELPER & CONFIG
|
||||||
|
# ==========================================
|
||||||
|
|
||||||
|
BASE_DIR = Path(__file__).resolve().parent.parent.parent
|
||||||
|
CONFIG_PATH = BASE_DIR / "config" / "types.yaml"
|
||||||
|
DEFAULT_PROFILE = {"strategy": "sliding_window", "target": 400, "max": 600, "overlap": (50, 80)}
|
||||||
|
_CONFIG_CACHE = None
|
||||||
|
|
||||||
|
def _load_yaml_config() -> Dict[str, Any]:
|
||||||
|
global _CONFIG_CACHE
|
||||||
|
if _CONFIG_CACHE is not None: return _CONFIG_CACHE
|
||||||
|
if not CONFIG_PATH.exists(): return {}
|
||||||
|
try:
|
||||||
|
with open(CONFIG_PATH, "r", encoding="utf-8") as f:
|
||||||
|
data = yaml.safe_load(f)
|
||||||
|
_CONFIG_CACHE = data
|
||||||
|
return data
|
||||||
|
except Exception: return {}
|
||||||
|
|
||||||
|
def get_chunk_config(note_type: str) -> Dict[str, Any]:
|
||||||
|
full_config = _load_yaml_config()
|
||||||
|
profiles = full_config.get("chunking_profiles", {})
|
||||||
|
type_def = full_config.get("types", {}).get(note_type.lower(), {})
|
||||||
|
profile_name = type_def.get("chunking_profile")
|
||||||
|
if not profile_name:
|
||||||
|
profile_name = full_config.get("defaults", {}).get("chunking_profile", "sliding_standard")
|
||||||
|
|
||||||
|
config = profiles.get(profile_name, DEFAULT_PROFILE).copy()
|
||||||
|
if "overlap" in config and isinstance(config["overlap"], list):
|
||||||
|
config["overlap"] = tuple(config["overlap"])
|
||||||
|
return config
|
||||||
|
|
||||||
|
def extract_frontmatter_from_text(md_text: str) -> Tuple[Dict[str, Any], str]:
|
||||||
|
fm_match = re.match(r'^\s*---\s*\n(.*?)\n---', md_text, re.DOTALL)
|
||||||
|
if not fm_match: return {}, md_text
|
||||||
|
try:
|
||||||
|
frontmatter = yaml.safe_load(fm_match.group(1))
|
||||||
|
if not isinstance(frontmatter, dict): frontmatter = {}
|
||||||
|
except yaml.YAMLError:
|
||||||
|
frontmatter = {}
|
||||||
|
text_without_fm = re.sub(r'^\s*---\s*\n(.*?)\n---', '', md_text, flags=re.DOTALL)
|
||||||
|
return frontmatter, text_without_fm.strip()
|
||||||
|
|
||||||
|
# ==========================================
|
||||||
|
# 2. DATA CLASSES
|
||||||
|
# ==========================================
|
||||||
|
|
||||||
|
_SENT_SPLIT = re.compile(r'(?<=[.!?])\s+(?=[A-ZÄÖÜ0-9„(])'); _WS = re.compile(r'\s+')
|
||||||
|
|
||||||
def estimate_tokens(text: str) -> int:
|
def estimate_tokens(text: str) -> int:
|
||||||
# leichte Approximation: 1 Token ≈ 4 Zeichen; robust + schnell
|
return max(1, math.ceil(len(text.strip()) / 4))
|
||||||
t = len(text.strip())
|
|
||||||
return max(1, math.ceil(t / 4))
|
|
||||||
|
|
||||||
def split_sentences(text: str) -> list[str]:
|
def split_sentences(text: str) -> list[str]:
|
||||||
text = _WS.sub(' ', text.strip())
|
text = _WS.sub(' ', text.strip())
|
||||||
if not text:
|
if not text: return []
|
||||||
return []
|
|
||||||
parts = _SENT_SPLIT.split(text)
|
parts = _SENT_SPLIT.split(text)
|
||||||
return [p.strip() for p in parts if p.strip()]
|
return [p.strip() for p in parts if p.strip()]
|
||||||
|
|
||||||
@dataclass
|
@dataclass
|
||||||
class RawBlock:
|
class RawBlock:
|
||||||
kind: str # "heading" | "paragraph" | "list" | "code" | "table" | "thematic_break" | "blockquote"
|
kind: str; text: str; level: Optional[int]; section_path: str; section_title: Optional[str]
|
||||||
text: str
|
|
||||||
level: Optional[int] # heading level (2,3,...) or None
|
|
||||||
section_path: str # e.g., "/H2 Title/H3 Subtitle"
|
|
||||||
|
|
||||||
@dataclass
|
@dataclass
|
||||||
class Chunk:
|
class Chunk:
|
||||||
id: str
|
id: str; note_id: str; index: int; text: str; window: str; token_count: int
|
||||||
note_id: str
|
section_title: Optional[str]; section_path: str
|
||||||
index: int
|
neighbors_prev: Optional[str]; neighbors_next: Optional[str]
|
||||||
text: str
|
suggested_edges: Optional[List[str]] = None
|
||||||
token_count: int
|
|
||||||
section_title: Optional[str]
|
|
||||||
section_path: str
|
|
||||||
neighbors_prev: Optional[str]
|
|
||||||
neighbors_next: Optional[str]
|
|
||||||
char_start: int
|
|
||||||
char_end: int
|
|
||||||
|
|
||||||
# --- Markdown zu RawBlocks: H2/H3 als Sections, andere Blöcke gruppiert ---
|
# ==========================================
|
||||||
def parse_blocks(md_text: str) -> List[RawBlock]:
|
# 3. PARSING & STRATEGIES (SYNCHRON)
|
||||||
md = MarkdownIt("commonmark").enable("table")
|
# ==========================================
|
||||||
tokens: List[Token] = md.parse(md_text)
|
|
||||||
|
|
||||||
blocks: List[RawBlock] = []
|
def parse_blocks(md_text: str) -> Tuple[List[RawBlock], str]:
|
||||||
h2, h3 = None, None
|
"""Zerlegt Text in logische Blöcke (Absätze, Header)."""
|
||||||
|
blocks = []
|
||||||
|
h1_title = "Dokument"
|
||||||
section_path = "/"
|
section_path = "/"
|
||||||
cur_text = []
|
current_h2 = None
|
||||||
cur_kind = None
|
|
||||||
|
fm, text_without_fm = extract_frontmatter_from_text(md_text)
|
||||||
|
|
||||||
|
h1_match = re.search(r'^#\s+(.*)', text_without_fm, re.MULTILINE)
|
||||||
|
if h1_match:
|
||||||
|
h1_title = h1_match.group(1).strip()
|
||||||
|
|
||||||
def push(kind: str, txt: str, lvl: Optional[int]):
|
lines = text_without_fm.split('\n')
|
||||||
nonlocal section_path
|
buffer = []
|
||||||
txt = txt.strip()
|
|
||||||
if not txt:
|
for line in lines:
|
||||||
return
|
stripped = line.strip()
|
||||||
title = None
|
if stripped.startswith('# '):
|
||||||
if kind == "heading" and lvl:
|
continue
|
||||||
title = txt
|
elif stripped.startswith('## '):
|
||||||
blocks.append(RawBlock(kind=kind, text=txt, level=lvl, section_path=section_path))
|
if buffer:
|
||||||
|
content = "\n".join(buffer).strip()
|
||||||
i = 0
|
if content:
|
||||||
while i < len(tokens):
|
blocks.append(RawBlock("paragraph", content, None, section_path, current_h2))
|
||||||
t = tokens[i]
|
buffer = []
|
||||||
if t.type == "heading_open":
|
current_h2 = stripped[3:].strip()
|
||||||
lvl = int(t.tag[1])
|
section_path = f"/{current_h2}"
|
||||||
# Sammle heading inline
|
blocks.append(RawBlock("heading", stripped, 2, section_path, current_h2))
|
||||||
i += 1
|
elif not stripped:
|
||||||
title_txt = ""
|
if buffer:
|
||||||
while i < len(tokens) and tokens[i].type != "heading_close":
|
content = "\n".join(buffer).strip()
|
||||||
if tokens[i].type == "inline":
|
if content:
|
||||||
title_txt += tokens[i].content
|
blocks.append(RawBlock("paragraph", content, None, section_path, current_h2))
|
||||||
i += 1
|
buffer = []
|
||||||
title_txt = title_txt.strip()
|
|
||||||
# Section-Pfad aktualisieren
|
|
||||||
if lvl == 2:
|
|
||||||
h2, h3 = title_txt, None
|
|
||||||
section_path = f"/{h2}"
|
|
||||||
elif lvl == 3:
|
|
||||||
h3 = title_txt
|
|
||||||
section_path = f"/{h2}/{h3}" if h2 else f"/{h3}"
|
|
||||||
push("heading", title_txt, lvl)
|
|
||||||
elif t.type in ("paragraph_open", "bullet_list_open", "ordered_list_open",
|
|
||||||
"fence", "code_block", "blockquote_open", "table_open", "hr"):
|
|
||||||
kind = {
|
|
||||||
"paragraph_open": "paragraph",
|
|
||||||
"bullet_list_open": "list",
|
|
||||||
"ordered_list_open": "list",
|
|
||||||
"fence": "code",
|
|
||||||
"code_block": "code",
|
|
||||||
"blockquote_open": "blockquote",
|
|
||||||
"table_open": "table",
|
|
||||||
"hr": "thematic_break",
|
|
||||||
}[t.type]
|
|
||||||
|
|
||||||
if t.type in ("fence", "code_block"):
|
|
||||||
# Codeblock hat eigenen content im selben Token
|
|
||||||
content = t.content or ""
|
|
||||||
push(kind, content, None)
|
|
||||||
else:
|
|
||||||
# inline sammeln bis close
|
|
||||||
content = ""
|
|
||||||
i += 1
|
|
||||||
depth = 1
|
|
||||||
while i < len(tokens) and depth > 0:
|
|
||||||
tk = tokens[i]
|
|
||||||
if tk.type.endswith("_open"):
|
|
||||||
depth += 1
|
|
||||||
elif tk.type.endswith("_close"):
|
|
||||||
depth -= 1
|
|
||||||
elif tk.type == "inline":
|
|
||||||
content += tk.content
|
|
||||||
i += 1
|
|
||||||
push(kind, content, None)
|
|
||||||
continue # wir sind schon auf nächstem Token
|
|
||||||
i += 1
|
|
||||||
|
|
||||||
return blocks
|
|
||||||
|
|
||||||
def assemble_chunks(note_id: str, md_text: str, note_type: str) -> List[Chunk]:
|
|
||||||
sizes = get_sizes(note_type)
|
|
||||||
target = sum(sizes["target"]) // 2 # mittlerer Zielwert
|
|
||||||
max_tokens = sizes["max"]
|
|
||||||
ov_min, ov_max = sizes["overlap"]
|
|
||||||
overlap = (ov_min + ov_max) // 2
|
|
||||||
|
|
||||||
blocks = parse_blocks(md_text)
|
|
||||||
|
|
||||||
chunks: List[Chunk] = []
|
|
||||||
buf: List[Tuple[str, str, str]] = [] # (text, section_title, section_path)
|
|
||||||
char_pos = 0
|
|
||||||
|
|
||||||
def flush_buffer(force=False):
|
|
||||||
nonlocal buf, chunks, char_pos
|
|
||||||
if not buf:
|
|
||||||
return
|
|
||||||
text = "\n\n".join([b[0] for b in buf]).strip()
|
|
||||||
if not text:
|
|
||||||
buf = []
|
|
||||||
return
|
|
||||||
|
|
||||||
# Wenn zu groß, satzbasiert weich umbrechen
|
|
||||||
toks = estimate_tokens(text)
|
|
||||||
if toks > max_tokens:
|
|
||||||
sentences = split_sentences(text)
|
|
||||||
cur = []
|
|
||||||
cur_tokens = 0
|
|
||||||
for s in sentences:
|
|
||||||
st = estimate_tokens(s)
|
|
||||||
if cur_tokens + st > target and cur:
|
|
||||||
_emit("\n".join(cur))
|
|
||||||
# Overlap: letzte Sätze wiederverwenden
|
|
||||||
ov_text = " ".join(cur)[-overlap*4:] # 4 chars/token Heuristik
|
|
||||||
cur = [ov_text, s] if ov_text else [s]
|
|
||||||
cur_tokens = estimate_tokens(" ".join(cur))
|
|
||||||
else:
|
|
||||||
cur.append(s)
|
|
||||||
cur_tokens += st
|
|
||||||
if cur:
|
|
||||||
_emit("\n".join(cur))
|
|
||||||
else:
|
else:
|
||||||
_emit(text)
|
buffer.append(line)
|
||||||
|
|
||||||
|
if buffer:
|
||||||
|
content = "\n".join(buffer).strip()
|
||||||
|
if content:
|
||||||
|
blocks.append(RawBlock("paragraph", content, None, section_path, current_h2))
|
||||||
|
|
||||||
|
return blocks, h1_title
|
||||||
|
|
||||||
|
def _strategy_sliding_window(blocks: List[RawBlock], config: Dict[str, Any], note_id: str, doc_title: str = "", context_prefix: str = "") -> List[Chunk]:
|
||||||
|
target = config.get("target", 400)
|
||||||
|
max_tokens = config.get("max", 600)
|
||||||
|
overlap_val = config.get("overlap", (50, 80))
|
||||||
|
overlap = sum(overlap_val) // 2 if isinstance(overlap_val, tuple) else overlap_val
|
||||||
|
chunks = []; buf = []
|
||||||
|
|
||||||
|
def _create_chunk(txt, win, sec, path):
|
||||||
|
idx = len(chunks)
|
||||||
|
chunks.append(Chunk(
|
||||||
|
id=f"{note_id}#c{idx:02d}", note_id=note_id, index=idx,
|
||||||
|
text=txt, window=win, token_count=estimate_tokens(txt),
|
||||||
|
section_title=sec, section_path=path, neighbors_prev=None, neighbors_next=None,
|
||||||
|
suggested_edges=[]
|
||||||
|
))
|
||||||
|
|
||||||
|
def flush_buffer():
|
||||||
|
nonlocal buf
|
||||||
|
if not buf: return
|
||||||
|
|
||||||
|
text_body = "\n\n".join([b.text for b in buf])
|
||||||
|
win_body = f"{context_prefix}\n{text_body}".strip() if context_prefix else text_body
|
||||||
|
|
||||||
|
if estimate_tokens(text_body) <= max_tokens:
|
||||||
|
_create_chunk(text_body, win_body, buf[-1].section_title, buf[-1].section_path)
|
||||||
|
else:
|
||||||
|
sentences = split_sentences(text_body)
|
||||||
|
current_chunk_sents = []
|
||||||
|
current_len = 0
|
||||||
|
|
||||||
|
for sent in sentences:
|
||||||
|
sent_len = estimate_tokens(sent)
|
||||||
|
if current_len + sent_len > target and current_chunk_sents:
|
||||||
|
c_txt = " ".join(current_chunk_sents)
|
||||||
|
c_win = f"{context_prefix}\n{c_txt}".strip() if context_prefix else c_txt
|
||||||
|
_create_chunk(c_txt, c_win, buf[-1].section_title, buf[-1].section_path)
|
||||||
|
|
||||||
|
overlap_sents = []
|
||||||
|
ov_len = 0
|
||||||
|
for s in reversed(current_chunk_sents):
|
||||||
|
if ov_len + estimate_tokens(s) < overlap:
|
||||||
|
overlap_sents.insert(0, s)
|
||||||
|
ov_len += estimate_tokens(s)
|
||||||
|
else:
|
||||||
|
break
|
||||||
|
|
||||||
|
current_chunk_sents = list(overlap_sents)
|
||||||
|
current_chunk_sents.append(sent)
|
||||||
|
current_len = ov_len + sent_len
|
||||||
|
else:
|
||||||
|
current_chunk_sents.append(sent)
|
||||||
|
current_len += sent_len
|
||||||
|
|
||||||
|
if current_chunk_sents:
|
||||||
|
c_txt = " ".join(current_chunk_sents)
|
||||||
|
c_win = f"{context_prefix}\n{c_txt}".strip() if context_prefix else c_txt
|
||||||
|
_create_chunk(c_txt, c_win, buf[-1].section_title, buf[-1].section_path)
|
||||||
|
|
||||||
buf = []
|
buf = []
|
||||||
|
|
||||||
def _emit(text_block: str):
|
|
||||||
nonlocal chunks, char_pos
|
|
||||||
idx = len(chunks)
|
|
||||||
chunk_id = f"{note_id}#c{idx:02d}"
|
|
||||||
token_count = estimate_tokens(text_block)
|
|
||||||
# section aus letztem buffer-entry ableiten
|
|
||||||
sec_title = buf[-1][1] if buf else None
|
|
||||||
sec_path = buf[-1][2] if buf else "/"
|
|
||||||
start = char_pos
|
|
||||||
end = start + len(text_block)
|
|
||||||
chunks.append(Chunk(
|
|
||||||
id=chunk_id,
|
|
||||||
note_id=note_id,
|
|
||||||
index=idx,
|
|
||||||
text=text_block,
|
|
||||||
token_count=token_count,
|
|
||||||
section_title=sec_title,
|
|
||||||
section_path=sec_path,
|
|
||||||
neighbors_prev=None,
|
|
||||||
neighbors_next=None,
|
|
||||||
char_start=start,
|
|
||||||
char_end=end
|
|
||||||
))
|
|
||||||
char_pos = end + 1
|
|
||||||
|
|
||||||
# Blocks in Puffer sammeln; bei Überschreiten Zielbereich flushen
|
|
||||||
cur_sec_title = None
|
|
||||||
for b in blocks:
|
for b in blocks:
|
||||||
if b.kind == "heading" and b.level in (2, 3):
|
if b.kind == "heading": continue
|
||||||
# Sectionwechsel ⇒ Buffer flushen
|
current_buf_text = "\n\n".join([x.text for x in buf])
|
||||||
|
if estimate_tokens(current_buf_text) + estimate_tokens(b.text) >= target:
|
||||||
flush_buffer()
|
flush_buffer()
|
||||||
cur_sec_title = b.text.strip()
|
buf.append(b)
|
||||||
# Heading selbst nicht als Chunk, aber als Kontexttitel nutzen
|
if estimate_tokens(b.text) >= target:
|
||||||
continue
|
|
||||||
|
|
||||||
txt = b.text.strip()
|
|
||||||
if not txt:
|
|
||||||
continue
|
|
||||||
|
|
||||||
tentative = "\n\n".join([*(x[0] for x in buf), txt]).strip()
|
|
||||||
if estimate_tokens(tentative) > max(get_sizes(note_type)["target"]):
|
|
||||||
# weicher Schnitt vor Hinzufügen
|
|
||||||
flush_buffer()
|
|
||||||
buf.append((txt, cur_sec_title, b.section_path))
|
|
||||||
|
|
||||||
# bei Erreichen ~Target flushen
|
|
||||||
if estimate_tokens("\n\n".join([x[0] for x in buf])) >= target:
|
|
||||||
flush_buffer()
|
flush_buffer()
|
||||||
|
|
||||||
flush_buffer(force=True)
|
flush_buffer()
|
||||||
|
return chunks
|
||||||
|
|
||||||
|
def _strategy_by_heading(blocks: List[RawBlock], config: Dict[str, Any], note_id: str, doc_title: str = "") -> List[Chunk]:
|
||||||
|
return _strategy_sliding_window(blocks, config, note_id, doc_title, context_prefix=f"# {doc_title}")
|
||||||
|
|
||||||
|
# ==========================================
|
||||||
|
# 4. ORCHESTRATION (ASYNC) - WP-15 CORE
|
||||||
|
# ==========================================
|
||||||
|
|
||||||
|
async def assemble_chunks(note_id: str, md_text: str, note_type: str, config: Optional[Dict] = None) -> List[Chunk]:
|
||||||
|
if config is None:
|
||||||
|
config = get_chunk_config(note_type)
|
||||||
|
|
||||||
|
fm, body_text = extract_frontmatter_from_text(md_text)
|
||||||
|
note_status = fm.get("status", "").lower()
|
||||||
|
|
||||||
|
primary_strategy = config.get("strategy", "sliding_window")
|
||||||
|
enable_smart_edges = config.get("enable_smart_edge_allocation", False)
|
||||||
|
|
||||||
|
if enable_smart_edges and note_status in ["draft", "initial_gen"]:
|
||||||
|
logger.info(f"Chunker: Skipping Smart Edges for draft '{note_id}'.")
|
||||||
|
enable_smart_edges = False
|
||||||
|
|
||||||
|
blocks, doc_title = parse_blocks(md_text)
|
||||||
|
|
||||||
|
if primary_strategy == "by_heading":
|
||||||
|
chunks = await asyncio.to_thread(_strategy_by_heading, blocks, config, note_id, doc_title)
|
||||||
|
else:
|
||||||
|
chunks = await asyncio.to_thread(_strategy_sliding_window, blocks, config, note_id, doc_title)
|
||||||
|
|
||||||
|
if not chunks:
|
||||||
|
return []
|
||||||
|
|
||||||
|
if enable_smart_edges:
|
||||||
|
# Hier rufen wir nun die Smart Edge Allocation auf
|
||||||
|
chunks = await _run_smart_edge_allocation(chunks, md_text, note_id, note_type)
|
||||||
|
|
||||||
# neighbors setzen
|
|
||||||
for i, ch in enumerate(chunks):
|
for i, ch in enumerate(chunks):
|
||||||
ch.neighbors_prev = chunks[i-1].id if i > 0 else None
|
ch.neighbors_prev = chunks[i-1].id if i > 0 else None
|
||||||
ch.neighbors_next = chunks[i+1].id if i < len(chunks)-1 else None
|
ch.neighbors_next = chunks[i+1].id if i < len(chunks)-1 else None
|
||||||
|
|
||||||
return chunks
|
return chunks
|
||||||
|
|
||||||
|
def _extract_all_edges_from_md(md_text: str, note_id: str, note_type: str) -> List[str]:
|
||||||
|
"""
|
||||||
|
Hilfsfunktion: Erstellt einen Dummy-Chunk für den gesamten Text und ruft
|
||||||
|
den Edge-Parser auf, um ALLE Kanten der Notiz zu finden.
|
||||||
|
"""
|
||||||
|
# 1. Dummy Chunk erstellen, der den gesamten Text enthält
|
||||||
|
# Das ist notwendig, da build_edges_for_note Kanten nur aus Chunks extrahiert.
|
||||||
|
dummy_chunk = {
|
||||||
|
"chunk_id": f"{note_id}#full",
|
||||||
|
"text": md_text,
|
||||||
|
"content": md_text, # Sicherstellen, dass der Parser Text findet
|
||||||
|
"window": md_text,
|
||||||
|
"type": note_type
|
||||||
|
}
|
||||||
|
|
||||||
|
# 2. Aufruf des Parsers (Signatur-Fix!)
|
||||||
|
# derive_edges.py: build_edges_for_note(note_id, chunks, note_level_references=None, include_note_scope_refs=False)
|
||||||
|
raw_edges = build_edges_for_note(
|
||||||
|
note_id,
|
||||||
|
[dummy_chunk],
|
||||||
|
note_level_references=None,
|
||||||
|
include_note_scope_refs=False
|
||||||
|
)
|
||||||
|
|
||||||
|
# 3. Kanten extrahieren
|
||||||
|
all_candidates = set()
|
||||||
|
for e in raw_edges:
|
||||||
|
kind = e.get("kind")
|
||||||
|
target = e.get("target_id")
|
||||||
|
if target and kind not in ["belongs_to", "next", "prev", "backlink"]:
|
||||||
|
all_candidates.add(f"{kind}:{target}")
|
||||||
|
|
||||||
|
return list(all_candidates)
|
||||||
|
|
||||||
|
async def _run_smart_edge_allocation(chunks: List[Chunk], full_text: str, note_id: str, note_type: str) -> List[Chunk]:
|
||||||
|
analyzer = get_semantic_analyzer()
|
||||||
|
|
||||||
|
# A. Alle potenziellen Kanten der Notiz sammeln (über den Dummy-Chunk Trick)
|
||||||
|
candidate_list = _extract_all_edges_from_md(full_text, note_id, note_type)
|
||||||
|
|
||||||
|
if not candidate_list:
|
||||||
|
return chunks
|
||||||
|
|
||||||
|
# B. LLM Filterung pro Chunk (Parallel)
|
||||||
|
tasks = []
|
||||||
|
for chunk in chunks:
|
||||||
|
tasks.append(analyzer.assign_edges_to_chunk(chunk.text, candidate_list, note_type))
|
||||||
|
|
||||||
|
results_per_chunk = await asyncio.gather(*tasks)
|
||||||
|
|
||||||
|
# C. Injection & Fallback
|
||||||
|
assigned_edges_global = set()
|
||||||
|
|
||||||
|
for i, confirmed_edges in enumerate(results_per_chunk):
|
||||||
|
chunk = chunks[i]
|
||||||
|
chunk.suggested_edges = confirmed_edges
|
||||||
|
assigned_edges_global.update(confirmed_edges)
|
||||||
|
|
||||||
|
if confirmed_edges:
|
||||||
|
injection_str = "\n" + " ".join([f"[[rel:{e.split(':')[0]}|{e.split(':')[1]}]]" for e in confirmed_edges if ':' in e])
|
||||||
|
chunk.text += injection_str
|
||||||
|
chunk.window += injection_str
|
||||||
|
|
||||||
|
# D. Fallback: Unassigned Kanten überall hin
|
||||||
|
unassigned = set(candidate_list) - assigned_edges_global
|
||||||
|
if unassigned:
|
||||||
|
fallback_str = "\n" + " ".join([f"[[rel:{e.split(':')[0]}|{e.split(':')[1]}]]" for e in unassigned if ':' in e])
|
||||||
|
for chunk in chunks:
|
||||||
|
chunk.text += fallback_str
|
||||||
|
chunk.window += fallback_str
|
||||||
|
if chunk.suggested_edges is None: chunk.suggested_edges = []
|
||||||
|
chunk.suggested_edges.extend(list(unassigned))
|
||||||
|
|
||||||
|
return chunks
|
||||||
@@ -0,0 +1,305 @@
|
|||||||
|
"""
|
||||||
|
app/core/ingestion.py
|
||||||
|
|
||||||
|
Zentraler Service für die Transformation von Markdown-Dateien in Qdrant-Objekte.
|
||||||
|
Version: 2.5.2 (Full Feature: Change Detection + Robust IO + Clean Config)
|
||||||
|
"""
|
||||||
|
import os
|
||||||
|
import logging
|
||||||
|
import asyncio
|
||||||
|
import time
|
||||||
|
from typing import Dict, List, Optional, Tuple, Any
|
||||||
|
|
||||||
|
# Core Module Imports
|
||||||
|
from app.core.parser import (
|
||||||
|
read_markdown,
|
||||||
|
normalize_frontmatter,
|
||||||
|
validate_required_frontmatter,
|
||||||
|
)
|
||||||
|
from app.core.note_payload import make_note_payload
|
||||||
|
from app.core.chunker import assemble_chunks, get_chunk_config
|
||||||
|
from app.core.chunk_payload import make_chunk_payloads
|
||||||
|
|
||||||
|
# Fallback für Edges
|
||||||
|
try:
|
||||||
|
from app.core.derive_edges import build_edges_for_note
|
||||||
|
except ImportError:
|
||||||
|
def build_edges_for_note(*args, **kwargs): return []
|
||||||
|
|
||||||
|
from app.core.qdrant import QdrantConfig, get_client, ensure_collections, ensure_payload_indexes
|
||||||
|
from app.core.qdrant_points import (
|
||||||
|
points_for_chunks,
|
||||||
|
points_for_note,
|
||||||
|
points_for_edges,
|
||||||
|
upsert_batch,
|
||||||
|
)
|
||||||
|
|
||||||
|
from app.services.embeddings_client import EmbeddingsClient
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
# --- Helper ---
|
||||||
|
def load_type_registry(custom_path: Optional[str] = None) -> dict:
|
||||||
|
import yaml
|
||||||
|
path = custom_path or os.getenv("MINDNET_TYPES_FILE", "config/types.yaml")
|
||||||
|
if not os.path.exists(path): return {}
|
||||||
|
try:
|
||||||
|
with open(path, "r", encoding="utf-8") as f: return yaml.safe_load(f) or {}
|
||||||
|
except Exception: return {}
|
||||||
|
|
||||||
|
def resolve_note_type(requested: Optional[str], reg: dict) -> str:
|
||||||
|
types = reg.get("types", {})
|
||||||
|
if requested and requested in types: return requested
|
||||||
|
return "concept"
|
||||||
|
|
||||||
|
def effective_chunk_profile(note_type: str, reg: dict) -> str:
|
||||||
|
t_cfg = reg.get("types", {}).get(note_type, {})
|
||||||
|
if t_cfg and t_cfg.get("chunk_profile"):
|
||||||
|
return t_cfg.get("chunk_profile")
|
||||||
|
return reg.get("defaults", {}).get("chunk_profile", "default")
|
||||||
|
|
||||||
|
def effective_retriever_weight(note_type: str, reg: dict) -> float:
|
||||||
|
t_cfg = reg.get("types", {}).get(note_type, {})
|
||||||
|
if t_cfg and "retriever_weight" in t_cfg:
|
||||||
|
return float(t_cfg["retriever_weight"])
|
||||||
|
return float(reg.get("defaults", {}).get("retriever_weight", 1.0))
|
||||||
|
|
||||||
|
|
||||||
|
class IngestionService:
|
||||||
|
def __init__(self, collection_prefix: str = None):
|
||||||
|
env_prefix = os.getenv("COLLECTION_PREFIX", "mindnet")
|
||||||
|
self.prefix = collection_prefix or env_prefix
|
||||||
|
|
||||||
|
self.cfg = QdrantConfig.from_env()
|
||||||
|
self.cfg.prefix = self.prefix
|
||||||
|
self.client = get_client(self.cfg)
|
||||||
|
self.dim = self.cfg.dim
|
||||||
|
self.registry = load_type_registry()
|
||||||
|
self.embedder = EmbeddingsClient()
|
||||||
|
|
||||||
|
try:
|
||||||
|
ensure_collections(self.client, self.prefix, self.dim)
|
||||||
|
ensure_payload_indexes(self.client, self.prefix)
|
||||||
|
except Exception as e:
|
||||||
|
logger.warning(f"DB init warning: {e}")
|
||||||
|
|
||||||
|
async def process_file(
|
||||||
|
self,
|
||||||
|
file_path: str,
|
||||||
|
vault_root: str,
|
||||||
|
force_replace: bool = False,
|
||||||
|
apply: bool = False,
|
||||||
|
purge_before: bool = False,
|
||||||
|
note_scope_refs: bool = False,
|
||||||
|
hash_mode: str = "body",
|
||||||
|
hash_source: str = "parsed",
|
||||||
|
hash_normalize: str = "canonical"
|
||||||
|
) -> Dict[str, Any]:
|
||||||
|
"""
|
||||||
|
Verarbeitet eine einzelne Datei (ASYNC).
|
||||||
|
Inklusive Change Detection (Hash-Check) gegen Qdrant.
|
||||||
|
"""
|
||||||
|
result = {
|
||||||
|
"path": file_path,
|
||||||
|
"status": "skipped",
|
||||||
|
"changed": False,
|
||||||
|
"error": None
|
||||||
|
}
|
||||||
|
|
||||||
|
# 1. Parse & Frontmatter Validation
|
||||||
|
try:
|
||||||
|
parsed = read_markdown(file_path)
|
||||||
|
if not parsed:
|
||||||
|
return {**result, "error": "Empty or unreadable file"}
|
||||||
|
|
||||||
|
fm = normalize_frontmatter(parsed.frontmatter)
|
||||||
|
validate_required_frontmatter(fm)
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"Validation failed for {file_path}: {e}")
|
||||||
|
return {**result, "error": f"Validation failed: {str(e)}"}
|
||||||
|
|
||||||
|
# 2. Type & Config Resolution
|
||||||
|
note_type = resolve_note_type(fm.get("type"), self.registry)
|
||||||
|
fm["type"] = note_type
|
||||||
|
fm["chunk_profile"] = effective_chunk_profile(note_type, self.registry)
|
||||||
|
|
||||||
|
weight = fm.get("retriever_weight")
|
||||||
|
if weight is None:
|
||||||
|
weight = effective_retriever_weight(note_type, self.registry)
|
||||||
|
fm["retriever_weight"] = float(weight)
|
||||||
|
|
||||||
|
# 3. Build Note Payload
|
||||||
|
try:
|
||||||
|
note_pl = make_note_payload(
|
||||||
|
parsed,
|
||||||
|
vault_root=vault_root,
|
||||||
|
hash_mode=hash_mode,
|
||||||
|
hash_normalize=hash_normalize,
|
||||||
|
hash_source=hash_source,
|
||||||
|
file_path=file_path
|
||||||
|
)
|
||||||
|
if not note_pl.get("fulltext"):
|
||||||
|
note_pl["fulltext"] = getattr(parsed, "body", "") or ""
|
||||||
|
note_pl["retriever_weight"] = fm["retriever_weight"]
|
||||||
|
|
||||||
|
note_id = note_pl["note_id"]
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"Payload build failed: {e}")
|
||||||
|
return {**result, "error": f"Payload build failed: {str(e)}"}
|
||||||
|
|
||||||
|
# 4. Change Detection (Das fehlende Stück!)
|
||||||
|
old_payload = None
|
||||||
|
if not force_replace:
|
||||||
|
old_payload = self._fetch_note_payload(note_id)
|
||||||
|
|
||||||
|
has_old = old_payload is not None
|
||||||
|
key_current = f"{hash_mode}:{hash_source}:{hash_normalize}"
|
||||||
|
old_hash = (old_payload or {}).get("hashes", {}).get(key_current)
|
||||||
|
new_hash = note_pl.get("hashes", {}).get(key_current)
|
||||||
|
|
||||||
|
hash_changed = (old_hash != new_hash)
|
||||||
|
chunks_missing, edges_missing = self._artifacts_missing(note_id)
|
||||||
|
|
||||||
|
should_write = force_replace or (not has_old) or hash_changed or chunks_missing or edges_missing
|
||||||
|
|
||||||
|
if not should_write:
|
||||||
|
return {**result, "status": "unchanged", "note_id": note_id}
|
||||||
|
|
||||||
|
if not apply:
|
||||||
|
return {**result, "status": "dry-run", "changed": True, "note_id": note_id}
|
||||||
|
|
||||||
|
# 5. Processing (Chunking, Embedding, Edges)
|
||||||
|
try:
|
||||||
|
body_text = getattr(parsed, "body", "") or ""
|
||||||
|
|
||||||
|
# --- Config Loading (Clean) ---
|
||||||
|
chunk_config = get_chunk_config(note_type)
|
||||||
|
# Hier greift die Logik aus types.yaml (smart=True/False)
|
||||||
|
|
||||||
|
chunks = await assemble_chunks(fm["id"], body_text, fm["type"], config=chunk_config)
|
||||||
|
chunk_pls = make_chunk_payloads(fm, note_pl["path"], chunks, note_text=body_text)
|
||||||
|
|
||||||
|
# Embedding
|
||||||
|
vecs = []
|
||||||
|
if chunk_pls:
|
||||||
|
texts = [c.get("window") or c.get("text") or "" for c in chunk_pls]
|
||||||
|
try:
|
||||||
|
if hasattr(self.embedder, 'embed_documents'):
|
||||||
|
vecs = await self.embedder.embed_documents(texts)
|
||||||
|
else:
|
||||||
|
for t in texts:
|
||||||
|
v = await self.embedder.embed_query(t)
|
||||||
|
vecs.append(v)
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"Embedding failed: {e}")
|
||||||
|
raise RuntimeError(f"Embedding failed: {e}")
|
||||||
|
|
||||||
|
# Edges
|
||||||
|
try:
|
||||||
|
edges = build_edges_for_note(
|
||||||
|
note_id,
|
||||||
|
chunk_pls,
|
||||||
|
note_level_references=note_pl.get("references", []),
|
||||||
|
include_note_scope_refs=note_scope_refs
|
||||||
|
)
|
||||||
|
except TypeError:
|
||||||
|
edges = build_edges_for_note(note_id, chunk_pls)
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"Processing failed: {e}", exc_info=True)
|
||||||
|
return {**result, "error": f"Processing failed: {str(e)}"}
|
||||||
|
|
||||||
|
# 6. Upsert Action
|
||||||
|
try:
|
||||||
|
if purge_before and has_old:
|
||||||
|
self._purge_artifacts(note_id)
|
||||||
|
|
||||||
|
n_name, n_pts = points_for_note(self.prefix, note_pl, None, self.dim)
|
||||||
|
upsert_batch(self.client, n_name, n_pts)
|
||||||
|
|
||||||
|
if chunk_pls and vecs:
|
||||||
|
c_name, c_pts = points_for_chunks(self.prefix, chunk_pls, vecs)
|
||||||
|
upsert_batch(self.client, c_name, c_pts)
|
||||||
|
|
||||||
|
if edges:
|
||||||
|
e_name, e_pts = points_for_edges(self.prefix, edges)
|
||||||
|
upsert_batch(self.client, e_name, e_pts)
|
||||||
|
|
||||||
|
return {
|
||||||
|
"path": file_path,
|
||||||
|
"status": "success",
|
||||||
|
"changed": True,
|
||||||
|
"note_id": note_id,
|
||||||
|
"chunks_count": len(chunk_pls),
|
||||||
|
"edges_count": len(edges)
|
||||||
|
}
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"Upsert failed: {e}", exc_info=True)
|
||||||
|
return {**result, "error": f"DB Upsert failed: {e}"}
|
||||||
|
|
||||||
|
# --- Qdrant Helper (Restored) ---
|
||||||
|
|
||||||
|
def _fetch_note_payload(self, note_id: str) -> Optional[dict]:
|
||||||
|
from qdrant_client.http import models as rest
|
||||||
|
col = f"{self.prefix}_notes"
|
||||||
|
try:
|
||||||
|
f = rest.Filter(must=[rest.FieldCondition(key="note_id", match=rest.MatchValue(value=note_id))])
|
||||||
|
pts, _ = self.client.scroll(collection_name=col, scroll_filter=f, limit=1, with_payload=True)
|
||||||
|
return pts[0].payload if pts else None
|
||||||
|
except: return None
|
||||||
|
|
||||||
|
def _artifacts_missing(self, note_id: str) -> Tuple[bool, bool]:
|
||||||
|
from qdrant_client.http import models as rest
|
||||||
|
c_col = f"{self.prefix}_chunks"
|
||||||
|
e_col = f"{self.prefix}_edges"
|
||||||
|
try:
|
||||||
|
f = rest.Filter(must=[rest.FieldCondition(key="note_id", match=rest.MatchValue(value=note_id))])
|
||||||
|
c_pts, _ = self.client.scroll(collection_name=c_col, scroll_filter=f, limit=1)
|
||||||
|
e_pts, _ = self.client.scroll(collection_name=e_col, scroll_filter=f, limit=1)
|
||||||
|
return (not bool(c_pts)), (not bool(e_pts))
|
||||||
|
except: return True, True
|
||||||
|
|
||||||
|
def _purge_artifacts(self, note_id: str):
|
||||||
|
from qdrant_client.http import models as rest
|
||||||
|
f = rest.Filter(must=[rest.FieldCondition(key="note_id", match=rest.MatchValue(value=note_id))])
|
||||||
|
selector = rest.FilterSelector(filter=f)
|
||||||
|
for suffix in ["chunks", "edges"]:
|
||||||
|
try:
|
||||||
|
self.client.delete(collection_name=f"{self.prefix}_{suffix}", points_selector=selector)
|
||||||
|
except Exception: pass
|
||||||
|
|
||||||
|
async def create_from_text(
|
||||||
|
self,
|
||||||
|
markdown_content: str,
|
||||||
|
filename: str,
|
||||||
|
vault_root: str,
|
||||||
|
folder: str = "00_Inbox"
|
||||||
|
) -> Dict[str, Any]:
|
||||||
|
"""
|
||||||
|
WP-11 Persistence API Entrypoint.
|
||||||
|
"""
|
||||||
|
target_dir = os.path.join(vault_root, folder)
|
||||||
|
os.makedirs(target_dir, exist_ok=True)
|
||||||
|
|
||||||
|
file_path = os.path.join(target_dir, filename)
|
||||||
|
|
||||||
|
try:
|
||||||
|
# Robust Write: Ensure Flush & Sync
|
||||||
|
with open(file_path, "w", encoding="utf-8") as f:
|
||||||
|
f.write(markdown_content)
|
||||||
|
f.flush()
|
||||||
|
os.fsync(f.fileno())
|
||||||
|
|
||||||
|
await asyncio.sleep(0.1)
|
||||||
|
|
||||||
|
logger.info(f"Written file to {file_path}")
|
||||||
|
except Exception as e:
|
||||||
|
return {"status": "error", "error": f"Disk write failed: {str(e)}"}
|
||||||
|
|
||||||
|
return await self.process_file(
|
||||||
|
file_path=file_path,
|
||||||
|
vault_root=vault_root,
|
||||||
|
apply=True,
|
||||||
|
force_replace=True,
|
||||||
|
purge_before=True
|
||||||
|
)
|
||||||
@@ -2,7 +2,7 @@
|
|||||||
# -*- coding: utf-8 -*-
|
# -*- coding: utf-8 -*-
|
||||||
"""
|
"""
|
||||||
Modul: app/core/note_payload.py
|
Modul: app/core/note_payload.py
|
||||||
Version: 2.0.0
|
Version: 2.1.0 (WP-11 Update: Aliases support)
|
||||||
|
|
||||||
Zweck
|
Zweck
|
||||||
-----
|
-----
|
||||||
@@ -145,6 +145,7 @@ def make_note_payload(note: Any, *args, **kwargs) -> Dict[str, Any]:
|
|||||||
- retriever_weight: effektives Gewicht für den Retriever
|
- retriever_weight: effektives Gewicht für den Retriever
|
||||||
- chunk_profile: Profil für Chunking (short|medium|long|default|...)
|
- chunk_profile: Profil für Chunking (short|medium|long|default|...)
|
||||||
- edge_defaults: Liste von Kanten-Typen, die als Defaults gelten
|
- edge_defaults: Liste von Kanten-Typen, die als Defaults gelten
|
||||||
|
- aliases: Liste von Synonymen (WP-11)
|
||||||
"""
|
"""
|
||||||
n = _as_dict(note)
|
n = _as_dict(note)
|
||||||
path_arg, types_cfg_explicit = _pick_args(*args, **kwargs)
|
path_arg, types_cfg_explicit = _pick_args(*args, **kwargs)
|
||||||
@@ -214,13 +215,22 @@ def make_note_payload(note: Any, *args, **kwargs) -> Dict[str, Any]:
|
|||||||
if tags:
|
if tags:
|
||||||
payload["tags"] = _ensure_list(tags)
|
payload["tags"] = _ensure_list(tags)
|
||||||
|
|
||||||
|
# WP-11: Aliases übernehmen (für Discovery Service)
|
||||||
|
aliases = fm.get("aliases")
|
||||||
|
if aliases:
|
||||||
|
payload["aliases"] = _ensure_list(aliases)
|
||||||
|
|
||||||
# Zeitliche Metadaten (sofern vorhanden)
|
# Zeitliche Metadaten (sofern vorhanden)
|
||||||
for k in ("created", "modified", "date"):
|
for k in ("created", "modified", "date"):
|
||||||
v = fm.get(k) or n.get(k)
|
v = fm.get(k) or n.get(k)
|
||||||
if v:
|
if v:
|
||||||
payload[k] = str(v)
|
payload[k] = str(v)
|
||||||
|
|
||||||
|
# Fulltext (Fallback, falls body im Input)
|
||||||
|
if "body" in n and n["body"]:
|
||||||
|
payload["fulltext"] = str(n["body"])
|
||||||
|
|
||||||
# JSON-Roundtrip zur harten Validierung (ASCII beibehalten)
|
# JSON-Roundtrip zur harten Validierung (ASCII beibehalten)
|
||||||
json.loads(json.dumps(payload, ensure_ascii=False))
|
json.loads(json.dumps(payload, ensure_ascii=False))
|
||||||
|
|
||||||
return payload
|
return payload
|
||||||
+10
-7
@@ -2,7 +2,7 @@
|
|||||||
app/core/retriever.py — Hybrider Such-Algorithmus
|
app/core/retriever.py — Hybrider Such-Algorithmus
|
||||||
|
|
||||||
Version:
|
Version:
|
||||||
0.5.2 (WP-05 Fix: Pass content in QueryHit source)
|
0.5.3 (WP-06 Fix: Populate 'payload' in QueryHit for meta-data access)
|
||||||
"""
|
"""
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
@@ -127,7 +127,9 @@ def _build_explanation(
|
|||||||
node_key: Optional[str]
|
node_key: Optional[str]
|
||||||
) -> Explanation:
|
) -> Explanation:
|
||||||
"""Erstellt ein Explanation-Objekt."""
|
"""Erstellt ein Explanation-Objekt."""
|
||||||
sem_w, edge_w, cent_w = _get_scoring_weights()
|
sem_w, _edge_w, _cent_w = _get_scoring_weights()
|
||||||
|
# Scoring weights erneut laden für Reason-Details
|
||||||
|
_, edge_w_cfg, cent_w_cfg = _get_scoring_weights()
|
||||||
|
|
||||||
try:
|
try:
|
||||||
type_weight = float(payload.get("retriever_weight", 1.0))
|
type_weight = float(payload.get("retriever_weight", 1.0))
|
||||||
@@ -138,8 +140,8 @@ def _build_explanation(
|
|||||||
|
|
||||||
breakdown = ScoreBreakdown(
|
breakdown = ScoreBreakdown(
|
||||||
semantic_contribution=(sem_w * semantic_score * type_weight),
|
semantic_contribution=(sem_w * semantic_score * type_weight),
|
||||||
edge_contribution=(edge_w * edge_bonus),
|
edge_contribution=(edge_w_cfg * edge_bonus),
|
||||||
centrality_contribution=(cent_w * cent_bonus),
|
centrality_contribution=(cent_w_cfg * cent_bonus),
|
||||||
raw_semantic=semantic_score,
|
raw_semantic=semantic_score,
|
||||||
raw_edge_bonus=edge_bonus,
|
raw_edge_bonus=edge_bonus,
|
||||||
raw_centrality=cent_bonus,
|
raw_centrality=cent_bonus,
|
||||||
@@ -179,7 +181,7 @@ def _build_explanation(
|
|||||||
|
|
||||||
all_edges = sorted(edges_dto, key=lambda e: e.weight, reverse=True)
|
all_edges = sorted(edges_dto, key=lambda e: e.weight, reverse=True)
|
||||||
for top_edge in all_edges[:3]:
|
for top_edge in all_edges[:3]:
|
||||||
impact = edge_w * top_edge.weight
|
impact = edge_w_cfg * top_edge.weight
|
||||||
dir_txt = "Verweist auf" if top_edge.direction == "out" else "Referenziert von"
|
dir_txt = "Verweist auf" if top_edge.direction == "out" else "Referenziert von"
|
||||||
tgt_txt = top_edge.target if top_edge.direction == "out" else top_edge.source
|
tgt_txt = top_edge.target if top_edge.direction == "out" else top_edge.source
|
||||||
reasons.append(Reason(kind="edge", message=f"{dir_txt} '{tgt_txt}' via '{top_edge.kind}'", score_impact=impact, details={"kind": top_edge.kind}))
|
reasons.append(Reason(kind="edge", message=f"{dir_txt} '{tgt_txt}' via '{top_edge.kind}'", score_impact=impact, details={"kind": top_edge.kind}))
|
||||||
@@ -261,7 +263,6 @@ def _build_hits_from_semantic(
|
|||||||
node_key=payload.get("chunk_id") or payload.get("note_id")
|
node_key=payload.get("chunk_id") or payload.get("note_id")
|
||||||
)
|
)
|
||||||
|
|
||||||
# FIX: Hier holen wir jetzt den Textinhalt (text, content oder page_content) aus dem Payload
|
|
||||||
text_content = payload.get("page_content") or payload.get("text") or payload.get("content")
|
text_content = payload.get("page_content") or payload.get("text") or payload.get("content")
|
||||||
|
|
||||||
results.append(QueryHit(
|
results.append(QueryHit(
|
||||||
@@ -275,8 +276,10 @@ def _build_hits_from_semantic(
|
|||||||
source={
|
source={
|
||||||
"path": payload.get("path"),
|
"path": payload.get("path"),
|
||||||
"section": payload.get("section") or payload.get("section_title"),
|
"section": payload.get("section") or payload.get("section_title"),
|
||||||
"text": text_content # WICHTIG: Inhalt durchreichen
|
"text": text_content
|
||||||
},
|
},
|
||||||
|
# --- FIX: Wir füllen das payload-Feld explizit ---
|
||||||
|
payload=payload,
|
||||||
explanation=explanation_obj
|
explanation=explanation_obj
|
||||||
))
|
))
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,533 @@
|
|||||||
|
import streamlit as st
|
||||||
|
import requests
|
||||||
|
import uuid
|
||||||
|
import os
|
||||||
|
import json
|
||||||
|
import re
|
||||||
|
import yaml
|
||||||
|
import unicodedata
|
||||||
|
from datetime import datetime
|
||||||
|
from pathlib import Path
|
||||||
|
from dotenv import load_dotenv
|
||||||
|
|
||||||
|
# --- CONFIGURATION ---
|
||||||
|
load_dotenv()
|
||||||
|
API_BASE_URL = os.getenv("MINDNET_API_URL", "http://localhost:8002")
|
||||||
|
CHAT_ENDPOINT = f"{API_BASE_URL}/chat"
|
||||||
|
FEEDBACK_ENDPOINT = f"{API_BASE_URL}/feedback"
|
||||||
|
INGEST_ANALYZE_ENDPOINT = f"{API_BASE_URL}/ingest/analyze"
|
||||||
|
INGEST_SAVE_ENDPOINT = f"{API_BASE_URL}/ingest/save"
|
||||||
|
HISTORY_FILE = Path("data/logs/search_history.jsonl")
|
||||||
|
|
||||||
|
# Timeout Strategy
|
||||||
|
timeout_setting = os.getenv("MINDNET_API_TIMEOUT") or os.getenv("MINDNET_LLM_TIMEOUT")
|
||||||
|
API_TIMEOUT = float(timeout_setting) if timeout_setting else 300.0
|
||||||
|
|
||||||
|
# --- PAGE SETUP ---
|
||||||
|
st.set_page_config(page_title="mindnet v2.5", page_icon="🧠", layout="wide")
|
||||||
|
|
||||||
|
# --- CSS STYLING ---
|
||||||
|
st.markdown("""
|
||||||
|
<style>
|
||||||
|
.block-container { padding-top: 2rem; max_width: 1000px; margin: auto; }
|
||||||
|
|
||||||
|
.intent-badge {
|
||||||
|
background-color: #e8f0fe; color: #1a73e8;
|
||||||
|
padding: 4px 10px; border-radius: 12px;
|
||||||
|
font-size: 0.8rem; font-weight: 600;
|
||||||
|
border: 1px solid #d2e3fc; display: inline-block; margin-bottom: 0.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.draft-box {
|
||||||
|
border: 1px solid #d0d7de;
|
||||||
|
border-radius: 6px;
|
||||||
|
padding: 16px;
|
||||||
|
background-color: #f6f8fa;
|
||||||
|
margin-top: 10px;
|
||||||
|
margin-bottom: 10px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.preview-box {
|
||||||
|
border: 1px solid #e0e0e0;
|
||||||
|
border-radius: 6px;
|
||||||
|
padding: 24px;
|
||||||
|
background-color: white;
|
||||||
|
font-family: -apple-system,BlinkMacSystemFont,"Segoe UI",Helvetica,Arial,sans-serif;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
""", unsafe_allow_html=True)
|
||||||
|
|
||||||
|
# --- SESSION STATE ---
|
||||||
|
if "messages" not in st.session_state: st.session_state.messages = []
|
||||||
|
if "user_id" not in st.session_state: st.session_state.user_id = str(uuid.uuid4())
|
||||||
|
|
||||||
|
# --- HELPER FUNCTIONS ---
|
||||||
|
|
||||||
|
def slugify(value):
|
||||||
|
if not value: return ""
|
||||||
|
value = str(value).lower()
|
||||||
|
replacements = {'ä': 'ae', 'ö': 'oe', 'ü': 'ue', 'ß': 'ss', '&': 'und', '+': 'und'}
|
||||||
|
for k, v in replacements.items():
|
||||||
|
value = value.replace(k, v)
|
||||||
|
|
||||||
|
value = unicodedata.normalize('NFKD', value).encode('ascii', 'ignore').decode('ascii')
|
||||||
|
value = re.sub(r'[^\w\s-]', '', value).strip()
|
||||||
|
return re.sub(r'[-\s]+', '-', value)
|
||||||
|
|
||||||
|
def normalize_meta_and_body(meta, body):
|
||||||
|
ALLOWED_KEYS = {"title", "type", "status", "tags", "id", "created", "updated", "aliases", "lang"}
|
||||||
|
clean_meta = {}
|
||||||
|
extra_content = []
|
||||||
|
|
||||||
|
if "titel" in meta and "title" not in meta:
|
||||||
|
meta["title"] = meta.pop("titel")
|
||||||
|
|
||||||
|
tag_candidates = ["tags", "emotionale_keywords", "keywords", "schluesselwoerter"]
|
||||||
|
all_tags = []
|
||||||
|
for key in tag_candidates:
|
||||||
|
if key in meta:
|
||||||
|
val = meta[key]
|
||||||
|
if isinstance(val, list): all_tags.extend(val)
|
||||||
|
elif isinstance(val, str): all_tags.extend([t.strip() for t in val.split(",")])
|
||||||
|
|
||||||
|
for key, val in meta.items():
|
||||||
|
if key in ALLOWED_KEYS:
|
||||||
|
clean_meta[key] = val
|
||||||
|
elif key in tag_candidates:
|
||||||
|
pass
|
||||||
|
else:
|
||||||
|
if val and isinstance(val, str):
|
||||||
|
header = key.replace("_", " ").title()
|
||||||
|
extra_content.append(f"## {header}\n{val}\n")
|
||||||
|
|
||||||
|
if all_tags:
|
||||||
|
clean_tags = []
|
||||||
|
for t in all_tags:
|
||||||
|
t_clean = str(t).replace("#", "").strip()
|
||||||
|
if t_clean: clean_tags.append(t_clean)
|
||||||
|
clean_meta["tags"] = list(set(clean_tags))
|
||||||
|
|
||||||
|
if extra_content:
|
||||||
|
new_section = "\n".join(extra_content)
|
||||||
|
final_body = f"{new_section}\n{body}"
|
||||||
|
else:
|
||||||
|
final_body = body
|
||||||
|
|
||||||
|
return clean_meta, final_body
|
||||||
|
|
||||||
|
def parse_markdown_draft(full_text):
|
||||||
|
"""
|
||||||
|
HEALING PARSER: Repariert kaputten LLM Output (z.B. fehlendes schließendes '---').
|
||||||
|
"""
|
||||||
|
clean_text = full_text.strip()
|
||||||
|
|
||||||
|
# 1. Code-Block Wrapper entfernen
|
||||||
|
pattern_block = r"```(?:markdown|md|yaml)?\s*(.*?)\s*```"
|
||||||
|
match_block = re.search(pattern_block, clean_text, re.DOTALL | re.IGNORECASE)
|
||||||
|
if match_block:
|
||||||
|
clean_text = match_block.group(1).strip()
|
||||||
|
|
||||||
|
meta = {}
|
||||||
|
body = clean_text
|
||||||
|
yaml_str = ""
|
||||||
|
|
||||||
|
# 2. Versuch A: Standard Split (Idealfall)
|
||||||
|
parts = re.split(r"^---+\s*$", clean_text, maxsplit=2, flags=re.MULTILINE)
|
||||||
|
|
||||||
|
if len(parts) >= 3:
|
||||||
|
yaml_str = parts[1]
|
||||||
|
body = parts[2]
|
||||||
|
|
||||||
|
# 3. Versuch B: Healing (Wenn LLM das schließende --- vergessen hat)
|
||||||
|
elif clean_text.startswith("---"):
|
||||||
|
# Wir suchen die erste Überschrift '#', da Frontmatter davor sein muss
|
||||||
|
# Pattern: Suche --- am Anfang, dann nimm alles bis zum ersten # am Zeilenanfang
|
||||||
|
fallback_match = re.search(r"^---\s*(.*?)(?=\n#)", clean_text, re.DOTALL | re.MULTILINE)
|
||||||
|
if fallback_match:
|
||||||
|
yaml_str = fallback_match.group(1)
|
||||||
|
# Der Body ist alles NACH dem YAML String (inklusive dem #)
|
||||||
|
body = clean_text.replace(f"---{yaml_str}", "", 1).strip()
|
||||||
|
|
||||||
|
# 4. YAML Parsing
|
||||||
|
if yaml_str:
|
||||||
|
yaml_str_clean = yaml_str.replace("#", "") # Tags cleanen
|
||||||
|
try:
|
||||||
|
parsed = yaml.safe_load(yaml_str_clean)
|
||||||
|
if isinstance(parsed, dict):
|
||||||
|
meta = parsed
|
||||||
|
except Exception as e:
|
||||||
|
print(f"YAML Parsing Warning: {e}")
|
||||||
|
|
||||||
|
# Fallback: Titel aus H1
|
||||||
|
if not meta.get("title"):
|
||||||
|
h1_match = re.search(r"^#\s+(.*)$", body, re.MULTILINE)
|
||||||
|
if h1_match:
|
||||||
|
meta["title"] = h1_match.group(1).strip()
|
||||||
|
|
||||||
|
# Correction: type/status swap
|
||||||
|
if meta.get("type") == "draft":
|
||||||
|
meta["status"] = "draft"
|
||||||
|
meta["type"] = "experience"
|
||||||
|
|
||||||
|
return normalize_meta_and_body(meta, body)
|
||||||
|
|
||||||
|
def build_markdown_doc(meta, body):
|
||||||
|
"""Baut das finale Dokument zusammen."""
|
||||||
|
if "id" not in meta or meta["id"] == "generated_on_save":
|
||||||
|
raw_title = meta.get('title', 'note')
|
||||||
|
clean_slug = slugify(raw_title)[:50] or "note"
|
||||||
|
meta["id"] = f"{datetime.now().strftime('%Y%m%d')}-{clean_slug}"
|
||||||
|
|
||||||
|
meta["updated"] = datetime.now().strftime("%Y-%m-%d")
|
||||||
|
|
||||||
|
ordered_meta = {}
|
||||||
|
prio_keys = ["id", "type", "title", "status", "tags"]
|
||||||
|
for k in prio_keys:
|
||||||
|
if k in meta: ordered_meta[k] = meta.pop(k)
|
||||||
|
ordered_meta.update(meta)
|
||||||
|
|
||||||
|
try:
|
||||||
|
yaml_str = yaml.dump(ordered_meta, default_flow_style=None, sort_keys=False, allow_unicode=True).strip()
|
||||||
|
except:
|
||||||
|
yaml_str = "error: generating_yaml"
|
||||||
|
|
||||||
|
return f"---\n{yaml_str}\n---\n\n{body}"
|
||||||
|
|
||||||
|
def load_history_from_logs(limit=10):
|
||||||
|
queries = []
|
||||||
|
if HISTORY_FILE.exists():
|
||||||
|
try:
|
||||||
|
with open(HISTORY_FILE, "r", encoding="utf-8") as f:
|
||||||
|
lines = f.readlines()
|
||||||
|
for line in reversed(lines):
|
||||||
|
try:
|
||||||
|
entry = json.loads(line)
|
||||||
|
q = entry.get("query_text")
|
||||||
|
if q and q not in queries:
|
||||||
|
queries.append(q)
|
||||||
|
if len(queries) >= limit: break
|
||||||
|
except: continue
|
||||||
|
except: pass
|
||||||
|
return queries
|
||||||
|
|
||||||
|
# --- API CLIENT ---
|
||||||
|
|
||||||
|
def send_chat_message(message: str, top_k: int, explain: bool):
|
||||||
|
try:
|
||||||
|
response = requests.post(
|
||||||
|
CHAT_ENDPOINT,
|
||||||
|
json={"message": message, "top_k": top_k, "explain": explain},
|
||||||
|
timeout=API_TIMEOUT
|
||||||
|
)
|
||||||
|
response.raise_for_status()
|
||||||
|
return response.json()
|
||||||
|
except Exception as e:
|
||||||
|
return {"error": str(e)}
|
||||||
|
|
||||||
|
def analyze_draft_text(text: str, n_type: str):
|
||||||
|
try:
|
||||||
|
response = requests.post(
|
||||||
|
INGEST_ANALYZE_ENDPOINT,
|
||||||
|
json={"text": text, "type": n_type},
|
||||||
|
timeout=15
|
||||||
|
)
|
||||||
|
response.raise_for_status()
|
||||||
|
return response.json()
|
||||||
|
except Exception as e:
|
||||||
|
return {"error": str(e)}
|
||||||
|
|
||||||
|
def save_draft_to_vault(markdown_content: str, filename: str = None):
|
||||||
|
try:
|
||||||
|
response = requests.post(
|
||||||
|
INGEST_SAVE_ENDPOINT,
|
||||||
|
json={"markdown_content": markdown_content, "filename": filename},
|
||||||
|
timeout=API_TIMEOUT
|
||||||
|
)
|
||||||
|
response.raise_for_status()
|
||||||
|
return response.json()
|
||||||
|
except Exception as e:
|
||||||
|
return {"error": str(e)}
|
||||||
|
|
||||||
|
def submit_feedback(query_id, node_id, score, comment=None):
|
||||||
|
try:
|
||||||
|
requests.post(FEEDBACK_ENDPOINT, json={"query_id": query_id, "node_id": node_id, "score": score, "comment": comment}, timeout=2)
|
||||||
|
st.toast(f"Feedback ({score}) gesendet!")
|
||||||
|
except: pass
|
||||||
|
|
||||||
|
# --- UI COMPONENTS ---
|
||||||
|
|
||||||
|
def render_sidebar():
|
||||||
|
with st.sidebar:
|
||||||
|
st.title("🧠 mindnet")
|
||||||
|
st.caption("v2.5 | Healing Parser")
|
||||||
|
mode = st.radio("Modus", ["💬 Chat", "📝 Manueller Editor"], index=0)
|
||||||
|
st.divider()
|
||||||
|
st.subheader("⚙️ Settings")
|
||||||
|
top_k = st.slider("Quellen (Top-K)", 1, 10, 5)
|
||||||
|
explain = st.toggle("Explanation Layer", True)
|
||||||
|
st.divider()
|
||||||
|
st.subheader("🕒 Verlauf")
|
||||||
|
for q in load_history_from_logs(8):
|
||||||
|
if st.button(f"🔎 {q[:25]}...", key=f"hist_{q}", use_container_width=True):
|
||||||
|
st.session_state.messages.append({"role": "user", "content": q})
|
||||||
|
st.rerun()
|
||||||
|
return mode, top_k, explain
|
||||||
|
|
||||||
|
def render_draft_editor(msg):
|
||||||
|
if "query_id" not in msg or not msg["query_id"]:
|
||||||
|
msg["query_id"] = str(uuid.uuid4())
|
||||||
|
|
||||||
|
qid = msg["query_id"]
|
||||||
|
key_base = f"draft_{qid}"
|
||||||
|
|
||||||
|
# State Keys
|
||||||
|
data_meta_key = f"{key_base}_data_meta"
|
||||||
|
data_sugg_key = f"{key_base}_data_suggestions"
|
||||||
|
widget_body_key = f"{key_base}_widget_body"
|
||||||
|
data_body_key = f"{key_base}_data_body"
|
||||||
|
|
||||||
|
# --- 1. INIT STATE ---
|
||||||
|
if f"{key_base}_init" not in st.session_state:
|
||||||
|
meta, body = parse_markdown_draft(msg["content"])
|
||||||
|
if "type" not in meta: meta["type"] = "default"
|
||||||
|
if "title" not in meta: meta["title"] = ""
|
||||||
|
tags = meta.get("tags", [])
|
||||||
|
meta["tags_str"] = ", ".join(tags) if isinstance(tags, list) else str(tags)
|
||||||
|
|
||||||
|
# Persistent Data
|
||||||
|
st.session_state[data_meta_key] = meta
|
||||||
|
st.session_state[data_sugg_key] = []
|
||||||
|
st.session_state[data_body_key] = body.strip()
|
||||||
|
|
||||||
|
# Init Widgets Keys
|
||||||
|
st.session_state[f"{key_base}_wdg_title"] = meta["title"]
|
||||||
|
st.session_state[f"{key_base}_wdg_type"] = meta["type"]
|
||||||
|
st.session_state[f"{key_base}_wdg_tags"] = meta["tags_str"]
|
||||||
|
|
||||||
|
st.session_state[f"{key_base}_init"] = True
|
||||||
|
|
||||||
|
# --- 2. RESURRECTION ---
|
||||||
|
if widget_body_key not in st.session_state and data_body_key in st.session_state:
|
||||||
|
st.session_state[widget_body_key] = st.session_state[data_body_key]
|
||||||
|
|
||||||
|
# --- CALLBACKS ---
|
||||||
|
def _sync_meta():
|
||||||
|
meta = st.session_state[data_meta_key]
|
||||||
|
meta["title"] = st.session_state.get(f"{key_base}_wdg_title", "")
|
||||||
|
meta["type"] = st.session_state.get(f"{key_base}_wdg_type", "default")
|
||||||
|
meta["tags_str"] = st.session_state.get(f"{key_base}_wdg_tags", "")
|
||||||
|
st.session_state[data_meta_key] = meta
|
||||||
|
|
||||||
|
def _sync_body():
|
||||||
|
st.session_state[data_body_key] = st.session_state[widget_body_key]
|
||||||
|
|
||||||
|
def _insert_text(text_to_insert):
|
||||||
|
current = st.session_state.get(widget_body_key, "")
|
||||||
|
new_text = f"{current}\n\n{text_to_insert}"
|
||||||
|
st.session_state[widget_body_key] = new_text
|
||||||
|
st.session_state[data_body_key] = new_text
|
||||||
|
|
||||||
|
def _remove_text(text_to_remove):
|
||||||
|
current = st.session_state.get(widget_body_key, "")
|
||||||
|
new_text = current.replace(text_to_remove, "").strip()
|
||||||
|
st.session_state[widget_body_key] = new_text
|
||||||
|
st.session_state[data_body_key] = new_text
|
||||||
|
|
||||||
|
# --- UI LAYOUT ---
|
||||||
|
st.markdown(f'<div class="draft-box">', unsafe_allow_html=True)
|
||||||
|
st.markdown("### 📝 Entwurf bearbeiten")
|
||||||
|
|
||||||
|
meta_ref = st.session_state[data_meta_key]
|
||||||
|
c1, c2 = st.columns([2, 1])
|
||||||
|
with c1:
|
||||||
|
st.text_input("Titel", key=f"{key_base}_wdg_title", on_change=_sync_meta)
|
||||||
|
|
||||||
|
with c2:
|
||||||
|
known_types = ["concept", "project", "decision", "experience", "journal", "value", "goal", "principle", "risk", "belief"]
|
||||||
|
curr_type = st.session_state.get(f"{key_base}_wdg_type", meta_ref["type"])
|
||||||
|
if curr_type not in known_types: known_types.append(curr_type)
|
||||||
|
st.selectbox("Typ", known_types, key=f"{key_base}_wdg_type", on_change=_sync_meta)
|
||||||
|
|
||||||
|
st.text_input("Tags", key=f"{key_base}_wdg_tags", on_change=_sync_meta)
|
||||||
|
|
||||||
|
tab_edit, tab_intel, tab_view = st.tabs(["✏️ Inhalt", "🧠 Intelligence", "👁️ Vorschau"])
|
||||||
|
|
||||||
|
# --- TAB 1: EDITOR ---
|
||||||
|
with tab_edit:
|
||||||
|
st.text_area(
|
||||||
|
"Body",
|
||||||
|
key=widget_body_key,
|
||||||
|
height=500,
|
||||||
|
on_change=_sync_body,
|
||||||
|
label_visibility="collapsed"
|
||||||
|
)
|
||||||
|
|
||||||
|
# --- TAB 2: INTELLIGENCE ---
|
||||||
|
with tab_intel:
|
||||||
|
st.info("Klicke auf 'Analysieren', um Verknüpfungen für den AKTUELLEN Text zu finden.")
|
||||||
|
|
||||||
|
if st.button("🔍 Analyse starten", key=f"{key_base}_analyze"):
|
||||||
|
st.session_state[data_sugg_key] = []
|
||||||
|
|
||||||
|
text_to_analyze = st.session_state.get(widget_body_key, st.session_state.get(data_body_key, ""))
|
||||||
|
current_doc_type = st.session_state.get(f"{key_base}_wdg_type", "concept")
|
||||||
|
|
||||||
|
with st.spinner("Analysiere..."):
|
||||||
|
analysis = analyze_draft_text(text_to_analyze, current_doc_type)
|
||||||
|
|
||||||
|
if "error" in analysis:
|
||||||
|
st.error(f"Fehler: {analysis['error']}")
|
||||||
|
else:
|
||||||
|
suggestions = analysis.get("suggestions", [])
|
||||||
|
st.session_state[data_sugg_key] = suggestions
|
||||||
|
if not suggestions:
|
||||||
|
st.warning("Keine Vorschläge gefunden.")
|
||||||
|
else:
|
||||||
|
st.success(f"{len(suggestions)} Vorschläge gefunden.")
|
||||||
|
|
||||||
|
suggestions = st.session_state[data_sugg_key]
|
||||||
|
if suggestions:
|
||||||
|
current_text_state = st.session_state.get(widget_body_key, "")
|
||||||
|
|
||||||
|
for idx, sugg in enumerate(suggestions):
|
||||||
|
link_text = sugg.get('suggested_markdown', '')
|
||||||
|
is_inserted = link_text in current_text_state
|
||||||
|
|
||||||
|
bg_color = "#e6fffa" if is_inserted else "#ffffff"
|
||||||
|
border = "3px solid #28a745" if is_inserted else "3px solid #1a73e8"
|
||||||
|
|
||||||
|
st.markdown(f"""
|
||||||
|
<div style="border-left: {border}; background-color: {bg_color}; padding: 10px; margin-bottom: 8px; border-radius: 4px; box-shadow: 0 1px 3px rgba(0,0,0,0.1);">
|
||||||
|
<b>{sugg.get('target_title')}</b> <small>({sugg.get('type')})</small><br>
|
||||||
|
<i>{sugg.get('reason')}</i><br>
|
||||||
|
<code>{link_text}</code>
|
||||||
|
</div>
|
||||||
|
""", unsafe_allow_html=True)
|
||||||
|
|
||||||
|
if is_inserted:
|
||||||
|
st.button("❌ Entfernen", key=f"del_{idx}_{key_base}", on_click=_remove_text, args=(link_text,))
|
||||||
|
else:
|
||||||
|
st.button("➕ Einfügen", key=f"add_{idx}_{key_base}", on_click=_insert_text, args=(link_text,))
|
||||||
|
|
||||||
|
# --- TAB 3: SAVE ---
|
||||||
|
final_tags_str = st.session_state.get(f"{key_base}_wdg_tags", "")
|
||||||
|
final_tags = [t.strip() for t in final_tags_str.split(",") if t.strip()]
|
||||||
|
|
||||||
|
final_meta = {
|
||||||
|
"id": "generated_on_save",
|
||||||
|
"type": st.session_state.get(f"{key_base}_wdg_type", "default"),
|
||||||
|
"title": st.session_state.get(f"{key_base}_wdg_title", "").strip(),
|
||||||
|
"status": "draft",
|
||||||
|
"tags": final_tags
|
||||||
|
}
|
||||||
|
|
||||||
|
final_body = st.session_state.get(widget_body_key, st.session_state[data_body_key])
|
||||||
|
|
||||||
|
if not final_meta["title"]:
|
||||||
|
h1_match = re.search(r"^#\s+(.*)$", final_body, re.MULTILINE)
|
||||||
|
if h1_match:
|
||||||
|
final_meta["title"] = h1_match.group(1).strip()
|
||||||
|
|
||||||
|
final_doc = build_markdown_doc(final_meta, final_body)
|
||||||
|
|
||||||
|
with tab_view:
|
||||||
|
st.markdown('<div class="preview-box">', unsafe_allow_html=True)
|
||||||
|
st.markdown(final_doc)
|
||||||
|
st.markdown('</div>', unsafe_allow_html=True)
|
||||||
|
|
||||||
|
st.markdown("---")
|
||||||
|
|
||||||
|
b1, b2 = st.columns([1, 1])
|
||||||
|
with b1:
|
||||||
|
if st.button("💾 Speichern & Indizieren", type="primary", key=f"{key_base}_save"):
|
||||||
|
with st.spinner("Speichere im Vault..."):
|
||||||
|
|
||||||
|
raw_title = final_meta.get("title", "")
|
||||||
|
if not raw_title:
|
||||||
|
clean_body = re.sub(r"[#*_\[\]()]", "", final_body).strip()
|
||||||
|
raw_title = clean_body[:40] if clean_body else "draft"
|
||||||
|
|
||||||
|
safe_title = slugify(raw_title)[:60] or "draft"
|
||||||
|
fname = f"{datetime.now().strftime('%Y%m%d')}-{safe_title}.md"
|
||||||
|
|
||||||
|
result = save_draft_to_vault(final_doc, filename=fname)
|
||||||
|
if "error" in result:
|
||||||
|
st.error(f"Fehler: {result['error']}")
|
||||||
|
else:
|
||||||
|
st.success(f"Gespeichert: {result.get('file_path')}")
|
||||||
|
st.balloons()
|
||||||
|
with b2:
|
||||||
|
if st.button("📋 Code anzeigen", key=f"{key_base}_btn_copy"):
|
||||||
|
st.code(final_doc, language="markdown")
|
||||||
|
|
||||||
|
st.markdown("</div>", unsafe_allow_html=True)
|
||||||
|
|
||||||
|
|
||||||
|
def render_chat_interface(top_k, explain):
|
||||||
|
for idx, msg in enumerate(st.session_state.messages):
|
||||||
|
with st.chat_message(msg["role"]):
|
||||||
|
if msg["role"] == "assistant":
|
||||||
|
intent = msg.get("intent", "UNKNOWN")
|
||||||
|
src = msg.get("intent_source", "?")
|
||||||
|
icon = {"EMPATHY":"❤️", "DECISION":"⚖️", "CODING":"💻", "FACT":"📚", "INTERVIEW":"📝"}.get(intent, "🧠")
|
||||||
|
st.markdown(f'<div class="intent-badge">{icon} Intent: {intent} <span style="opacity:0.6; font-size:0.8em">({src})</span></div>', unsafe_allow_html=True)
|
||||||
|
|
||||||
|
with st.expander("🐞 Debug Raw Payload", expanded=False):
|
||||||
|
st.json(msg)
|
||||||
|
|
||||||
|
if intent == "INTERVIEW":
|
||||||
|
render_draft_editor(msg)
|
||||||
|
else:
|
||||||
|
st.markdown(msg["content"])
|
||||||
|
|
||||||
|
if "sources" in msg and msg["sources"]:
|
||||||
|
for hit in msg["sources"]:
|
||||||
|
with st.expander(f"📄 {hit.get('note_id', '?')} ({hit.get('total_score', 0):.2f})"):
|
||||||
|
st.markdown(f"_{hit.get('source', {}).get('text', '')[:300]}..._")
|
||||||
|
if hit.get('explanation'):
|
||||||
|
st.caption(f"Grund: {hit['explanation']['reasons'][0]['message']}")
|
||||||
|
def _cb(qid=msg.get("query_id"), nid=hit.get('node_id')):
|
||||||
|
val = st.session_state.get(f"fb_src_{qid}_{nid}")
|
||||||
|
if val is not None: submit_feedback(qid, nid, val+1)
|
||||||
|
st.feedback("faces", key=f"fb_src_{msg.get('query_id')}_{hit.get('node_id')}", on_change=_cb)
|
||||||
|
|
||||||
|
if "query_id" in msg:
|
||||||
|
qid = msg["query_id"]
|
||||||
|
st.feedback("stars", key=f"fb_glob_{qid}", on_change=lambda: submit_feedback(qid, "generated_answer", st.session_state[f"fb_glob_{qid}"]+1))
|
||||||
|
else:
|
||||||
|
st.markdown(msg["content"])
|
||||||
|
|
||||||
|
if prompt := st.chat_input("Frage Mindnet..."):
|
||||||
|
st.session_state.messages.append({"role": "user", "content": prompt})
|
||||||
|
st.rerun()
|
||||||
|
|
||||||
|
if len(st.session_state.messages) > 0 and st.session_state.messages[-1]["role"] == "user":
|
||||||
|
with st.chat_message("assistant"):
|
||||||
|
with st.spinner("Thinking..."):
|
||||||
|
resp = send_chat_message(st.session_state.messages[-1]["content"], top_k, explain)
|
||||||
|
if "error" in resp:
|
||||||
|
st.error(resp["error"])
|
||||||
|
else:
|
||||||
|
st.session_state.messages.append({
|
||||||
|
"role": "assistant",
|
||||||
|
"content": resp.get("answer"),
|
||||||
|
"intent": resp.get("intent", "FACT"),
|
||||||
|
"intent_source": resp.get("intent_source", "Unknown"),
|
||||||
|
"sources": resp.get("sources", []),
|
||||||
|
"query_id": resp.get("query_id")
|
||||||
|
})
|
||||||
|
st.rerun()
|
||||||
|
|
||||||
|
def render_manual_editor():
|
||||||
|
mock_msg = {
|
||||||
|
"content": "---\ntype: concept\ntitle: Neue Notiz\nstatus: draft\ntags: []\n---\n# Titel\n",
|
||||||
|
"query_id": "manual_mode_v2"
|
||||||
|
}
|
||||||
|
render_draft_editor(mock_msg)
|
||||||
|
|
||||||
|
# --- MAIN ---
|
||||||
|
mode, top_k, explain = render_sidebar()
|
||||||
|
if mode == "💬 Chat":
|
||||||
|
render_chat_interface(top_k, explain)
|
||||||
|
else:
|
||||||
|
render_manual_editor()
|
||||||
+6
-1
@@ -13,6 +13,8 @@ from .routers.tools import router as tools_router
|
|||||||
from .routers.feedback import router as feedback_router
|
from .routers.feedback import router as feedback_router
|
||||||
# NEU: Chat Router (WP-05)
|
# NEU: Chat Router (WP-05)
|
||||||
from .routers.chat import router as chat_router
|
from .routers.chat import router as chat_router
|
||||||
|
# NEU: Ingest Router (WP-11)
|
||||||
|
from .routers.ingest import router as ingest_router
|
||||||
|
|
||||||
try:
|
try:
|
||||||
from .routers.admin import router as admin_router
|
from .routers.admin import router as admin_router
|
||||||
@@ -20,7 +22,7 @@ except Exception:
|
|||||||
admin_router = None
|
admin_router = None
|
||||||
|
|
||||||
def create_app() -> FastAPI:
|
def create_app() -> FastAPI:
|
||||||
app = FastAPI(title="mindnet API", version="0.5.0") # Version bump WP-05
|
app = FastAPI(title="mindnet API", version="0.6.0") # Version bump WP-11
|
||||||
s = get_settings()
|
s = get_settings()
|
||||||
|
|
||||||
@app.get("/healthz")
|
@app.get("/healthz")
|
||||||
@@ -38,6 +40,9 @@ def create_app() -> FastAPI:
|
|||||||
# NEU: Chat Endpoint
|
# NEU: Chat Endpoint
|
||||||
app.include_router(chat_router, prefix="/chat", tags=["chat"])
|
app.include_router(chat_router, prefix="/chat", tags=["chat"])
|
||||||
|
|
||||||
|
# NEU: Ingest Endpoint
|
||||||
|
app.include_router(ingest_router, prefix="/ingest", tags=["ingest"])
|
||||||
|
|
||||||
if admin_router:
|
if admin_router:
|
||||||
app.include_router(admin_router, prefix="/admin", tags=["admin"])
|
app.include_router(admin_router, prefix="/admin", tags=["admin"])
|
||||||
|
|
||||||
|
|||||||
+14
-7
@@ -3,12 +3,12 @@ app/models/dto.py — Pydantic-Modelle (DTOs) für WP-04/WP-05/WP-06
|
|||||||
|
|
||||||
Zweck:
|
Zweck:
|
||||||
Laufzeit-Modelle für FastAPI (Requests/Responses).
|
Laufzeit-Modelle für FastAPI (Requests/Responses).
|
||||||
WP-06 Update: Intent in ChatResponse.
|
WP-06 Update: Intent & Intent-Source in ChatResponse.
|
||||||
|
|
||||||
Version:
|
Version:
|
||||||
0.6.0 (WP-06: Decision Engine)
|
0.6.2 (WP-06: Decision Engine Transparency, Erweiterung des Feeback Request)
|
||||||
Stand:
|
Stand:
|
||||||
2025-12-08
|
2025-12-09
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
@@ -64,11 +64,14 @@ class QueryRequest(BaseModel):
|
|||||||
|
|
||||||
class FeedbackRequest(BaseModel):
|
class FeedbackRequest(BaseModel):
|
||||||
"""
|
"""
|
||||||
User-Feedback zu einem spezifischen Treffer.
|
User-Feedback zu einem spezifischen Treffer oder der Gesamtantwort.
|
||||||
"""
|
"""
|
||||||
query_id: str = Field(..., description="ID der ursprünglichen Suche")
|
query_id: str = Field(..., description="ID der ursprünglichen Suche")
|
||||||
node_id: str = Field(..., description="ID des bewerteten Treffers")
|
# node_id ist optional: Wenn leer oder "generated_answer", gilt es für die Antwort.
|
||||||
score: int = Field(..., ge=0, le=1, description="1 (Positiv) oder 0 (Negativ/Irrelevant)")
|
# Wenn eine echte Chunk-ID, gilt es für die Quelle.
|
||||||
|
node_id: str = Field(..., description="ID des bewerteten Treffers oder 'generated_answer'")
|
||||||
|
# Update: Range auf 1-5 erweitert für differenziertes Tuning
|
||||||
|
score: int = Field(..., ge=1, le=5, description="1 (Irrelevant/Falsch) bis 5 (Perfekt)")
|
||||||
comment: Optional[str] = None
|
comment: Optional[str] = None
|
||||||
|
|
||||||
|
|
||||||
@@ -123,6 +126,7 @@ class QueryHit(BaseModel):
|
|||||||
total_score: float
|
total_score: float
|
||||||
paths: Optional[List[List[Dict]]] = None
|
paths: Optional[List[List[Dict]]] = None
|
||||||
source: Optional[Dict] = None
|
source: Optional[Dict] = None
|
||||||
|
payload: Optional[Dict] = None # Added for flexibility & WP-06 meta-data
|
||||||
explanation: Optional[Explanation] = None
|
explanation: Optional[Explanation] = None
|
||||||
|
|
||||||
|
|
||||||
@@ -150,4 +154,7 @@ class ChatResponse(BaseModel):
|
|||||||
answer: str = Field(..., description="Generierte Antwort vom LLM")
|
answer: str = Field(..., description="Generierte Antwort vom LLM")
|
||||||
sources: List[QueryHit] = Field(..., description="Die für die Antwort genutzten Quellen")
|
sources: List[QueryHit] = Field(..., description="Die für die Antwort genutzten Quellen")
|
||||||
latency_ms: int
|
latency_ms: int
|
||||||
intent: Optional[str] = Field("FACT", description="WP-06: Erkannter Intent (FACT/DECISION)")
|
intent: Optional[str] = Field("FACT", description="WP-06: Erkannter Intent (FACT/DECISION)")
|
||||||
|
intent_source: Optional[str] = Field("Unknown", description="WP-06: Quelle der Intent-Erkennung (Keyword vs. LLM)")
|
||||||
|
|
||||||
|
|
||||||
+209
-94
@@ -1,20 +1,22 @@
|
|||||||
"""
|
"""
|
||||||
app/routers/chat.py — RAG Endpunkt (WP-06 Hybrid Router v2)
|
app/routers/chat.py — RAG Endpunkt
|
||||||
Update: Robusteres LLM-Parsing für Small Language Models (SLMs).
|
Version: 2.5.0 (Fix: Question Detection protects against False-Positive Interviews)
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from fastapi import APIRouter, HTTPException, Depends
|
from fastapi import APIRouter, HTTPException, Depends
|
||||||
from typing import List, Dict, Any
|
from typing import List, Dict, Any, Optional
|
||||||
import time
|
import time
|
||||||
import uuid
|
import uuid
|
||||||
import logging
|
import logging
|
||||||
import yaml
|
import yaml
|
||||||
|
import os
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
from app.config import get_settings
|
from app.config import get_settings
|
||||||
from app.models.dto import ChatRequest, ChatResponse, QueryRequest, QueryHit
|
from app.models.dto import ChatRequest, ChatResponse, QueryRequest, QueryHit
|
||||||
from app.services.llm_service import LLMService
|
from app.services.llm_service import LLMService
|
||||||
from app.core.retriever import Retriever
|
from app.core.retriever import Retriever
|
||||||
|
from app.services.feedback_service import log_search
|
||||||
|
|
||||||
router = APIRouter()
|
router = APIRouter()
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
@@ -22,6 +24,7 @@ logger = logging.getLogger(__name__)
|
|||||||
# --- Helper: Config Loader ---
|
# --- Helper: Config Loader ---
|
||||||
|
|
||||||
_DECISION_CONFIG_CACHE = None
|
_DECISION_CONFIG_CACHE = None
|
||||||
|
_TYPES_CONFIG_CACHE = None
|
||||||
|
|
||||||
def _load_decision_config() -> Dict[str, Any]:
|
def _load_decision_config() -> Dict[str, Any]:
|
||||||
settings = get_settings()
|
settings = get_settings()
|
||||||
@@ -43,17 +46,73 @@ def _load_decision_config() -> Dict[str, Any]:
|
|||||||
logger.error(f"Failed to load decision config: {e}")
|
logger.error(f"Failed to load decision config: {e}")
|
||||||
return default_config
|
return default_config
|
||||||
|
|
||||||
|
def _load_types_config() -> Dict[str, Any]:
|
||||||
|
"""Lädt die types.yaml für Keyword-Erkennung."""
|
||||||
|
path = os.getenv("MINDNET_TYPES_FILE", "config/types.yaml")
|
||||||
|
try:
|
||||||
|
with open(path, "r", encoding="utf-8") as f:
|
||||||
|
return yaml.safe_load(f) or {}
|
||||||
|
except Exception:
|
||||||
|
return {}
|
||||||
|
|
||||||
def get_full_config() -> Dict[str, Any]:
|
def get_full_config() -> Dict[str, Any]:
|
||||||
global _DECISION_CONFIG_CACHE
|
global _DECISION_CONFIG_CACHE
|
||||||
if _DECISION_CONFIG_CACHE is None:
|
if _DECISION_CONFIG_CACHE is None:
|
||||||
_DECISION_CONFIG_CACHE = _load_decision_config()
|
_DECISION_CONFIG_CACHE = _load_decision_config()
|
||||||
return _DECISION_CONFIG_CACHE
|
return _DECISION_CONFIG_CACHE
|
||||||
|
|
||||||
|
def get_types_config() -> Dict[str, Any]:
|
||||||
|
global _TYPES_CONFIG_CACHE
|
||||||
|
if _TYPES_CONFIG_CACHE is None:
|
||||||
|
_TYPES_CONFIG_CACHE = _load_types_config()
|
||||||
|
return _TYPES_CONFIG_CACHE
|
||||||
|
|
||||||
def get_decision_strategy(intent: str) -> Dict[str, Any]:
|
def get_decision_strategy(intent: str) -> Dict[str, Any]:
|
||||||
config = get_full_config()
|
config = get_full_config()
|
||||||
strategies = config.get("strategies", {})
|
strategies = config.get("strategies", {})
|
||||||
return strategies.get(intent, strategies.get("FACT", {}))
|
return strategies.get(intent, strategies.get("FACT", {}))
|
||||||
|
|
||||||
|
# --- Helper: Target Type Detection (WP-07) ---
|
||||||
|
|
||||||
|
def _detect_target_type(message: str, configured_schemas: Dict[str, Any]) -> str:
|
||||||
|
"""
|
||||||
|
Versucht zu erraten, welchen Notiz-Typ der User erstellen will.
|
||||||
|
Nutzt Keywords aus types.yaml UND Mappings.
|
||||||
|
"""
|
||||||
|
message_lower = message.lower()
|
||||||
|
|
||||||
|
# 1. Check types.yaml detection_keywords (Priority!)
|
||||||
|
types_cfg = get_types_config()
|
||||||
|
types_def = types_cfg.get("types", {})
|
||||||
|
|
||||||
|
for type_name, type_data in types_def.items():
|
||||||
|
keywords = type_data.get("detection_keywords", [])
|
||||||
|
for kw in keywords:
|
||||||
|
if kw.lower() in message_lower:
|
||||||
|
return type_name
|
||||||
|
|
||||||
|
# 2. Direkter Match mit Schema-Keys
|
||||||
|
for type_key in configured_schemas.keys():
|
||||||
|
if type_key == "default": continue
|
||||||
|
if type_key in message_lower:
|
||||||
|
return type_key
|
||||||
|
|
||||||
|
# 3. Synonym-Mapping (Legacy Fallback)
|
||||||
|
synonyms = {
|
||||||
|
"projekt": "project", "vorhaben": "project",
|
||||||
|
"entscheidung": "decision", "beschluss": "decision",
|
||||||
|
"ziel": "goal",
|
||||||
|
"erfahrung": "experience", "lektion": "experience",
|
||||||
|
"wert": "value",
|
||||||
|
"prinzip": "principle",
|
||||||
|
"notiz": "default", "idee": "default"
|
||||||
|
}
|
||||||
|
|
||||||
|
for term, schema_key in synonyms.items():
|
||||||
|
if term in message_lower:
|
||||||
|
return schema_key
|
||||||
|
|
||||||
|
return "default"
|
||||||
|
|
||||||
# --- Dependencies ---
|
# --- Dependencies ---
|
||||||
|
|
||||||
@@ -76,7 +135,10 @@ def _build_enriched_context(hits: List[QueryHit]) -> str:
|
|||||||
"[Kein Text]"
|
"[Kein Text]"
|
||||||
)
|
)
|
||||||
title = hit.note_id or "Unbekannt"
|
title = hit.note_id or "Unbekannt"
|
||||||
note_type = source.get("type", "unknown").upper()
|
|
||||||
|
payload = hit.payload or {}
|
||||||
|
note_type = payload.get("type") or source.get("type", "unknown")
|
||||||
|
note_type = str(note_type).upper()
|
||||||
|
|
||||||
entry = (
|
entry = (
|
||||||
f"### QUELLE {i}: {title}\n"
|
f"### QUELLE {i}: {title}\n"
|
||||||
@@ -87,70 +149,79 @@ def _build_enriched_context(hits: List[QueryHit]) -> str:
|
|||||||
|
|
||||||
return "\n\n".join(context_parts)
|
return "\n\n".join(context_parts)
|
||||||
|
|
||||||
async def _classify_intent(query: str, llm: LLMService) -> str:
|
def _is_question(query: str) -> bool:
|
||||||
|
"""Prüft, ob der Input wahrscheinlich eine Frage ist."""
|
||||||
|
q = query.strip().lower()
|
||||||
|
if "?" in q: return True
|
||||||
|
|
||||||
|
# W-Fragen Indikatoren (falls User das ? vergisst)
|
||||||
|
starters = ["wer", "wie", "was", "wo", "wann", "warum", "weshalb", "wozu", "welche", "bist du", "entspricht"]
|
||||||
|
if any(q.startswith(s + " ") for s in starters):
|
||||||
|
return True
|
||||||
|
|
||||||
|
return False
|
||||||
|
|
||||||
|
async def _classify_intent(query: str, llm: LLMService) -> tuple[str, str]:
|
||||||
"""
|
"""
|
||||||
Hybrid Router v2:
|
Hybrid Router v5:
|
||||||
1. Keyword Check (Best/Longest Match) -> FAST
|
1. Decision Keywords (Strategie) -> Prio 1
|
||||||
2. LLM Fallback (Robust Parsing) -> SMART
|
2. Type Keywords (Interview Trigger) -> Prio 2, ABER NUR WENN KEINE FRAGE!
|
||||||
|
3. LLM (Fallback) -> Prio 3
|
||||||
"""
|
"""
|
||||||
config = get_full_config()
|
config = get_full_config()
|
||||||
strategies = config.get("strategies", {})
|
strategies = config.get("strategies", {})
|
||||||
settings = config.get("settings", {})
|
settings = config.get("settings", {})
|
||||||
|
|
||||||
query_lower = query.lower()
|
query_lower = query.lower()
|
||||||
best_intent = None
|
|
||||||
max_match_length = 0
|
|
||||||
|
|
||||||
# 1. FAST PATH: Keywords
|
# 1. FAST PATH A: Strategie Keywords (z.B. "Soll ich...")
|
||||||
for intent_name, strategy in strategies.items():
|
for intent_name, strategy in strategies.items():
|
||||||
if intent_name == "FACT": continue
|
if intent_name == "FACT": continue
|
||||||
keywords = strategy.get("trigger_keywords", [])
|
keywords = strategy.get("trigger_keywords", [])
|
||||||
for k in keywords:
|
for k in keywords:
|
||||||
if k.lower() in query_lower:
|
if k.lower() in query_lower:
|
||||||
if len(k) > max_match_length:
|
return intent_name, "Keyword (Strategy)"
|
||||||
max_match_length = len(k)
|
|
||||||
best_intent = intent_name
|
|
||||||
|
|
||||||
if best_intent:
|
# 2. FAST PATH B: Type Keywords (z.B. "Projekt", "Werte") -> INTERVIEW
|
||||||
logger.info(f"Intent detected via KEYWORD: {best_intent}")
|
# FIX: Wir prüfen, ob es eine Frage ist. Fragen zu Typen sollen RAG (FACT/DECISION) sein,
|
||||||
return best_intent
|
# keine Interviews. Wir überlassen das dann dem LLM Router (Slow Path).
|
||||||
|
|
||||||
|
if not _is_question(query_lower):
|
||||||
|
types_cfg = get_types_config()
|
||||||
|
types_def = types_cfg.get("types", {})
|
||||||
|
|
||||||
|
for type_name, type_data in types_def.items():
|
||||||
|
keywords = type_data.get("detection_keywords", [])
|
||||||
|
for kw in keywords:
|
||||||
|
if kw.lower() in query_lower:
|
||||||
|
return "INTERVIEW", f"Keyword (Type: {type_name})"
|
||||||
|
|
||||||
# 2. SLOW PATH: LLM Router
|
# 3. SLOW PATH: LLM Router
|
||||||
if settings.get("llm_fallback_enabled", False):
|
if settings.get("llm_fallback_enabled", False):
|
||||||
router_prompt_template = settings.get("llm_router_prompt", "")
|
# Nutze Prompts aus prompts.yaml (via LLM Service)
|
||||||
|
router_prompt_template = llm.prompts.get("router_prompt", "")
|
||||||
|
|
||||||
if router_prompt_template:
|
if router_prompt_template:
|
||||||
prompt = router_prompt_template.replace("{query}", query)
|
prompt = router_prompt_template.replace("{query}", query)
|
||||||
logger.info("Keywords failed. Asking LLM for Intent...")
|
logger.info("Keywords failed (or Question detected). Asking LLM for Intent...")
|
||||||
|
|
||||||
# Kurzer Raw Call
|
try:
|
||||||
raw_response = await llm.generate_raw_response(prompt)
|
# Nutze priority="realtime" für den Router, damit er nicht wartet
|
||||||
|
raw_response = await llm.generate_raw_response(prompt, priority="realtime")
|
||||||
# --- Robust Parsing für SLMs ---
|
llm_output_upper = raw_response.upper()
|
||||||
# Wir suchen nach den bekannten Strategie-Namen im Output
|
|
||||||
llm_output_upper = raw_response.upper()
|
|
||||||
logger.info(f"LLM Router Raw Output: '{raw_response}'") # Debugging
|
|
||||||
|
|
||||||
found_intents = []
|
|
||||||
for strat_key in strategies.keys():
|
|
||||||
# Wir prüfen, ob der Strategie-Name (z.B. "EMPATHY") im Text vorkommt
|
|
||||||
if strat_key in llm_output_upper:
|
|
||||||
found_intents.append(strat_key)
|
|
||||||
|
|
||||||
# Entscheidung
|
|
||||||
final_intent = "FACT"
|
|
||||||
if len(found_intents) == 1:
|
|
||||||
# Eindeutiger Treffer
|
|
||||||
final_intent = found_intents[0]
|
|
||||||
logger.info(f"Intent detected via LLM (Parsed): {final_intent}")
|
|
||||||
return final_intent
|
|
||||||
elif len(found_intents) > 1:
|
|
||||||
# Mehrere Treffer (z.B. "Es ist FACT oder DECISION") -> Nimm den ersten oder Fallback
|
|
||||||
logger.warning(f"LLM returned multiple intents {found_intents}. Using first match: {found_intents[0]}")
|
|
||||||
return found_intents[0]
|
|
||||||
else:
|
|
||||||
logger.warning(f"LLM did not return a valid strategy name. Falling back to FACT.")
|
|
||||||
|
|
||||||
return "FACT"
|
# Zuerst INTERVIEW prüfen
|
||||||
|
if "INTERVIEW" in llm_output_upper or "CREATE" in llm_output_upper:
|
||||||
|
return "INTERVIEW", "LLM Router"
|
||||||
|
|
||||||
|
for strat_key in strategies.keys():
|
||||||
|
if strat_key in llm_output_upper:
|
||||||
|
return strat_key, "LLM Router"
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"Router LLM failed: {e}")
|
||||||
|
|
||||||
|
return "FACT", "Default (No Match)"
|
||||||
|
|
||||||
@router.post("/", response_model=ChatResponse)
|
@router.post("/", response_model=ChatResponse)
|
||||||
async def chat_endpoint(
|
async def chat_endpoint(
|
||||||
@@ -164,70 +235,114 @@ async def chat_endpoint(
|
|||||||
|
|
||||||
try:
|
try:
|
||||||
# 1. Intent Detection
|
# 1. Intent Detection
|
||||||
intent = await _classify_intent(request.message, llm)
|
intent, intent_source = await _classify_intent(request.message, llm)
|
||||||
logger.info(f"[{query_id}] Final Intent: {intent}")
|
logger.info(f"[{query_id}] Final Intent: {intent} via {intent_source}")
|
||||||
|
|
||||||
# Strategy Load
|
# Strategy Load
|
||||||
strategy = get_decision_strategy(intent)
|
strategy = get_decision_strategy(intent)
|
||||||
inject_types = strategy.get("inject_types", [])
|
|
||||||
prompt_key = strategy.get("prompt_template", "rag_template")
|
prompt_key = strategy.get("prompt_template", "rag_template")
|
||||||
prepend_instr = strategy.get("prepend_instruction", "")
|
|
||||||
|
|
||||||
# 2. Primary Retrieval
|
|
||||||
query_req = QueryRequest(
|
|
||||||
query=request.message,
|
|
||||||
mode="hybrid",
|
|
||||||
top_k=request.top_k,
|
|
||||||
explain=request.explain
|
|
||||||
)
|
|
||||||
retrieve_result = await retriever.search(query_req)
|
|
||||||
hits = retrieve_result.results
|
|
||||||
|
|
||||||
# 3. Strategic Retrieval
|
sources_hits = []
|
||||||
if inject_types:
|
final_prompt = ""
|
||||||
logger.info(f"[{query_id}] Executing Strategic Retrieval for types: {inject_types}...")
|
|
||||||
strategy_req = QueryRequest(
|
if intent == "INTERVIEW":
|
||||||
query=request.message,
|
# --- INTERVIEW MODE ---
|
||||||
mode="hybrid",
|
target_type = _detect_target_type(request.message, strategy.get("schemas", {}))
|
||||||
top_k=3,
|
|
||||||
filters={"type": inject_types},
|
|
||||||
explain=False
|
|
||||||
)
|
|
||||||
strategy_result = await retriever.search(strategy_req)
|
|
||||||
|
|
||||||
existing_ids = {h.node_id for h in hits}
|
types_cfg = get_types_config()
|
||||||
for strat_hit in strategy_result.results:
|
type_def = types_cfg.get("types", {}).get(target_type, {})
|
||||||
if strat_hit.node_id not in existing_ids:
|
fields_list = type_def.get("schema", [])
|
||||||
hits.append(strat_hit)
|
|
||||||
|
if not fields_list:
|
||||||
|
configured_schemas = strategy.get("schemas", {})
|
||||||
|
fallback_schema = configured_schemas.get(target_type, configured_schemas.get("default"))
|
||||||
|
if isinstance(fallback_schema, dict):
|
||||||
|
fields_list = fallback_schema.get("fields", [])
|
||||||
|
else:
|
||||||
|
fields_list = fallback_schema or []
|
||||||
|
|
||||||
# 4. Context Building
|
logger.info(f"[{query_id}] Interview Type: {target_type}. Fields: {len(fields_list)}")
|
||||||
if not hits:
|
fields_str = "\n- " + "\n- ".join(fields_list)
|
||||||
context_str = "Keine relevanten Notizen gefunden."
|
|
||||||
|
template = llm.prompts.get(prompt_key, "")
|
||||||
|
final_prompt = template.replace("{context_str}", "Dialogverlauf...") \
|
||||||
|
.replace("{query}", request.message) \
|
||||||
|
.replace("{target_type}", target_type) \
|
||||||
|
.replace("{schema_fields}", fields_str) \
|
||||||
|
.replace("{schema_hint}", "")
|
||||||
|
sources_hits = []
|
||||||
|
|
||||||
else:
|
else:
|
||||||
context_str = _build_enriched_context(hits)
|
# --- RAG MODE ---
|
||||||
|
inject_types = strategy.get("inject_types", [])
|
||||||
|
prepend_instr = strategy.get("prepend_instruction", "")
|
||||||
|
|
||||||
# 5. Generation
|
query_req = QueryRequest(
|
||||||
template = llm.prompts.get(prompt_key, "{context_str}\n\n{query}")
|
query=request.message,
|
||||||
|
mode="hybrid",
|
||||||
|
top_k=request.top_k,
|
||||||
|
explain=request.explain
|
||||||
|
)
|
||||||
|
retrieve_result = await retriever.search(query_req)
|
||||||
|
hits = retrieve_result.results
|
||||||
|
|
||||||
|
if inject_types:
|
||||||
|
strategy_req = QueryRequest(
|
||||||
|
query=request.message,
|
||||||
|
mode="hybrid",
|
||||||
|
top_k=3,
|
||||||
|
filters={"type": inject_types},
|
||||||
|
explain=False
|
||||||
|
)
|
||||||
|
strategy_result = await retriever.search(strategy_req)
|
||||||
|
existing_ids = {h.node_id for h in hits}
|
||||||
|
for strat_hit in strategy_result.results:
|
||||||
|
if strat_hit.node_id not in existing_ids:
|
||||||
|
hits.append(strat_hit)
|
||||||
|
|
||||||
|
if not hits:
|
||||||
|
context_str = "Keine relevanten Notizen gefunden."
|
||||||
|
else:
|
||||||
|
context_str = _build_enriched_context(hits)
|
||||||
|
|
||||||
|
template = llm.prompts.get(prompt_key, "{context_str}\n\n{query}")
|
||||||
|
|
||||||
|
if prepend_instr:
|
||||||
|
context_str = f"{prepend_instr}\n\n{context_str}"
|
||||||
|
|
||||||
|
final_prompt = template.replace("{context_str}", context_str).replace("{query}", request.message)
|
||||||
|
sources_hits = hits
|
||||||
|
|
||||||
|
# --- GENERATION ---
|
||||||
system_prompt = llm.prompts.get("system_prompt", "")
|
system_prompt = llm.prompts.get("system_prompt", "")
|
||||||
|
|
||||||
if prepend_instr:
|
# Chat nutzt IMMER realtime priority
|
||||||
context_str = f"{prepend_instr}\n\n{context_str}"
|
answer_text = await llm.generate_raw_response(
|
||||||
|
prompt=final_prompt,
|
||||||
final_prompt = template.replace("{context_str}", context_str).replace("{query}", request.message)
|
system=system_prompt,
|
||||||
|
priority="realtime"
|
||||||
logger.info(f"[{query_id}] Sending to LLM (Intent: {intent}, Template: {prompt_key})...")
|
)
|
||||||
|
|
||||||
# System-Prompt separat übergeben
|
|
||||||
answer_text = await llm.generate_raw_response(prompt=final_prompt, system=system_prompt)
|
|
||||||
|
|
||||||
duration_ms = int((time.time() - start_time) * 1000)
|
duration_ms = int((time.time() - start_time) * 1000)
|
||||||
|
|
||||||
|
# Logging
|
||||||
|
try:
|
||||||
|
log_search(
|
||||||
|
query_id=query_id,
|
||||||
|
query_text=request.message,
|
||||||
|
results=sources_hits,
|
||||||
|
mode="interview" if intent == "INTERVIEW" else "chat_rag",
|
||||||
|
metadata={"intent": intent, "source": intent_source}
|
||||||
|
)
|
||||||
|
except: pass
|
||||||
|
|
||||||
return ChatResponse(
|
return ChatResponse(
|
||||||
query_id=query_id,
|
query_id=query_id,
|
||||||
answer=answer_text,
|
answer=answer_text,
|
||||||
sources=hits,
|
sources=sources_hits,
|
||||||
latency_ms=duration_ms,
|
latency_ms=duration_ms,
|
||||||
intent=intent
|
intent=intent,
|
||||||
|
intent_source=intent_source
|
||||||
)
|
)
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
|
|||||||
@@ -0,0 +1,89 @@
|
|||||||
|
"""
|
||||||
|
app/routers/ingest.py
|
||||||
|
API-Endpunkte für WP-11 (Discovery & Persistence).
|
||||||
|
Delegiert an Services.
|
||||||
|
"""
|
||||||
|
import os
|
||||||
|
import time
|
||||||
|
import logging
|
||||||
|
from fastapi import APIRouter, HTTPException
|
||||||
|
from pydantic import BaseModel
|
||||||
|
from typing import Optional, Dict, Any
|
||||||
|
|
||||||
|
from app.core.ingestion import IngestionService
|
||||||
|
from app.services.discovery import DiscoveryService
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
router = APIRouter()
|
||||||
|
|
||||||
|
# Services Init (Global oder via Dependency Injection)
|
||||||
|
discovery_service = DiscoveryService()
|
||||||
|
|
||||||
|
class AnalyzeRequest(BaseModel):
|
||||||
|
text: str
|
||||||
|
type: str = "concept"
|
||||||
|
|
||||||
|
class SaveRequest(BaseModel):
|
||||||
|
markdown_content: str
|
||||||
|
filename: Optional[str] = None
|
||||||
|
folder: str = "00_Inbox"
|
||||||
|
|
||||||
|
class SaveResponse(BaseModel):
|
||||||
|
status: str
|
||||||
|
file_path: str
|
||||||
|
note_id: str
|
||||||
|
stats: Dict[str, Any]
|
||||||
|
|
||||||
|
@router.post("/analyze")
|
||||||
|
async def analyze_draft(req: AnalyzeRequest):
|
||||||
|
"""
|
||||||
|
WP-11 Intelligence: Liefert Link-Vorschläge via DiscoveryService.
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
# Hier rufen wir jetzt den verbesserten Service auf
|
||||||
|
result = await discovery_service.analyze_draft(req.text, req.type)
|
||||||
|
return result
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"Analyze failed: {e}", exc_info=True)
|
||||||
|
return {"suggestions": [], "error": str(e)}
|
||||||
|
|
||||||
|
@router.post("/save", response_model=SaveResponse)
|
||||||
|
async def save_note(req: SaveRequest):
|
||||||
|
"""
|
||||||
|
WP-11 Persistence: Speichert und indiziert.
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
vault_root = os.getenv("MINDNET_VAULT_ROOT", "./vault")
|
||||||
|
abs_vault_root = os.path.abspath(vault_root)
|
||||||
|
|
||||||
|
if not os.path.exists(abs_vault_root):
|
||||||
|
try: os.makedirs(abs_vault_root, exist_ok=True)
|
||||||
|
except: pass
|
||||||
|
|
||||||
|
final_filename = req.filename or f"draft_{int(time.time())}.md"
|
||||||
|
ingest_service = IngestionService()
|
||||||
|
|
||||||
|
# Async Call
|
||||||
|
result = await ingest_service.create_from_text(
|
||||||
|
markdown_content=req.markdown_content,
|
||||||
|
filename=final_filename,
|
||||||
|
vault_root=abs_vault_root,
|
||||||
|
folder=req.folder
|
||||||
|
)
|
||||||
|
|
||||||
|
if result.get("status") == "error":
|
||||||
|
raise HTTPException(status_code=500, detail=result.get("error"))
|
||||||
|
|
||||||
|
return SaveResponse(
|
||||||
|
status="success",
|
||||||
|
file_path=result.get("path", "unknown"),
|
||||||
|
note_id=result.get("note_id", "unknown"),
|
||||||
|
stats={
|
||||||
|
"chunks": result.get("chunks_count", 0),
|
||||||
|
"edges": result.get("edges_count", 0)
|
||||||
|
}
|
||||||
|
)
|
||||||
|
except HTTPException as he: raise he
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"Save failed: {e}", exc_info=True)
|
||||||
|
raise HTTPException(status_code=500, detail=f"Save failed: {str(e)}")
|
||||||
@@ -0,0 +1,255 @@
|
|||||||
|
"""
|
||||||
|
app/services/discovery.py
|
||||||
|
Service für Link-Vorschläge und Knowledge-Discovery (WP-11).
|
||||||
|
|
||||||
|
Features:
|
||||||
|
- Sliding Window Analyse für lange Texte.
|
||||||
|
- Footer-Scan für Projekt-Referenzen.
|
||||||
|
- 'Matrix-Logic' für intelligente Kanten-Typen (Experience -> Value = based_on).
|
||||||
|
- Async & Nomic-Embeddings kompatibel.
|
||||||
|
"""
|
||||||
|
import logging
|
||||||
|
import asyncio
|
||||||
|
import os
|
||||||
|
from typing import List, Dict, Any, Optional, Set
|
||||||
|
import yaml
|
||||||
|
|
||||||
|
from app.core.qdrant import QdrantConfig, get_client
|
||||||
|
from app.models.dto import QueryRequest
|
||||||
|
from app.core.retriever import hybrid_retrieve
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
class DiscoveryService:
|
||||||
|
def __init__(self, collection_prefix: str = None):
|
||||||
|
self.cfg = QdrantConfig.from_env()
|
||||||
|
self.prefix = collection_prefix or self.cfg.prefix or "mindnet"
|
||||||
|
self.client = get_client(self.cfg)
|
||||||
|
self.registry = self._load_type_registry()
|
||||||
|
|
||||||
|
async def analyze_draft(self, text: str, current_type: str) -> Dict[str, Any]:
|
||||||
|
"""
|
||||||
|
Analysiert den Text und liefert Vorschläge mit kontext-sensitiven Kanten-Typen.
|
||||||
|
"""
|
||||||
|
suggestions = []
|
||||||
|
|
||||||
|
# Fallback, falls keine spezielle Regel greift
|
||||||
|
default_edge_type = self._get_default_edge_type(current_type)
|
||||||
|
|
||||||
|
# Tracking-Sets für Deduplizierung (Wir merken uns NOTE-IDs)
|
||||||
|
seen_target_note_ids = set()
|
||||||
|
|
||||||
|
# ---------------------------------------------------------
|
||||||
|
# 1. Exact Match: Titel/Aliases
|
||||||
|
# ---------------------------------------------------------
|
||||||
|
# Holt Titel, Aliases UND Typen aus dem Index
|
||||||
|
known_entities = self._fetch_all_titles_and_aliases()
|
||||||
|
found_entities = self._find_entities_in_text(text, known_entities)
|
||||||
|
|
||||||
|
for entity in found_entities:
|
||||||
|
if entity["id"] in seen_target_note_ids:
|
||||||
|
continue
|
||||||
|
seen_target_note_ids.add(entity["id"])
|
||||||
|
|
||||||
|
# INTELLIGENTE KANTEN-LOGIK (MATRIX)
|
||||||
|
target_type = entity.get("type", "concept")
|
||||||
|
smart_edge = self._resolve_edge_type(current_type, target_type)
|
||||||
|
|
||||||
|
suggestions.append({
|
||||||
|
"type": "exact_match",
|
||||||
|
"text_found": entity["match"],
|
||||||
|
"target_title": entity["title"],
|
||||||
|
"target_id": entity["id"],
|
||||||
|
"suggested_edge_type": smart_edge,
|
||||||
|
"suggested_markdown": f"[[rel:{smart_edge} {entity['title']}]]",
|
||||||
|
"confidence": 1.0,
|
||||||
|
"reason": f"Exakter Treffer: '{entity['match']}' ({target_type})"
|
||||||
|
})
|
||||||
|
|
||||||
|
# ---------------------------------------------------------
|
||||||
|
# 2. Semantic Match: Sliding Window & Footer Focus
|
||||||
|
# ---------------------------------------------------------
|
||||||
|
search_queries = self._generate_search_queries(text)
|
||||||
|
|
||||||
|
# Async parallel abfragen
|
||||||
|
tasks = [self._get_semantic_suggestions_async(q) for q in search_queries]
|
||||||
|
results_list = await asyncio.gather(*tasks)
|
||||||
|
|
||||||
|
# Ergebnisse verarbeiten
|
||||||
|
for hits in results_list:
|
||||||
|
for hit in hits:
|
||||||
|
note_id = hit.payload.get("note_id")
|
||||||
|
if not note_id: continue
|
||||||
|
|
||||||
|
# Deduplizierung (Notiz-Ebene)
|
||||||
|
if note_id in seen_target_note_ids:
|
||||||
|
continue
|
||||||
|
|
||||||
|
# Score Check (Threshold 0.50 für nomic-embed-text)
|
||||||
|
if hit.total_score > 0.50:
|
||||||
|
seen_target_note_ids.add(note_id)
|
||||||
|
|
||||||
|
target_title = hit.payload.get("title") or "Unbekannt"
|
||||||
|
|
||||||
|
# INTELLIGENTE KANTEN-LOGIK (MATRIX)
|
||||||
|
# Den Typ der gefundenen Notiz aus dem Payload lesen
|
||||||
|
target_type = hit.payload.get("type", "concept")
|
||||||
|
smart_edge = self._resolve_edge_type(current_type, target_type)
|
||||||
|
|
||||||
|
suggestions.append({
|
||||||
|
"type": "semantic_match",
|
||||||
|
"text_found": (hit.source.get("text") or "")[:60] + "...",
|
||||||
|
"target_title": target_title,
|
||||||
|
"target_id": note_id,
|
||||||
|
"suggested_edge_type": smart_edge,
|
||||||
|
"suggested_markdown": f"[[rel:{smart_edge} {target_title}]]",
|
||||||
|
"confidence": round(hit.total_score, 2),
|
||||||
|
"reason": f"Semantisch ähnlich zu {target_type} ({hit.total_score:.2f})"
|
||||||
|
})
|
||||||
|
|
||||||
|
# Sortieren nach Confidence
|
||||||
|
suggestions.sort(key=lambda x: x["confidence"], reverse=True)
|
||||||
|
|
||||||
|
return {
|
||||||
|
"draft_length": len(text),
|
||||||
|
"analyzed_windows": len(search_queries),
|
||||||
|
"suggestions_count": len(suggestions),
|
||||||
|
"suggestions": suggestions[:10]
|
||||||
|
}
|
||||||
|
|
||||||
|
# ---------------------------------------------------------
|
||||||
|
# Core Logic: Die Matrix
|
||||||
|
# ---------------------------------------------------------
|
||||||
|
|
||||||
|
def _resolve_edge_type(self, source_type: str, target_type: str) -> str:
|
||||||
|
"""
|
||||||
|
Entscheidungsmatrix für komplexe Verbindungen.
|
||||||
|
Definiert, wie Typ A auf Typ B verlinken sollte.
|
||||||
|
"""
|
||||||
|
st = source_type.lower()
|
||||||
|
tt = target_type.lower()
|
||||||
|
|
||||||
|
# Regeln für 'experience' (Erfahrungen)
|
||||||
|
if st == "experience":
|
||||||
|
if tt == "value": return "based_on"
|
||||||
|
if tt == "principle": return "derived_from"
|
||||||
|
if tt == "trip": return "part_of"
|
||||||
|
if tt == "lesson": return "learned"
|
||||||
|
if tt == "project": return "related_to" # oder belongs_to
|
||||||
|
|
||||||
|
# Regeln für 'project'
|
||||||
|
if st == "project":
|
||||||
|
if tt == "decision": return "depends_on"
|
||||||
|
if tt == "concept": return "uses"
|
||||||
|
if tt == "person": return "managed_by"
|
||||||
|
|
||||||
|
# Regeln für 'decision' (ADR)
|
||||||
|
if st == "decision":
|
||||||
|
if tt == "principle": return "compliant_with"
|
||||||
|
if tt == "requirement": return "addresses"
|
||||||
|
|
||||||
|
# Fallback: Standard aus der types.yaml für den Source-Typ
|
||||||
|
return self._get_default_edge_type(st)
|
||||||
|
|
||||||
|
# ---------------------------------------------------------
|
||||||
|
# Sliding Windows
|
||||||
|
# ---------------------------------------------------------
|
||||||
|
|
||||||
|
def _generate_search_queries(self, text: str) -> List[str]:
|
||||||
|
"""
|
||||||
|
Erzeugt intelligente Fenster + Footer Scan.
|
||||||
|
"""
|
||||||
|
text_len = len(text)
|
||||||
|
if not text: return []
|
||||||
|
|
||||||
|
queries = []
|
||||||
|
|
||||||
|
# 1. Start / Gesamtkontext
|
||||||
|
queries.append(text[:600])
|
||||||
|
|
||||||
|
# 2. Footer-Scan (Wichtig für "Projekt"-Referenzen am Ende)
|
||||||
|
if text_len > 150:
|
||||||
|
footer = text[-250:]
|
||||||
|
if footer not in queries:
|
||||||
|
queries.append(footer)
|
||||||
|
|
||||||
|
# 3. Sliding Window für lange Texte
|
||||||
|
if text_len > 800:
|
||||||
|
window_size = 500
|
||||||
|
step = 1500
|
||||||
|
for i in range(window_size, text_len - window_size, step):
|
||||||
|
end_pos = min(i + window_size, text_len)
|
||||||
|
chunk = text[i:end_pos]
|
||||||
|
if len(chunk) > 100:
|
||||||
|
queries.append(chunk)
|
||||||
|
|
||||||
|
return queries
|
||||||
|
|
||||||
|
# ---------------------------------------------------------
|
||||||
|
# Standard Helpers
|
||||||
|
# ---------------------------------------------------------
|
||||||
|
|
||||||
|
async def _get_semantic_suggestions_async(self, text: str):
|
||||||
|
req = QueryRequest(query=text, top_k=5, explain=False)
|
||||||
|
try:
|
||||||
|
res = hybrid_retrieve(req)
|
||||||
|
return res.results
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"Semantic suggestion error: {e}")
|
||||||
|
return []
|
||||||
|
|
||||||
|
def _load_type_registry(self) -> dict:
|
||||||
|
path = os.getenv("MINDNET_TYPES_FILE", "config/types.yaml")
|
||||||
|
if not os.path.exists(path):
|
||||||
|
if os.path.exists("types.yaml"): path = "types.yaml"
|
||||||
|
else: return {}
|
||||||
|
try:
|
||||||
|
with open(path, "r", encoding="utf-8") as f: return yaml.safe_load(f) or {}
|
||||||
|
except Exception: return {}
|
||||||
|
|
||||||
|
def _get_default_edge_type(self, note_type: str) -> str:
|
||||||
|
types_cfg = self.registry.get("types", {})
|
||||||
|
type_def = types_cfg.get(note_type, {})
|
||||||
|
defaults = type_def.get("edge_defaults")
|
||||||
|
return defaults[0] if defaults else "related_to"
|
||||||
|
|
||||||
|
def _fetch_all_titles_and_aliases(self) -> List[Dict]:
|
||||||
|
notes = []
|
||||||
|
next_page = None
|
||||||
|
col = f"{self.prefix}_notes"
|
||||||
|
try:
|
||||||
|
while True:
|
||||||
|
res, next_page = self.client.scroll(
|
||||||
|
collection_name=col, limit=1000, offset=next_page,
|
||||||
|
with_payload=True, with_vectors=False
|
||||||
|
)
|
||||||
|
for point in res:
|
||||||
|
pl = point.payload or {}
|
||||||
|
aliases = pl.get("aliases") or []
|
||||||
|
if isinstance(aliases, str): aliases = [aliases]
|
||||||
|
|
||||||
|
notes.append({
|
||||||
|
"id": pl.get("note_id"),
|
||||||
|
"title": pl.get("title"),
|
||||||
|
"aliases": aliases,
|
||||||
|
"type": pl.get("type", "concept") # WICHTIG: Typ laden für Matrix
|
||||||
|
})
|
||||||
|
if next_page is None: break
|
||||||
|
except Exception: pass
|
||||||
|
return notes
|
||||||
|
|
||||||
|
def _find_entities_in_text(self, text: str, entities: List[Dict]) -> List[Dict]:
|
||||||
|
found = []
|
||||||
|
text_lower = text.lower()
|
||||||
|
for entity in entities:
|
||||||
|
# Title Check
|
||||||
|
title = entity.get("title")
|
||||||
|
if title and title.lower() in text_lower:
|
||||||
|
found.append({"match": title, "title": title, "id": entity["id"], "type": entity["type"]})
|
||||||
|
continue
|
||||||
|
# Alias Check
|
||||||
|
for alias in entity.get("aliases", []):
|
||||||
|
if str(alias).lower() in text_lower:
|
||||||
|
found.append({"match": alias, "title": title, "id": entity["id"], "type": entity["type"]})
|
||||||
|
break
|
||||||
|
return found
|
||||||
@@ -1,46 +1,90 @@
|
|||||||
"""
|
"""
|
||||||
app/services/embeddings_client.py — Text→Embedding (WP-04)
|
app/services/embeddings_client.py — Text→Embedding Service
|
||||||
|
|
||||||
Zweck:
|
Zweck:
|
||||||
Liefert 384-d Embeddings für Textqueries (lazy load, einmal pro Prozess).
|
Einheitlicher Client für Embeddings via Ollama (Nomic).
|
||||||
Standard: Sentence-Transformers (MODEL_NAME aus app.config.Settings).
|
Stellt sicher, dass sowohl Async (Ingestion) als auch Sync (Retriever)
|
||||||
Hinweis: Kein Netz-Zugriff; nutzt lokal installierte Modelle.
|
denselben Vektorraum (768 Dim) nutzen.
|
||||||
Kompatibilität:
|
|
||||||
Python 3.12+, sentence-transformers 5.x
|
|
||||||
Version:
|
|
||||||
0.1.0 (Erstanlage)
|
|
||||||
Stand:
|
|
||||||
2025-10-07
|
|
||||||
Bezug:
|
|
||||||
- app/core/retriever.py (nutzt embed_text_if_needed)
|
|
||||||
- app/config.py (MODEL_NAME, VECTOR_SIZE)
|
|
||||||
Nutzung:
|
|
||||||
from app.services.embeddings_client import embed_text
|
|
||||||
Änderungsverlauf:
|
|
||||||
0.1.0 (2025-10-07) – Erstanlage.
|
|
||||||
"""
|
|
||||||
|
|
||||||
|
Version: 2.5.0 (Unified Ollama)
|
||||||
|
"""
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
import os
|
||||||
|
import logging
|
||||||
|
import httpx
|
||||||
|
import requests # Für den synchronen Fallback
|
||||||
from typing import List
|
from typing import List
|
||||||
from functools import lru_cache
|
|
||||||
from app.config import get_settings
|
from app.config import get_settings
|
||||||
|
|
||||||
# Lazy import, damit Testläufe ohne Modell-Laden schnell sind
|
logger = logging.getLogger(__name__)
|
||||||
def _load_model():
|
|
||||||
from sentence_transformers import SentenceTransformer # import hier, nicht top-level
|
|
||||||
s = get_settings()
|
|
||||||
return SentenceTransformer(s.MODEL_NAME, device="cpu")
|
|
||||||
|
|
||||||
@lru_cache(maxsize=1)
|
class EmbeddingsClient:
|
||||||
def _cached_model():
|
"""
|
||||||
return _load_model()
|
Async Client für Embeddings via Ollama.
|
||||||
|
"""
|
||||||
|
def __init__(self):
|
||||||
|
self.settings = get_settings()
|
||||||
|
self.base_url = os.getenv("MINDNET_OLLAMA_URL", "http://127.0.0.1:11434")
|
||||||
|
self.model = os.getenv("MINDNET_EMBEDDING_MODEL")
|
||||||
|
|
||||||
|
if not self.model:
|
||||||
|
self.model = os.getenv("MINDNET_LLM_MODEL", "phi3:mini")
|
||||||
|
logger.warning(f"No MINDNET_EMBEDDING_MODEL set. Fallback to '{self.model}'.")
|
||||||
|
|
||||||
|
async def embed_query(self, text: str) -> List[float]:
|
||||||
|
return await self._request_embedding(text)
|
||||||
|
|
||||||
|
async def embed_documents(self, texts: List[str]) -> List[List[float]]:
|
||||||
|
vectors = []
|
||||||
|
# Längeres Timeout für Batches
|
||||||
|
async with httpx.AsyncClient(timeout=120.0) as client:
|
||||||
|
for text in texts:
|
||||||
|
vec = await self._request_embedding_with_client(client, text)
|
||||||
|
vectors.append(vec)
|
||||||
|
return vectors
|
||||||
|
|
||||||
|
async def _request_embedding(self, text: str) -> List[float]:
|
||||||
|
async with httpx.AsyncClient(timeout=30.0) as client:
|
||||||
|
return await self._request_embedding_with_client(client, text)
|
||||||
|
|
||||||
|
async def _request_embedding_with_client(self, client: httpx.AsyncClient, text: str) -> List[float]:
|
||||||
|
if not text or not text.strip(): return []
|
||||||
|
url = f"{self.base_url}/api/embeddings"
|
||||||
|
try:
|
||||||
|
response = await client.post(url, json={"model": self.model, "prompt": text})
|
||||||
|
response.raise_for_status()
|
||||||
|
return response.json().get("embedding", [])
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"Async embedding failed: {e}")
|
||||||
|
return []
|
||||||
|
|
||||||
|
# ==============================================================================
|
||||||
|
# TEIL 2: SYNCHRONER FALLBACK (Unified)
|
||||||
|
# ==============================================================================
|
||||||
|
|
||||||
def embed_text(text: str) -> List[float]:
|
def embed_text(text: str) -> List[float]:
|
||||||
"""
|
"""
|
||||||
Erzeugt einen 384-d Vektor (oder laut Settings.VECTOR_SIZE) für den gegebenen Text.
|
LEGACY/SYNC: Nutzt jetzt ebenfalls OLLAMA via 'requests'.
|
||||||
|
Ersetzt SentenceTransformers, um Dimensionskonflikte (768 vs 384) zu lösen.
|
||||||
"""
|
"""
|
||||||
if not text or not text.strip():
|
if not text or not text.strip():
|
||||||
raise ValueError("embed_text: leerer Text")
|
return []
|
||||||
model = _cached_model()
|
|
||||||
vec = model.encode([text], normalize_embeddings=True)[0]
|
base_url = os.getenv("MINDNET_OLLAMA_URL", "http://127.0.0.1:11434")
|
||||||
return vec.astype(float).tolist()
|
model = os.getenv("MINDNET_EMBEDDING_MODEL")
|
||||||
|
|
||||||
|
# Fallback logik identisch zur Klasse
|
||||||
|
if not model:
|
||||||
|
model = os.getenv("MINDNET_LLM_MODEL", "phi3:mini")
|
||||||
|
|
||||||
|
url = f"{base_url}/api/embeddings"
|
||||||
|
|
||||||
|
try:
|
||||||
|
# Synchroner Request (blockierend)
|
||||||
|
response = requests.post(url, json={"model": model, "prompt": text}, timeout=30)
|
||||||
|
response.raise_for_status()
|
||||||
|
data = response.json()
|
||||||
|
return data.get("embedding", [])
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"Sync embedding (Ollama) failed: {e}")
|
||||||
|
return []
|
||||||
@@ -2,13 +2,18 @@
|
|||||||
app/services/feedback_service.py
|
app/services/feedback_service.py
|
||||||
Service zum Loggen von Suchanfragen und Feedback (WP-04c).
|
Service zum Loggen von Suchanfragen und Feedback (WP-04c).
|
||||||
Speichert Daten als JSONL für späteres Self-Tuning (WP-08).
|
Speichert Daten als JSONL für späteres Self-Tuning (WP-08).
|
||||||
|
|
||||||
|
Version: 1.1 (Chat-Support)
|
||||||
"""
|
"""
|
||||||
import json
|
import json
|
||||||
import os
|
import os
|
||||||
import time
|
import time
|
||||||
|
import logging
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import Dict, Any, List
|
from typing import Dict, Any, List, Union
|
||||||
from app.models.dto import QueryRequest, QueryResponse, FeedbackRequest
|
from app.models.dto import QueryRequest, QueryResponse, FeedbackRequest, QueryHit
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
# Pfad für Logs (lokal auf dem Beelink/PC)
|
# Pfad für Logs (lokal auf dem Beelink/PC)
|
||||||
LOG_DIR = Path("data/logs")
|
LOG_DIR = Path("data/logs")
|
||||||
@@ -19,18 +24,35 @@ def _ensure_log_dir():
|
|||||||
if not LOG_DIR.exists():
|
if not LOG_DIR.exists():
|
||||||
os.makedirs(LOG_DIR, exist_ok=True)
|
os.makedirs(LOG_DIR, exist_ok=True)
|
||||||
|
|
||||||
def log_search(req: QueryRequest, res: QueryResponse):
|
def _append_jsonl(file_path: Path, data: dict):
|
||||||
|
try:
|
||||||
|
with open(file_path, "a", encoding="utf-8") as f:
|
||||||
|
f.write(json.dumps(data, ensure_ascii=False) + "\n")
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"Failed to write log: {e}")
|
||||||
|
|
||||||
|
def log_search(
|
||||||
|
query_id: str,
|
||||||
|
query_text: str,
|
||||||
|
results: List[QueryHit],
|
||||||
|
mode: str = "unknown",
|
||||||
|
metadata: Dict[str, Any] = None
|
||||||
|
):
|
||||||
"""
|
"""
|
||||||
Speichert den "Snapshot" der Suche.
|
Generische Logging-Funktion für Suche UND Chat.
|
||||||
WICHTIG: Wir speichern die Scores (Breakdown), damit wir später wissen,
|
|
||||||
warum das System so entschieden hat.
|
Args:
|
||||||
|
query_id: UUID der Anfrage.
|
||||||
|
query_text: User-Eingabe.
|
||||||
|
results: Liste der Treffer (QueryHit Objekte).
|
||||||
|
mode: z.B. "semantic", "hybrid", "chat_rag".
|
||||||
|
metadata: Zusätzliche Infos (z.B. generierte Antwort, Intent).
|
||||||
"""
|
"""
|
||||||
_ensure_log_dir()
|
_ensure_log_dir()
|
||||||
|
|
||||||
# Wir reduzieren die Datenmenge etwas (z.B. keine vollen Texte)
|
|
||||||
hits_summary = []
|
hits_summary = []
|
||||||
for hit in res.results:
|
for hit in results:
|
||||||
# Falls Explanation an war, speichern wir den Breakdown, sonst die Scores
|
# Pydantic Model Dump für saubere Serialisierung
|
||||||
breakdown = None
|
breakdown = None
|
||||||
if hit.explanation and hit.explanation.breakdown:
|
if hit.explanation and hit.explanation.breakdown:
|
||||||
breakdown = hit.explanation.breakdown.model_dump()
|
breakdown = hit.explanation.breakdown.model_dump()
|
||||||
@@ -39,25 +61,24 @@ def log_search(req: QueryRequest, res: QueryResponse):
|
|||||||
"node_id": hit.node_id,
|
"node_id": hit.node_id,
|
||||||
"note_id": hit.note_id,
|
"note_id": hit.note_id,
|
||||||
"total_score": hit.total_score,
|
"total_score": hit.total_score,
|
||||||
"breakdown": breakdown, # Wichtig für Training!
|
"breakdown": breakdown,
|
||||||
"rank_semantic": hit.semantic_score,
|
"rank_semantic": hit.semantic_score,
|
||||||
"rank_edge": hit.edge_bonus
|
"rank_edge": hit.edge_bonus,
|
||||||
|
"type": hit.source.get("type") if hit.source else "unknown"
|
||||||
})
|
})
|
||||||
|
|
||||||
entry = {
|
entry = {
|
||||||
"timestamp": time.time(),
|
"timestamp": time.time(),
|
||||||
"query_id": res.query_id,
|
"query_id": query_id,
|
||||||
"query_text": req.query,
|
"query_text": query_text,
|
||||||
"mode": req.mode,
|
"mode": mode,
|
||||||
"top_k": req.top_k,
|
"hits_count": len(hits_summary),
|
||||||
"hits": hits_summary
|
"hits": hits_summary,
|
||||||
|
"metadata": metadata or {}
|
||||||
}
|
}
|
||||||
|
|
||||||
try:
|
_append_jsonl(SEARCH_LOG_FILE, entry)
|
||||||
with open(SEARCH_LOG_FILE, "a", encoding="utf-8") as f:
|
logger.info(f"Logged search/chat interaction {query_id}")
|
||||||
f.write(json.dumps(entry, ensure_ascii=False) + "\n")
|
|
||||||
except Exception as e:
|
|
||||||
print(f"ERROR logging search: {e}")
|
|
||||||
|
|
||||||
def log_feedback(fb: FeedbackRequest):
|
def log_feedback(fb: FeedbackRequest):
|
||||||
"""
|
"""
|
||||||
@@ -73,8 +94,5 @@ def log_feedback(fb: FeedbackRequest):
|
|||||||
"comment": fb.comment
|
"comment": fb.comment
|
||||||
}
|
}
|
||||||
|
|
||||||
try:
|
_append_jsonl(FEEDBACK_LOG_FILE, entry)
|
||||||
with open(FEEDBACK_LOG_FILE, "a", encoding="utf-8") as f:
|
logger.info(f"Logged feedback for {fb.query_id}")
|
||||||
f.write(json.dumps(entry, ensure_ascii=False) + "\n")
|
|
||||||
except Exception as e:
|
|
||||||
print(f"ERROR logging feedback: {e}")
|
|
||||||
+95
-33
@@ -1,80 +1,142 @@
|
|||||||
"""
|
"""
|
||||||
app/services/llm_service.py — LLM Client (Ollama)
|
app/services/llm_service.py — LLM Client
|
||||||
Version: 0.2.1 (Fix: System Prompt Handling for Phi-3)
|
Version: 2.8.0 (Configurable Concurrency Limit)
|
||||||
"""
|
"""
|
||||||
|
|
||||||
import httpx
|
import httpx
|
||||||
import yaml
|
import yaml
|
||||||
import logging
|
import logging
|
||||||
import os
|
import os
|
||||||
|
import asyncio
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from app.config import get_settings
|
from typing import Optional, Dict, Any, Literal
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
class Settings:
|
||||||
|
OLLAMA_URL = os.getenv("MINDNET_OLLAMA_URL", "http://127.0.0.1:11434")
|
||||||
|
LLM_TIMEOUT = float(os.getenv("MINDNET_LLM_TIMEOUT", 300.0))
|
||||||
|
LLM_MODEL = os.getenv("MINDNET_LLM_MODEL", "phi3:mini")
|
||||||
|
PROMPTS_PATH = os.getenv("MINDNET_PROMPTS_PATH", "./config/prompts.yaml")
|
||||||
|
|
||||||
|
# NEU: Konfigurierbares Limit für Hintergrund-Last
|
||||||
|
# Default auf 2 (konservativ), kann in .env erhöht werden.
|
||||||
|
BACKGROUND_LIMIT = int(os.getenv("MINDNET_LLM_BACKGROUND_LIMIT", "2"))
|
||||||
|
|
||||||
|
def get_settings():
|
||||||
|
return Settings()
|
||||||
|
|
||||||
class LLMService:
|
class LLMService:
|
||||||
|
# GLOBALER SEMAPHOR (Lazy Initialization)
|
||||||
|
# Wir initialisieren ihn erst, wenn wir die Settings kennen.
|
||||||
|
_background_semaphore = None
|
||||||
|
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
self.settings = get_settings()
|
self.settings = get_settings()
|
||||||
self.prompts = self._load_prompts()
|
self.prompts = self._load_prompts()
|
||||||
|
|
||||||
|
# Initialisiere Semaphore einmalig auf Klassen-Ebene basierend auf Config
|
||||||
|
if LLMService._background_semaphore is None:
|
||||||
|
limit = self.settings.BACKGROUND_LIMIT
|
||||||
|
logger.info(f"🚦 LLMService: Initializing Background Semaphore with limit: {limit}")
|
||||||
|
LLMService._background_semaphore = asyncio.Semaphore(limit)
|
||||||
|
|
||||||
|
self.timeout = httpx.Timeout(self.settings.LLM_TIMEOUT, connect=10.0)
|
||||||
|
|
||||||
self.client = httpx.AsyncClient(
|
self.client = httpx.AsyncClient(
|
||||||
base_url=self.settings.OLLAMA_URL,
|
base_url=self.settings.OLLAMA_URL,
|
||||||
timeout=self.settings.LLM_TIMEOUT
|
timeout=self.timeout
|
||||||
)
|
)
|
||||||
|
|
||||||
def _load_prompts(self) -> dict:
|
def _load_prompts(self) -> dict:
|
||||||
path = Path(self.settings.PROMPTS_PATH)
|
path = Path(self.settings.PROMPTS_PATH)
|
||||||
if not path.exists():
|
if not path.exists(): return {}
|
||||||
return {}
|
|
||||||
try:
|
try:
|
||||||
with open(path, "r", encoding="utf-8") as f:
|
with open(path, "r", encoding="utf-8") as f: return yaml.safe_load(f)
|
||||||
return yaml.safe_load(f)
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"Failed to load prompts: {e}")
|
logger.error(f"Failed to load prompts: {e}")
|
||||||
return {}
|
return {}
|
||||||
|
|
||||||
async def generate_raw_response(self, prompt: str, system: str = None) -> str:
|
async def generate_raw_response(
|
||||||
|
self,
|
||||||
|
prompt: str,
|
||||||
|
system: str = None,
|
||||||
|
force_json: bool = False,
|
||||||
|
max_retries: int = 0,
|
||||||
|
base_delay: float = 2.0,
|
||||||
|
priority: Literal["realtime", "background"] = "realtime"
|
||||||
|
) -> str:
|
||||||
"""
|
"""
|
||||||
Führt einen LLM Call aus.
|
Führt einen LLM Call aus.
|
||||||
Unterstützt nun explizite System-Prompts für sauberes Templating.
|
priority="realtime": Chat (Sofort, keine Bremse).
|
||||||
|
priority="background": Import/Analyse (Gedrosselt durch Semaphore).
|
||||||
"""
|
"""
|
||||||
payload = {
|
|
||||||
|
use_semaphore = (priority == "background")
|
||||||
|
|
||||||
|
if use_semaphore and LLMService._background_semaphore:
|
||||||
|
async with LLMService._background_semaphore:
|
||||||
|
return await self._execute_request(prompt, system, force_json, max_retries, base_delay)
|
||||||
|
else:
|
||||||
|
# Realtime oder Fallback (falls Semaphore Init fehlschlug)
|
||||||
|
return await self._execute_request(prompt, system, force_json, max_retries, base_delay)
|
||||||
|
|
||||||
|
async def _execute_request(self, prompt, system, force_json, max_retries, base_delay):
|
||||||
|
payload: Dict[str, Any] = {
|
||||||
"model": self.settings.LLM_MODEL,
|
"model": self.settings.LLM_MODEL,
|
||||||
"prompt": prompt,
|
"prompt": prompt,
|
||||||
"stream": False,
|
"stream": False,
|
||||||
"options": {
|
"options": {
|
||||||
# Temperature etwas höher für Empathie, niedriger für Code?
|
"temperature": 0.1 if force_json else 0.7,
|
||||||
# Wir lassen es auf Standard, oder steuern es später via Config.
|
"num_ctx": 8192
|
||||||
"temperature": 0.7,
|
|
||||||
"num_ctx": 2048
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
# WICHTIG: System-Prompt separat übergeben, damit Ollama formatiert
|
if force_json:
|
||||||
|
payload["format"] = "json"
|
||||||
|
|
||||||
if system:
|
if system:
|
||||||
payload["system"] = system
|
payload["system"] = system
|
||||||
|
|
||||||
try:
|
attempt = 0
|
||||||
response = await self.client.post("/api/generate", json=payload)
|
|
||||||
if response.status_code != 200:
|
while True:
|
||||||
logger.error(f"Ollama Error ({response.status_code}): {response.text}")
|
try:
|
||||||
return "Fehler bei der Generierung."
|
response = await self.client.post("/api/generate", json=payload)
|
||||||
|
|
||||||
data = response.json()
|
if response.status_code == 200:
|
||||||
return data.get("response", "").strip()
|
data = response.json()
|
||||||
|
return data.get("response", "").strip()
|
||||||
except Exception as e:
|
else:
|
||||||
logger.error(f"LLM Raw Gen Error: {e}")
|
response.raise_for_status()
|
||||||
return "Interner LLM Fehler."
|
|
||||||
|
except Exception as e:
|
||||||
|
attempt += 1
|
||||||
|
if attempt > max_retries:
|
||||||
|
logger.error(f"LLM Final Error (Versuch {attempt}): {e}")
|
||||||
|
raise e
|
||||||
|
|
||||||
|
wait_time = base_delay * (2 ** (attempt - 1))
|
||||||
|
logger.warning(f"⚠️ LLM Retry ({attempt}/{max_retries}) in {wait_time}s: {e}")
|
||||||
|
await asyncio.sleep(wait_time)
|
||||||
|
|
||||||
async def generate_rag_response(self, query: str, context_str: str) -> str:
|
async def generate_rag_response(self, query: str, context_str: str) -> str:
|
||||||
"""Legacy Support"""
|
"""
|
||||||
|
Chat-Wrapper: Immer Realtime.
|
||||||
|
"""
|
||||||
system_prompt = self.prompts.get("system_prompt", "")
|
system_prompt = self.prompts.get("system_prompt", "")
|
||||||
rag_template = self.prompts.get("rag_template", "{context_str}\n\n{query}")
|
rag_template = self.prompts.get("rag_template", "{context_str}\n\n{query}")
|
||||||
|
|
||||||
final_prompt = rag_template.format(context_str=context_str, query=query)
|
final_prompt = rag_template.format(context_str=context_str, query=query)
|
||||||
|
|
||||||
# Leite an die neue Methode weiter
|
return await self.generate_raw_response(
|
||||||
return await self.generate_raw_response(final_prompt, system=system_prompt)
|
final_prompt,
|
||||||
|
system=system_prompt,
|
||||||
|
max_retries=0,
|
||||||
|
force_json=False,
|
||||||
|
priority="realtime"
|
||||||
|
)
|
||||||
|
|
||||||
async def close(self):
|
async def close(self):
|
||||||
await self.client.aclose()
|
if self.client:
|
||||||
|
await self.client.aclose()
|
||||||
@@ -0,0 +1,138 @@
|
|||||||
|
"""
|
||||||
|
app/services/semantic_analyzer.py — Edge Validation & Filtering
|
||||||
|
Version: 2.0 (Update: Background Priority for Batch Jobs)
|
||||||
|
"""
|
||||||
|
|
||||||
|
import json
|
||||||
|
import logging
|
||||||
|
from typing import List, Optional
|
||||||
|
from dataclasses import dataclass
|
||||||
|
|
||||||
|
# Importe
|
||||||
|
from app.services.llm_service import LLMService
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
class SemanticAnalyzer:
|
||||||
|
def __init__(self):
|
||||||
|
self.llm = LLMService()
|
||||||
|
|
||||||
|
async def assign_edges_to_chunk(self, chunk_text: str, all_edges: List[str], note_type: str) -> List[str]:
|
||||||
|
"""
|
||||||
|
Sendet einen Chunk und eine Liste potenzieller Kanten an das LLM.
|
||||||
|
Das LLM filtert heraus, welche Kanten für diesen Chunk relevant sind.
|
||||||
|
|
||||||
|
Features:
|
||||||
|
- Retry Strategy: Wartet bei Überlastung (max_retries=5).
|
||||||
|
- Priority Queue: Läuft als "background" Task, um den Chat nicht zu blockieren.
|
||||||
|
- Observability: Loggt Input-Größe, Raw-Response und Parsing-Details.
|
||||||
|
"""
|
||||||
|
if not all_edges:
|
||||||
|
return []
|
||||||
|
|
||||||
|
# 1. Prompt laden
|
||||||
|
prompt_template = self.llm.prompts.get("edge_allocation_template")
|
||||||
|
|
||||||
|
if not prompt_template:
|
||||||
|
logger.warning("⚠️ [SemanticAnalyzer] Prompt 'edge_allocation_template' fehlt. Nutze Fallback.")
|
||||||
|
prompt_template = (
|
||||||
|
"TASK: Wähle aus den Kandidaten die relevanten Kanten für den Text.\n"
|
||||||
|
"TEXT: {chunk_text}\n"
|
||||||
|
"KANDIDATEN: {edge_list}\n"
|
||||||
|
"OUTPUT: JSON Liste von Strings [\"kind:target\"]."
|
||||||
|
)
|
||||||
|
|
||||||
|
# 2. Kandidaten-Liste formatieren
|
||||||
|
edges_str = "\n".join([f"- {e}" for e in all_edges])
|
||||||
|
|
||||||
|
# LOG: Request Info
|
||||||
|
logger.debug(f"🔍 [SemanticAnalyzer] Request: {len(chunk_text)} chars Text, {len(all_edges)} Candidates.")
|
||||||
|
|
||||||
|
# 3. Prompt füllen
|
||||||
|
final_prompt = prompt_template.format(
|
||||||
|
chunk_text=chunk_text[:3500],
|
||||||
|
edge_list=edges_str
|
||||||
|
)
|
||||||
|
|
||||||
|
try:
|
||||||
|
# 4. LLM Call mit Traffic Control (NEU: priority="background")
|
||||||
|
# Wir nutzen die "Slow Lane", damit der User im Chat nicht warten muss.
|
||||||
|
response_json = await self.llm.generate_raw_response(
|
||||||
|
prompt=final_prompt,
|
||||||
|
force_json=True,
|
||||||
|
max_retries=5,
|
||||||
|
base_delay=5.0,
|
||||||
|
priority="background" # <--- WICHTIG: Drosselung aktivieren
|
||||||
|
)
|
||||||
|
|
||||||
|
# LOG: Raw Response Preview
|
||||||
|
logger.debug(f"📥 [SemanticAnalyzer] Raw Response (Preview): {response_json[:200]}...")
|
||||||
|
|
||||||
|
# 5. Parsing & Cleaning
|
||||||
|
clean_json = response_json.replace("```json", "").replace("```", "").strip()
|
||||||
|
|
||||||
|
if not clean_json:
|
||||||
|
logger.warning("⚠️ [SemanticAnalyzer] Leere Antwort vom LLM erhalten. Trigger Fallback.")
|
||||||
|
return []
|
||||||
|
|
||||||
|
try:
|
||||||
|
data = json.loads(clean_json)
|
||||||
|
except json.JSONDecodeError as json_err:
|
||||||
|
logger.error(f"❌ [SemanticAnalyzer] JSON Decode Error.")
|
||||||
|
logger.error(f" Grund: {json_err}")
|
||||||
|
logger.error(f" Empfangener String: {clean_json[:500]}")
|
||||||
|
logger.info(" -> Workaround: Fallback auf 'Alle Kanten' (durch Chunker).")
|
||||||
|
return []
|
||||||
|
|
||||||
|
valid_edges = []
|
||||||
|
|
||||||
|
# 6. Robuste Validierung (List vs Dict)
|
||||||
|
if isinstance(data, list):
|
||||||
|
# Standardfall: ["kind:target", ...]
|
||||||
|
valid_edges = [str(e) for e in data if isinstance(e, str) and ":" in e]
|
||||||
|
|
||||||
|
elif isinstance(data, dict):
|
||||||
|
# Abweichende Formate behandeln
|
||||||
|
logger.info(f"ℹ️ [SemanticAnalyzer] LLM lieferte Dict statt Liste. Versuche Reparatur. Keys: {list(data.keys())}")
|
||||||
|
|
||||||
|
for key, val in data.items():
|
||||||
|
# Fall A: {"edges": ["kind:target"]}
|
||||||
|
if key.lower() in ["edges", "results", "kanten", "matches"] and isinstance(val, list):
|
||||||
|
valid_edges.extend([str(e) for e in val if isinstance(e, str) and ":" in e])
|
||||||
|
|
||||||
|
# Fall B: {"kind": "target"}
|
||||||
|
elif isinstance(val, str):
|
||||||
|
valid_edges.append(f"{key}:{val}")
|
||||||
|
|
||||||
|
# Fall C: {"kind": ["target1", "target2"]}
|
||||||
|
elif isinstance(val, list):
|
||||||
|
for target in val:
|
||||||
|
if isinstance(target, str):
|
||||||
|
valid_edges.append(f"{key}:{target}")
|
||||||
|
|
||||||
|
# Safety: Filtere nur Kanten, die halbwegs valide aussehen
|
||||||
|
final_result = [e for e in valid_edges if ":" in e]
|
||||||
|
|
||||||
|
# LOG: Ergebnis
|
||||||
|
if final_result:
|
||||||
|
logger.info(f"✅ [SemanticAnalyzer] Success. {len(final_result)} Kanten zugewiesen.")
|
||||||
|
else:
|
||||||
|
logger.debug(" [SemanticAnalyzer] Keine spezifischen Kanten erkannt (Empty Result).")
|
||||||
|
|
||||||
|
return final_result
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"💥 [SemanticAnalyzer] Kritischer Fehler: {e}", exc_info=True)
|
||||||
|
return []
|
||||||
|
|
||||||
|
async def close(self):
|
||||||
|
if self.llm:
|
||||||
|
await self.llm.close()
|
||||||
|
|
||||||
|
# Singleton Helper
|
||||||
|
_analyzer_instance = None
|
||||||
|
def get_semantic_analyzer():
|
||||||
|
global _analyzer_instance
|
||||||
|
if _analyzer_instance is None:
|
||||||
|
_analyzer_instance = SemanticAnalyzer()
|
||||||
|
return _analyzer_instance
|
||||||
+45
-12
@@ -1,28 +1,31 @@
|
|||||||
# config/decision_engine.yaml
|
# config/decision_engine.yaml
|
||||||
# Steuerung der Decision Engine (WP-06)
|
# Steuerung der Decision Engine (Intent Recognition)
|
||||||
# Hybrid-Modus: Keywords (Fast) + LLM Router (Smart Fallback)
|
# Version: 2.4.0 (Clean Architecture: Generic Intents only)
|
||||||
version: 1.2
|
|
||||||
|
version: 1.4
|
||||||
|
|
||||||
settings:
|
settings:
|
||||||
llm_fallback_enabled: true
|
llm_fallback_enabled: true
|
||||||
|
|
||||||
# Few-Shot Prompting für bessere SLM-Performance
|
# Few-Shot Prompting für den LLM-Router (Slow Path)
|
||||||
llm_router_prompt: |
|
llm_router_prompt: |
|
||||||
Du bist ein Klassifikator. Analysiere die Nachricht und wähle die passende Strategie.
|
Du bist ein Klassifikator. Analysiere die Nachricht und wähle die passende Strategie.
|
||||||
Antworte NUR mit dem Namen der Strategie.
|
Antworte NUR mit dem Namen der Strategie.
|
||||||
|
|
||||||
STRATEGIEN:
|
STRATEGIEN:
|
||||||
|
- INTERVIEW: User will Wissen erfassen, Notizen anlegen oder Dinge festhalten.
|
||||||
- DECISION: Rat, Strategie, Vor/Nachteile, "Soll ich".
|
- DECISION: Rat, Strategie, Vor/Nachteile, "Soll ich".
|
||||||
- EMPATHY: Gefühle, Frust, Freude, Probleme, "Alles ist sinnlos", "Ich bin traurig".
|
- EMPATHY: Gefühle, Frust, Freude, Probleme.
|
||||||
- CODING: Code, Syntax, Programmierung, Python.
|
- CODING: Code, Syntax, Programmierung.
|
||||||
- FACT: Wissen, Fakten, Definitionen.
|
- FACT: Wissen, Fakten, Definitionen.
|
||||||
|
|
||||||
BEISPIELE:
|
BEISPIELE:
|
||||||
User: "Wie funktioniert Qdrant?" -> FACT
|
User: "Wie funktioniert Qdrant?" -> FACT
|
||||||
User: "Soll ich Qdrant nutzen?" -> DECISION
|
User: "Soll ich Qdrant nutzen?" -> DECISION
|
||||||
|
User: "Ich möchte etwas notieren" -> INTERVIEW
|
||||||
|
User: "Lass uns das festhalten" -> INTERVIEW
|
||||||
User: "Schreibe ein Python Script" -> CODING
|
User: "Schreibe ein Python Script" -> CODING
|
||||||
User: "Alles ist grau und sinnlos" -> EMPATHY
|
User: "Alles ist grau und sinnlos" -> EMPATHY
|
||||||
User: "Mir geht es heute gut" -> EMPATHY
|
|
||||||
|
|
||||||
NACHRICHT: "{query}"
|
NACHRICHT: "{query}"
|
||||||
|
|
||||||
@@ -47,11 +50,9 @@ strategies:
|
|||||||
- "empfehlung"
|
- "empfehlung"
|
||||||
- "strategie"
|
- "strategie"
|
||||||
- "entscheidung"
|
- "entscheidung"
|
||||||
- "wert"
|
|
||||||
- "prinzip"
|
|
||||||
- "vor- und nachteile"
|
|
||||||
- "abwägung"
|
- "abwägung"
|
||||||
inject_types: ["value", "principle", "goal"]
|
- "vergleich"
|
||||||
|
inject_types: ["value", "principle", "goal", "risk"]
|
||||||
prompt_template: "decision_template"
|
prompt_template: "decision_template"
|
||||||
prepend_instruction: |
|
prepend_instruction: |
|
||||||
!!! ENTSCHEIDUNGS-MODUS !!!
|
!!! ENTSCHEIDUNGS-MODUS !!!
|
||||||
@@ -68,6 +69,7 @@ strategies:
|
|||||||
- "angst"
|
- "angst"
|
||||||
- "nervt"
|
- "nervt"
|
||||||
- "überfordert"
|
- "überfordert"
|
||||||
|
- "müde"
|
||||||
inject_types: ["experience", "belief", "profile"]
|
inject_types: ["experience", "belief", "profile"]
|
||||||
prompt_template: "empathy_template"
|
prompt_template: "empathy_template"
|
||||||
prepend_instruction: null
|
prepend_instruction: null
|
||||||
@@ -84,6 +86,37 @@ strategies:
|
|||||||
- "syntax"
|
- "syntax"
|
||||||
- "json"
|
- "json"
|
||||||
- "yaml"
|
- "yaml"
|
||||||
|
- "bash"
|
||||||
inject_types: ["snippet", "reference", "source"]
|
inject_types: ["snippet", "reference", "source"]
|
||||||
prompt_template: "technical_template"
|
prompt_template: "technical_template"
|
||||||
prepend_instruction: null
|
prepend_instruction: null
|
||||||
|
|
||||||
|
# 5. Interview / Datenerfassung
|
||||||
|
# HINWEIS: Spezifische Typen (Projekt, Ziel etc.) werden automatisch
|
||||||
|
# über die types.yaml erkannt. Hier stehen nur generische Trigger.
|
||||||
|
INTERVIEW:
|
||||||
|
description: "Der User möchte Wissen erfassen."
|
||||||
|
trigger_keywords:
|
||||||
|
- "neue notiz"
|
||||||
|
- "etwas notieren"
|
||||||
|
- "festhalten"
|
||||||
|
- "erstellen"
|
||||||
|
- "dokumentieren"
|
||||||
|
- "anlegen"
|
||||||
|
- "interview"
|
||||||
|
- "erfassen"
|
||||||
|
- "idee speichern"
|
||||||
|
- "draft"
|
||||||
|
inject_types: []
|
||||||
|
prompt_template: "interview_template"
|
||||||
|
prepend_instruction: null
|
||||||
|
|
||||||
|
# Schemas: Hier nur der Fallback.
|
||||||
|
# Spezifische Schemas (Project, Experience) kommen jetzt aus types.yaml!
|
||||||
|
schemas:
|
||||||
|
default:
|
||||||
|
fields:
|
||||||
|
- "Titel"
|
||||||
|
- "Thema/Inhalt"
|
||||||
|
- "Tags"
|
||||||
|
hint: "Halte es einfach und übersichtlich."
|
||||||
+67
-1
@@ -93,4 +93,70 @@ technical_template: |
|
|||||||
FORMAT:
|
FORMAT:
|
||||||
- Kurze Erklärung des Ansatzes.
|
- Kurze Erklärung des Ansatzes.
|
||||||
- Markdown Code-Block (Copy-Paste fertig).
|
- Markdown Code-Block (Copy-Paste fertig).
|
||||||
- Wichtige Edge-Cases.
|
- Wichtige Edge-Cases.
|
||||||
|
# ---------------------------------------------------------
|
||||||
|
# 5. INTERVIEW: Der "One-Shot Extractor" (Performance Mode)
|
||||||
|
# ---------------------------------------------------------
|
||||||
|
interview_template: |
|
||||||
|
TASK:
|
||||||
|
Du bist ein professioneller Ghostwriter. Verwandle den "USER INPUT" in eine strukturierte Notiz vom Typ '{target_type}'.
|
||||||
|
|
||||||
|
STRUKTUR (Nutze EXAKT diese Überschriften):
|
||||||
|
{schema_fields}
|
||||||
|
|
||||||
|
USER INPUT:
|
||||||
|
"{query}"
|
||||||
|
|
||||||
|
ANWEISUNG ZUM INHALT:
|
||||||
|
1. Analysiere den Input genau.
|
||||||
|
2. Schreibe die Inhalte unter die passenden Überschriften aus der STRUKTUR-Liste oben.
|
||||||
|
3. STIL: Schreibe flüssig, professionell und in der Ich-Perspektive. Korrigiere Grammatikfehler, aber behalte den persönlichen Ton bei.
|
||||||
|
4. Wenn Informationen für einen Abschnitt fehlen, schreibe nur: "[TODO: Ergänzen]". Erfinde nichts dazu.
|
||||||
|
|
||||||
|
OUTPUT FORMAT (YAML + MARKDOWN):
|
||||||
|
---
|
||||||
|
type: {target_type}
|
||||||
|
status: draft
|
||||||
|
title: (Erstelle einen treffenden, kurzen Titel für den Inhalt)
|
||||||
|
tags: [Tag1, Tag2]
|
||||||
|
---
|
||||||
|
|
||||||
|
# (Wiederhole den Titel hier)
|
||||||
|
|
||||||
|
## (Erster Begriff aus STRUKTUR)
|
||||||
|
(Text...)
|
||||||
|
|
||||||
|
## (Zweiter Begriff aus STRUKTUR)
|
||||||
|
(Text...)
|
||||||
|
|
||||||
|
(usw.)
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------
|
||||||
|
# 6. EDGE_ALLOCATION: Kantenfilter (Intent: OFFLINE_FILTER)
|
||||||
|
# ---------------------------------------------------------
|
||||||
|
edge_allocation_template: |
|
||||||
|
TASK:
|
||||||
|
Du bist ein strikter Selektor. Du erhältst eine Liste von "Kandidaten-Kanten" (Strings).
|
||||||
|
Wähle jene aus, die inhaltlich im "Textabschnitt" vorkommen oder relevant sind.
|
||||||
|
|
||||||
|
TEXTABSCHNITT:
|
||||||
|
"""
|
||||||
|
{chunk_text}
|
||||||
|
"""
|
||||||
|
|
||||||
|
KANDIDATEN (Auswahl-Pool):
|
||||||
|
{edge_list}
|
||||||
|
|
||||||
|
REGELN:
|
||||||
|
1. Die Kanten haben das Format "typ:ziel". Der "typ" ist variabel und kann ALLES sein (z.B. uses, blocks, inspired_by, loves, etc.).
|
||||||
|
2. Gib NUR die Strings aus der Kandidaten-Liste zurück, die zum Text passen.
|
||||||
|
3. Erfinde KEINE neuen Kanten. Nutze exakt die Schreibweise aus der Liste.
|
||||||
|
4. Antworte als flache JSON-Liste.
|
||||||
|
|
||||||
|
BEISPIEL (Zur Demonstration der Logik):
|
||||||
|
Input Text: "Das Projekt Alpha scheitert, weil Budget fehlt."
|
||||||
|
Input Kandidaten: ["blocks:Projekt Alpha", "inspired_by:Buch der Weisen", "needs:Budget"]
|
||||||
|
Output: ["blocks:Projekt Alpha", "needs:Budget"]
|
||||||
|
|
||||||
|
DEIN OUTPUT (JSON):
|
||||||
+179
-54
@@ -1,76 +1,201 @@
|
|||||||
version: 1.0
|
version: 2.4.0 # Optimized for Async Intelligence & Hybrid Router
|
||||||
|
|
||||||
|
# ==============================================================================
|
||||||
|
# 1. CHUNKING PROFILES
|
||||||
|
# ==============================================================================
|
||||||
|
|
||||||
|
chunking_profiles:
|
||||||
|
|
||||||
|
# A. SHORT & FAST
|
||||||
|
# Für Glossar, Tasks, Risiken. Kleine Schnipsel.
|
||||||
|
sliding_short:
|
||||||
|
strategy: sliding_window
|
||||||
|
enable_smart_edge_allocation: false
|
||||||
|
target: 200
|
||||||
|
max: 350
|
||||||
|
overlap: [30, 50]
|
||||||
|
|
||||||
|
# B. STANDARD & FAST
|
||||||
|
# Der "Traktor": Robust für Quellen, Journal, Daily Logs.
|
||||||
|
sliding_standard:
|
||||||
|
strategy: sliding_window
|
||||||
|
enable_smart_edge_allocation: false
|
||||||
|
target: 450
|
||||||
|
max: 650
|
||||||
|
overlap: [50, 100]
|
||||||
|
|
||||||
|
# C. SMART FLOW (Performance-Safe Mode)
|
||||||
|
# Für Konzepte, Projekte, Erfahrungen.
|
||||||
|
# HINWEIS: 'enable_smart_edge_allocation' ist vorerst FALSE, um Ollama
|
||||||
|
# bei der Generierung nicht zu überlasten. Später wieder aktivieren.
|
||||||
|
sliding_smart_edges:
|
||||||
|
strategy: sliding_window
|
||||||
|
enable_smart_edge_allocation: true
|
||||||
|
target: 400
|
||||||
|
max: 600
|
||||||
|
overlap: [50, 80]
|
||||||
|
|
||||||
|
# D. SMART STRUCTURE
|
||||||
|
# Für Profile, Werte, Prinzipien. Trennt hart an Überschriften (H2).
|
||||||
|
structured_smart_edges:
|
||||||
|
strategy: by_heading
|
||||||
|
enable_smart_edge_allocation: true
|
||||||
|
split_level: 2
|
||||||
|
max: 600
|
||||||
|
target: 400
|
||||||
|
overlap: [50, 80]
|
||||||
|
|
||||||
|
# ==============================================================================
|
||||||
|
# 2. DEFAULTS
|
||||||
|
# ==============================================================================
|
||||||
defaults:
|
defaults:
|
||||||
retriever_weight: 1.0
|
retriever_weight: 1.0
|
||||||
chunk_profile: default
|
chunking_profile: sliding_standard
|
||||||
edge_defaults: [] # Leerliste → keine impliziten Kanten, wenn nicht gesetzt
|
edge_defaults: []
|
||||||
|
|
||||||
|
# ==============================================================================
|
||||||
|
# 3. TYPE DEFINITIONS
|
||||||
|
# ==============================================================================
|
||||||
|
|
||||||
types:
|
types:
|
||||||
# Wissensbausteine
|
|
||||||
concept:
|
|
||||||
chunk_profile: medium
|
|
||||||
retriever_weight: 0.60
|
|
||||||
edge_defaults: ["references", "related_to"]
|
|
||||||
|
|
||||||
source:
|
# --- KERNTYPEN (Hoch priorisiert & Smart) ---
|
||||||
chunk_profile: short
|
|
||||||
retriever_weight: 0.50
|
|
||||||
edge_defaults: [] # Quellen sind i. d. R. Ziel von Kanten, erzeugen selbst keine Default-Kanten
|
|
||||||
|
|
||||||
glossary:
|
experience:
|
||||||
chunk_profile: short
|
chunking_profile: sliding_smart_edges
|
||||||
retriever_weight: 0.40
|
|
||||||
edge_defaults: ["related_to"]
|
|
||||||
|
|
||||||
# Person & Persönlichkeit
|
|
||||||
profile: # z. B. "Persönliches Leitbild (Kurzprofil)"
|
|
||||||
chunk_profile: long
|
|
||||||
retriever_weight: 0.66
|
|
||||||
edge_defaults: ["references", "related_to"]
|
|
||||||
|
|
||||||
value: # Werte (z. B. "Mut", "Fairness")
|
|
||||||
chunk_profile: short
|
|
||||||
retriever_weight: 0.90
|
retriever_weight: 0.90
|
||||||
edge_defaults: ["related_to"]
|
edge_defaults: ["derived_from", "references"]
|
||||||
|
# Hybrid Classifier: Wenn diese Worte fallen, ist es eine Experience
|
||||||
|
detection_keywords:
|
||||||
|
- "passiert"
|
||||||
|
- "erlebt"
|
||||||
|
- "gefühl"
|
||||||
|
- "situation"
|
||||||
|
- "stolz"
|
||||||
|
- "geärgert"
|
||||||
|
- "reaktion"
|
||||||
|
- "moment"
|
||||||
|
- "konflikt"
|
||||||
|
# Ghostwriter Schema: Sprechende Anweisungen für besseren Textfluss
|
||||||
|
schema:
|
||||||
|
- "Situation (Was ist passiert?)"
|
||||||
|
- "Meine Reaktion (Was habe ich getan?)"
|
||||||
|
- "Ergebnis & Auswirkung"
|
||||||
|
- "Reflexion & Learning (Was lerne ich daraus?)"
|
||||||
|
|
||||||
principle: # Prinzipien/Leitsätze
|
project:
|
||||||
chunk_profile: short
|
chunking_profile: sliding_smart_edges
|
||||||
retriever_weight: 0.90
|
retriever_weight: 0.97
|
||||||
edge_defaults: ["related_to", "references"]
|
edge_defaults: ["references", "depends_on"]
|
||||||
|
detection_keywords:
|
||||||
experience: # prägende Erlebnisse/Erfahrungen
|
- "projekt"
|
||||||
chunk_profile: medium
|
- "vorhaben"
|
||||||
retriever_weight: 0.90
|
- "ziel ist"
|
||||||
edge_defaults: ["related_to", "references"]
|
- "meilenstein"
|
||||||
|
- "planen"
|
||||||
# Ziele, Entscheidungen, Meilensteine
|
- "starten"
|
||||||
goal:
|
- "mission"
|
||||||
chunk_profile: medium
|
schema:
|
||||||
retriever_weight: 0.90
|
- "Mission & Zielsetzung"
|
||||||
edge_defaults: ["depends_on", "related_to", "references"]
|
- "Aktueller Status & Blockaden"
|
||||||
|
- "Nächste konkrete Schritte"
|
||||||
|
- "Stakeholder & Ressourcen"
|
||||||
|
|
||||||
decision:
|
decision:
|
||||||
chunk_profile: short
|
chunking_profile: structured_smart_edges
|
||||||
|
retriever_weight: 1.00 # MAX: Entscheidungen sind Gesetz
|
||||||
|
edge_defaults: ["caused_by", "references"]
|
||||||
|
detection_keywords:
|
||||||
|
- "entschieden"
|
||||||
|
- "wahl"
|
||||||
|
- "optionen"
|
||||||
|
- "alternativen"
|
||||||
|
- "beschluss"
|
||||||
|
- "adr"
|
||||||
|
schema:
|
||||||
|
- "Kontext & Problemstellung"
|
||||||
|
- "Betrachtete Optionen (Alternativen)"
|
||||||
|
- "Die Entscheidung"
|
||||||
|
- "Begründung (Warum diese Wahl?)"
|
||||||
|
|
||||||
|
# --- PERSÖNLICHKEIT & IDENTITÄT ---
|
||||||
|
|
||||||
|
value:
|
||||||
|
chunking_profile: structured_smart_edges
|
||||||
|
retriever_weight: 1.00
|
||||||
|
edge_defaults: ["related_to"]
|
||||||
|
detection_keywords: ["wert", "wichtig ist", "moral", "ethik"]
|
||||||
|
schema: ["Definition", "Warum mir das wichtig ist", "Leitsätze für den Alltag"]
|
||||||
|
|
||||||
|
principle:
|
||||||
|
chunking_profile: structured_smart_edges
|
||||||
|
retriever_weight: 0.95
|
||||||
|
edge_defaults: ["derived_from", "references"]
|
||||||
|
detection_keywords: ["prinzip", "regel", "grundsatz", "leitlinie"]
|
||||||
|
schema: ["Das Prinzip", "Anwendung & Beispiele"]
|
||||||
|
|
||||||
|
belief:
|
||||||
|
chunking_profile: sliding_short
|
||||||
retriever_weight: 0.90
|
retriever_weight: 0.90
|
||||||
edge_defaults: ["depends_on", "references", "related_to"] # „Worauf stützte sich die Entscheidung?“
|
edge_defaults: ["related_to"]
|
||||||
|
detection_keywords: ["glaube", "überzeugung", "denke dass", "meinung"]
|
||||||
|
schema: ["Der Glaubenssatz", "Ursprung & Reflexion"]
|
||||||
|
|
||||||
milestone:
|
profile:
|
||||||
chunk_profile: short
|
chunking_profile: structured_smart_edges
|
||||||
retriever_weight: 0.70
|
retriever_weight: 0.70
|
||||||
edge_defaults: ["related_to", "references"]
|
edge_defaults: ["references", "related_to"]
|
||||||
|
schema: ["Rolle / Identität", "Fakten & Daten", "Historie"]
|
||||||
|
|
||||||
# Operativ: Projekte, Aufgaben, Journal
|
# --- STRATEGIE & RISIKO ---
|
||||||
project:
|
|
||||||
chunk_profile: long
|
goal:
|
||||||
retriever_weight: 0.97
|
chunking_profile: sliding_smart_edges
|
||||||
edge_defaults: ["references", "depends_on"] # Projekt stützt sich auf Konzepte/Quellen und hängt von Bausteinen ab
|
retriever_weight: 0.95
|
||||||
|
edge_defaults: ["depends_on", "related_to"]
|
||||||
|
schema: ["Zielzustand", "Zeitrahmen & KPIs", "Motivation"]
|
||||||
|
|
||||||
|
risk:
|
||||||
|
chunking_profile: sliding_short
|
||||||
|
retriever_weight: 0.85
|
||||||
|
edge_defaults: ["related_to", "blocks"]
|
||||||
|
detection_keywords: ["risiko", "gefahr", "bedrohung", "problem", "angst"]
|
||||||
|
schema: ["Beschreibung des Risikos", "Mögliche Auswirkungen", "Gegenmaßnahmen"]
|
||||||
|
|
||||||
|
# --- BASIS & WISSEN ---
|
||||||
|
|
||||||
|
concept:
|
||||||
|
chunking_profile: sliding_smart_edges
|
||||||
|
retriever_weight: 0.60
|
||||||
|
edge_defaults: ["references", "related_to"]
|
||||||
|
schema:
|
||||||
|
- "Definition"
|
||||||
|
- "Kontext & Hintergrund"
|
||||||
|
- "Verwandte Konzepte"
|
||||||
|
|
||||||
task:
|
task:
|
||||||
chunk_profile: short
|
chunking_profile: sliding_short
|
||||||
retriever_weight: 0.80
|
retriever_weight: 0.80
|
||||||
edge_defaults: ["depends_on", "references"]
|
edge_defaults: ["depends_on", "part_of"]
|
||||||
|
schema: ["Aufgabe", "Kontext", "Definition of Done"]
|
||||||
|
|
||||||
journal:
|
journal:
|
||||||
chunk_profile: medium
|
chunking_profile: sliding_standard
|
||||||
retriever_weight: 0.80
|
retriever_weight: 0.80
|
||||||
edge_defaults: ["references", "related_to"]
|
edge_defaults: ["references", "related_to"]
|
||||||
|
schema: ["Log-Eintrag", "Gedanken & Erkenntnisse"]
|
||||||
|
|
||||||
|
source:
|
||||||
|
chunking_profile: sliding_standard
|
||||||
|
retriever_weight: 0.50
|
||||||
|
edge_defaults: []
|
||||||
|
schema:
|
||||||
|
- "Metadaten (Autor, URL, Datum)"
|
||||||
|
- "Kernaussage / Zusammenfassung"
|
||||||
|
- "Zitate & Notizen"
|
||||||
|
|
||||||
|
glossary:
|
||||||
|
chunking_profile: sliding_short
|
||||||
|
retriever_weight: 0.40
|
||||||
|
edge_defaults: ["related_to"]
|
||||||
|
schema: ["Begriff", "Definition"]
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
# mindnet v2.2 – Knowledge Design Manual
|
# mindnet v2.4 – Knowledge Design Manual
|
||||||
**Datei:** `docs/mindnet_knowledge_design_manual_v2.2.md`
|
**Datei:** `docs/mindnet_knowledge_design_manual_v2.6.md`
|
||||||
**Stand:** 2025-12-09
|
**Stand:** 2025-12-12
|
||||||
**Status:** **FINAL** (Integrierter Stand WP01–WP06)
|
**Status:** **FINAL** (Integrierter Stand WP01–WP15)
|
||||||
**Quellen:** `knowledge_design.md`, `TYPE_REGISTRY_MANUAL.md`, `chunking_strategy.md`, `mindnet_functional_architecture.md`.
|
**Quellen:** `knowledge_design.md`, `TYPE_REGISTRY_MANUAL.md`, `chunking_strategy.md`, `mindnet_functional_architecture.md`.
|
||||||
|
|
||||||
---
|
---
|
||||||
@@ -24,9 +24,11 @@ Dieses Handbuch ist die **primäre Arbeitsanweisung** für dich als Mindmaster (
|
|||||||
|
|
||||||
### 1.1 Zielsetzung
|
### 1.1 Zielsetzung
|
||||||
Mindnet ist mehr als eine Dokumentablage. Es ist ein vernetztes System, das deine Persönlichkeit, Entscheidungen und Erfahrungen abbildet.
|
Mindnet ist mehr als eine Dokumentablage. Es ist ein vernetztes System, das deine Persönlichkeit, Entscheidungen und Erfahrungen abbildet.
|
||||||
Seit Version 2.3.1 verfügt Mindnet über:
|
Seit Version 2.6 verfügt Mindnet über:
|
||||||
* **Hybrid Router:** Das System erkennt, ob du Fakten, Entscheidungen oder Empathie brauchst.
|
* **Hybrid Router:** Das System erkennt, ob du Fakten, Entscheidungen oder Empathie brauchst.
|
||||||
* **Context Intelligence:** Das System lädt je nach Situation unterschiedliche Notiz-Typen (z.B. Werte bei Entscheidungen).
|
* **Smart Edge Allocation:** Das System prüft deine Links intelligent und bindet sie nur an die Textabschnitte (Chunks), wo sie wirklich relevant sind.
|
||||||
|
* **Web UI (WP10):** Du kannst direkt sehen, welche Quellen genutzt wurden.
|
||||||
|
* **Active Intelligence (WP11):** Das System hilft dir beim Schreiben und Vernetzen (Link-Vorschläge).
|
||||||
|
|
||||||
### 1.2 Der Vault als „Source of Truth“
|
### 1.2 Der Vault als „Source of Truth“
|
||||||
Die Markdown-Dateien in deinem Vault sind die **einzige Quelle der Wahrheit**.
|
Die Markdown-Dateien in deinem Vault sind die **einzige Quelle der Wahrheit**.
|
||||||
@@ -47,7 +49,7 @@ Jede Datei muss mindestens folgende Felder enthalten, um korrekt verarbeitet zu
|
|||||||
id: 20251110-projekt-alpha-8a9b2c # Eindeutige Kennung (YYYYMMDD-slug)
|
id: 20251110-projekt-alpha-8a9b2c # Eindeutige Kennung (YYYYMMDD-slug)
|
||||||
title: Projekt Alpha # Sprechender Titel (wird in Suchergebnissen angezeigt)
|
title: Projekt Alpha # Sprechender Titel (wird in Suchergebnissen angezeigt)
|
||||||
type: project # Steuert Verarbeitung & Vernetzung (siehe Kap. 3)
|
type: project # Steuert Verarbeitung & Vernetzung (siehe Kap. 3)
|
||||||
status: active # Status (z.B. draft, active, archived)
|
status: active # active, archived oder 'draft' (für generierte Notes)
|
||||||
created: 2025-11-10 # Erstellungsdatum (ISO 8601 oder YYYY-MM-DD)
|
created: 2025-11-10 # Erstellungsdatum (ISO 8601 oder YYYY-MM-DD)
|
||||||
updated: 2025-12-07 # Letzte Änderung
|
updated: 2025-12-07 # Letzte Änderung
|
||||||
tags: [ki, entwicklung] # Taxonomie für Filterung
|
tags: [ki, entwicklung] # Taxonomie für Filterung
|
||||||
@@ -57,7 +59,7 @@ Jede Datei muss mindestens folgende Felder enthalten, um korrekt verarbeitet zu
|
|||||||
Diese Felder sind technisch nicht zwingend, aber für bestimmte Typen sinnvoll:
|
Diese Felder sind technisch nicht zwingend, aber für bestimmte Typen sinnvoll:
|
||||||
|
|
||||||
lang: de # Sprache (Default: de)
|
lang: de # Sprache (Default: de)
|
||||||
aliases: [Alpha Projekt, Project A] # Synonyme für die Suche
|
aliases: [Alpha Projekt, Project A] # Synonyme (WICHTIG für Exact Match in Intelligence)
|
||||||
visibility: internal # internal (default), public, private
|
visibility: internal # internal (default), public, private
|
||||||
|
|
||||||
> **Hinweis:** Felder wie `retriever_weight` oder `chunk_profile` sollten **nicht** mehr manuell im Frontmatter gesetzt werden. Diese werden zentral über den `type` gesteuert (siehe Kap. 3), um die Wartbarkeit zu sichern.
|
> **Hinweis:** Felder wie `retriever_weight` oder `chunk_profile` sollten **nicht** mehr manuell im Frontmatter gesetzt werden. Diese werden zentral über den `type` gesteuert (siehe Kap. 3), um die Wartbarkeit zu sichern.
|
||||||
@@ -67,7 +69,7 @@ Diese Felder sind technisch nicht zwingend, aber für bestimmte Typen sinnvoll:
|
|||||||
**Die ID (Identifikator):**
|
**Die ID (Identifikator):**
|
||||||
* Muss global eindeutig und **stabil** sein.
|
* Muss global eindeutig und **stabil** sein.
|
||||||
* Darf sich nicht ändern, wenn die Datei umbenannt oder verschoben wird.
|
* Darf sich nicht ändern, wenn die Datei umbenannt oder verschoben wird.
|
||||||
* **Empfehlung:** `YYYYMMDD-slug-hash` (z. B. `20231027-vektor-db-a1b2`). Dies garantiert Eindeutigkeit und Chronologie.
|
* **Empfehlung:** `YYYYMMDD-slug` (z. B. `20231027-vektor-db`). Dies garantiert Eindeutigkeit und Chronologie.
|
||||||
|
|
||||||
**Dateinamen & Pfade:**
|
**Dateinamen & Pfade:**
|
||||||
* Pfade dienen der menschlichen Ordnung (Ordnerstruktur), sind für Mindnet aber sekundär.
|
* Pfade dienen der menschlichen Ordnung (Ordnerstruktur), sind für Mindnet aber sekundär.
|
||||||
@@ -78,23 +80,26 @@ Diese Felder sind technisch nicht zwingend, aber für bestimmte Typen sinnvoll:
|
|||||||
|
|
||||||
## 3. Note-Typen & Typ-Registry
|
## 3. Note-Typen & Typ-Registry
|
||||||
|
|
||||||
Der `type` ist der wichtigste Hebel im Knowledge Design. Er steuert nicht nur das Gewicht bei der Suche, sondern seit WP-06 auch, **wann** eine Notiz aktiv in den Chat geholt wird ("Strategic Retrieval").
|
Der `type` ist der wichtigste Hebel im Knowledge Design. Er steuert nicht nur das Gewicht bei der Suche, sondern seit WP-06 auch, **wann** eine Notiz aktiv in den Chat geholt wird ("Strategic Retrieval") und seit WP-15, **ob Smart Edges aktiviert sind**.
|
||||||
|
|
||||||
### 3.1 Übersicht der Kern-Typen
|
### 3.1 Übersicht der Kern-Typen
|
||||||
|
|
||||||
Mindnet unterscheidet verschiedene Wissensarten. Wähle den Typ, der die **Rolle** der Notiz am besten beschreibt:
|
Mindnet unterscheidet verschiedene Wissensarten. Wähle den Typ, der die **Rolle** der Notiz am besten beschreibt:
|
||||||
|
|
||||||
| Typ | Beschreibung & Einsatzzweck | Rolle im Chat (Intent) |
|
| Typ | Beschreibung & Einsatzzweck | Rolle im Chat (Intent) | Interview Schema (WP07) | Matrix-Logik (WP11) |
|
||||||
| :--- | :--- | :--- |
|
| :--- | :--- | :--- | :--- | :--- |
|
||||||
| **`concept`** | Fachbegriffe, Theorien. Zeitloses Wissen. | **FACT** (Basiswissen) |
|
| **`concept`** | Fachbegriffe, Theorien. Zeitloses Wissen. | **FACT** | Titel, Definition, Tags | Ziel für `uses` |
|
||||||
| **`project`** | Ein Vorhaben mit Ziel, Dauer und Aufgaben. | **FACT / DECISION** (Kontext) |
|
| **`project`** | Ein Vorhaben mit Ziel, Dauer und Aufgaben. | **FACT / DECISION** | Ziel, Status, Stakeholder | Quelle für `uses`, `depends_on` |
|
||||||
| **`experience`** | Persönliche Erfahrung, Lektion oder Erkenntnis. | **EMPATHY** (Spiegelung) |
|
| **`experience`** | Persönliche Erfahrung, Lektion oder Erkenntnis. | **EMPATHY** | Situation, Erkenntnis, Emotionen | Quelle für `based_on`, `derived_from` |
|
||||||
| **`decision`** | Eine bewusst getroffene Entscheidung (ADR). | **DECISION** (Begründung "Warum") |
|
| **`decision`** | Eine bewusst getroffene Entscheidung (ADR). | **DECISION** | Kontext, Entscheidung, Alternativen | Quelle für `depends_on`, `caused_by` |
|
||||||
| **`value`** | Ein persönlicher Wert oder ein Prinzip. | **DECISION** (Moralischer Kompass) |
|
| **`value`** | Ein persönlicher Wert oder ein Prinzip. | **DECISION** | Definition, Anti-Beispiel | Ziel für `based_on` |
|
||||||
| **`goal`** | Ein strategisches Ziel (kurz- oder langfristig). | **DECISION** (Abgleich) |
|
| **`principle`** | Handlungsleitlinie. | **DECISION** | Regel, Ausnahme | Quelle für `derived_from` |
|
||||||
| **`person`** | Eine reale Person (Netzwerk, Autor). | **FACT** |
|
| **`goal`** | Ein strategisches Ziel (kurz- oder langfristig). | **DECISION** | Zeitrahmen, KPIs, Werte | Ziel für `related_to` |
|
||||||
| **`journal`** | Zeitbezogener Log-Eintrag, Daily Note. | **FACT** (Historie) |
|
| **`risk`** | Ein identifiziertes Risiko oder eine Gefahr. | **DECISION** | Auswirkung, Wahrscheinlichkeit | Quelle für `blocks` |
|
||||||
| **`source`** | Externe Quelle (Buch, PDF, Artikel). | **FACT** (Faktenbasis) |
|
| **`belief`** | Glaubenssatz / Überzeugung. | **EMPATHY** | Ursprung, Mantra | - |
|
||||||
|
| **`person`** | Eine reale Person (Netzwerk, Autor). | **FACT** | Rolle, Kontext | - |
|
||||||
|
| **`journal`** | Zeitbezogener Log-Eintrag, Daily Note. | **FACT** | Datum, Tags | - |
|
||||||
|
| **`source`** | Externe Quelle (Buch, PDF, Artikel). | **FACT** | Autor, URL | - |
|
||||||
|
|
||||||
### 3.2 Zusammenspiel mit `types.yaml`
|
### 3.2 Zusammenspiel mit `types.yaml`
|
||||||
|
|
||||||
@@ -102,13 +107,11 @@ Der `type` steuert im Hintergrund drei technische Mechanismen:
|
|||||||
|
|
||||||
1. **`retriever_weight` (Wichtigkeit):**
|
1. **`retriever_weight` (Wichtigkeit):**
|
||||||
* Ein `concept` (0.6) wiegt weniger als ein `project` (0.97) oder eine `decision` (1.0).
|
* Ein `concept` (0.6) wiegt weniger als ein `project` (0.97) oder eine `decision` (1.0).
|
||||||
* **Warum?** Bei einer Suche nach "Datenbank" soll Mindnet bevorzugt deine *Entscheidung* ("Warum wir X nutzen") anzeigen.
|
|
||||||
2. **`chunk_profile` (Textzerlegung):**
|
2. **`chunk_profile` (Textzerlegung):**
|
||||||
* `journal` (short): Wird fein zerlegt.
|
* `journal` (short): Wird fein zerlegt.
|
||||||
* `project` (long): Längere Kontext-Fenster.
|
* `experience` (sliding_smart_edges): Wird intelligent analysiert.
|
||||||
3. **`edge_defaults` (Automatische Vernetzung):**
|
3. **`enable_smart_edge_allocation` (WP15):**
|
||||||
* Mindnet ergänzt automatisch Kanten.
|
* Wenn `true`: Das System analysiert jeden Abschnitt mit KI, um zu prüfen, ob verlinkte Themen dort wirklich relevant sind. Das erhöht die Präzision massiv.
|
||||||
* Beispiel: Ein Link in einem `project` wird automatisch als `depends_on` (Abhängigkeit) interpretiert.
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -135,8 +138,12 @@ Dies ist die **mächtigste** Methode. Du sagst dem System explizit, **wie** Ding
|
|||||||
* `depends_on`: Hängt ab von / Benötigt. (Trigger für hohe Graph-Relevanz).
|
* `depends_on`: Hängt ab von / Benötigt. (Trigger für hohe Graph-Relevanz).
|
||||||
* `similar_to`: Ähnelt / Ist vergleichbar mit.
|
* `similar_to`: Ähnelt / Ist vergleichbar mit.
|
||||||
* `related_to`: Hat zu tun mit (allgemein).
|
* `related_to`: Hat zu tun mit (allgemein).
|
||||||
* `caused_by`: Wurde verursacht durch.
|
* `caused_by`: Wurde verursacht durch (Kausalität).
|
||||||
* `solves`: Löst (Problem).
|
* `solves`: Löst (Problem).
|
||||||
|
* **`blocks`:** Blockiert oder gefährdet (z.B. Risiko -> Projekt).
|
||||||
|
* **`derived_from`:** Stammt ab von (z.B. Prinzip -> Buch, Erfahrung -> Wert).
|
||||||
|
* **`based_on`:** Basiert auf (Fundament).
|
||||||
|
* **`uses`:** Nutzt (Werkzeug/Konzept).
|
||||||
|
|
||||||
### 4.3 Callout-Edges (Kuratierte Listen)
|
### 4.3 Callout-Edges (Kuratierte Listen)
|
||||||
Für Zusammenfassungen oder "Siehe auch"-Blöcke am Ende einer Notiz.
|
Für Zusammenfassungen oder "Siehe auch"-Blöcke am Ende einer Notiz.
|
||||||
@@ -147,7 +154,7 @@ Für Zusammenfassungen oder "Siehe auch"-Blöcke am Ende einer Notiz.
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 5. Schreiben für den KI-Zwilling (New in v2.3)
|
## 5. Schreiben für den KI-Zwilling (New in v2.3/2.4)
|
||||||
|
|
||||||
Damit der **RAG-Chat (WP05/06)** nicht nur dumm Fakten wiedergibt, sondern dich berät, musst du "Futter" für die Decision Engine und das Empathie-Modul liefern.
|
Damit der **RAG-Chat (WP05/06)** nicht nur dumm Fakten wiedergibt, sondern dich berät, musst du "Futter" für die Decision Engine und das Empathie-Modul liefern.
|
||||||
|
|
||||||
@@ -194,6 +201,36 @@ Erstelle Notizen mit `type: experience`. Nutze im Text **emotionale Brückenwör
|
|||||||
|
|
||||||
*Effekt:* Wenn du im Chat jammerst ("Alles ist sinnlos"), findet das System diese Notiz und spiegelt dir deine eigene Erfahrung zurück.
|
*Effekt:* Wenn du im Chat jammerst ("Alles ist sinnlos"), findet das System diese Notiz und spiegelt dir deine eigene Erfahrung zurück.
|
||||||
|
|
||||||
|
### 5.3 Schreiben für den Chat (UI Optimization)
|
||||||
|
Da deine Notizen im Web-Interface (WP10) angezeigt werden:
|
||||||
|
* **Kurze Absätze:** Das LLM liest besser, und der Mensch scannt schneller.
|
||||||
|
* **Klare Headings:** Nutze H1/H2, um dem Chunker logische Trennlinien zu geben.
|
||||||
|
|
||||||
|
### 5.4 Der Interview-Modus (Auto-Drafting)
|
||||||
|
Seit v2.4 (WP07) kann Mindnet Notizen für dich entwerfen.
|
||||||
|
|
||||||
|
* **Wie:** Schreibe im Chat einfach: *"Ich möchte ein neues Projekt 'Alpha' anlegen, Ziel ist die Markteroberung."*
|
||||||
|
* **Was passiert:** Mindnet erkennt den Wunsch (`INTERVIEW`), wählt das Schema für `project` und generiert **sofort** einen Markdown-Entwurf.
|
||||||
|
* **Ergebnis:** Du erhältst einen Code-Block mit `status: draft`. Diesen kannst du im Draft-Editor (UI) direkt bearbeiten und herunterladen.
|
||||||
|
* **Drafts:** Enthalten oft Platzhalter `[TODO]`. Das ist Absicht. Ergänze sie im Editor.
|
||||||
|
|
||||||
|
### 5.5 Futter für das Risikomanagement (`DECISION`)
|
||||||
|
Damit Mindnet dich vor Fehlern warnen kann, musst du Risiken explizit machen.
|
||||||
|
|
||||||
|
**Best Practice: Risiken definieren**
|
||||||
|
Erstelle Notizen mit `type: risk`. Nutze `blocks` oder `related_to`, um sie mit Projekten zu verknüpfen.
|
||||||
|
|
||||||
|
---
|
||||||
|
type: risk
|
||||||
|
title: Risiko: Vendor Lock-in bei Cloud-DBs
|
||||||
|
tags: [architektur, kosten, abhängigkeit]
|
||||||
|
---
|
||||||
|
# Risiko: Vendor Lock-in bei Cloud-DBs
|
||||||
|
Die Nutzung proprietärer Cloud-Datenbanken führt langfristig zu hohen Migrationskosten.
|
||||||
|
Dies [[rel:blocks Ziel Unabhängigkeit 2026]].
|
||||||
|
|
||||||
|
*Effekt:* Wenn du fragst "Soll ich AWS DynamoDB nutzen?", erkennt die Decision Engine den Konflikt mit deinem Ziel "Unabhängigkeit" durch die Kante `blocks` und den hohen `retriever_weight` des Risikos.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 6. Best Practices & Beispiele (Klassik)
|
## 6. Best Practices & Beispiele (Klassik)
|
||||||
@@ -252,4 +289,4 @@ Wir vermeiden es, Logik in den Markdown-Dateien hart zu kodieren.
|
|||||||
|
|
||||||
### 7.2 Was bedeutet das für dich?
|
### 7.2 Was bedeutet das für dich?
|
||||||
* Du kannst dich auf den Inhalt konzentrieren.
|
* Du kannst dich auf den Inhalt konzentrieren.
|
||||||
* Wenn wir in Zukunft (WP08) basierend auf Feedback lernen, dass "Projekte" noch wichtiger sind, ändern wir **eine Zeile** in der Konfiguration, und das gesamte System passt sich beim nächsten Import an.
|
* Wenn wir in Zukunft basierend auf Feedback lernen, dass "Projekte" noch wichtiger sind, ändern wir **eine Zeile** in der Konfiguration, und das gesamte System passt sich beim nächsten Import an.
|
||||||
+48
-38
@@ -1,8 +1,8 @@
|
|||||||
# Mindnet v2.2 – Overview & Einstieg
|
# Mindnet v2.4 – Overview & Einstieg
|
||||||
**Datei:** `docs/mindnet_overview_v2.2.md`
|
**Datei:** `docs/mindnet_overview_v2.6.md`
|
||||||
**Stand:** 2025-12-09
|
**Stand:** 2025-12-12
|
||||||
**Status:** **FINAL** (Post-WP06 Release)
|
**Status:** **FINAL** (Inkl. Smart Edges, Traffic Control & Healing UI)
|
||||||
**Version:** 2.3.1
|
**Version:** 2.6.0
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -13,10 +13,11 @@
|
|||||||
Anders als herkömmliche Notiz-Apps (wie Obsidian oder Evernote), die Texte nur passiv speichern, ist Mindnet ein **aktives System**:
|
Anders als herkömmliche Notiz-Apps (wie Obsidian oder Evernote), die Texte nur passiv speichern, ist Mindnet ein **aktives System**:
|
||||||
* Es **versteht** Zusammenhänge über einen Wissensgraphen.
|
* Es **versteht** Zusammenhänge über einen Wissensgraphen.
|
||||||
* Es **begründet** Antworten ("Warum ist das so?").
|
* Es **begründet** Antworten ("Warum ist das so?").
|
||||||
* Es **antwortet** situativ angepasst: Mal als harter Strategieberater, mal als empathischer Spiegel.
|
* Es **unterstützt** beim Schreiben: Es schlägt automatisch Verbindungen zu bestehendem Wissen vor ("Active Intelligence").
|
||||||
|
* Es **antwortet** situativ angepasst: Mal als Strategieberater, mal als empathischer Spiegel, und neu: **als Interviewer, der hilft, Wissen zu erfassen.**
|
||||||
|
|
||||||
### Die Vision
|
### Die Vision
|
||||||
> „Ein System, das nicht nur speichert, was ich weiß, sondern auch wie ich denke und fühle.“
|
> „Ein System, das nicht nur speichert, was ich weiß, sondern auch wie ich denke, fühle und arbeite.“
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -27,22 +28,26 @@ Mindnet arbeitet auf drei Schichten, die aufeinander aufbauen:
|
|||||||
### Ebene 1: Content (Das Gedächtnis)
|
### Ebene 1: Content (Das Gedächtnis)
|
||||||
* **Quelle:** Dein lokaler Obsidian-Vault (Markdown).
|
* **Quelle:** Dein lokaler Obsidian-Vault (Markdown).
|
||||||
* **Funktion:** Speicherung von Fakten, Projekten und Logs.
|
* **Funktion:** Speicherung von Fakten, Projekten und Logs.
|
||||||
* **Technik:** Import-Pipeline, Chunking, Vektor-Datenbank (Qdrant).
|
* **Technik:** Async Import-Pipeline, Smart Chunking (LLM-gestützte Kantenzuweisung), Vektor-Datenbank (Qdrant).
|
||||||
* **Status:** 🟢 Live (WP01–WP03).
|
* **Status:** 🟢 Live (WP01–WP03, WP11, WP15).
|
||||||
|
|
||||||
### Ebene 2: Semantik (Das Verstehen)
|
### Ebene 2: Semantik (Das Verstehen)
|
||||||
* **Funktion:** Verknüpfung von isolierten Notizen zu einem Netzwerk.
|
* **Funktion:** Verknüpfung von isolierten Notizen zu einem Netzwerk.
|
||||||
* **Logik:** "Projekt A *hängt ab von* Entscheidung B".
|
* **Logik:** "Projekt A *hängt ab von* Entscheidung B".
|
||||||
* **Technik:** Hybrider Retriever (Graph + Vektor), Explanation Engine.
|
* **Technik:** Hybrider Retriever (Graph + Nomic Embeddings), Explanation Engine.
|
||||||
* **Status:** 🟢 Live (WP04).
|
* **Status:** 🟢 Live (WP04, WP11, WP15).
|
||||||
|
|
||||||
### Ebene 3: Identität (Die Persönlichkeit)
|
### Ebene 3: Identität & Interaktion (Die Persönlichkeit)
|
||||||
* **Funktion:** Interaktion und Bewertung. Das System nimmt eine Haltung ein.
|
* **Funktion:** Interaktion, Bewertung und Co-Creation.
|
||||||
* **Logik:** "Ich empfehle Lösung X, weil sie unserem Wert 'Datensparsamkeit' entspricht."
|
* **Logik:**
|
||||||
* **Technik:** * **Intent Router:** Erkennt Absichten (Fakt vs. Gefühl vs. Entscheidung).
|
* "Ich empfehle Lösung X, weil sie unserem Wert 'Datensparsamkeit' entspricht."
|
||||||
* **Strategic Retrieval:** Lädt gezielt Werte oder Erfahrungen nach.
|
* "Ich sehe, du willst ein Projekt starten. Lass uns die Eckdaten erfassen."
|
||||||
* **Multi-Persona:** Passt den Tonfall an.
|
* **Technik:**
|
||||||
* **Status:** 🟢 Live (WP05–WP06).
|
* **Hybrid Router v5:** Erkennt Absichten (Frage vs. Befehl) und unterscheidet Objekte (`types.yaml`) von Handlungen (`decision_engine.yaml`).
|
||||||
|
* **Traffic Control:** Priorisiert Chat-Anfragen ("Realtime") vor Hintergrund-Jobs ("Background").
|
||||||
|
* **One-Shot Extraction:** Generiert Entwürfe für neue Notizen.
|
||||||
|
* **Active Intelligence:** Schlägt Links während des Schreibens vor.
|
||||||
|
* **Status:** 🟢 Live (WP05–WP07, WP10, WP15).
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -50,18 +55,23 @@ Mindnet arbeitet auf drei Schichten, die aufeinander aufbauen:
|
|||||||
|
|
||||||
Der Datenfluss in Mindnet ist zyklisch ("Data Flywheel"):
|
Der Datenfluss in Mindnet ist zyklisch ("Data Flywheel"):
|
||||||
|
|
||||||
1. **Input:** Du schreibst Notizen in Obsidian.
|
1. **Input:** Du schreibst Notizen in Obsidian **ODER** lässt sie von Mindnet im Chat entwerfen.
|
||||||
2. **Ingest:** Ein Python-Skript importiert, zerlegt (Chunking) und vernetzt (Edges) die Daten in Qdrant.
|
2. **Intelligence (Live):** Während du schreibst, analysiert Mindnet den Text und schlägt Verknüpfungen vor (Sliding Window Analyse).
|
||||||
3. **Intent Recognition:** Der Router analysiert deine Frage: Willst du Fakten, Code oder Empathie?
|
3. **Ingest:** Ein asynchrones Python-Skript importiert und zerlegt die Daten.
|
||||||
4. **Retrieval:** Das System sucht Inhalte passend zum Intent (z.B. "Lade Erfahrungen bei Empathie").
|
* **Neu (Smart Edges):** Ein LLM analysiert jeden Textabschnitt und entscheidet, welche Kanten relevant sind.
|
||||||
5. **Generation:** Ein lokales LLM (Ollama) formuliert die Antwort.
|
4. **Intent Recognition:** Der Router analysiert deine Eingabe: Ist es eine Frage (RAG) oder ein Befehl (Interview)?
|
||||||
6. **Feedback:** Du bewertest die Antwort. Das System lernt (langfristig) daraus.
|
5. **Retrieval / Action:**
|
||||||
|
* Bei Fragen: Das System sucht Inhalte passend zum Intent.
|
||||||
|
* Bei Interviews: Das System wählt das passende Schema (z.B. Projekt-Vorlage).
|
||||||
|
6. **Generation:** Ein lokales LLM (Ollama) formuliert die Antwort oder den Markdown-Draft.
|
||||||
|
7. **Feedback:** Du bewertest die Antwort. Das System lernt (langfristig) daraus.
|
||||||
|
|
||||||
**Tech-Stack:**
|
**Tech-Stack:**
|
||||||
* **Backend:** Python 3.12, FastAPI.
|
* **Backend:** Python 3.10+, FastAPI (Async).
|
||||||
* **Datenbank:** Qdrant (Vektor & Graph).
|
* **Datenbank:** Qdrant (Vektor & Graph, 768 Dim).
|
||||||
* **KI:** Ollama (Phi-3 Mini / Mistral) – 100% lokal.
|
* **KI:** Ollama (Phi-3 Mini für Chat, Nomic für Embeddings) – 100% lokal.
|
||||||
* **Frontend:** Terminal (aktuell) / Web-UI (geplant WP10).
|
* **Traffic Control:** Semaphore-Logik zur Lastverteilung zwischen Chat und Import.
|
||||||
|
* **Frontend:** Streamlit Web-UI (v2.5) mit Healing Parser.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -71,25 +81,25 @@ Wo findest du was?
|
|||||||
|
|
||||||
| Wenn du... | ...lies dieses Dokument |
|
| Wenn du... | ...lies dieses Dokument |
|
||||||
| :--- | :--- |
|
| :--- | :--- |
|
||||||
| **...wissen willst, wie man Notizen schreibt.** | `mindnet_knowledge_design_manual_v2.2.md` |
|
| **...wissen willst, wie man Notizen schreibt.** | `mindnet_knowledge_design_manual_v2.6.md` |
|
||||||
| **...das System installieren oder betreiben musst.** | `mindnet_admin_guide_v2.2.md` |
|
| **...das System installieren oder betreiben musst.** | `mindnet_admin_guide_v2.6.md` |
|
||||||
| **...am Python-Code entwickeln willst.** | `mindnet_developer_guide_v2.2.md` |
|
| **...am Python-Code entwickeln willst.** | `mindnet_developer_guide_v2.6.md` |
|
||||||
| **...die Pipeline (Import -> RAG) verstehen willst.** | `mindnet_pipeline_playbook_v2.2.md` |
|
| **...die Pipeline (Import -> RAG) verstehen willst.** | `mindnet_pipeline_playbook_v2.6.md` |
|
||||||
| **...die genaue JSON-Struktur oder APIs suchst.** | `mindnet_technical_architecture.md` |
|
| **...die genaue JSON-Struktur oder APIs suchst.** | `mindnet_technical_architecture_v2.6.md` |
|
||||||
| **...verstehen willst, was fachlich passiert.** | `mindnet_functional_architecture.md` |
|
| **...verstehen willst, was fachlich passiert.** | `mindnet_functional_architecture_v2.6.md` |
|
||||||
| **...den aktuellen Projektstatus suchst.** | `Programmplan_V2.2.md` |
|
| **...den aktuellen Projektstatus suchst.** | `mindnet_appendices_v2.6.md` |
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 5. Rollen im System
|
## 5. Rollen im System
|
||||||
|
|
||||||
* **Mindmaster (User/Owner):** Du. Du erstellst Inhalte, stellst Fragen und gibst Feedback. Du definierst die Werte (`type: value`).
|
* **Mindmaster (User/Owner):** Du. Du erstellst Inhalte, stellst Fragen und gibst Feedback. Du definierst die Werte (`type: value`).
|
||||||
* **Mindnet (Der Agent):** Der digitale Zwilling. Er agiert als pragmatischer, transparenter Assistent im Chat.
|
* **Mindnet (Der Agent):** Der digitale Zwilling. Er agiert als pragmatischer, transparenter Assistent und Analyst.
|
||||||
* **Administrator:** Verantwortlich für Docker-Container, Backups und LLM-Ressourcen.
|
* **Administrator:** Verantwortlich für Docker-Container, Backups und LLM-Ressourcen.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 6. Aktueller Fokus
|
## 6. Aktueller Fokus
|
||||||
|
|
||||||
Wir haben **Phase C (Persönlichkeit)** mit WP06 (Decision Engine) abgeschlossen.
|
Wir haben die **Smart Edge Allocation (WP15)** und die **System-Stabilisierung (Traffic Control)** erfolgreich abgeschlossen.
|
||||||
Das System kann nun strategisch denken und fühlen. Als Nächstes folgt **Phase D (Interaktion)** mit dem **Chat Interface (WP10)** für bessere Usability.
|
Das System kann nun aktiv helfen, Wissen zu strukturieren, ohne dabei unter Last zusammenzubrechen. Der Fokus verschiebt sich nun in Richtung **Conversational Memory (WP17)** und **MCP Integration (WP13)**.
|
||||||
+126
-81
@@ -1,19 +1,19 @@
|
|||||||
# Mindnet v2.2 – Admin Guide
|
# Mindnet v2.4 – Admin Guide
|
||||||
**Datei:** `docs/mindnet_admin_guide_v2.2.md`
|
**Datei:** `docs/mindnet_admin_guide_v2.6.md`
|
||||||
**Stand:** 2025-12-09
|
**Stand:** 2025-12-12
|
||||||
**Status:** **FINAL** (Inkl. RAG, Decision Engine & LLM Ops)
|
**Status:** **FINAL** (Inkl. Traffic Control & Smart Edge Config)
|
||||||
**Quellen:** `Handbuch.md`, `mindnet_developer_guide_v2.2.md`.
|
**Quellen:** `Handbuch.md`, `mindnet_developer_guide_v2.6.md`.
|
||||||
|
|
||||||
> Dieses Handbuch richtet sich an **Administratoren**. Es beschreibt Installation, Konfiguration, Backup-Strategien, Monitoring und den sicheren Betrieb der Mindnet-Instanz (API + DB + LLM).
|
> Dieses Handbuch richtet sich an **Administratoren**. Es beschreibt Installation, Konfiguration, Backup-Strategien, Monitoring und den sicheren Betrieb der Mindnet-Instanz (API + UI + DB).
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 1. Zielgruppe & Scope
|
## 1. Zielgruppe & Scope
|
||||||
|
|
||||||
Mindnet ist als **Single-Node System** konzipiert, das lokal (z.B. Laptop) oder auf einem privaten Server (Homelab, Intranet) läuft.
|
Mindnet ist als **Multi-Service-Architektur** konzipiert, die lokal oder auf einem privaten Server läuft.
|
||||||
Wir unterscheiden strikt zwischen:
|
Wir unterscheiden strikt zwischen:
|
||||||
* **Production (Port 8001):** Stabiler `main` Branch.
|
* **Production:** Backend (8001) + Frontend (8501). Stabiler `main` Branch.
|
||||||
* **Development (Port 8002):** Experimentelle Feature-Branches.
|
* **Development:** Backend (8002) + Frontend (8502). Experimentelle Feature-Branches.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -23,7 +23,7 @@ Wir unterscheiden strikt zwischen:
|
|||||||
* **OS:** Linux (Ubuntu 22.04+ empfohlen) oder macOS.
|
* **OS:** Linux (Ubuntu 22.04+ empfohlen) oder macOS.
|
||||||
* **Runtime:** Python 3.10+, Docker (für Qdrant), Ollama (für LLM).
|
* **Runtime:** Python 3.10+, Docker (für Qdrant), Ollama (für LLM).
|
||||||
* **Hardware:**
|
* **Hardware:**
|
||||||
* CPU: 4+ Cores empfohlen (für Import & Inference).
|
* CPU: 4+ Cores empfohlen (für Async Import & Inference).
|
||||||
* RAM: Min. 8GB empfohlen (4GB System + 4GB für Phi-3/Qdrant).
|
* RAM: Min. 8GB empfohlen (4GB System + 4GB für Phi-3/Qdrant).
|
||||||
* Disk: SSD empfohlen für Qdrant-Performance.
|
* Disk: SSD empfohlen für Qdrant-Performance.
|
||||||
|
|
||||||
@@ -36,10 +36,12 @@ Wir unterscheiden strikt zwischen:
|
|||||||
# 2. Umgebung einrichten
|
# 2. Umgebung einrichten
|
||||||
python3 -m venv .venv
|
python3 -m venv .venv
|
||||||
source .venv/bin/activate
|
source .venv/bin/activate
|
||||||
|
|
||||||
|
# 3. Dependencies installieren (inkl. Streamlit, HTTPX)
|
||||||
pip install -r requirements.txt
|
pip install -r requirements.txt
|
||||||
|
|
||||||
# 3. Verzeichnisse anlegen
|
# 4. Verzeichnisse anlegen
|
||||||
mkdir -p logs qdrant_storage data/logs
|
mkdir -p logs qdrant_storage data/logs vault
|
||||||
|
|
||||||
### 2.3 Qdrant Setup (Docker)
|
### 2.3 Qdrant Setup (Docker)
|
||||||
Wir nutzen Qdrant als Vektor-Datenbank. Persistenz ist wichtig.
|
Wir nutzen Qdrant als Vektor-Datenbank. Persistenz ist wichtig.
|
||||||
@@ -51,105 +53,155 @@ Wir nutzen Qdrant als Vektor-Datenbank. Persistenz ist wichtig.
|
|||||||
-v $(pwd)/qdrant_storage:/qdrant/storage \
|
-v $(pwd)/qdrant_storage:/qdrant/storage \
|
||||||
qdrant/qdrant
|
qdrant/qdrant
|
||||||
|
|
||||||
### 2.4 Ollama Setup (LLM Service)
|
### 2.4 Ollama Setup (LLM & Embeddings)
|
||||||
Mindnet benötigt einen lokalen LLM-Server für den Chat.
|
Mindnet benötigt einen lokalen LLM-Server für Chat UND Embeddings.
|
||||||
|
**WICHTIG (Update v2.4):** Es muss zwingend `nomic-embed-text` installiert sein, sonst startet der Import nicht.
|
||||||
|
|
||||||
# 1. Installieren (Linux Script)
|
# 1. Installieren (Linux Script)
|
||||||
curl -fsSL https://ollama.com/install.sh | sh
|
curl -fsSL https://ollama.com/install.sh | sh
|
||||||
|
|
||||||
# 2. Modell laden (Phi-3 Mini für CPU-Performance)
|
# 2. Modelle laden
|
||||||
ollama pull phi3:mini
|
ollama pull phi3:mini # Für Chat/Reasoning
|
||||||
|
ollama pull nomic-embed-text # Für Vektoren (768 Dim)
|
||||||
|
|
||||||
# 3. Testen
|
# 3. Testen
|
||||||
curl http://localhost:11434/api/generate -d '{"model": "phi3:mini", "prompt":"Hi"}'
|
curl http://localhost:11434/api/generate -d '{"model": "phi3:mini", "prompt":"Hi"}'
|
||||||
|
|
||||||
### 2.5 Konfiguration (ENV)
|
### 2.5 Konfiguration (ENV)
|
||||||
Erstelle eine `.env` Datei im Root-Verzeichnis. Die neuen Settings für WP-06 (Timeout, Decision Config) sind essenziell für stabilen Betrieb auf CPUs.
|
Erstelle eine `.env` Datei im Root-Verzeichnis. Achte besonders auf `VECTOR_DIM` und das neue `MINDNET_LLM_BACKGROUND_LIMIT`.
|
||||||
|
|
||||||
|
# Server Config
|
||||||
|
UVICORN_HOST=0.0.0.0
|
||||||
|
|
||||||
# Qdrant Verbindung
|
# Qdrant Verbindung
|
||||||
QDRANT_URL="http://localhost:6333"
|
QDRANT_URL="http://localhost:6333"
|
||||||
|
|
||||||
# Mindnet Core Settings
|
# Mindnet Core Settings
|
||||||
COLLECTION_PREFIX="mindnet"
|
COLLECTION_PREFIX="mindnet"
|
||||||
MINDNET_TYPES_FILE="./config/types.yaml"
|
MINDNET_TYPES_FILE="./config/types.yaml"
|
||||||
|
MINDNET_VAULT_ROOT="./vault"
|
||||||
|
|
||||||
# LLM / RAG Settings
|
# WICHTIG: Dimension auf 768 setzen (für Nomic)
|
||||||
MINDNET_LLM_MODEL="phi3:mini"
|
VECTOR_DIM=768
|
||||||
|
|
||||||
|
# AI Modelle (Ollama)
|
||||||
MINDNET_OLLAMA_URL="http://127.0.0.1:11434"
|
MINDNET_OLLAMA_URL="http://127.0.0.1:11434"
|
||||||
|
MINDNET_LLM_MODEL="phi3:mini"
|
||||||
|
MINDNET_EMBEDDING_MODEL="nomic-embed-text"
|
||||||
|
|
||||||
# NEU in v2.3: Config & Timeouts
|
# Timeouts (Erhöht für Async/Nomic/Smart Edges)
|
||||||
# Pfad zu Prompts
|
|
||||||
MINDNET_PROMPTS_PATH="./config/prompts.yaml"
|
|
||||||
# Pfad zur Decision Engine Config
|
|
||||||
MINDNET_DECISION_CONFIG="./config/decision_engine.yaml"
|
|
||||||
# Timeout in Sekunden (300s = 5min fuer Cold Starts)
|
|
||||||
MINDNET_LLM_TIMEOUT=300.0
|
MINDNET_LLM_TIMEOUT=300.0
|
||||||
|
MINDNET_API_TIMEOUT=300.0 # Wichtig: Frontend muss warten können
|
||||||
|
|
||||||
|
# Traffic Control (Neu in v2.6)
|
||||||
|
# Begrenzt parallele LLM-Calls im Import, um Chat stabil zu halten.
|
||||||
|
MINDNET_LLM_BACKGROUND_LIMIT=2
|
||||||
|
|
||||||
|
# Configs
|
||||||
|
MINDNET_PROMPTS_PATH="./config/prompts.yaml"
|
||||||
|
MINDNET_DECISION_CONFIG="./config/decision_engine.yaml"
|
||||||
|
|
||||||
### 2.6 Deployment via Systemd
|
### 2.6 Deployment via Systemd (Backend & Frontend)
|
||||||
Mindnet wird als Systemdienst gestartet. Ollama läuft meist als eigener Dienst (`ollama.service`).
|
|
||||||
|
|
||||||
**Production Service (`/etc/systemd/system/mindnet-prod.service`):**
|
Mindnet benötigt zwei Services pro Umgebung: API (Uvicorn) und UI (Streamlit).
|
||||||
* Läuft auf Port 8001.
|
|
||||||
* Autostart (`enabled`).
|
**Production Backend (`/etc/systemd/system/mindnet-prod.service`):**
|
||||||
* Restart Policy: `always`.
|
|
||||||
* Abhängigkeit: Sollte nach `docker` und `ollama` starten.
|
[Unit]
|
||||||
|
Description=Mindnet API Prod (8001)
|
||||||
|
After=network.target
|
||||||
|
|
||||||
|
[Service]
|
||||||
|
User=llmadmin
|
||||||
|
Group=llmadmin
|
||||||
|
WorkingDirectory=/home/llmadmin/mindnet
|
||||||
|
# Async Server Start
|
||||||
|
ExecStart=/home/llmadmin/mindnet/.venv/bin/uvicorn app.main:app --host 0.0.0.0 --port 8001 --env-file .env
|
||||||
|
Restart=always
|
||||||
|
RestartSec=5
|
||||||
|
|
||||||
|
[Install]
|
||||||
|
WantedBy=multi-user.target
|
||||||
|
|
||||||
|
**Production Frontend (`/etc/systemd/system/mindnet-ui-prod.service`):**
|
||||||
|
|
||||||
|
[Unit]
|
||||||
|
Description=Mindnet UI Prod (8501)
|
||||||
|
After=mindnet-prod.service
|
||||||
|
|
||||||
|
[Service]
|
||||||
|
User=llmadmin
|
||||||
|
Group=llmadmin
|
||||||
|
WorkingDirectory=/home/llmadmin/mindnet
|
||||||
|
|
||||||
|
# Environment Variables
|
||||||
|
Environment="MINDNET_API_URL=http://localhost:8001"
|
||||||
|
Environment="MINDNET_API_TIMEOUT=300"
|
||||||
|
Environment="STREAMLIT_SERVER_PORT=8501"
|
||||||
|
Environment="STREAMLIT_SERVER_ADDRESS=0.0.0.0"
|
||||||
|
Environment="STREAMLIT_SERVER_HEADLESS=true"
|
||||||
|
|
||||||
|
ExecStart=/home/llmadmin/mindnet/.venv/bin/streamlit run app/frontend/ui.py
|
||||||
|
Restart=always
|
||||||
|
RestartSec=5
|
||||||
|
|
||||||
|
[Install]
|
||||||
|
WantedBy=multi-user.target
|
||||||
|
|
||||||
|
**Firewall (UFW):**
|
||||||
|
Öffne die Ports für den Zugriff:
|
||||||
|
|
||||||
|
sudo ufw allow 8501/tcp # Prod UI
|
||||||
|
sudo ufw allow 8502/tcp # Dev UI (falls gewünscht)
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 3. Betrieb im Alltag
|
## 3. Betrieb im Alltag
|
||||||
|
|
||||||
### 3.1 Regelmäßige Importe
|
### 3.1 Regelmäßige Importe
|
||||||
Der Vault-Zustand sollte regelmäßig (z.B. stündlich per Cronjob) nach Qdrant synchronisiert werden.
|
Der Vault-Zustand sollte regelmäßig (z.B. stündlich per Cronjob) nach Qdrant synchronisiert werden. Das Skript nutzt nun **AsyncIO**, **Smart Edges** und **Traffic Control**.
|
||||||
|
|
||||||
**Cronjob-Beispiel (stündlich):**
|
**Cronjob-Beispiel (stündlich):**
|
||||||
|
|
||||||
0 * * * * cd /home/llmadmin/mindnet && .venv/bin/python3 -m scripts.import_markdown --vault /path/to/vault --prefix "mindnet" --apply --purge-before-upsert --sync-deletes >> ./logs/import.log 2>&1
|
0 * * * * cd /home/llmadmin/mindnet && .venv/bin/python3 -m scripts.import_markdown --vault ./vault --prefix "mindnet" --apply --purge-before-upsert --sync-deletes >> ./logs/import.log 2>&1
|
||||||
|
|
||||||
|
**Hinweis zu Smart Edges:**
|
||||||
|
Der Import dauert nun länger (ca. 2-3 Min pro Datei), da das LLM intensiv genutzt wird. Dank `MINDNET_LLM_BACKGROUND_LIMIT=2` bleibt der Server dabei aber für den Chat responsive.
|
||||||
|
|
||||||
### 3.2 Health-Checks
|
### 3.2 Health-Checks
|
||||||
Prüfe regelmäßig, ob alle drei Komponenten (API, DB, LLM) laufen.
|
Prüfe regelmäßig, ob alle Komponenten laufen.
|
||||||
|
|
||||||
**Status prüfen:**
|
|
||||||
|
|
||||||
sudo systemctl status mindnet-prod
|
sudo systemctl status mindnet-prod
|
||||||
|
sudo systemctl status mindnet-ui-prod
|
||||||
sudo systemctl status ollama
|
sudo systemctl status ollama
|
||||||
|
|
||||||
**Logischer Smoke-Test:**
|
|
||||||
|
|
||||||
python3 scripts/test_retriever_smoke.py --mode hybrid --url http://localhost:8001/query
|
|
||||||
|
|
||||||
### 3.3 Logs & Monitoring
|
### 3.3 Logs & Monitoring
|
||||||
* **Technische Fehler (API):** `journalctl -u mindnet-prod -f`
|
* **Backend Fehler:** `journalctl -u mindnet-prod -f`
|
||||||
* Achte auf: `LLM Router Raw Output`. Hier siehst du, wie die Decision Engine entscheidet.
|
* **Frontend Fehler:** `journalctl -u mindnet-ui-prod -f`
|
||||||
* **LLM Fehler (Ollama):** `journalctl -u ollama -f`
|
* **LLM Fehler:** `journalctl -u ollama -f`
|
||||||
* **Fachliche Logs:** `data/logs/search_history.jsonl`
|
* **Fachliche Logs:** `data/logs/search_history.jsonl`
|
||||||
|
|
||||||
**Troubleshooting Chat:**
|
|
||||||
* Wenn `/chat` in den Timeout läuft (>300s): Prüfe `MINDNET_LLM_TIMEOUT` in `.env` und ob das Modell im RAM liegt.
|
|
||||||
* Wenn `/chat` halluziniert: Prüfe `config/prompts.yaml` und ob der Import aktuell ist.
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 4. Update-Prozess
|
## 4. Troubleshooting (Update v2.6)
|
||||||
|
|
||||||
Wenn neue Versionen ausgerollt werden (Deployment):
|
### "Vector dimension error: expected dim: 768, got 384"
|
||||||
|
* **Ursache:** Du versuchst, in eine alte Qdrant-Collection (mit 384 Dim aus v2.2) neue Embeddings (mit 768 Dim von Nomic) zu schreiben.
|
||||||
|
* **Lösung:** Full Reset erforderlich.
|
||||||
|
1. `python -m scripts.reset_qdrant --mode wipe --prefix mindnet --yes` (Löscht DB).
|
||||||
|
2. `python -m scripts.import_markdown ...` (Baut neu auf).
|
||||||
|
|
||||||
1. **Code aktualisieren:**
|
### "500 Internal Server Error" beim Speichern/Chatten
|
||||||
|
* **Ursache:** Oft Timeout bei Ollama, wenn `nomic-embed-text` noch nicht im RAM geladen ist ("Cold Start") oder der Import die GPU blockiert.
|
||||||
cd /home/llmadmin/mindnet
|
* **Lösung:**
|
||||||
git pull origin main
|
1. `MINDNET_LLM_TIMEOUT` in `.env` auf `300.0` setzen.
|
||||||
|
2. `MINDNET_LLM_BACKGROUND_LIMIT` auf `1` reduzieren (falls Hardware schwach).
|
||||||
|
|
||||||
2. **Dependencies prüfen:**
|
### Import ist sehr langsam
|
||||||
|
* **Ursache:** Smart Edges sind aktiv (`types.yaml`) und analysieren jeden Chunk.
|
||||||
source .venv/bin/activate
|
* **Lösung:**
|
||||||
pip install -r requirements.txt
|
* Akzeptieren (für bessere Qualität).
|
||||||
|
* Oder für Massen-Initial-Import in `types.yaml` temporär `enable_smart_edge_allocation: false` setzen.
|
||||||
3. **Dienst neustarten (Zwingend!):**
|
|
||||||
|
|
||||||
sudo systemctl restart mindnet-prod
|
|
||||||
|
|
||||||
4. **Schema-Migration (falls nötig):**
|
|
||||||
|
|
||||||
python3 -m scripts.import_markdown ... --apply
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -158,7 +210,7 @@ Wenn neue Versionen ausgerollt werden (Deployment):
|
|||||||
Datensicherheit ruht auf drei Säulen: Vault (Source), Qdrant (Index), JSONL-Logs (Lern-Daten).
|
Datensicherheit ruht auf drei Säulen: Vault (Source), Qdrant (Index), JSONL-Logs (Lern-Daten).
|
||||||
|
|
||||||
### 5.1 Vault-Backup (Priorität 1)
|
### 5.1 Vault-Backup (Priorität 1)
|
||||||
Der Markdown-Vault ist die **Single Source of Truth**. Er muss klassisch gesichert werden (Git/NAS).
|
Der Markdown-Vault ist die **Single Source of Truth**.
|
||||||
|
|
||||||
### 5.2 Qdrant-Snapshots (Priorität 2)
|
### 5.2 Qdrant-Snapshots (Priorität 2)
|
||||||
Für schnelle Wiederherstellung des Suchindex.
|
Für schnelle Wiederherstellung des Suchindex.
|
||||||
@@ -167,16 +219,13 @@ Für schnelle Wiederherstellung des Suchindex.
|
|||||||
tar -czf qdrant_backup_$(date +%F).tar.gz ./qdrant_storage
|
tar -czf qdrant_backup_$(date +%F).tar.gz ./qdrant_storage
|
||||||
docker start mindnet_qdrant
|
docker start mindnet_qdrant
|
||||||
|
|
||||||
### 5.3 Log-Daten (Priorität 3)
|
### 5.3 Notfall-Wiederherstellung (Rebuild)
|
||||||
Sichere den Ordner `data/logs/`. Verlust dieser Daten bedeutet, dass das System vergisst, welche Antworten Nutzer hilfreich fanden.
|
Wenn die Datenbank korrupt ist oder Modelle gewechselt werden:
|
||||||
|
|
||||||
### 5.4 Notfall-Wiederherstellung (Rebuild)
|
|
||||||
Wenn die Datenbank korrupt ist:
|
|
||||||
|
|
||||||
# 1. DB komplett leeren (Wipe)
|
# 1. DB komplett leeren (Wipe)
|
||||||
python3 -m scripts.reset_qdrant --mode wipe --prefix "mindnet" --yes
|
python3 -m scripts.reset_qdrant --mode wipe --prefix "mindnet" --yes
|
||||||
# 2. Alles neu importieren
|
# 2. Alles neu importieren (Force re-calculates Hashes)
|
||||||
python3 -m scripts.import_markdown --vault /path/to/vault --prefix "mindnet" --apply
|
python3 -m scripts.import_markdown --vault ./vault --prefix "mindnet" --apply --force
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -184,10 +233,6 @@ Wenn die Datenbank korrupt ist:
|
|||||||
|
|
||||||
### 6.1 Zugriffsschutz
|
### 6.1 Zugriffsschutz
|
||||||
Mindnet hat aktuell **keine integrierte Authentifizierung**.
|
Mindnet hat aktuell **keine integrierte Authentifizierung**.
|
||||||
* **API:** Muss hinter einem Reverse Proxy (Nginx) mit Basic Auth laufen.
|
* **Frontend:** Streamlit auf Port 8501 ist offen. Nutze Nginx Basic Auth oder VPN.
|
||||||
* **Qdrant:** Sollte via Firewall (ufw) auf `127.0.0.1` beschränkt sein.
|
* **API:** Sollte nicht direkt im öffentlichen Netz stehen.
|
||||||
* **Ollama:** Standardmäßig hört Ollama nur auf `localhost`. Das ist sicher.
|
* **Qdrant:** Auf `127.0.0.1` beschränken.
|
||||||
|
|
||||||
### 6.2 Typen-Governance
|
|
||||||
Änderungen an der `types.yaml` (z.B. neue Gewichte) wirken global.
|
|
||||||
* **Prozess:** Änderungen sollten getestet werden (Smoke-Test), bevor sie produktiv gehen.
|
|
||||||
+61
-32
@@ -1,7 +1,7 @@
|
|||||||
# Mindnet v2.2 – Appendices & Referenzen
|
# Mindnet v2.4 – Appendices & Referenzen
|
||||||
**Datei:** `docs/mindnet_appendices_v2.2.md`
|
**Datei:** `docs/mindnet_appendices_v2.6.md`
|
||||||
**Stand:** 2025-12-09
|
**Stand:** 2025-12-12
|
||||||
**Status:** **FINAL** (Integrierter Stand WP01–WP06)
|
**Status:** **FINAL** (Integrierter Stand WP01–WP15)
|
||||||
**Quellen:** `TYPE_REGISTRY_MANUAL.md`, `chunking_strategy.md`, `mindnet_technical_architecture.md`, `Handbuch.md`.
|
**Quellen:** `TYPE_REGISTRY_MANUAL.md`, `chunking_strategy.md`, `mindnet_technical_architecture.md`, `Handbuch.md`.
|
||||||
|
|
||||||
> Dieses Dokument bündelt Tabellen, Schemata und technische Referenzen, die in den Prozess-Dokumenten (Playbook, Guides) den Lesefluss stören würden.
|
> Dieses Dokument bündelt Tabellen, Schemata und technische Referenzen, die in den Prozess-Dokumenten (Playbook, Guides) den Lesefluss stören würden.
|
||||||
@@ -10,22 +10,27 @@
|
|||||||
|
|
||||||
## Anhang A: Typ-Registry Referenz (Default-Werte)
|
## Anhang A: Typ-Registry Referenz (Default-Werte)
|
||||||
|
|
||||||
Diese Tabelle zeigt die Standard-Konfiguration der `types.yaml` (Stand v2.3.1).
|
Diese Tabelle zeigt die Standard-Konfiguration der `types.yaml` (Stand v2.6 / Config v1.6).
|
||||||
|
|
||||||
| Typ (`type`) | Chunk Profile | Retriever Weight | Edge Defaults (Auto-Kanten) | Beschreibung |
|
| Typ (`type`) | Chunk Profile | Retriever Weight | Smart Edges? | Beschreibung |
|
||||||
| :--- | :--- | :--- | :--- | :--- |
|
| :--- | :--- | :--- | :--- | :--- |
|
||||||
| **concept** | `medium` | 0.60 | `references`, `related_to` | Abstrakte Begriffe, Theorien. |
|
| **concept** | `sliding_smart_edges` | 0.60 | **Ja** | Abstrakte Begriffe, Theorien. |
|
||||||
| **project** | `long` | 0.97 | `references`, `depends_on` | Aktive Vorhaben. Hohe Priorität. |
|
| **project** | `sliding_smart_edges` | 0.97 | **Ja** | Aktive Vorhaben. Hohe Priorität. |
|
||||||
| **decision** | `long` | 1.00 | `caused_by`, `references` | Entscheidungen (ADRs). Höchste Prio. |
|
| **decision** | `structured_smart_edges` | 1.00 | **Ja** | Entscheidungen (ADRs). Höchste Prio. |
|
||||||
| **experience** | `medium` | 0.90 | `derived_from`, `inspired_by` | Persönliche Learnings. |
|
| **experience** | `sliding_smart_edges` | 0.90 | **Ja** | Persönliche Learnings. Intensiv analysiert. |
|
||||||
| **journal** | `short` | 0.80 | `related_to` | Zeitgebundene Logs. Fein granular. |
|
| **journal** | `sliding_standard` | 0.80 | Nein | Zeitgebundene Logs. Performance-optimiert. |
|
||||||
| **person** | `short` | 0.50 | `related_to` | Personen-Profile. |
|
| **person** | `sliding_standard` | 0.50 | Nein | Personen-Profile. |
|
||||||
| **source** | `long` | 0.50 | *(keine)* | Externe Quellen (Bücher, PDFs). |
|
| **source** | `sliding_standard` | 0.50 | Nein | Externe Quellen (Bücher, PDFs). |
|
||||||
| **event** | `short` | 0.60 | `related_to` | Meetings, Konferenzen. |
|
| **event** | `sliding_standard` | 0.60 | Nein | Meetings, Konferenzen. |
|
||||||
| **value** | `medium` | 1.00 | `related_to` | Persönliche Werte/Prinzipien. |
|
| **value** | `structured_smart_edges` | 1.00 | **Ja** | Persönliche Werte/Prinzipien. |
|
||||||
| **goal** | `medium` | 0.95 | `depends_on` | Strategische Ziele (Neu in WP06). |
|
| **principle** | `structured_smart_edges` | 1.00 | **Ja** | Handlungsleitlinien. |
|
||||||
| **belief** | `medium` | 0.90 | `related_to` | Glaubenssätze (Neu in WP06). |
|
| **profile** | `structured_smart_edges` | 0.80 | **Ja** | Eigene Identitäts-Beschreibungen. |
|
||||||
| **default** | `medium` | 1.00 | `references` | Fallback, wenn Typ unbekannt. |
|
| **goal** | `sliding_standard` | 0.95 | Nein | Strategische Ziele. |
|
||||||
|
| **belief** | `sliding_short` | 0.90 | Nein | Glaubenssätze. |
|
||||||
|
| **risk** | `sliding_short` | 0.90 | Nein | Risiken & Gefahren. |
|
||||||
|
| **task** | `sliding_short` | 0.70 | Nein | Aufgaben. |
|
||||||
|
| **glossary** | `sliding_short` | 0.50 | Nein | Begriffsdefinitionen. |
|
||||||
|
| **default** | `sliding_standard` | 1.00 | Nein | Fallback, wenn Typ unbekannt. |
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -43,7 +48,10 @@ Referenz aller implementierten Kantenarten (`kind`).
|
|||||||
| `similar_to` | Inline | Ja | Inhaltliche Ähnlichkeit. "Ist wie X". |
|
| `similar_to` | Inline | Ja | Inhaltliche Ähnlichkeit. "Ist wie X". |
|
||||||
| `caused_by` | Inline | Nein | Kausalität. "X ist der Grund für Y". |
|
| `caused_by` | Inline | Nein | Kausalität. "X ist der Grund für Y". |
|
||||||
| `solves` | Inline | Nein | Lösung. "Tool X löst Problem Y". |
|
| `solves` | Inline | Nein | Lösung. "Tool X löst Problem Y". |
|
||||||
| `derived_from` | Default (Exp) | Nein | Herkunft. "Erkenntnis stammt aus Quelle X". |
|
| `blocks` | Inline | Nein | **NEU:** Blockade. "Risiko X blockiert Projekt Y". |
|
||||||
|
| `derived_from` | Matrix / Default | Nein | Herkunft. "Erkenntnis stammt aus Prinzip X". |
|
||||||
|
| `based_on` | Matrix | Nein | Fundament. "Erfahrung basiert auf Wert Y". |
|
||||||
|
| `uses` | Matrix | Nein | Nutzung. "Projekt nutzt Konzept Z". |
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -58,7 +66,7 @@ Diese sind die Felder, die effektiv in Qdrant gespeichert werden.
|
|||||||
"title": "string (text)", // Titel aus Frontmatter
|
"title": "string (text)", // Titel aus Frontmatter
|
||||||
"type": "string (keyword)", // Typ (z.B. 'project')
|
"type": "string (keyword)", // Typ (z.B. 'project')
|
||||||
"retriever_weight": "float", // Numerische Wichtigkeit (0.0-1.0)
|
"retriever_weight": "float", // Numerische Wichtigkeit (0.0-1.0)
|
||||||
"chunk_profile": "string", // Genutztes Profil (z.B. 'long')
|
"chunk_profile": "string", // Genutztes Profil (z.B. 'sliding_smart_edges')
|
||||||
"edge_defaults": ["string"], // Liste der aktiven Default-Kanten
|
"edge_defaults": ["string"], // Liste der aktiven Default-Kanten
|
||||||
"tags": ["string"], // Liste von Tags
|
"tags": ["string"], // Liste von Tags
|
||||||
"created": "string (iso-date)", // Erstellungsdatum
|
"created": "string (iso-date)", // Erstellungsdatum
|
||||||
@@ -71,10 +79,12 @@ Diese sind die Felder, die effektiv in Qdrant gespeichert werden.
|
|||||||
{
|
{
|
||||||
"chunk_id": "string (keyword)", // Format: {note_id}#c{index}
|
"chunk_id": "string (keyword)", // Format: {note_id}#c{index}
|
||||||
"note_id": "string (keyword)", // FK zur Note
|
"note_id": "string (keyword)", // FK zur Note
|
||||||
|
"type": "string (keyword)", // Typ-Kopie aus Note
|
||||||
"text": "string (text)", // Reintext für Anzeige (ohne Overlap)
|
"text": "string (text)", // Reintext für Anzeige (ohne Overlap)
|
||||||
"window": "string (text)", // Text + Overlap (für Embedding)
|
"window": "string (text)", // Text + Overlap (für Embedding)
|
||||||
"ord": "integer", // Laufende Nummer (1..N)
|
"ord": "integer", // Laufende Nummer (1..N)
|
||||||
"retriever_weight": "float", // Kopie aus Note (für Query-Speed)
|
"retriever_weight": "float", // Kopie aus Note (für Query-Speed)
|
||||||
|
"chunk_profile": "string", // Vererbt von Note
|
||||||
"neighbors_prev": ["string"], // ID des Vorgängers
|
"neighbors_prev": ["string"], // ID des Vorgängers
|
||||||
"neighbors_next": ["string"] // ID des Nachfolgers
|
"neighbors_next": ["string"] // ID des Nachfolgers
|
||||||
}
|
}
|
||||||
@@ -86,10 +96,11 @@ Diese sind die Felder, die effektiv in Qdrant gespeichert werden.
|
|||||||
"source_id": "string (keyword)", // Chunk-ID (Start)
|
"source_id": "string (keyword)", // Chunk-ID (Start)
|
||||||
"target_id": "string (keyword)", // Chunk-ID oder Note-Titel (Ziel)
|
"target_id": "string (keyword)", // Chunk-ID oder Note-Titel (Ziel)
|
||||||
"kind": "string (keyword)", // z.B. 'depends_on'
|
"kind": "string (keyword)", // z.B. 'depends_on'
|
||||||
"scope": "string (keyword)", // Immer 'chunk' in v2.2
|
"scope": "string (keyword)", // Immer 'chunk'
|
||||||
"rule_id": "string (keyword)", // Traceability: 'inline:rel', 'explicit:wikilink'
|
"rule_id": "string (keyword)", // Traceability: 'inline:rel', 'explicit:wikilink'
|
||||||
"confidence": "float", // 0.0 - 1.0
|
"confidence": "float", // 0.0 - 1.0
|
||||||
"note_id": "string (keyword)" // Owner Note ID (für Löschung)
|
"note_id": "string (keyword)", // Owner Note ID
|
||||||
|
"provenance": "keyword" // 'explicit', 'rule', 'smart' (NEU)
|
||||||
}
|
}
|
||||||
|
|
||||||
---
|
---
|
||||||
@@ -103,31 +114,43 @@ Diese Variablen steuern das Verhalten der Skripte und Container.
|
|||||||
| `QDRANT_URL` | `http://localhost:6333` | URL zur Vektor-DB. |
|
| `QDRANT_URL` | `http://localhost:6333` | URL zur Vektor-DB. |
|
||||||
| `QDRANT_API_KEY` | *(leer)* | API-Key für Absicherung (optional). |
|
| `QDRANT_API_KEY` | *(leer)* | API-Key für Absicherung (optional). |
|
||||||
| `COLLECTION_PREFIX` | `mindnet` | Namensraum für Collections (`{prefix}_notes` etc). |
|
| `COLLECTION_PREFIX` | `mindnet` | Namensraum für Collections (`{prefix}_notes` etc). |
|
||||||
|
| `VECTOR_DIM` | `768` | **NEU:** Dimension für Embeddings (für Nomic). |
|
||||||
| `MINDNET_TYPES_FILE` | `config/types.yaml` | Pfad zur Typ-Registry. |
|
| `MINDNET_TYPES_FILE` | `config/types.yaml` | Pfad zur Typ-Registry. |
|
||||||
| `MINDNET_RETRIEVER_CONFIG`| `config/retriever.yaml`| Pfad zur Scoring-Konfiguration. |
|
| `MINDNET_RETRIEVER_CONFIG`| `config/retriever.yaml`| Pfad zur Scoring-Konfiguration. |
|
||||||
| `MINDNET_PROMPTS_PATH` | `config/prompts.yaml` | Pfad zu LLM-Prompts (Neu in v2.2). |
|
| `MINDNET_PROMPTS_PATH` | `config/prompts.yaml` | Pfad zu LLM-Prompts (Neu in v2.2). |
|
||||||
| `MINDNET_DECISION_CONFIG` | `config/decision_engine.yaml` | Pfad zur Router-Config (Neu in v2.3). |
|
| `MINDNET_DECISION_CONFIG` | `config/decision_engine.yaml` | Router & Interview Config (Neu in v2.3). |
|
||||||
| `MINDNET_LLM_MODEL` | `phi3:mini` | Name des Ollama-Modells (Neu in v2.2). |
|
| `MINDNET_LLM_MODEL` | `phi3:mini` | Name des Chat-Modells. |
|
||||||
|
| `MINDNET_EMBEDDING_MODEL` | `nomic-embed-text` | **NEU:** Name des Vektor-Modells. |
|
||||||
| `MINDNET_OLLAMA_URL` | `http://127.0.0.1:11434`| URL zum LLM-Server (Neu in v2.2). |
|
| `MINDNET_OLLAMA_URL` | `http://127.0.0.1:11434`| URL zum LLM-Server (Neu in v2.2). |
|
||||||
| `MINDNET_LLM_TIMEOUT` | `120.0` | Timeout für Ollama (Erhöhen auf 300.0 für CPU). |
|
| `MINDNET_LLM_TIMEOUT` | `300.0` | Timeout für Ollama (Erhöht für CPU-Inference). |
|
||||||
|
| `MINDNET_API_TIMEOUT` | `300.0` | **NEU:** Frontend Timeout (Erhöht für Smart Edges). |
|
||||||
|
| `MINDNET_LLM_BACKGROUND_LIMIT`| `2` | **NEU:** Max. parallele Import-Tasks (Traffic Control). |
|
||||||
|
| `MINDNET_VAULT_ROOT` | `./vault` | **NEU:** Pfad für Write-Back Operationen. |
|
||||||
| `MINDNET_HASH_COMPARE` | `Body` | Vergleichsmodus für Import (`Body`, `Frontmatter`, `Full`). |
|
| `MINDNET_HASH_COMPARE` | `Body` | Vergleichsmodus für Import (`Body`, `Frontmatter`, `Full`). |
|
||||||
| `MINDNET_HASH_SOURCE` | `parsed` | Quelle für Hash (`parsed`, `raw`, `file`). |
|
| `MINDNET_HASH_SOURCE` | `parsed` | Quelle für Hash (`parsed`, `raw`, `file`). |
|
||||||
| `VECTOR_DIM` | `384` | Dimension der Embeddings (Modellabhängig). |
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Anhang E: Glossar
|
## Anhang E: Glossar
|
||||||
|
|
||||||
* **Callout-Edge:** Kante via `> [!edge]`.
|
* **Active Intelligence:** Feature, das während des Schreibens Links vorschlägt.
|
||||||
|
* **Async Ingestion:** Non-blocking Import-Prozess zur Vermeidung von Timeouts.
|
||||||
* **Decision Engine:** Komponente, die den Intent prüft und Strategien wählt (WP06).
|
* **Decision Engine:** Komponente, die den Intent prüft und Strategien wählt (WP06).
|
||||||
|
* **Draft Editor:** Web-Komponente zur Bearbeitung generierter Notizen (WP10a).
|
||||||
* **Explanation Layer:** Komponente, die Scores und Graphen als Begründung liefert.
|
* **Explanation Layer:** Komponente, die Scores und Graphen als Begründung liefert.
|
||||||
|
* **Healing Parser:** UI-Funktion, die defektes YAML von LLMs repariert (v2.5).
|
||||||
* **Hybrid Router:** Kombination aus Keyword-Matching und LLM-Klassifizierung für Intents.
|
* **Hybrid Router:** Kombination aus Keyword-Matching und LLM-Klassifizierung für Intents.
|
||||||
|
* **Matrix Logic:** Regelwerk, das Kanten-Typen basierend auf Quell- und Ziel-Typ bestimmt.
|
||||||
|
* **Nomic:** Das neue, hochpräzise Embedding-Modell (768 Dim).
|
||||||
|
* **One-Shot Extractor:** LLM-Strategie zur sofortigen Generierung von Drafts ohne Rückfragen (WP07).
|
||||||
* **RAG (Retrieval Augmented Generation):** Kombination aus Suche und Text-Generierung.
|
* **RAG (Retrieval Augmented Generation):** Kombination aus Suche und Text-Generierung.
|
||||||
* **Strategic Retrieval:** Gezieltes Nachladen von Werten (`value`) bei Entscheidungfragen.
|
* **Resurrection Pattern:** UI-Technik, um Eingaben bei Tab-Wechseln zu erhalten.
|
||||||
|
* **Smart Edge Allocation:** LLM-basierte Prüfung, ob ein Link zu einem Chunk passt (WP15).
|
||||||
|
* **Traffic Control:** Priorisierung von Chat-Anfragen ("Realtime") vor Import-Last ("Background") im LLM-Service (v2.6).
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Anhang F: Workpackage Status (v2.3.1)
|
## Anhang F: Workpackage Status (v2.6.0)
|
||||||
|
|
||||||
Aktueller Implementierungsstand der Module.
|
Aktueller Implementierungsstand der Module.
|
||||||
|
|
||||||
@@ -139,7 +162,13 @@ Aktueller Implementierungsstand der Module.
|
|||||||
| **WP04a**| Retriever Scoring | 🟢 Live | Hybrider Score (Semantik + Graph). |
|
| **WP04a**| Retriever Scoring | 🟢 Live | Hybrider Score (Semantik + Graph). |
|
||||||
| **WP04b**| Explanation Layer | 🟢 Live | API liefert Reasons & Breakdown. |
|
| **WP04b**| Explanation Layer | 🟢 Live | API liefert Reasons & Breakdown. |
|
||||||
| **WP04c**| Feedback Loop | 🟢 Live | Logging (JSONL) & Traceability aktiv. |
|
| **WP04c**| Feedback Loop | 🟢 Live | Logging (JSONL) & Traceability aktiv. |
|
||||||
| **WP05** | Persönlichkeit / Chat | 🟢 Live | RAG-Chat mit Context Enrichment. |
|
| **WP05** | Persönlichkeit / Chat | 🟢 Live | RAG-Integration mit Context Enrichment. |
|
||||||
| **WP06** | Decision Engine | 🟢 Live | Hybrid Router, Strategic Retrieval, Multi-Persona. |
|
| **WP06** | Decision Engine | 🟢 Live | Hybrid Router v5, Strategic Retrieval. |
|
||||||
|
| **WP07** | Interview Assistent | 🟢 Live | **One-Shot Extractor & Schemas aktiv.** |
|
||||||
| **WP08** | Self-Tuning | 🔴 Geplant | Auto-Adjustment der Gewichte. |
|
| **WP08** | Self-Tuning | 🔴 Geplant | Auto-Adjustment der Gewichte. |
|
||||||
| **WP10** | Chat Interface | 🟡 Geplant | Nächster Schritt (Frontend). |
|
| **WP10** | Chat Interface | 🟢 Live | Web-Interface (Streamlit). |
|
||||||
|
| **WP10a**| Draft Editor | 🟢 Live | **Interaktives UI & Healing Parser.** |
|
||||||
|
| **WP11** | Backend Intelligence | 🟢 Live | **Async Ingestion, Nomic, Matrix.** |
|
||||||
|
| **WP15** | Smart Edge Allocation | 🟢 Live | **LLM-Filter & Traffic Control.** |
|
||||||
|
| **WP16** | Auto-Discovery | 🟡 Geplant | UX & Retrieval Tuning. |
|
||||||
|
| **WP17** | Conversational Memory | 🟡 Geplant | Dialog-Gedächtnis. |
|
||||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
+76
-45
@@ -1,6 +1,6 @@
|
|||||||
# Mindnet v2.2 – Entwickler-Workflow
|
# Mindnet v2.4 – Entwickler-Workflow
|
||||||
**Datei:** `DEV_WORKFLOW.md`
|
**Datei:** `docs/DEV_WORKFLOW.md`
|
||||||
**Stand:** 2025-12-09 (Aktualisiert: LLM Timeouts & Systemd)
|
**Stand:** 2025-12-12 (Aktualisiert: v2.6 mit Traffic Control)
|
||||||
|
|
||||||
Dieses Handbuch beschreibt den Entwicklungszyklus zwischen **Windows PC** (IDE), **Raspberry Pi** (Gitea) und **Beelink** (Runtime/Server).
|
Dieses Handbuch beschreibt den Entwicklungszyklus zwischen **Windows PC** (IDE), **Raspberry Pi** (Gitea) und **Beelink** (Runtime/Server).
|
||||||
|
|
||||||
@@ -11,8 +11,12 @@ Dieses Handbuch beschreibt den Entwicklungszyklus zwischen **Windows PC** (IDE),
|
|||||||
* **Windows 11 (VS Code):** Hier schreibst du Code. **Nie** direkt auf `main` arbeiten!
|
* **Windows 11 (VS Code):** Hier schreibst du Code. **Nie** direkt auf `main` arbeiten!
|
||||||
* **Raspberry Pi (Gitea):** Der Tresor. Speichert den Code und verwaltet Versionen.
|
* **Raspberry Pi (Gitea):** Der Tresor. Speichert den Code und verwaltet Versionen.
|
||||||
* **Beelink (Runtime):** Hier läuft die Software. Wir nutzen **Systemd-Services**:
|
* **Beelink (Runtime):** Hier läuft die Software. Wir nutzen **Systemd-Services**:
|
||||||
* **PROD (`mindnet-prod`):** Läuft stabil auf `main`. Ordner: `~/mindnet`. **Port 8001**.
|
* **PROD:**
|
||||||
* **DEV (`mindnet-dev`):** Deine Spielwiese. Ordner: `~/mindnet_dev`. **Port 8002**.
|
* API: `mindnet-prod` (Port 8001). Ordner: `~/mindnet`.
|
||||||
|
* UI: `mindnet-ui-prod` (Port 8501).
|
||||||
|
* **DEV:**
|
||||||
|
* API: `mindnet-dev` (Port 8002). Ordner: `~/mindnet_dev`.
|
||||||
|
* UI: `mindnet-ui-dev` (Port 8502).
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -31,14 +35,14 @@ Hier erstellst du die neue Funktion in einer sicheren Umgebung.
|
|||||||
2. **Branch erstellen:**
|
2. **Branch erstellen:**
|
||||||
* Klicke wieder unten links auf `main`.
|
* Klicke wieder unten links auf `main`.
|
||||||
* Wähle `+ Create new branch...`.
|
* Wähle `+ Create new branch...`.
|
||||||
* Gib den Namen ein: `feature/was-ich-tue` (z.B. `feature/wp06-decision`).
|
* Gib den Namen ein: `feature/was-ich-tue` (z.B. `feature/wp15-traffic-control`).
|
||||||
* Drücke **Enter**.
|
* Drücke **Enter**.
|
||||||
|
|
||||||
3. **Sicherheits-Check:**
|
3. **Sicherheits-Check:**
|
||||||
* Steht unten links jetzt dein Feature-Branch? **Nur dann darfst du Code ändern!**
|
* Steht unten links jetzt dein Feature-Branch? **Nur dann darfst du Code ändern!**
|
||||||
|
|
||||||
4. **Coden:**
|
4. **Coden:**
|
||||||
* Nimm deine Änderungen vor (z.B. neue YAML-Configs).
|
* Nimm deine Änderungen vor (z.B. neue Schemas in `types.yaml` oder Async-Logik in `ingestion.py`).
|
||||||
|
|
||||||
5. **Sichern & Hochladen:**
|
5. **Sichern & Hochladen:**
|
||||||
* **Source Control** Icon (Gabel-Symbol) -> Nachricht eingeben -> **Commit**.
|
* **Source Control** Icon (Gabel-Symbol) -> Nachricht eingeben -> **Commit**.
|
||||||
@@ -60,23 +64,40 @@ Hier prüfst du, ob dein neuer Code auf dem echten Server läuft.
|
|||||||
```bash
|
```bash
|
||||||
git fetch
|
git fetch
|
||||||
# Tipp: 'git branch -r' zeigt alle verfügbaren Branches an
|
# Tipp: 'git branch -r' zeigt alle verfügbaren Branches an
|
||||||
git checkout feature/wp06-decision
|
git checkout feature/wp15-traffic-control
|
||||||
git pull
|
git pull
|
||||||
```
|
```
|
||||||
|
|
||||||
4. **Umgebung vorbereiten (bei Bedarf):**
|
4. **Umgebung vorbereiten (WICHTIG für v2.6):**
|
||||||
|
Prüfe deine `.env` Datei. Sie benötigt jetzt Einträge für die Traffic Control.
|
||||||
|
```bash
|
||||||
|
nano .env
|
||||||
|
```
|
||||||
|
**Ergänze/Prüfe:**
|
||||||
|
```ini
|
||||||
|
# Traffic Control (Neu in v2.6)
|
||||||
|
MINDNET_LLM_BACKGROUND_LIMIT=2 # Max. parallele Import-Tasks
|
||||||
|
MINDNET_API_TIMEOUT=300.0 # Frontend wartet länger
|
||||||
|
MINDNET_EMBEDDING_MODEL="nomic-embed-text"
|
||||||
|
```
|
||||||
|
|
||||||
|
**Dependencies aktualisieren:**
|
||||||
```bash
|
```bash
|
||||||
source .venv/bin/activate
|
source .venv/bin/activate
|
||||||
pip install -r requirements.txt # Nur nötig bei neuen Paketen
|
pip install -r requirements.txt
|
||||||
|
ollama pull nomic-embed-text
|
||||||
```
|
```
|
||||||
|
|
||||||
5. **Test-Server aktualisieren (WICHTIG):**
|
5. **Test-Server aktualisieren (WICHTIG):**
|
||||||
Der Code ist da, aber der Prozess im RAM ist noch alt. Wir müssen den Service neustarten.
|
Der Code ist da, aber die Prozesse im RAM sind noch alt. Wir müssen die Services neustarten.
|
||||||
|
|
||||||
**Option A: Standard (Als Service laufen lassen)**
|
**Option A: Standard (Als Service laufen lassen)**
|
||||||
Ideal, wenn du nur testen willst, ob es läuft.
|
Ideal, wenn du nur testen willst, ob es läuft.
|
||||||
```bash
|
```bash
|
||||||
|
# 1. API neustarten (Backend)
|
||||||
sudo systemctl restart mindnet-dev
|
sudo systemctl restart mindnet-dev
|
||||||
|
# 2. UI neustarten (Frontend)
|
||||||
|
sudo systemctl restart mindnet-ui-dev
|
||||||
|
|
||||||
# Logs prüfen (um Fehler zu sehen):
|
# Logs prüfen (um Fehler zu sehen):
|
||||||
journalctl -u mindnet-dev -f
|
journalctl -u mindnet-dev -f
|
||||||
@@ -85,31 +106,32 @@ Hier prüfst du, ob dein neuer Code auf dem echten Server läuft.
|
|||||||
**Option B: Manuell Debuggen (Direct Output)**
|
**Option B: Manuell Debuggen (Direct Output)**
|
||||||
Ideal, wenn du Print-Ausgaben direkt sehen willst oder der Service dauernd crasht.
|
Ideal, wenn du Print-Ausgaben direkt sehen willst oder der Service dauernd crasht.
|
||||||
```bash
|
```bash
|
||||||
# 1. Service stoppen (wichtig, sonst ist Port 8002 belegt!)
|
# 1. Services stoppen (wichtig, sonst sind Ports 8002/8502 belegt!)
|
||||||
sudo systemctl stop mindnet-dev
|
sudo systemctl stop mindnet-dev
|
||||||
|
sudo systemctl stop mindnet-ui-dev
|
||||||
|
|
||||||
# 2. Manuell starten
|
# 2. Manuell starten (z.B. API)
|
||||||
uvicorn app.main:app --host 0.0.0.0 --port 8002 --env-file .env
|
uvicorn app.main:app --host 0.0.0.0 --port 8002 --env-file .env
|
||||||
|
|
||||||
# ... Testen ...
|
|
||||||
|
|
||||||
# 3. Wenn fertig: Service wieder anschalten (Optional)
|
|
||||||
# Strg+C drücken
|
|
||||||
sudo systemctl start mindnet-dev
|
|
||||||
```
|
```
|
||||||
|
|
||||||
6. **Validieren:**
|
6. **Validieren (Smoke Tests v2.6):**
|
||||||
Führe deine Tests in einem **zweiten Terminal** aus:
|
|
||||||
```bash
|
* **Test A: Last-Test (Traffic Control):**
|
||||||
# Beispiel für Decision Engine Test
|
1. Starte einen Import im Terminal: `python3 -m scripts.import_markdown ...`
|
||||||
python tests/test_wp06_decision.py -p 8002 -q "Soll ich...?"
|
2. Öffne **gleichzeitig** `http://<IP>:8502` im Browser.
|
||||||
```
|
3. Stelle eine Chat-Frage ("Was ist Mindnet?").
|
||||||
|
4. **Erwartung:** Der Chat antwortet sofort (Realtime Lane), während der Import im Hintergrund weiterläuft (Background Lane).
|
||||||
|
|
||||||
|
* **Test B: API Check**
|
||||||
|
```bash
|
||||||
|
curl -X POST "http://localhost:8002/ingest/analyze" -d '{"text": "mindnet", "type": "journal"}'
|
||||||
|
```
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
### Phase 3: Release (Gitea / Raspberry Pi)
|
### Phase 3: Release (Gitea / Raspberry Pi)
|
||||||
|
|
||||||
Wenn der Test auf Port 8002 erfolgreich war:
|
Wenn der Test auf Port 8002 / 8502 erfolgreich war:
|
||||||
|
|
||||||
1. Öffne Gitea im Browser.
|
1. Öffne Gitea im Browser.
|
||||||
2. Erstelle einen **Pull Request** (Dein Branch -> `main`).
|
2. Erstelle einen **Pull Request** (Dein Branch -> `main`).
|
||||||
@@ -119,7 +141,7 @@ Wenn der Test auf Port 8002 erfolgreich war:
|
|||||||
|
|
||||||
### Phase 4: Deployment (Beelink / `mindnet`)
|
### Phase 4: Deployment (Beelink / `mindnet`)
|
||||||
|
|
||||||
Jetzt bringen wir die Änderung in das Live-System (Port 8001).
|
Jetzt bringen wir die Änderung in das Live-System (Port 8001 / 8501).
|
||||||
|
|
||||||
1. **Deploy-Agent (Automatisch):**
|
1. **Deploy-Agent (Automatisch):**
|
||||||
Wenn dein `deploy.yml` aktiv ist, passiert das jetzt von selbst!
|
Wenn dein `deploy.yml` aktiv ist, passiert das jetzt von selbst!
|
||||||
@@ -129,11 +151,21 @@ Jetzt bringen wir die Änderung in das Live-System (Port 8001).
|
|||||||
cd /home/llmadmin/mindnet
|
cd /home/llmadmin/mindnet
|
||||||
git pull origin main
|
git pull origin main
|
||||||
|
|
||||||
# Produktions-Service neustarten
|
# Dependencies updaten & Modelle checken
|
||||||
sudo systemctl restart mindnet-prod
|
source .venv/bin/activate
|
||||||
|
pip install -r requirements.txt
|
||||||
|
ollama pull nomic-embed-text
|
||||||
|
|
||||||
# Kurz prüfen, ob er läuft
|
# .env prüfen (Traffic Control)
|
||||||
sudo systemctl status mindnet-prod
|
# Ggf. MINDNET_LLM_BACKGROUND_LIMIT=2 hinzufügen
|
||||||
|
|
||||||
|
# Falls sich die Vektor-Dimension geändert hat (v2.4 Upgrade):
|
||||||
|
# python3 -m scripts.reset_qdrant --mode wipe --prefix "mindnet" --yes
|
||||||
|
# python3 -m scripts.import_markdown --vault ./vault --prefix "mindnet" --apply --force
|
||||||
|
|
||||||
|
# Produktions-Services neustarten
|
||||||
|
sudo systemctl restart mindnet-prod
|
||||||
|
sudo systemctl restart mindnet-ui-prod
|
||||||
```
|
```
|
||||||
|
|
||||||
---
|
---
|
||||||
@@ -148,7 +180,7 @@ Damit das Chaos nicht wächst, löschen wir den fertigen Branch.
|
|||||||
cd ~/mindnet_dev
|
cd ~/mindnet_dev
|
||||||
git checkout main
|
git checkout main
|
||||||
git pull
|
git pull
|
||||||
git branch -d feature/wp06-decision
|
git branch -d feature/wp15-traffic-control
|
||||||
```
|
```
|
||||||
3. **VS Code:**
|
3. **VS Code:**
|
||||||
* Auf `main` wechseln.
|
* Auf `main` wechseln.
|
||||||
@@ -161,25 +193,24 @@ Damit das Chaos nicht wächst, löschen wir den fertigen Branch.
|
|||||||
|
|
||||||
| Wo? | Befehl | Was tut es? |
|
| Wo? | Befehl | Was tut es? |
|
||||||
| :--- | :--- | :--- |
|
| :--- | :--- | :--- |
|
||||||
| **VS Code** | `Sync (auf main)` | **WICHTIG:** Holt neuesten Code vom Server. |
|
| **Beelink** | `sudo systemctl restart mindnet-dev` | **Neustart Dev-Backend (Port 8002).** |
|
||||||
| **Beelink** | `git fetch` | Aktualisiert Liste der Remote-Branches. |
|
| **Beelink** | `journalctl -u mindnet-dev -f` | **Live-Logs Backend.** |
|
||||||
| **Beelink** | `sudo systemctl restart mindnet-dev` | **Neustart Dev-Server (Port 8002).** |
|
| **Beelink** | `python debug_analysis.py` | **Prüft Aliases & Scores.** |
|
||||||
| **Beelink** | `journalctl -u mindnet-dev -f` | **Live-Logs vom Dev-Server sehen.** |
|
| **Beelink** | `python -m scripts.reset_qdrant ...` | **Löscht & Repariert DB.** |
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 4. Troubleshooting
|
## 4. Troubleshooting
|
||||||
|
|
||||||
**"Read timed out (120s)" / 500 Error beim Chat**
|
**"Read timed out" im Frontend**
|
||||||
* **Ursache:** Das LLM (Ollama) braucht zu lange zum Laden ("Cold Start").
|
* **Ursache:** Backend braucht für Smart Edges länger als 60s.
|
||||||
* **Lösung:**
|
* **Lösung:** `MINDNET_API_TIMEOUT=300.0` in `.env` setzen und Services neustarten.
|
||||||
1. Erhöhe in `.env` den Wert: `MINDNET_LLM_TIMEOUT=300.0`.
|
|
||||||
2. Starte den Server neu (`sudo systemctl restart mindnet-dev`).
|
|
||||||
3. Stelle sicher, dass dein Test-Skript (Client) auch ein hohes Timeout hat.
|
|
||||||
|
|
||||||
**"Port 8002 already in use"**
|
**Import ist extrem langsam**
|
||||||
* **Ursache:** Du willst `uvicorn` manuell starten, aber der Service läuft noch.
|
* **Ursache:** Smart Edges analysieren jeden Chunk mit LLM.
|
||||||
* **Lösung:** `sudo systemctl stop mindnet-dev`.
|
* **Lösung:**
|
||||||
|
* Akzeptieren (Qualität vor Speed).
|
||||||
|
* Oder temporär in `config/types.yaml`: `enable_smart_edge_allocation: false`.
|
||||||
|
|
||||||
**"UnicodeDecodeError in .env"**
|
**"UnicodeDecodeError in .env"**
|
||||||
* **Ursache:** Umlaute oder Sonderzeichen in der `.env` Datei.
|
* **Ursache:** Umlaute oder Sonderzeichen in der `.env` Datei.
|
||||||
|
|||||||
+114
-69
@@ -1,24 +1,27 @@
|
|||||||
# Mindnet v2.2 – Developer Guide
|
# Mindnet v2.4 – Developer Guide
|
||||||
**Datei:** `docs/mindnet_developer_guide_v2.2.md`
|
**Datei:** `docs/mindnet_developer_guide_v2.6.md`
|
||||||
**Stand:** 2025-12-09
|
**Stand:** 2025-12-12
|
||||||
**Status:** **FINAL** (Inkl. RAG, Decision Engine & AI-Teaching)
|
**Status:** **FINAL** (Inkl. Async Core, Nomic, Traffic Control & Frontend State)
|
||||||
**Quellen:** `mindnet_technical_architecture.md`, `Handbuch.md`, `DEV_WORKFLOW.md`.
|
**Quellen:** `mindnet_technical_architecture.md`, `Handbuch.md`, `DEV_WORKFLOW.md`.
|
||||||
|
|
||||||
> **Zielgruppe:** Entwickler:innen.
|
> **Zielgruppe:** Entwickler:innen.
|
||||||
> **Zweck:** Anleitung zum Aufsetzen der Entwicklungsumgebung, Verständnis der Modulstruktur und Durchführung von Tests.
|
> **Zweck:** Anleitung zum Aufsetzen der Entwicklungsumgebung, Verständnis der Modulstruktur und Durchführung von Tests.
|
||||||
|
|
||||||
---
|
---
|
||||||
- [Mindnet v2.2 – Developer Guide](#mindnet-v22--developer-guide)
|
- [Mindnet v2.4 – Developer Guide](#mindnet-v24--developer-guide)
|
||||||
- [1. Projektstruktur (Post-WP06)](#1-projektstruktur-post-wp06)
|
- [1. Projektstruktur (Post-WP15)](#1-projektstruktur-post-wp15)
|
||||||
- [2. Lokales Setup (Development)](#2-lokales-setup-development)
|
- [2. Lokales Setup (Development)](#2-lokales-setup-development)
|
||||||
- [2.1 Voraussetzungen](#21-voraussetzungen)
|
- [2.1 Voraussetzungen](#21-voraussetzungen)
|
||||||
- [2.2 Installation](#22-installation)
|
- [2.2 Installation](#22-installation)
|
||||||
- [2.3 Konfiguration (Environment)](#23-konfiguration-environment)
|
- [2.3 Konfiguration (Environment)](#23-konfiguration-environment)
|
||||||
- [2.4 Dienste starten (Systemd bevorzugt)](#24-dienste-starten-systemd-bevorzugt)
|
- [2.4 Dienste starten (API \& UI)](#24-dienste-starten-api--ui)
|
||||||
- [3. Core-Module \& Entwicklung](#3-core-module--entwicklung)
|
- [3. Core-Module \& Entwicklung](#3-core-module--entwicklung)
|
||||||
- [3.1 Der Importer (`scripts.import_markdown`)](#31-der-importer-scriptsimport_markdown)
|
- [3.1 Der Importer (`scripts.import_markdown`)](#31-der-importer-scriptsimport_markdown)
|
||||||
- [3.2 Der Hybrid Router (`app.routers.chat`)](#32-der-hybrid-router-approuterschat)
|
- [3.2 Der Hybrid Router (`app.routers.chat`)](#32-der-hybrid-router-approuterschat)
|
||||||
- [3.3 Der Retriever (`app.core.retriever`)](#33-der-retriever-appcoreretriever)
|
- [3.3 Der Retriever (`app.core.retriever`)](#33-der-retriever-appcoreretriever)
|
||||||
|
- [3.4 Das Frontend (`app.frontend.ui`)](#34-das-frontend-appfrontendui)
|
||||||
|
- [3.5 Embedding Service (`app.services.embeddings_client`)](#35-embedding-service-appservicesembeddings_client)
|
||||||
|
- [3.6 Traffic Control (`app.services.llm_service`)](#36-traffic-control-appservicesllm_service)
|
||||||
- [4. Tests \& Debugging](#4-tests--debugging)
|
- [4. Tests \& Debugging](#4-tests--debugging)
|
||||||
- [4.1 Unit Tests (Pytest)](#41-unit-tests-pytest)
|
- [4.1 Unit Tests (Pytest)](#41-unit-tests-pytest)
|
||||||
- [4.2 Integration / Pipeline Tests](#42-integration--pipeline-tests)
|
- [4.2 Integration / Pipeline Tests](#42-integration--pipeline-tests)
|
||||||
@@ -26,19 +29,21 @@
|
|||||||
- [5. Das "Teach-the-AI" Paradigma (Context Intelligence)](#5-das-teach-the-ai-paradigma-context-intelligence)
|
- [5. Das "Teach-the-AI" Paradigma (Context Intelligence)](#5-das-teach-the-ai-paradigma-context-intelligence)
|
||||||
- [A. Workflow: Einen neuen Typ implementieren (z. B. `type: risk`)](#a-workflow-einen-neuen-typ-implementieren-z-b-type-risk)
|
- [A. Workflow: Einen neuen Typ implementieren (z. B. `type: risk`)](#a-workflow-einen-neuen-typ-implementieren-z-b-type-risk)
|
||||||
- [B. Workflow: Neue Beziehungen (Edges) nutzen (z. B. `beeinflusst_von`)](#b-workflow-neue-beziehungen-edges-nutzen-z-b-beeinflusst_von)
|
- [B. Workflow: Neue Beziehungen (Edges) nutzen (z. B. `beeinflusst_von`)](#b-workflow-neue-beziehungen-edges-nutzen-z-b-beeinflusst_von)
|
||||||
|
- [C. Workflow: Interview-Schema anpassen (WP07)](#c-workflow-interview-schema-anpassen-wp07)
|
||||||
- [Fazit](#fazit)
|
- [Fazit](#fazit)
|
||||||
- [6. Nützliche Einzeiler](#6-nützliche-einzeiler)
|
- [6. Nützliche Einzeiler](#6-nützliche-einzeiler)
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 1. Projektstruktur (Post-WP06)
|
## 1. Projektstruktur (Post-WP15)
|
||||||
|
|
||||||
Der Code ist modular in `app` (Logik), `scripts` (CLI) und `config` (Steuerung) getrennt.
|
Der Code ist modular in `app` (Logik), `scripts` (CLI) und `config` (Steuerung) getrennt.
|
||||||
|
|
||||||
mindnet/
|
mindnet/
|
||||||
├── app/
|
├── app/
|
||||||
│ ├── core/ # Kernlogik
|
│ ├── core/ # Kernlogik
|
||||||
│ │ ├── chunker.py # Text-Zerlegung
|
│ │ ├── ingestion.py # NEU: Async Ingestion Service mit Change Detection
|
||||||
|
│ │ ├── chunker.py # Smart Chunker Orchestrator
|
||||||
│ │ ├── derive_edges.py # Edge-Erzeugung (WP03 Logik)
|
│ │ ├── derive_edges.py # Edge-Erzeugung (WP03 Logik)
|
||||||
│ │ ├── retriever.py # Scoring & Hybrid Search
|
│ │ ├── retriever.py # Scoring & Hybrid Search
|
||||||
│ │ ├── qdrant.py # DB-Verbindung
|
│ │ ├── qdrant.py # DB-Verbindung
|
||||||
@@ -47,18 +52,23 @@ Der Code ist modular in `app` (Logik), `scripts` (CLI) und `config` (Steuerung)
|
|||||||
│ │ └── dto.py # Zentrale DTO-Definition
|
│ │ └── dto.py # Zentrale DTO-Definition
|
||||||
│ ├── routers/ # FastAPI Endpoints
|
│ ├── routers/ # FastAPI Endpoints
|
||||||
│ │ ├── query.py # Suche
|
│ │ ├── query.py # Suche
|
||||||
│ │ ├── chat.py # Hybrid Router & Decision Engine (WP06)
|
│ │ ├── ingest.py # NEU: Save/Analyze (WP11)
|
||||||
|
│ │ ├── chat.py # Hybrid Router v5 & Interview Logic
|
||||||
│ │ ├── feedback.py # Feedback (WP04c)
|
│ │ ├── feedback.py # Feedback (WP04c)
|
||||||
│ │ └── ...
|
│ │ └── ...
|
||||||
│ ├── services/ # Interne & Externe Dienste
|
│ ├── services/ # Interne & Externe Dienste
|
||||||
│ │ ├── llm_service.py # Ollama Client (Mit Timeout & Raw-Mode)
|
│ │ ├── llm_service.py # Ollama Client mit Traffic Control
|
||||||
|
│ │ ├── semantic_analyzer.py# NEU: LLM-Filter für Edges (WP15)
|
||||||
|
│ │ ├── embeddings_client.py# Async Embeddings (HTTPX)
|
||||||
│ │ ├── feedback_service.py # Logging (JSONL Writer)
|
│ │ ├── feedback_service.py # Logging (JSONL Writer)
|
||||||
│ │ └── embeddings_client.py
|
│ │ └── discovery.py # NEU: Intelligence Logic (WP11)
|
||||||
|
│ ├── frontend/ # NEU (WP10)
|
||||||
|
│ │ └── ui.py # Streamlit Application inkl. Healing Parser
|
||||||
│ └── main.py # Entrypoint der API
|
│ └── main.py # Entrypoint der API
|
||||||
├── config/ # YAML-Konfigurationen (Single Source of Truth)
|
├── config/ # YAML-Konfigurationen (Single Source of Truth)
|
||||||
│ ├── types.yaml # Import-Regeln
|
│ ├── types.yaml # Import-Regeln & Smart-Edge Config
|
||||||
│ ├── prompts.yaml # LLM Prompts & RAG Templates (WP06)
|
│ ├── prompts.yaml # LLM Prompts & Interview Templates
|
||||||
│ ├── decision_engine.yaml # Router-Strategien (WP06)
|
│ ├── decision_engine.yaml # Router-Strategien (Actions only)
|
||||||
│ └── retriever.yaml # Scoring-Regeln & Kantengewichte
|
│ └── retriever.yaml # Scoring-Regeln & Kantengewichte
|
||||||
├── data/
|
├── data/
|
||||||
│ └── logs/ # Lokale Logs (search_history.jsonl, feedback.jsonl)
|
│ └── logs/ # Lokale Logs (search_history.jsonl, feedback.jsonl)
|
||||||
@@ -73,7 +83,7 @@ Der Code ist modular in `app` (Logik), `scripts` (CLI) und `config` (Steuerung)
|
|||||||
### 2.1 Voraussetzungen
|
### 2.1 Voraussetzungen
|
||||||
* **Python:** 3.10 oder höher.
|
* **Python:** 3.10 oder höher.
|
||||||
* **Docker:** Für Qdrant.
|
* **Docker:** Für Qdrant.
|
||||||
* **Ollama:** Für lokale LLM-Inference (erforderlich für `/chat`).
|
* **Ollama:** Für lokale LLM-Inference (erforderlich für `/chat` und Embeddings).
|
||||||
* **Vault:** Ein Ordner mit Markdown-Dateien (z.B. `./mindnet_v2_test_vault` für Tests).
|
* **Vault:** Ein Ordner mit Markdown-Dateien (z.B. `./mindnet_v2_test_vault` für Tests).
|
||||||
|
|
||||||
### 2.2 Installation
|
### 2.2 Installation
|
||||||
@@ -86,15 +96,17 @@ Der Code ist modular in `app` (Logik), `scripts` (CLI) und `config` (Steuerung)
|
|||||||
python3 -m venv .venv
|
python3 -m venv .venv
|
||||||
source .venv/bin/activate
|
source .venv/bin/activate
|
||||||
|
|
||||||
# 3. Abhängigkeiten installieren
|
# 3. Abhängigkeiten installieren (inkl. Streamlit)
|
||||||
pip install -r requirements.txt
|
pip install -r requirements.txt
|
||||||
|
|
||||||
# 4. Ollama Setup (Modell laden)
|
# 4. Ollama Setup (Modelle laden)
|
||||||
# Wir nutzen Phi-3 Mini für schnelle CPU-Inference
|
# Chat-Modell (Phi-3)
|
||||||
ollama pull phi3:mini
|
ollama pull phi3:mini
|
||||||
|
# Embedding-Modell (Nomic) - PFLICHT für v2.4!
|
||||||
|
ollama pull nomic-embed-text
|
||||||
|
|
||||||
### 2.3 Konfiguration (Environment)
|
### 2.3 Konfiguration (Environment)
|
||||||
Erstelle eine `.env` Datei im Root-Verzeichnis. Die Timeout-Settings sind kritisch für CPU-Inference.
|
Erstelle eine `.env` Datei im Root-Verzeichnis.
|
||||||
|
|
||||||
# Qdrant Verbindung
|
# Qdrant Verbindung
|
||||||
QDRANT_URL="http://localhost:6333"
|
QDRANT_URL="http://localhost:6333"
|
||||||
@@ -102,59 +114,82 @@ Erstelle eine `.env` Datei im Root-Verzeichnis. Die Timeout-Settings sind kritis
|
|||||||
|
|
||||||
# Mindnet Core Settings
|
# Mindnet Core Settings
|
||||||
COLLECTION_PREFIX="mindnet_dev"
|
COLLECTION_PREFIX="mindnet_dev"
|
||||||
|
VECTOR_DIM=768 # NEU: 768 für Nomic (vorher 384)
|
||||||
MINDNET_TYPES_FILE="./config/types.yaml"
|
MINDNET_TYPES_FILE="./config/types.yaml"
|
||||||
MINDNET_RETRIEVER_CONFIG="./config/retriever.yaml"
|
MINDNET_RETRIEVER_CONFIG="./config/retriever.yaml"
|
||||||
|
MINDNET_VAULT_ROOT="./vault"
|
||||||
|
|
||||||
# LLM / RAG Settings (WP06)
|
# LLM / RAG Settings (WP06/07)
|
||||||
MINDNET_LLM_MODEL="phi3:mini"
|
MINDNET_LLM_MODEL="phi3:mini"
|
||||||
|
MINDNET_EMBEDDING_MODEL="nomic-embed-text" # NEU
|
||||||
MINDNET_OLLAMA_URL="http://127.0.0.1:11434"
|
MINDNET_OLLAMA_URL="http://127.0.0.1:11434"
|
||||||
MINDNET_LLM_TIMEOUT=300.0
|
MINDNET_LLM_TIMEOUT=300.0 # Timeout für CPU-Inference Cold-Starts
|
||||||
MINDNET_PROMPTS_PATH="./config/prompts.yaml"
|
|
||||||
MINDNET_DECISION_CONFIG="./config/decision_engine.yaml"
|
MINDNET_DECISION_CONFIG="./config/decision_engine.yaml"
|
||||||
|
MINDNET_LLM_BACKGROUND_LIMIT=2 # NEU: Limit für parallele Import-Tasks
|
||||||
|
|
||||||
|
# Frontend Settings (WP10)
|
||||||
|
MINDNET_API_URL="http://localhost:8002"
|
||||||
|
MINDNET_API_TIMEOUT=300.0 # Erhöht wegen Smart Edge Berechnung
|
||||||
|
|
||||||
# Import-Strategie
|
# Import-Strategie
|
||||||
MINDNET_HASH_COMPARE="Body"
|
MINDNET_HASH_COMPARE="Body"
|
||||||
MINDNET_HASH_SOURCE="parsed"
|
MINDNET_HASH_SOURCE="parsed"
|
||||||
|
|
||||||
### 2.4 Dienste starten (Systemd bevorzugt)
|
### 2.4 Dienste starten (API & UI)
|
||||||
Auf dem Entwicklungsserver (Beelink) nutzen wir Systemd.
|
|
||||||
|
|
||||||
# Starten / Neustarten
|
Wir entwickeln mit zwei Services. Du kannst sie manuell in zwei Terminals starten oder die Systemd-Services nutzen (siehe `admin_guide.md`).
|
||||||
sudo systemctl restart mindnet-dev
|
|
||||||
|
|
||||||
# Logs prüfen (Wichtig für LLM Debugging)
|
|
||||||
journalctl -u mindnet-dev -f
|
|
||||||
|
|
||||||
Falls du lokal auf Windows entwickelst:
|
**Terminal A: Backend (API)**
|
||||||
|
|
||||||
# 1. Qdrant starten
|
# Startet auf Port 8002 (Dev Standard)
|
||||||
docker run -p 6333:6333 qdrant/qdrant
|
|
||||||
# 2. Ollama starten
|
|
||||||
ollama serve
|
|
||||||
# 3. API starten
|
|
||||||
uvicorn app.main:app --host 0.0.0.0 --port 8002 --env-file .env --reload
|
uvicorn app.main:app --host 0.0.0.0 --port 8002 --env-file .env --reload
|
||||||
|
|
||||||
|
**Terminal B: Frontend (UI)**
|
||||||
|
|
||||||
|
# Startet auf Port 8502 (Dev Standard)
|
||||||
|
# --server.port 8502 verhindert Konflikte mit Prod (8501)
|
||||||
|
streamlit run app/frontend/ui.py --server.port 8502
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 3. Core-Module & Entwicklung
|
## 3. Core-Module & Entwicklung
|
||||||
|
|
||||||
### 3.1 Der Importer (`scripts.import_markdown`)
|
### 3.1 Der Importer (`scripts.import_markdown`)
|
||||||
Dies ist das komplexeste Modul.
|
Dies ist das komplexeste Modul.
|
||||||
* **Einstieg:** `scripts/import_markdown.py` -> `main()`.
|
* **Einstieg:** `scripts/import_markdown.py` -> `main_async()`.
|
||||||
|
* **Smart Edges:** Nutzt `app.core.chunker` und `app.services.semantic_analyzer` zur Kanten-Filterung.
|
||||||
* **Idempotenz:** Der Importer muss mehrfach laufen können, ohne Duplikate zu erzeugen. Wir nutzen deterministische IDs (UUIDv5).
|
* **Idempotenz:** Der Importer muss mehrfach laufen können, ohne Duplikate zu erzeugen. Wir nutzen deterministische IDs (UUIDv5).
|
||||||
* **Debugging:** Nutze `--dry-run` oder `scripts/payload_dryrun.py`.
|
* **Robustheit:** In `ingestion.py` sind Mechanismen wie Change Detection und Robust File I/O (fsync) implementiert.
|
||||||
|
|
||||||
### 3.2 Der Hybrid Router (`app.routers.chat`)
|
### 3.2 Der Hybrid Router (`app.routers.chat`)
|
||||||
Hier liegt die Logik für Intent Detection (WP06).
|
Hier liegt die Logik für Intent Detection (WP06) und Interview-Modus (WP07).
|
||||||
* **Logic:** `_classify_intent` prüft zuerst Keywords (Fast Path) und fällt auf `llm_service.generate_raw_response` zurück (Slow Path), wenn konfiguriert.
|
* **Question Detection:** Prüft zuerst, ob der Input eine Frage ist. Falls ja -> RAG.
|
||||||
* **Config:** Gesteuert durch `decision_engine.yaml`.
|
* **Keyword Match:** Prüft Keywords in `decision_engine.yaml` und `types.yaml`.
|
||||||
* **Erweiterung:** Um neue Intents hinzuzufügen, editiere nur die YAML, nicht den Python-Code (Late Binding).
|
* **Priority:** Ruft `llm_service` mit `priority="realtime"` auf.
|
||||||
|
|
||||||
### 3.3 Der Retriever (`app.core.retriever`)
|
### 3.3 Der Retriever (`app.core.retriever`)
|
||||||
Hier passiert das Scoring.
|
Hier passiert das Scoring.
|
||||||
* **Hybrid Search:** Der Chat-Endpoint erzwingt `mode="hybrid"`.
|
* **Hybrid Search:** Der Chat-Endpoint erzwingt `mode="hybrid"`.
|
||||||
* **Strategic Retrieval:** In `chat.py` wird der Retriever *zweimal* aufgerufen, wenn ein Intent (z.B. `DECISION`) eine Injection (`value`) erfordert.
|
* **Strategic Retrieval:** In `chat.py` wird der Retriever *zweimal* aufgerufen, wenn ein Intent (z.B. `DECISION`) eine Injection (`value`) erfordert.
|
||||||
|
|
||||||
|
### 3.4 Das Frontend (`app.frontend.ui`)
|
||||||
|
Eine Streamlit-App (WP10).
|
||||||
|
* **Resurrection Pattern:** Das UI nutzt ein spezielles State-Management, um Eingaben bei Tab-Wechseln (Chat <-> Editor) zu erhalten. Widgets synchronisieren sich mit `st.session_state`.
|
||||||
|
* **Healing Parser:** Die Funktion `parse_markdown_draft` repariert defekte YAML-Frontmatter (fehlendes `---`) automatisch.
|
||||||
|
* **Logik:** Ruft `/chat`, `/feedback` und `/ingest/analyze` Endpoints der API auf.
|
||||||
|
|
||||||
|
### 3.5 Embedding Service (`app.services.embeddings_client`)
|
||||||
|
**Neu in v2.4:**
|
||||||
|
* Nutzt `httpx.AsyncClient` für non-blocking Calls an Ollama (Primary Mode).
|
||||||
|
* Besitzt einen **Fallback** auf `requests` (Synchron), falls Legacy-Skripte ihn nutzen.
|
||||||
|
* Unterstützt dediziertes Embedding-Modell (`nomic-embed-text`) getrennt vom Chat-Modell.
|
||||||
|
|
||||||
|
### 3.6 Traffic Control (`app.services.llm_service`)
|
||||||
|
**Neu in v2.6 (Version 2.8.0):**
|
||||||
|
* Stellt sicher, dass Batch-Prozesse (Import) den Live-Chat nicht ausbremsen.
|
||||||
|
* **Methode:** `generate_raw_response(..., priority="background")` aktiviert eine Semaphore.
|
||||||
|
* **Limit:** Konfigurierbar über `MINDNET_LLM_BACKGROUND_LIMIT` (Default: 2) in der `.env`.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 4. Tests & Debugging
|
## 4. Tests & Debugging
|
||||||
@@ -179,27 +214,26 @@ Prüfen den Datenfluss von Markdown bis Qdrant-JSON.
|
|||||||
python3 -m scripts.edges_full_check
|
python3 -m scripts.edges_full_check
|
||||||
|
|
||||||
### 4.3 Smoke Tests (E2E)
|
### 4.3 Smoke Tests (E2E)
|
||||||
Prüfen das laufende System (API) gegen eine echte Qdrant-Instanz und Ollama.
|
Prüfen das laufende System gegen eine echte Qdrant-Instanz und Ollama.
|
||||||
|
|
||||||
# 1. Retriever Test (Hybrid + Explanation)
|
# 1. API Test (Decision Engine)
|
||||||
python scripts/test_retriever_smoke.py --query "Test" --mode hybrid --top-k 5 --explain
|
|
||||||
|
|
||||||
# 2. Decision Engine Test (WP06)
|
|
||||||
# Prüft Intent, Retrieval und Reasoning (mit Timeout-Handling)
|
|
||||||
python tests/test_wp06_decision.py -p 8002 -e DECISION -q "Soll ich X tun?"
|
python tests/test_wp06_decision.py -p 8002 -e DECISION -q "Soll ich X tun?"
|
||||||
|
|
||||||
# 3. Empathy Test (WP06)
|
# 2. UI Test (Manuell)
|
||||||
# Prüft LLM-Router Fallback
|
# Öffne http://localhost:8502
|
||||||
python tests/test_wp06_decision.py -p 8002 -e EMPATHY -q "Alles ist grau"
|
# Stelle eine Frage und prüfe Intent-Badge und Quellen-Anzeige.
|
||||||
|
|
||||||
# 4. Feedback Test (WP04c)
|
# 3. Feedback Test
|
||||||
python tests/test_feedback_smoke.py --url http://localhost:8002/query
|
python tests/test_feedback_smoke.py --url http://localhost:8002/query
|
||||||
|
|
||||||
|
# 4. Intelligence Test (WP11)
|
||||||
|
python debug_analysis.py
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 5. Das "Teach-the-AI" Paradigma (Context Intelligence)
|
## 5. Das "Teach-the-AI" Paradigma (Context Intelligence)
|
||||||
|
|
||||||
Mindnet lernt nicht durch Training (Fine-Tuning), sondern durch **Konfiguration**, **Vernetzung** und **Prompting**. Wenn du dem System ein neues Konzept beibringen willst, musst du in der Regel an drei Stellen eingreifen. Dies ist der **Core-Workflow** für Erweiterungen.
|
Mindnet lernt nicht durch Training (Fine-Tuning), sondern durch **Konfiguration**, **Vernetzung** und **Prompting**. Dies ist der **Core-Workflow** für Erweiterungen.
|
||||||
|
|
||||||
### A. Workflow: Einen neuen Typ implementieren (z. B. `type: risk`)
|
### A. Workflow: Einen neuen Typ implementieren (z. B. `type: risk`)
|
||||||
|
|
||||||
@@ -207,9 +241,10 @@ Mindnet lernt nicht durch Training (Fine-Tuning), sondern durch **Konfiguration*
|
|||||||
Definiere die "Physik" des Typs (Import-Regeln und Basis-Wichtigkeit).
|
Definiere die "Physik" des Typs (Import-Regeln und Basis-Wichtigkeit).
|
||||||
|
|
||||||
risk:
|
risk:
|
||||||
chunk_profile: short # Risiken sind oft kurze Statements
|
chunk_profile: sliding_short # Risiken sind oft kurze Statements
|
||||||
retriever_weight: 0.90 # Sehr wichtig, fast so hoch wie Decisions
|
retriever_weight: 0.90 # Sehr wichtig
|
||||||
edge_defaults: ["blocks"] # Automatische Kante zu verlinkten Projekten
|
edge_defaults: ["blocks"] # Automatische Kante zu verlinkten Projekten
|
||||||
|
detection_keywords: ["gefahr", "risiko"]
|
||||||
|
|
||||||
**2. Strategie-Ebene (`config/decision_engine.yaml`)**
|
**2. Strategie-Ebene (`config/decision_engine.yaml`)**
|
||||||
Damit dieser Typ aktiv geladen wird, musst du ihn einer Strategie zuordnen.
|
Damit dieser Typ aktiv geladen wird, musst du ihn einer Strategie zuordnen.
|
||||||
@@ -222,26 +257,32 @@ Damit dieser Typ aktiv geladen wird, musst du ihn einer Strategie zuordnen.
|
|||||||
**3. Kognitive Ebene (`config/prompts.yaml`)**
|
**3. Kognitive Ebene (`config/prompts.yaml`)**
|
||||||
Erkläre dem LLM im Template, was es damit tun soll.
|
Erkläre dem LLM im Template, was es damit tun soll.
|
||||||
|
|
||||||
decision_template: |
|
|
||||||
...
|
|
||||||
- Prüfe auf [RISK]: Wenn vorhanden, warne mich davor!
|
|
||||||
|
|
||||||
### B. Workflow: Neue Beziehungen (Edges) nutzen (z. B. `beeinflusst_von`)
|
### B. Workflow: Neue Beziehungen (Edges) nutzen (z. B. `beeinflusst_von`)
|
||||||
|
|
||||||
Beziehungen sind der Klebstoff für die "Why"-Erklärungen.
|
Beziehungen sind der Klebstoff für die "Why"-Erklärungen.
|
||||||
|
|
||||||
**1. Erfassung im Vault (Markdown)**
|
**1. Erfassung im Vault (Markdown)**
|
||||||
Du musst dem System keinen neuen Edge-Typ "beibringen" (Schema-less). Du nutzt ihn einfach.
|
|
||||||
Nutze die Inline-Syntax im Fließtext:
|
Nutze die Inline-Syntax im Fließtext:
|
||||||
|
> "Die Entscheidung für Qdrant wurde [[rel:beeinflusst_von Budgetkürzung 2024]]."
|
||||||
Die Entscheidung für Qdrant wurde [[rel:beeinflusst_von Budgetkürzung 2024]].
|
|
||||||
|
|
||||||
**2. Gewichtung (`config/retriever.yaml`)**
|
**2. Gewichtung (`config/retriever.yaml`)**
|
||||||
Standardmäßig werden alle expliziten Kanten gleich behandelt. Wenn Kausalität wichtiger ist als Ähnlichkeit, konfiguriere dies hier.
|
Konfiguriere `edge_weights`, wenn Kausalität wichtiger ist als Ähnlichkeit.
|
||||||
|
|
||||||
scoring:
|
### C. Workflow: Interview-Schema anpassen (WP07)
|
||||||
edge_type_weights:
|
|
||||||
beeinflusst_von: 1.5 # Sehr starker Einfluss auf das Ranking
|
Wenn Mindnet neue Fragen stellen soll:
|
||||||
|
|
||||||
|
**1. Schema erweitern (`config/types.yaml`)**
|
||||||
|
Füge das Feld in die Liste ein (Neu: Schemas liegen jetzt hier).
|
||||||
|
|
||||||
|
project:
|
||||||
|
schema:
|
||||||
|
- "Titel"
|
||||||
|
- "Ziel"
|
||||||
|
- "Budget (Neu)"
|
||||||
|
|
||||||
|
**2. Keine Code-Änderung nötig**
|
||||||
|
Der `One-Shot Extractor` (Prompt Template) liest diese Liste dynamisch.
|
||||||
|
|
||||||
### Fazit
|
### Fazit
|
||||||
* **Vault:** Liefert das Wissen.
|
* **Vault:** Liefert das Wissen.
|
||||||
@@ -254,12 +295,16 @@ Standardmäßig werden alle expliziten Kanten gleich behandelt. Wenn Kausalität
|
|||||||
|
|
||||||
**DB komplett zurücksetzen (Vorsicht!):**
|
**DB komplett zurücksetzen (Vorsicht!):**
|
||||||
|
|
||||||
|
# --yes überspringt die Bestätigung
|
||||||
python3 -m scripts.reset_qdrant --mode wipe --prefix "mindnet_dev" --yes
|
python3 -m scripts.reset_qdrant --mode wipe --prefix "mindnet_dev" --yes
|
||||||
|
|
||||||
**Einen einzelnen File inspizieren (Parser-Sicht):**
|
**Einen einzelnen File inspizieren (Parser-Sicht):**
|
||||||
|
|
||||||
python3 tests/inspect_one_note.py --file ./vault/MeinFile.md
|
python3 tests/inspect_one_note.py --file ./vault/MeinFile.md
|
||||||
|
|
||||||
**Live-Logs sehen (Beelink) - inkl. LLM Thoughts:**
|
**Live-Logs sehen (Systemd):**
|
||||||
|
|
||||||
journalctl -u mindnet-dev -f
|
# Backend
|
||||||
|
journalctl -u mindnet-dev -f
|
||||||
|
# Frontend
|
||||||
|
journalctl -u mindnet-ui-dev -f
|
||||||
@@ -1,15 +1,15 @@
|
|||||||
# Mindnet v2.2 – Fachliche Architektur
|
# Mindnet v2.4 – Fachliche Architektur
|
||||||
**Datei:** `docs/mindnet_functional_architecture_v2.2.md`
|
**Datei:** `docs/mindnet_functional_architecture_v2.6.md`
|
||||||
**Stand:** 2025-12-09
|
**Stand:** 2025-12-12
|
||||||
**Status:** **FINAL** (Integrierter Stand WP01–WP06)
|
**Status:** **FINAL** (Integrierter Stand WP01–WP15: Smart Edges & Traffic Control)
|
||||||
|
|
||||||
> Dieses Dokument beschreibt **was** Mindnet fachlich tut und **warum** – mit Fokus auf die Erzeugung und Nutzung von **Edges** (Kanten), die Logik des Retrievers und den neuen **RAG-Chat** (Decision Engine & Persönlichkeit). Die technische Umsetzung wird im technischen Dokument detailliert.
|
> Dieses Dokument beschreibt **was** Mindnet fachlich tut und **warum** – mit Fokus auf die Erzeugung und Nutzung von **Smart Edges** (Kanten), die Logik des Retrievers und den **RAG-Chat** (Decision Engine, Interview-Modus & Persönlichkeit).
|
||||||
|
|
||||||
---
|
---
|
||||||
<details>
|
<details>
|
||||||
<summary>📖 <b>Inhaltsverzeichnis (Klicken zum Öffnen)</b></summary>
|
<summary>📖 <b>Inhaltsverzeichnis (Klicken zum Öffnen)</b></summary>
|
||||||
|
|
||||||
- [Mindnet v2.2 – Fachliche Architektur](#mindnet-v22--fachliche-architektur)
|
- [Mindnet v2.4 – Fachliche Architektur](#mindnet-v24--fachliche-architektur)
|
||||||
- [](#)
|
- [](#)
|
||||||
- [0) Zielbild \& Grundprinzip](#0-zielbild--grundprinzip)
|
- [0) Zielbild \& Grundprinzip](#0-zielbild--grundprinzip)
|
||||||
- [1) Notizen \& Chunks (fachliche Perspektive)](#1-notizen--chunks-fachliche-perspektive)
|
- [1) Notizen \& Chunks (fachliche Perspektive)](#1-notizen--chunks-fachliche-perspektive)
|
||||||
@@ -19,6 +19,8 @@
|
|||||||
- [2.1 Struktur-Kanten (Das Skelett)](#21-struktur-kanten-das-skelett)
|
- [2.1 Struktur-Kanten (Das Skelett)](#21-struktur-kanten-das-skelett)
|
||||||
- [2.2 Inhalts-Kanten (explizit)](#22-inhalts-kanten-explizit)
|
- [2.2 Inhalts-Kanten (explizit)](#22-inhalts-kanten-explizit)
|
||||||
- [2.3 Typ-basierte Default-Kanten (Regelbasiert)](#23-typ-basierte-default-kanten-regelbasiert)
|
- [2.3 Typ-basierte Default-Kanten (Regelbasiert)](#23-typ-basierte-default-kanten-regelbasiert)
|
||||||
|
- [2.4 Smart Edge Allocation (LLM-gefiltert) – Neu in v2.6](#24-smart-edge-allocation-llm-gefiltert--neu-in-v26)
|
||||||
|
- [2.5 Matrix-Logik (Kontextsensitive Kanten)](#25-matrix-logik-kontextsensitive-kanten)
|
||||||
- [3) Edge-Payload – Felder \& Semantik](#3-edge-payload--felder--semantik)
|
- [3) Edge-Payload – Felder \& Semantik](#3-edge-payload--felder--semantik)
|
||||||
- [4) Typ-Registry (`config/types.yaml`)](#4-typ-registry-configtypesyaml)
|
- [4) Typ-Registry (`config/types.yaml`)](#4-typ-registry-configtypesyaml)
|
||||||
- [4.1 Zweck](#41-zweck)
|
- [4.1 Zweck](#41-zweck)
|
||||||
@@ -26,11 +28,15 @@
|
|||||||
- [5) Der Retriever (Funktionaler Layer)](#5-der-retriever-funktionaler-layer)
|
- [5) Der Retriever (Funktionaler Layer)](#5-der-retriever-funktionaler-layer)
|
||||||
- [5.1 Scoring-Modell](#51-scoring-modell)
|
- [5.1 Scoring-Modell](#51-scoring-modell)
|
||||||
- [5.2 Erklärbarkeit (Explainability) – WP04b](#52-erklärbarkeit-explainability--wp04b)
|
- [5.2 Erklärbarkeit (Explainability) – WP04b](#52-erklärbarkeit-explainability--wp04b)
|
||||||
- [6) Context Intelligence \& Intent Router (WP06)](#6-context-intelligence--intent-router-wp06)
|
- [5.3 Graph-Expansion](#53-graph-expansion)
|
||||||
|
- [6) Context Intelligence \& Intent Router (WP06–WP15)](#6-context-intelligence--intent-router-wp06wp15)
|
||||||
- [6.1 Das Problem: Statische vs. Dynamische Antworten](#61-das-problem-statische-vs-dynamische-antworten)
|
- [6.1 Das Problem: Statische vs. Dynamische Antworten](#61-das-problem-statische-vs-dynamische-antworten)
|
||||||
- [6.2 Der Intent-Router (Keyword \& Semantik)](#62-der-intent-router-keyword--semantik)
|
- [6.2 Der Hybrid Router v5 (Action vs. Question)](#62-der-hybrid-router-v5-action-vs-question)
|
||||||
- [6.3 Strategic Retrieval (Injektion von Werten)](#63-strategic-retrieval-injektion-von-werten)
|
- [6.3 Traffic Control (Realtime vs. Background)](#63-traffic-control-realtime-vs-background)
|
||||||
- [6.4 Reasoning (Das Gewissen)](#64-reasoning-das-gewissen)
|
- [6.4 Strategic Retrieval (Injektion von Werten)](#64-strategic-retrieval-injektion-von-werten)
|
||||||
|
- [6.5 Reasoning (Das Gewissen)](#65-reasoning-das-gewissen)
|
||||||
|
- [6.6 Der Interview-Modus (One-Shot Extraction)](#66-der-interview-modus-one-shot-extraction)
|
||||||
|
- [6.7 Active Intelligence (Link Suggestions)](#67-active-intelligence-link-suggestions)
|
||||||
- [7) Future Concepts: The Empathic Digital Twin (Ausblick)](#7-future-concepts-the-empathic-digital-twin-ausblick)
|
- [7) Future Concepts: The Empathic Digital Twin (Ausblick)](#7-future-concepts-the-empathic-digital-twin-ausblick)
|
||||||
- [7.1 Antizipation durch Erfahrung](#71-antizipation-durch-erfahrung)
|
- [7.1 Antizipation durch Erfahrung](#71-antizipation-durch-erfahrung)
|
||||||
- [7.2 Empathie \& "Ich"-Modus](#72-empathie--ich-modus)
|
- [7.2 Empathie \& "Ich"-Modus](#72-empathie--ich-modus)
|
||||||
@@ -38,15 +44,15 @@
|
|||||||
- [8) Erweiterbarkeit \& Teaching (Context Intelligence)](#8-erweiterbarkeit--teaching-context-intelligence)
|
- [8) Erweiterbarkeit \& Teaching (Context Intelligence)](#8-erweiterbarkeit--teaching-context-intelligence)
|
||||||
- [A. Workflow: Einen neuen Typ implementieren (z. B. `type: risk`)](#a-workflow-einen-neuen-typ-implementieren-z-b-type-risk)
|
- [A. Workflow: Einen neuen Typ implementieren (z. B. `type: risk`)](#a-workflow-einen-neuen-typ-implementieren-z-b-type-risk)
|
||||||
- [B. Workflow: Neue Beziehungen nutzen (z. B. `beeinflusst_von`)](#b-workflow-neue-beziehungen-nutzen-z-b-beeinflusst_von)
|
- [B. Workflow: Neue Beziehungen nutzen (z. B. `beeinflusst_von`)](#b-workflow-neue-beziehungen-nutzen-z-b-beeinflusst_von)
|
||||||
- [9) Feedback \& Lernen – WP04c](#9-feedback--lernen--wp04c)
|
- [9) Feedback \& Lernen – WP04c/WP10](#9-feedback--lernen--wp04cwp10)
|
||||||
- [9.1 Der Feedback-Loop](#91-der-feedback-loop)
|
- [9.1 Der Feedback-Loop](#91-der-feedback-loop)
|
||||||
- [10) Confidence \& Provenance – wozu?](#10-confidence--provenance--wozu)
|
- [10) Confidence \& Provenance – wozu?](#10-confidence--provenance--wozu)
|
||||||
- [11) Semantik ausgewählter `kind`-Werte](#11-semantik-ausgewählter-kind-werte)
|
- [11) Semantik ausgewählter `kind`-Werte](#11-semantik-ausgewählter-kind-werte)
|
||||||
- [12) Frontmatter-Eigenschaften – Rolle \& Empfehlung](#12-frontmatter-eigenschaften--rolle--empfehlung)
|
- [12) Frontmatter-Eigenschaften – Rolle \& Empfehlung](#12-frontmatter-eigenschaften--rolle--empfehlung)
|
||||||
- [13) Lösch-/Update-Garantien (Idempotenz)](#13-lösch-update-garantien-idempotenz)
|
- [13) Lösch-/Update-Garantien (Idempotenz)](#13-lösch-update-garantien-idempotenz)
|
||||||
- [14) Beispiel – Von Markdown zu Kanten (v2.2)](#14-beispiel--von-markdown-zu-kanten-v22)
|
- [14) Beispiel – Von Markdown zu Kanten](#14-beispiel--von-markdown-zu-kanten)
|
||||||
- [15) Referenzen (Projektdateien \& Leitlinien)](#15-referenzen-projektdateien--leitlinien)
|
- [15) Referenzen (Projektdateien \& Leitlinien)](#15-referenzen-projektdateien--leitlinien)
|
||||||
- [16) Workpackage Status (v2.3.1)](#16-workpackage-status-v231)
|
- [16) Workpackage Status (v2.6.0)](#16-workpackage-status-v260)
|
||||||
|
|
||||||
</details>
|
</details>
|
||||||
---
|
---
|
||||||
@@ -60,7 +66,7 @@ Die drei zentralen Artefakt-Sammlungen lauten:
|
|||||||
- `mindnet_chunks` – semantische Teilstücke einer Note (Fenster/„Chunks“)
|
- `mindnet_chunks` – semantische Teilstücke einer Note (Fenster/„Chunks“)
|
||||||
- `mindnet_edges` – gerichtete Beziehungen zwischen Knoten (Chunks/Notes)
|
- `mindnet_edges` – gerichtete Beziehungen zwischen Knoten (Chunks/Notes)
|
||||||
|
|
||||||
Die Import-Pipeline erzeugt diese Artefakte **deterministisch** und **idempotent** (erneute Läufe überschreiben konsistent statt zu duplizieren). Die Import-Schritte sind: *parse → chunk → edge → upsert*.
|
Die Import-Pipeline (seit v2.6 mit **Traffic Control** und **Smart Edges**) erzeugt diese Artefakte **deterministisch** und **idempotent** (erneute Läufe überschreiben konsistent statt zu duplizieren). Die Import-Schritte sind: *parse → chunk → embed → smart-edge-allocation → upsert*.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -76,9 +82,10 @@ Die Import-Pipeline erzeugt diese Artefakte **deterministisch** und **idempotent
|
|||||||
- Ausschnitt/Textfenster aus der Note, als eigenständiger Such-Anker.
|
- Ausschnitt/Textfenster aus der Note, als eigenständiger Such-Anker.
|
||||||
- Jeder Chunk gehört **genau einer** Note.
|
- Jeder Chunk gehört **genau einer** Note.
|
||||||
- Chunks bilden eine Sequenz (1…N) – das ermöglicht *next/prev*.
|
- Chunks bilden eine Sequenz (1…N) – das ermöglicht *next/prev*.
|
||||||
- **Neu in v2.2:** Alle Kanten entstehen ausschließlich zwischen Chunks (Scope="chunk"), nie zwischen Notes direkt. Notes dienen nur noch als Metadatencontainer.
|
- **Update v2.4:** Chunks werden jetzt durch das Modell `nomic-embed-text` in **768-dimensionale Vektoren** umgewandelt. Dies erlaubt eine deutlich höhere semantische Auflösung als frühere Modelle (384 Dim).
|
||||||
|
- **Update v2.6 (Smart Chunking):** Ein Chunk ist nicht mehr nur ein dummer Textblock, der alle Links der Mutter-Notiz erbt. Durch die **Smart Edge Allocation (WP15)** "weiß" jeder Chunk genau, welche Kanten inhaltlich zu ihm gehören (siehe 2.4).
|
||||||
|
|
||||||
> **Wichtig:** Chunking-Profile (short/medium/long) kommen aus `types.yaml` (per Note-Typ), können aber lokal überschrieben werden. Die effektiven Werte werden bei der Payload-Erzeugung bestimmt.
|
> **Wichtig:** Chunking-Profile (short/medium/long/sliding_smart_edges) kommen aus `types.yaml` (per Note-Typ), können aber lokal überschrieben werden. Die effektiven Werte werden bei der Payload-Erzeugung bestimmt.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -93,7 +100,7 @@ Edges kodieren Beziehungen. Sie sind **gerichtet** und werden in `mindnet_edges`
|
|||||||
Diese Kanten entstehen immer, unabhängig von Inhalten.
|
Diese Kanten entstehen immer, unabhängig von Inhalten.
|
||||||
|
|
||||||
### 2.2 Inhalts-Kanten (explizit)
|
### 2.2 Inhalts-Kanten (explizit)
|
||||||
Hier unterscheidet v2.2 präzise zwischen verschiedenen Quellen der Evidenz:
|
Hier unterscheidet v2.6 präzise zwischen verschiedenen Quellen der Evidenz:
|
||||||
|
|
||||||
1. **Explizite Inline-Relationen (Höchste Priorität):**
|
1. **Explizite Inline-Relationen (Höchste Priorität):**
|
||||||
Im Fließtext notierte, semantisch qualifizierte Relationen.
|
Im Fließtext notierte, semantisch qualifizierte Relationen.
|
||||||
@@ -127,20 +134,42 @@ Regel: **Für jede gefundene explizite Referenz** (s. o.) werden **zusätzliche*
|
|||||||
Beispiel: Ein *project* mit `edge_defaults=["depends_on"]` erzeugt zu *jedem* explizit referenzierten Ziel **zusätzlich** eine `depends_on`-Kante.
|
Beispiel: Ein *project* mit `edge_defaults=["depends_on"]` erzeugt zu *jedem* explizit referenzierten Ziel **zusätzlich** eine `depends_on`-Kante.
|
||||||
Diese Kanten tragen *provenance=rule* und eine **rule_id** der Form `edge_defaults:{note_type}:{relation}` sowie eine geringere Confidence (~0.7).
|
Diese Kanten tragen *provenance=rule* und eine **rule_id** der Form `edge_defaults:{note_type}:{relation}` sowie eine geringere Confidence (~0.7).
|
||||||
|
|
||||||
|
### 2.4 Smart Edge Allocation (LLM-gefiltert) – Neu in v2.6
|
||||||
|
Mit **WP15** wurde ein intelligenter Filter eingeführt, um das Problem des "Broadcasting" zu lösen. Früher erbte jeder Chunk einer Notiz *alle* Links der Notiz, was zu unpräzisem Retrieval führte.
|
||||||
|
|
||||||
|
**Der neue Prozess:**
|
||||||
|
1. **Scan:** Das System sammelt alle expliziten Links der gesamten Notiz.
|
||||||
|
2. **Chunking:** Der Text wird in Abschnitte zerlegt.
|
||||||
|
3. **Analyse (LLM):** Ein lokales LLM (Semantic Analyzer) liest jeden Chunk einzeln.
|
||||||
|
4. **Entscheidung:** Das LLM entscheidet für jeden Link aus Schritt 1: *"Ist dieser Link im Kontext dieses spezifischen Textabschnitts relevant?"*
|
||||||
|
5. **Zuweisung:** Nur wenn das LLM zustimmt, wird die Kante am Chunk erstellt.
|
||||||
|
|
||||||
|
*Steuerung:* Dies ist pro Typ in der `types.yaml` konfigurierbar (`enable_smart_edge_allocation: true`).
|
||||||
|
|
||||||
|
### 2.5 Matrix-Logik (Kontextsensitive Kanten)
|
||||||
|
Mit WP-11 wurde eine Intelligenz eingeführt, die Kanten-Typen nicht nur anhand des Quell-Typs, sondern auch anhand des Ziel-Typs bestimmt ("Matrix").
|
||||||
|
|
||||||
|
**Beispiel für `Source Type: experience`:**
|
||||||
|
* Wenn Ziel ist `value` -> Kante: `based_on`
|
||||||
|
* Wenn Ziel ist `principle` -> Kante: `derived_from`
|
||||||
|
* Wenn Ziel ist `project` -> Kante: `related_to`
|
||||||
|
|
||||||
|
Dies ermöglicht im Graphen präzise Abfragen wie "Zeige alle Erfahrungen, die auf Wert X basieren" (via `based_on`), was mit generischen `related_to` Kanten nicht möglich wäre.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 3) Edge-Payload – Felder & Semantik
|
## 3) Edge-Payload – Felder & Semantik
|
||||||
|
|
||||||
Jede Kante hat mindestens:
|
Jede Kante hat mindestens:
|
||||||
|
|
||||||
- `kind` – Beziehungsart *(belongs_to, next, prev, references, related_to, depends_on, similar_to, …)*
|
- `kind` – Beziehungsart *(belongs_to, next, prev, references, related_to, depends_on, similar_to, based_on, uses, …)*
|
||||||
- `scope` – `"chunk"` (Standard in v2.2)
|
- `scope` – `"chunk"` (Standard in v2.2)
|
||||||
- `source_id`, `target_id` – Quell-/Ziel-Knoten (Chunk-IDs oder Note-Titel bei unresolved Targets)
|
- `source_id`, `target_id` – Quell-/Ziel-Knoten (Chunk-IDs oder Note-Titel bei unresolved Targets)
|
||||||
- `note_id` – **Owner-Note** (die Note, aus der die Kante stammt)
|
- `note_id` – **Owner-Note** (die Note, aus der die Kante stammt)
|
||||||
|
|
||||||
Erweiterte/abgeleitete Felder (WP03 Superset):
|
Erweiterte/abgeleitete Felder (WP03 Superset):
|
||||||
|
|
||||||
- `provenance` – `"explicit"` (Wikilink/Inline/Callout) oder `"rule"` (Typ-Defaults)
|
- `provenance` – `"explicit"` (Wikilink/Inline/Callout), `"rule"` (Typ-Defaults) oder neu `"smart"` (vom LLM validiert).
|
||||||
- `rule_id` – maschinenlesbare Regelquelle (z.B. `inline:rel`, `edge_defaults:project:depends_on`)
|
- `rule_id` – maschinenlesbare Regelquelle (z.B. `inline:rel`, `edge_defaults:project:depends_on`)
|
||||||
- `confidence` – 0.0–1.0; Heuristik zur Gewichtung im Scoring.
|
- `confidence` – 0.0–1.0; Heuristik zur Gewichtung im Scoring.
|
||||||
|
|
||||||
@@ -154,20 +183,24 @@ Erweiterte/abgeleitete Felder (WP03 Superset):
|
|||||||
- Steuert **Chunking-Profile** (`short|medium|long`) **pro Typ**
|
- Steuert **Chunking-Profile** (`short|medium|long`) **pro Typ**
|
||||||
- Liefert **retriever_weight** (Note-/Chunk-Gewichtung im Ranking) **pro Typ**
|
- Liefert **retriever_weight** (Note-/Chunk-Gewichtung im Ranking) **pro Typ**
|
||||||
- Definiert **edge_defaults** je Typ (s. o.)
|
- Definiert **edge_defaults** je Typ (s. o.)
|
||||||
|
- **Neu in v2.6:** Steuert `enable_smart_edge_allocation` (LLM-Filter) und `detection_keywords` für den Hybrid Router.
|
||||||
|
|
||||||
Der Importer lädt die Registry aus `MINDNET_TYPES_FILE` oder nutzt Fallbacks. **Frontmatter-Overrides** für Profile werden in v2.2 weitgehend ignoriert zugunsten einer zentralen Governance in der YAML-Datei.
|
Der Importer lädt die Registry aus `MINDNET_TYPES_FILE` oder nutzt Fallbacks. **Frontmatter-Overrides** für Profile werden in v2.2 weitgehend ignoriert zugunsten einer zentralen Governance in der YAML-Datei.
|
||||||
|
|
||||||
### 4.2 Beispiel (auslieferungsnah)
|
### 4.2 Beispiel (auslieferungsnah)
|
||||||
version: 1.0
|
version: 2.6.0
|
||||||
types:
|
types:
|
||||||
concept:
|
concept:
|
||||||
chunk_profile: medium
|
chunk_profile: medium
|
||||||
edge_defaults: ["references", "related_to"]
|
edge_defaults: ["references", "related_to"]
|
||||||
retriever_weight: 0.60
|
retriever_weight: 0.60
|
||||||
project:
|
experience:
|
||||||
chunk_profile: long
|
chunk_profile: sliding_smart_edges
|
||||||
edge_defaults: ["references", "depends_on"]
|
enable_smart_edge_allocation: true # WP15: LLM prüft Kanten
|
||||||
retriever_weight: 0.97
|
detection_keywords: ["passiert", "erlebt", "situation"] # WP06: Router-Trigger
|
||||||
|
schema: # WP07: Interview-Struktur
|
||||||
|
- "Situation (Was ist passiert?)"
|
||||||
|
- "Meine Reaktion (Was habe ich getan?)"
|
||||||
|
|
||||||
**Auflösung im Importer**
|
**Auflösung im Importer**
|
||||||
- `effective_chunk_profile(note_type, registry)` → `"short|medium|long"|None`
|
- `effective_chunk_profile(note_type, registry)` → `"short|medium|long"|None`
|
||||||
@@ -206,40 +239,65 @@ Der Retriever ist keine Blackbox mehr. Er liefert auf Wunsch (`explain=True`) ei
|
|||||||
|
|
||||||
Die API gibt diese Analysen als menschenlesbare Sätze (`reasons`) und als Datenstruktur (`score_breakdown`) zurück.
|
Die API gibt diese Analysen als menschenlesbare Sätze (`reasons`) und als Datenstruktur (`score_breakdown`) zurück.
|
||||||
|
|
||||||
|
### 5.3 Graph-Expansion
|
||||||
|
Der Hybrid-Modus lädt dynamisch die Nachbarschaft der Top-K Vektor-Treffer ("Seeds") über `graph_adapter.expand`. Dies baut einen temporären `NetworkX`-artigen Graphen im Speicher (Klasse `Subgraph`), auf dem Boni berechnet werden.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 6) Context Intelligence & Intent Router (WP06)
|
## 6) Context Intelligence & Intent Router (WP06–WP15)
|
||||||
|
|
||||||
Seit WP06 agiert Mindnet nicht mehr statisch, sondern passt seine Suchstrategie dem **Intent** (der Absicht) des Nutzers an. Dies ist die Transformation vom reinen Wissens-Abrufer zum strategischen Entscheidungspartner.
|
Seit WP06 agiert Mindnet nicht mehr statisch, sondern passt seine Suchstrategie dem **Intent** (der Absicht) des Nutzers an. Dies ist die Transformation vom reinen Wissens-Abrufer zum strategischen Partner.
|
||||||
|
|
||||||
### 6.1 Das Problem: Statische vs. Dynamische Antworten
|
### 6.1 Das Problem: Statische vs. Dynamische Antworten
|
||||||
* **Früher (Pre-WP06):** Jede Frage ("Was ist X?" oder "Soll ich X?") wurde gleich behandelt -> Fakten-Retrieval.
|
* **Früher (Pre-WP06):** Jede Frage ("Was ist X?" oder "Soll ich X?") wurde gleich behandelt -> Fakten-Retrieval.
|
||||||
* **Heute (WP06):** Das System erkennt, *was* der User will, und lädt unterschiedliche Wissensbausteine.
|
* **Heute (WP06):** Das System erkennt, *was* der User will (Rat, Fakten oder Datenerfassung) und wechselt den Modus.
|
||||||
|
|
||||||
### 6.2 Der Intent-Router (Keyword & Semantik)
|
### 6.2 Der Hybrid Router v5 (Action vs. Question)
|
||||||
Der Router prüft vor jeder Antwort die Absicht über konfigurierbare Strategien (`config/decision_engine.yaml`):
|
Der Router wurde in v2.6 (WP15) weiterentwickelt, um Fehlalarme zu vermeiden.
|
||||||
|
|
||||||
1. **FACT:** Reine Wissensfrage ("Was ist Qdrant?"). → Standard RAG.
|
1. **Frage-Erkennung:**
|
||||||
2. **DECISION:** Frage nach Rat oder Strategie ("Soll ich Qdrant nutzen?"). → Aktiviert die Decision Engine.
|
* Das System prüft zuerst: Enthält der Satz ein `?` oder typische W-Wörter (Wer, Wie, Was)?
|
||||||
3. **EMPATHY:** Emotionale Zustände ("Ich bin gestresst"). → Aktiviert den empathischen Modus.
|
* Wenn **JA** -> Gehe in den **RAG Modus** (Intent `FACT` oder `DECISION`). Interviews werden hier blockiert.
|
||||||
4. **CODING:** Technische Anfragen.
|
|
||||||
|
2. **Befehls-Erkennung (Fast Path):**
|
||||||
|
* Wenn **NEIN** (keine Frage), prüft das System auf Keywords in `types.yaml` ("Projekt", "Erfahrung").
|
||||||
|
* Treffer -> **INTERVIEW Modus** (Erfassen). Das Schema wird aus `types.yaml` geladen.
|
||||||
|
|
||||||
**Erkennung:**
|
3. **LLM Fallback (Slow Path):**
|
||||||
* **Fast Path:** Prüfung auf Schlüsselwörter (z.B. "soll ich").
|
* Wenn beides fehlschlägt, entscheidet das LLM über den Intent.
|
||||||
* **Slow Path (Smart Fallback):** Wenn kein Keyword passt, prüft ein LLM (Phi-3) die Semantik des Satzes.
|
|
||||||
|
|
||||||
### 6.3 Strategic Retrieval (Injektion von Werten)
|
### 6.3 Traffic Control (Realtime vs. Background)
|
||||||
|
Um den Live-Betrieb (Chat) nicht durch den ressourcenintensiven Smart-Import (LLM-Analyse) zu gefährden, implementiert v2.6 ein **Traffic Control System** im `LLMService`.
|
||||||
|
|
||||||
|
* **Realtime Lane (Chat):** Anfragen aus dem Chat erhalten `priority="realtime"`. Sie umgehen alle Warteschlangen und werden sofort bearbeitet.
|
||||||
|
* **Background Lane (Import):** Anfragen zur Kantenanalyse erhalten `priority="background"`. Sie werden durch eine **Semaphore** gedrosselt (Standard: max 2 parallel), um die Hardware nicht zu überlasten.
|
||||||
|
|
||||||
|
### 6.4 Strategic Retrieval (Injektion von Werten)
|
||||||
Im Modus `DECISION` führt das System eine **zweite Suchstufe** aus. Es sucht nicht nur nach semantisch passenden Texten zur Frage, sondern erzwingt das Laden von strategischen Notizen wie:
|
Im Modus `DECISION` führt das System eine **zweite Suchstufe** aus. Es sucht nicht nur nach semantisch passenden Texten zur Frage, sondern erzwingt das Laden von strategischen Notizen wie:
|
||||||
* **Values (`type: value`):** Moralische Werte (z.B. "Privacy First").
|
* **Values (`type: value`):** Moralische Werte (z.B. "Privacy First").
|
||||||
* **Principles (`type: principle`):** Handlungsanweisungen.
|
* **Principles (`type: principle`):** Handlungsanweisungen.
|
||||||
* **Goals (`type: goal`):** Strategische Ziele.
|
* **Goals (`type: goal`):** Strategische Ziele.
|
||||||
|
|
||||||
Dies wird über **Late Binding** in `config/decision_engine.yaml` gesteuert. Neue Facetten der Persönlichkeit können dort konfiguriert werden, ohne den Code zu ändern.
|
### 6.5 Reasoning (Das Gewissen)
|
||||||
|
|
||||||
### 6.4 Reasoning (Das Gewissen)
|
|
||||||
Das LLM erhält im Prompt die explizite Anweisung: *"Wäge die Fakten (aus der Suche) gegen die injizierten Werte ab."*
|
Das LLM erhält im Prompt die explizite Anweisung: *"Wäge die Fakten (aus der Suche) gegen die injizierten Werte ab."*
|
||||||
Dadurch entstehen Antworten, die nicht nur technisch korrekt sind, sondern subjektiv passend ("Tool X passt nicht zu deinem Ziel Z").
|
Dadurch entstehen Antworten, die nicht nur technisch korrekt sind, sondern subjektiv passend ("Tool X passt nicht zu deinem Ziel Z").
|
||||||
|
|
||||||
|
### 6.6 Der Interview-Modus (One-Shot Extraction)
|
||||||
|
Wenn der User Wissen erfassen will ("Ich möchte ein neues Projekt anlegen"), wechselt Mindnet in den **Interview-Modus**.
|
||||||
|
|
||||||
|
* **Late Binding Schema:** Das System lädt ein konfiguriertes Schema für den Ziel-Typ (z.B. `project`: Pflichtfelder sind Titel, Ziel, Status).
|
||||||
|
* **One-Shot Extraction:** Statt eines langen Dialogs extrahiert das LLM **sofort** alle verfügbaren Infos aus dem Prompt und generiert einen validen Markdown-Draft mit Frontmatter.
|
||||||
|
* **Healing Parser (v2.5):** Falls das LLM die YAML-Syntax beschädigt (z.B. fehlendes Ende), repariert das Frontend den Entwurf automatisch.
|
||||||
|
* **UI-Integration:** Das Frontend rendert statt einer Chat-Antwort einen **interaktiven Editor** (WP10), in dem der Entwurf finalisiert werden kann.
|
||||||
|
|
||||||
|
### 6.7 Active Intelligence (Link Suggestions)
|
||||||
|
Im **Draft Editor** (Frontend) unterstützt das System den Autor aktiv.
|
||||||
|
* **Analyse:** Ein "Sliding Window" scannt den Text im Hintergrund (auch lange Entwürfe).
|
||||||
|
* **Erkennung:** Es findet Begriffe ("Mindnet") und semantische Konzepte ("Autofahrt in Italien").
|
||||||
|
* **Matching:** Es prüft gegen den Index (Aliases und Vektoren).
|
||||||
|
* **Vorschlag:** Es bietet fertige Markdown-Links an (z.B. `[[rel:related_to ...]]`), die per Klick eingefügt werden.
|
||||||
|
* **Logik:** Dabei kommt die in 2.5 beschriebene **Matrix-Logik** zum Einsatz, um den korrekten Kanten-Typ vorzuschlagen.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 7) Future Concepts: The Empathic Digital Twin (Ausblick)
|
## 7) Future Concepts: The Empathic Digital Twin (Ausblick)
|
||||||
@@ -273,11 +331,12 @@ Mindnet lernt nicht durch klassisches Training (Fine-Tuning), sondern durch **Ko
|
|||||||
Steuere, wie schwer der Inhalt wiegt und wie er vernetzt wird.
|
Steuere, wie schwer der Inhalt wiegt und wie er vernetzt wird.
|
||||||
```yaml
|
```yaml
|
||||||
risk:
|
risk:
|
||||||
chunk_profile: short # Risiken sind prägnant
|
chunk_profile: short # Risiken sind oft kurze Statements
|
||||||
retriever_weight: 0.90 # Hohe Priorität im Ranking
|
retriever_weight: 0.90 # Hohe Priorität im Ranking
|
||||||
edge_defaults: ["blocks"] # Automatische Kante zu verlinkten Projekten
|
edge_defaults: ["blocks"] # Automatische Kante zu verlinkten Projekten
|
||||||
|
detection_keywords: ["gefahr", "risiko"] # Für den Hybrid Router
|
||||||
```
|
```
|
||||||
*Effekt:* Der Retriever spült diese Notizen bei relevanten Anfragen nach oben.
|
*Effekt:* Der Router erkennt das Wort "Risiko" und bietet ein Interview an. Der Retriever spült diese Notizen bei relevanten Anfragen nach oben.
|
||||||
|
|
||||||
2. **Semantik erklären (`config/prompts.yaml` / `decision_engine.yaml`)**
|
2. **Semantik erklären (`config/prompts.yaml` / `decision_engine.yaml`)**
|
||||||
Bringe dem LLM bei, wie es mit diesem Typ umgehen soll. Füge `risk` zur `DECISION`-Strategie hinzu (`inject_types`), damit es bei Entscheidungen geladen wird.
|
Bringe dem LLM bei, wie es mit diesem Typ umgehen soll. Füge `risk` zur `DECISION`-Strategie hinzu (`inject_types`), damit es bei Entscheidungen geladen wird.
|
||||||
@@ -308,11 +367,13 @@ Beziehungen sind der Klebstoff für logische Schlussfolgerungen.
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 9) Feedback & Lernen – WP04c
|
## 9) Feedback & Lernen – WP04c/WP10
|
||||||
|
|
||||||
Das System verfügt nun über ein **Kurzzeitgedächtnis für Interaktionen**, das die Basis für zukünftiges Lernen bildet.
|
Das System verfügt nun über ein **Kurzzeitgedächtnis für Interaktionen**, das die Basis für zukünftiges Lernen bildet.
|
||||||
|
|
||||||
### 9.1 Der Feedback-Loop
|
### 9.1 Der Feedback-Loop
|
||||||
|
Die Interaktion erfolgt primär über das **Web-Interface (WP10)**.
|
||||||
|
|
||||||
1. **Suche (Situation):**
|
1. **Suche (Situation):**
|
||||||
Wenn ein Nutzer eine Anfrage stellt, loggt Mindnet die "Situation":
|
Wenn ein Nutzer eine Anfrage stellt, loggt Mindnet die "Situation":
|
||||||
* Den Query-Text.
|
* Den Query-Text.
|
||||||
@@ -321,8 +382,8 @@ Das System verfügt nun über ein **Kurzzeitgedächtnis für Interaktionen**, da
|
|||||||
* Eine eindeutige `query_id` wird generiert.
|
* Eine eindeutige `query_id` wird generiert.
|
||||||
|
|
||||||
2. **Bewertung (Label):**
|
2. **Bewertung (Label):**
|
||||||
Der Nutzer (oder ein Agent) bewertet einen spezifischen Treffer (`node_id`) positiv oder negativ (Score 1-5).
|
Der Nutzer bewertet die Antwort (**Sterne**) oder einzelne Quellen (**Faces**) im Frontend.
|
||||||
Dieses Feedback wird unter Referenzierung der `query_id` gespeichert.
|
Dieses Feedback wird unter Referenzierung der `query_id` in `feedback.jsonl` gespeichert.
|
||||||
|
|
||||||
3. **Lernen (Perspektive WP08):**
|
3. **Lernen (Perspektive WP08):**
|
||||||
Durch die Verknüpfung von Situation und Bewertung entstehen Trainingsdaten. Mindnet kann später analysieren: *"Nutzer bevorzugen Treffer mit hohem Edge-Bonus, auch wenn der Text weniger passt."* -> Konsequenz: `edge_weight` erhöhen.
|
Durch die Verknüpfung von Situation und Bewertung entstehen Trainingsdaten. Mindnet kann später analysieren: *"Nutzer bevorzugen Treffer mit hohem Edge-Bonus, auch wenn der Text weniger passt."* -> Konsequenz: `edge_weight` erhöhen.
|
||||||
@@ -332,12 +393,12 @@ Das System verfügt nun über ein **Kurzzeitgedächtnis für Interaktionen**, da
|
|||||||
## 10) Confidence & Provenance – wozu?
|
## 10) Confidence & Provenance – wozu?
|
||||||
|
|
||||||
Der Retriever kann Edges gewichten:
|
Der Retriever kann Edges gewichten:
|
||||||
- **provenance**: *explicit* > *rule*
|
- **provenance**: *explicit* > *smart* (Neu) > *rule*
|
||||||
- **confidence**: numerische Feinsteuerung
|
- **confidence**: numerische Feinsteuerung
|
||||||
- **retriever_weight (Note/Chunk)**: skaliert die Relevanz des gesamten Knotens
|
- **retriever_weight (Note/Chunk)**: skaliert die Relevanz des gesamten Knotens
|
||||||
|
|
||||||
Eine typische Gewichtung (konfigurierbar in `retriever.yaml`) ist:
|
Eine typische Gewichtung (konfigurierbar in `retriever.yaml`) ist:
|
||||||
`explicit: 1.0`, `rule: 0.8`. Damit bevorzugt der Graph **kuratiertes Wissen** (explizit notierte Links) vor „erweiterten“ Default-Ableitungen.
|
`explicit: 1.0`, `smart: 0.9`, `rule: 0.8`. Damit bevorzugt der Graph **kuratiertes Wissen** (explizit notierte Links) vor „erweiterten“ Default-Ableitungen.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -347,6 +408,10 @@ Eine typische Gewichtung (konfigurierbar in `retriever.yaml`) ist:
|
|||||||
- `related_to` – Ähnlichkeit/Verwandtschaft (symmetrisch interpretierbar).
|
- `related_to` – Ähnlichkeit/Verwandtschaft (symmetrisch interpretierbar).
|
||||||
- `similar_to` – noch engere Ähnlichkeit; oft aus Inline-Rel (bewusst gesetzt).
|
- `similar_to` – noch engere Ähnlichkeit; oft aus Inline-Rel (bewusst gesetzt).
|
||||||
- `depends_on` – fachliche Abhängigkeit (z. B. „Projekt X hängt von Y ab“).
|
- `depends_on` – fachliche Abhängigkeit (z. B. „Projekt X hängt von Y ab“).
|
||||||
|
- **Neu in v2.4 (Matrix):**
|
||||||
|
- `based_on` – Erfahrung basiert auf Wert.
|
||||||
|
- `derived_from` – Erkenntnis stammt aus Prinzip.
|
||||||
|
- `uses` – Projekt nutzt Konzept.
|
||||||
- `belongs_to`, `next`, `prev` – Struktur.
|
- `belongs_to`, `next`, `prev` – Struktur.
|
||||||
|
|
||||||
> Symmetrische Relationen (z. B. `related_to`, `similar_to`) können **explizit** nur einseitig notiert sein, aber im Retriever beidseitig interpretiert werden.
|
> Symmetrische Relationen (z. B. `related_to`, `similar_to`) können **explizit** nur einseitig notiert sein, aber im Retriever beidseitig interpretiert werden.
|
||||||
@@ -371,7 +436,7 @@ Frontmatter-Eigenschaften (Properties) bleiben **minimiert**:
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 14) Beispiel – Von Markdown zu Kanten (v2.2)
|
## 14) Beispiel – Von Markdown zu Kanten
|
||||||
|
|
||||||
**Markdown (Auszug)**
|
**Markdown (Auszug)**
|
||||||
# Relations Showcase
|
# Relations Showcase
|
||||||
@@ -382,11 +447,11 @@ Frontmatter-Eigenschaften (Properties) bleiben **minimiert**:
|
|||||||
|
|
||||||
> [!edge] related_to: [[Vector DB Basics]]
|
> [!edge] related_to: [[Vector DB Basics]]
|
||||||
|
|
||||||
**Ergebnis (fachlich)**
|
**Ergebnis (fachlich - Smart Edges)**
|
||||||
1. `depends_on(Chunk→Qdrant)` mit `rule_id=inline:rel`, `confidence≈0.95`.
|
Das LLM analysiert jeden Chunk.
|
||||||
2. `references(Chunk→Embeddings 101)` mit `rule_id=explicit:wikilink`, `confidence=1.0`.
|
1. Chunk 1 ("Wir nutzen..."): Enthält `depends_on(Chunk→Qdrant)`. Das LLM bestätigt: Relevant. -> Kante wird erstellt.
|
||||||
3. `related_to(Chunk→Vector DB Basics)` via Callout; `rule_id=callout:edge`, `confidence≈0.90`.
|
2. Chunk 2 ("Siehe auch..."): Enthält `references(Chunk→Embeddings)`. Das LLM bestätigt.
|
||||||
4. **Typ-Defaults:** Falls die Note vom Typ `project` ist, entstehen zusätzlich `depends_on`-Kanten zu den Zielen aus (2) und (3).
|
3. **Wichtig:** Ein Chunk 3 ("Die Benutzeroberfläche ist blau..."), der keine Erwähnung von Qdrant hat, bekommt **keine** `depends_on` Kante zu Qdrant, auch wenn die Note global verlinkt ist. Das ist der Gewinn von WP15.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -394,15 +459,18 @@ Frontmatter-Eigenschaften (Properties) bleiben **minimiert**:
|
|||||||
|
|
||||||
- Import-Pipeline & Registry-Auflösung: `scripts/import_markdown.py`.
|
- Import-Pipeline & Registry-Auflösung: `scripts/import_markdown.py`.
|
||||||
- Kantenbildung (V2-Logic): `app/core/derive_edges.py`.
|
- Kantenbildung (V2-Logic): `app/core/derive_edges.py`.
|
||||||
|
- Smart Chunking & Traffic Control: `app/core/chunker.py` & `app/services/llm_service.py`.
|
||||||
- Typ-Registry: `config/types.yaml` & `TYPE_REGISTRY_MANUAL.md`.
|
- Typ-Registry: `config/types.yaml` & `TYPE_REGISTRY_MANUAL.md`.
|
||||||
- Retriever-Scoring & Explanation: `app/core/retriever.py`.
|
- Retriever-Scoring & Explanation: `app/core/retriever.py`.
|
||||||
- Persönlichkeit & Chat: `config/prompts.yaml` & `app/routers/chat.py`.
|
- Persönlichkeit & Chat: `config/prompts.yaml` & `app/routers/chat.py`.
|
||||||
- Decision Engine: `config/decision_engine.yaml`.
|
- Decision Engine: `config/decision_engine.yaml`.
|
||||||
- Logging Service: `app/services/feedback_service.py`.
|
- Logging Service: `app/services/feedback_service.py`.
|
||||||
|
- Frontend UI: `app/frontend/ui.py`.
|
||||||
|
- Intelligence Logic: `app/services/discovery.py`.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 16) Workpackage Status (v2.3.1)
|
## 16) Workpackage Status (v2.6.0)
|
||||||
|
|
||||||
Aktueller Implementierungsstand der Module.
|
Aktueller Implementierungsstand der Module.
|
||||||
|
|
||||||
@@ -415,5 +483,12 @@ Aktueller Implementierungsstand der Module.
|
|||||||
| **WP04b**| Explanation Layer | 🟢 Live | API liefert Reasons & Breakdown. |
|
| **WP04b**| Explanation Layer | 🟢 Live | API liefert Reasons & Breakdown. |
|
||||||
| **WP04c**| Feedback Loop | 🟢 Live | Logging (JSONL) & Traceability aktiv. |
|
| **WP04c**| Feedback Loop | 🟢 Live | Logging (JSONL) & Traceability aktiv. |
|
||||||
| **WP05** | Persönlichkeit / Chat | 🟢 Live | RAG-Integration mit Context Enrichment. |
|
| **WP05** | Persönlichkeit / Chat | 🟢 Live | RAG-Integration mit Context Enrichment. |
|
||||||
| **WP06** | Decision Engine | 🟢 Live | Intent-Router & Strategic Retrieval. |
|
| **WP06** | Decision Engine | 🟢 Live | Hybrid Router, Strategic Retrieval. |
|
||||||
| **WP08** | Self-Tuning | 🔴 Geplant | Auto-Adjustment der Gewichte. |
|
| **WP07** | Interview Assistent | 🟢 Live | **One-Shot Extractor & Schemas aktiv.** |
|
||||||
|
| **WP08** | Self-Tuning | 🔴 Geplant | Auto-Adjustment der Gewichte. |
|
||||||
|
| **WP10** | Chat Interface | 🟢 Live | Web-Interface (Streamlit). |
|
||||||
|
| **WP10a**| Draft Editor | 🟢 Live | **Interaktives UI & Healing Parser.** |
|
||||||
|
| **WP11** | Backend Intelligence | 🟢 Live | **Async Ingestion, Nomic Embeddings, Matrix Logic.** |
|
||||||
|
| **WP15** | Smart Edge Allocation | 🟢 Live | **LLM-Filter & Traffic Control aktiv.** |
|
||||||
|
| **WP16** | Auto-Discovery | 🟡 Geplant | UX & Retrieval Tuning. |
|
||||||
|
| **WP17** | Conversational Memory | 🟡 Geplant | Dialog-Gedächtnis. |
|
||||||
@@ -1,21 +1,21 @@
|
|||||||
# Mindnet v2.2 – Technische Architektur
|
# Mindnet v2.6 – Technische Architektur
|
||||||
**Datei:** `docs/mindnet_technical_architecture_v2.2.md`
|
**Datei:** `docs/mindnet_technical_architecture_v2.6.md`
|
||||||
**Stand:** 2025-12-09
|
**Stand:** 2025-12-12
|
||||||
**Status:** **FINAL** (Integrierter Stand WP01–WP06)
|
**Status:** **FINAL** (Integrierter Stand WP01–WP15: Smart Edges & Traffic Control)
|
||||||
**Quellen:** `Programmplan_V2.2.md`, `Handbuch.md`, `chunking_strategy.md`, `wp04_retriever_scoring.md`.
|
**Quellen:** `Programmplan_V2.6.md`, `Handbuch.md`, `chunking_strategy.md`, `wp04_retriever_scoring.md`.
|
||||||
|
|
||||||
> **Ziel dieses Dokuments:**
|
> **Ziel dieses Dokuments:**
|
||||||
> Vollständige Beschreibung der technischen Architektur inkl. Graph-Datenbank, Retrieval-Logik und der **neuen RAG-Komponenten (Decision Engine & Hybrid Router)**.
|
> Vollständige Beschreibung der technischen Architektur inkl. Graph-Datenbank, Retrieval-Logik, der **RAG-Komponenten (Decision Engine & Hybrid Router)**, des **Traffic Control Systems** und dem **Frontend (Streamlit)**.
|
||||||
|
|
||||||
---
|
---
|
||||||
<details>
|
<details>
|
||||||
<summary>📖 <b>Inhaltsverzeichnis (Klicken zum Öffnen)</b></summary>
|
<summary>📖 <b>Inhaltsverzeichnis (Klicken zum Öffnen)</b></summary>
|
||||||
|
|
||||||
- [Mindnet v2.2 – Technische Architektur](#mindnet-v22--technische-architektur)
|
- [Mindnet v2.6 – Technische Architektur](#mindnet-v26--technische-architektur)
|
||||||
- [](#)
|
- [](#)
|
||||||
- [1. Systemüberblick](#1-systemüberblick)
|
- [1. Systemüberblick](#1-systemüberblick)
|
||||||
- [1.1 Architektur-Zielbild](#11-architektur-zielbild)
|
- [1.1 Architektur-Zielbild](#11-architektur-zielbild)
|
||||||
- [1.2 Verzeichnisstruktur \& Komponenten (Post-WP06)](#12-verzeichnisstruktur--komponenten-post-wp06)
|
- [1.2 Verzeichnisstruktur \& Komponenten (Post-WP15)](#12-verzeichnisstruktur--komponenten-post-wp15)
|
||||||
- [2. Datenmodell \& Collections (Qdrant)](#2-datenmodell--collections-qdrant)
|
- [2. Datenmodell \& Collections (Qdrant)](#2-datenmodell--collections-qdrant)
|
||||||
- [2.1 Notes Collection (`<prefix>_notes`)](#21-notes-collection-prefix_notes)
|
- [2.1 Notes Collection (`<prefix>_notes`)](#21-notes-collection-prefix_notes)
|
||||||
- [2.2 Chunks Collection (`<prefix>_chunks`)](#22-chunks-collection-prefix_chunks)
|
- [2.2 Chunks Collection (`<prefix>_chunks`)](#22-chunks-collection-prefix_chunks)
|
||||||
@@ -27,24 +27,31 @@
|
|||||||
- [3.4 Prompts (`config/prompts.yaml`)](#34-prompts-configpromptsyaml)
|
- [3.4 Prompts (`config/prompts.yaml`)](#34-prompts-configpromptsyaml)
|
||||||
- [3.5 Environment (`.env`)](#35-environment-env)
|
- [3.5 Environment (`.env`)](#35-environment-env)
|
||||||
- [4. Import-Pipeline (Markdown → Qdrant)](#4-import-pipeline-markdown--qdrant)
|
- [4. Import-Pipeline (Markdown → Qdrant)](#4-import-pipeline-markdown--qdrant)
|
||||||
- [4.1 Verarbeitungsschritte](#41-verarbeitungsschritte)
|
- [4.1 Verarbeitungsschritte (Async + Smart)](#41-verarbeitungsschritte-async--smart)
|
||||||
- [5. Retriever-Architektur \& Scoring](#5-retriever-architektur--scoring)
|
- [5. Retriever-Architektur \& Scoring](#5-retriever-architektur--scoring)
|
||||||
- [5.1 Betriebsmodi](#51-betriebsmodi)
|
- [5.1 Betriebsmodi](#51-betriebsmodi)
|
||||||
- [5.2 Scoring-Formel (WP04a)](#52-scoring-formel-wp04a)
|
- [5.2 Scoring-Formel (WP04a)](#52-scoring-formel-wp04a)
|
||||||
- [5.3 Explanation Layer (WP04b)](#53-explanation-layer-wp04b)
|
- [5.3 Explanation Layer (WP04b)](#53-explanation-layer-wp04b)
|
||||||
- [5.4 Graph-Expansion](#54-graph-expansion)
|
- [5.4 Graph-Expansion](#54-graph-expansion)
|
||||||
- [6. RAG \& Chat Architektur (WP06 Hybrid Router)](#6-rag--chat-architektur-wp06-hybrid-router)
|
- [6. RAG \& Chat Architektur (WP06 Hybrid Router + WP07 Interview)](#6-rag--chat-architektur-wp06-hybrid-router--wp07-interview)
|
||||||
- [6.1 Architektur-Pattern: Intent Router](#61-architektur-pattern-intent-router)
|
- [6.1 Architektur-Pattern: Intent Router v5](#61-architektur-pattern-intent-router-v5)
|
||||||
- [6.2 Schritt 1: Intent Detection (Hybrid)](#62-schritt-1-intent-detection-hybrid)
|
- [6.2 Traffic Control (Priorisierung)](#62-traffic-control-priorisierung)
|
||||||
- [6.3 Schritt 2: Strategy Resolution (Late Binding)](#63-schritt-2-strategy-resolution-late-binding)
|
- [6.3 Schritt 1: Intent Detection (Question vs. Action)](#63-schritt-1-intent-detection-question-vs-action)
|
||||||
- [6.4 Schritt 3: Multi-Stage Retrieval](#64-schritt-3-multi-stage-retrieval)
|
- [6.4 Schritt 2: Strategy Resolution](#64-schritt-2-strategy-resolution)
|
||||||
- [6.5 Schritt 4: Generation \& Response](#65-schritt-4-generation--response)
|
- [6.5 Schritt 3: Retrieval vs. Extraction](#65-schritt-3-retrieval-vs-extraction)
|
||||||
- [7. Feedback \& Logging Architektur (WP04c)](#7-feedback--logging-architektur-wp04c)
|
- [6.6 Schritt 4: Generation \& Response](#66-schritt-4-generation--response)
|
||||||
- [7.1 Komponenten](#71-komponenten)
|
- [7. Frontend Architektur (WP10)](#7-frontend-architektur-wp10)
|
||||||
- [7.2 Log-Dateien](#72-log-dateien)
|
- [7.1 Kommunikation](#71-kommunikation)
|
||||||
- [7.3 Traceability](#73-traceability)
|
- [7.2 Features \& UI-Logik](#72-features--ui-logik)
|
||||||
- [8. Indizes \& Performance](#8-indizes--performance)
|
- [7.3 Draft-Editor \& Healing Parser (Neu in WP10a/v2.5)](#73-draft-editor--healing-parser-neu-in-wp10av25)
|
||||||
- [9. Offene Punkte / Known Limitations](#9-offene-punkte--known-limitations)
|
- [7.4 State Management (Resurrection Pattern)](#74-state-management-resurrection-pattern)
|
||||||
|
- [7.5 Deployment Ports](#75-deployment-ports)
|
||||||
|
- [8. Feedback \& Logging Architektur (WP04c)](#8-feedback--logging-architektur-wp04c)
|
||||||
|
- [8.1 Komponenten](#81-komponenten)
|
||||||
|
- [8.2 Log-Dateien](#82-log-dateien)
|
||||||
|
- [8.3 Traceability](#83-traceability)
|
||||||
|
- [9. Indizes \& Performance](#9-indizes--performance)
|
||||||
|
- [10. Offene Punkte / Known Limitations](#10-offene-punkte--known-limitations)
|
||||||
|
|
||||||
|
|
||||||
</details>
|
</details>
|
||||||
@@ -53,54 +60,66 @@
|
|||||||
## 1. Systemüberblick
|
## 1. Systemüberblick
|
||||||
|
|
||||||
### 1.1 Architektur-Zielbild
|
### 1.1 Architektur-Zielbild
|
||||||
Mindnet ist ein **lokales RAG-System (Retrieval Augmented Generation)**.
|
Mindnet ist ein **lokales RAG-System (Retrieval Augmented Generation)** mit Web-Interface.
|
||||||
1. **Source:** Markdown-Notizen in einem Vault (Obsidian-kompatibel).
|
1. **Source:** Markdown-Notizen in einem Vault (Obsidian-kompatibel).
|
||||||
2. **Pipeline:** Ein Python-Importer transformiert diese in **Notes**, **Chunks** und **Edges**.
|
2. **Pipeline:** Ein Python-Importer transformiert diese in **Notes**, **Chunks** und **Edges**.
|
||||||
|
* **Neu in v2.6:** Intelligente Kanten-Zuweisung durch lokale LLMs (**Smart Edge Allocation**).
|
||||||
3. **Storage:**
|
3. **Storage:**
|
||||||
* **Qdrant:** Vektor-Datenbank für Graph und Semantik (Collections: notes, chunks, edges).
|
* **Qdrant:** Vektor-Datenbank für Graph und Semantik (Collections: notes, chunks, edges).
|
||||||
* **Local Files (JSONL):** Append-Only Logs für Feedback und Search-History (Data Flywheel).
|
* **Local Files (JSONL):** Append-Only Logs für Feedback und Search-History (Data Flywheel).
|
||||||
4. **Service:** Eine FastAPI-Anwendung stellt Endpunkte für **Semantische** und **Hybride Suche** sowie **Feedback** bereit.
|
4. **Backend:** Eine FastAPI-Anwendung stellt Endpunkte für **Semantische** und **Hybride Suche** sowie **Feedback** bereit.
|
||||||
5. **Inference:** Lokales LLM (Ollama: Phi-3 Mini) für RAG-Chat und Antwortgenerierung.
|
* **Update v2.6:** Der Core arbeitet nun vollständig **asynchron (AsyncIO)** mit **Traffic Control** (Semaphore zur Lastverteilung).
|
||||||
|
5. **Frontend:** Streamlit-App (`ui.py`) für Interaktion und Visualisierung inkl. **Draft Editor**, **Active Intelligence** und **Healing Parser**.
|
||||||
|
6. **Inference:** Lokales LLM (Ollama: Phi-3 Mini) für RAG-Chat und Antwortgenerierung. Embedding via `nomic-embed-text`.
|
||||||
|
|
||||||
Das System arbeitet **deterministisch** (stabile IDs) und ist **konfigurationsgetrieben** (`types.yaml`, `retriever.yaml`, `decision_engine.yaml`, `prompts.yaml`).
|
Das System arbeitet **deterministisch** (stabile IDs) und ist **konfigurationsgetrieben** (`types.yaml`, `retriever.yaml`, `decision_engine.yaml`, `prompts.yaml`).
|
||||||
|
|
||||||
### 1.2 Verzeichnisstruktur & Komponenten (Post-WP06)
|
### 1.2 Verzeichnisstruktur & Komponenten (Post-WP15)
|
||||||
|
|
||||||
/mindnet/
|
/mindnet/
|
||||||
├── app/
|
├── app/
|
||||||
│ ├── main.py # FastAPI Einstiegspunkt
|
│ ├── main.py # FastAPI Einstiegspunkt
|
||||||
│ ├── core/
|
│ ├── core/
|
||||||
|
│ │ ├── ingestion.py # NEU: Async Ingestion mit Change Detection
|
||||||
│ │ ├── qdrant.py # Client-Factory & Connection
|
│ │ ├── qdrant.py # Client-Factory & Connection
|
||||||
│ │ ├── qdrant_points.py # Low-Level Point Operations (Upsert/Delete)
|
│ │ ├── qdrant_points.py # Low-Level Point Operations (Upsert/Delete)
|
||||||
│ │ ├── note_payload.py # Bau der Note-Objekte
|
│ │ ├── note_payload.py # Bau der Note-Objekte
|
||||||
│ │ ├── chunk_payload.py # Bau der Chunk-Objekte
|
│ │ ├── chunk_payload.py # Bau der Chunk-Objekte
|
||||||
│ │ ├── chunker.py # Text-Zerlegung (Profiling)
|
│ │ ├── chunker.py # Smart Chunker Orchestrator (WP15)
|
||||||
│ │ ├── edges.py # Edge-Datenstrukturen
|
│ │ ├── edges.py # Edge-Datenstrukturen
|
||||||
│ │ ├── derive_edges.py # Logik der Kantenableitung (WP03)
|
│ │ ├── derive_edges.py # Logik der Kantenableitung (WP03)
|
||||||
│ │ ├── graph_adapter.py # Subgraph & Reverse-Lookup (WP04b)
|
│ │ ├── graph_adapter.py # Subgraph & Reverse-Lookup (WP04b)
|
||||||
│ │ └── retriever.py # Scoring, Expansion & Explanation (WP04a/b)
|
│ │ └── retriever.py # Scoring, Expansion & Explanation (WP04a/b)
|
||||||
│ ├── models/ # Pydantic DTOs
|
│ ├── models/ # Pydantic DTOs
|
||||||
|
│ │ └── dto.py # Zentrale DTO-Definition
|
||||||
│ ├── routers/
|
│ ├── routers/
|
||||||
│ │ ├── query.py # Such-Endpunkt
|
│ │ ├── query.py # Such-Endpunkt
|
||||||
│ │ ├── chat.py # Hybrid Router & Decision Engine (WP06)
|
│ │ ├── ingest.py # NEU: API für Save & Analyze (WP11)
|
||||||
|
│ │ ├── chat.py # Hybrid Router v5 & Interview Logic (WP06/07)
|
||||||
│ │ ├── feedback.py # Feedback-Endpunkt (WP04c)
|
│ │ ├── feedback.py # Feedback-Endpunkt (WP04c)
|
||||||
│ │ └── ...
|
│ │ └── ...
|
||||||
│ ├── services/
|
│ ├── services/
|
||||||
│ │ ├── llm_service.py # Ollama Client mit Timeout & Raw-Mode
|
│ │ ├── llm_service.py # Ollama Chat Client mit Traffic Control (v2.8.0)
|
||||||
│ │ ├── feedback_service.py # JSONL Logging (WP04c)
|
│ │ ├── semantic_analyzer.py# NEU: LLM-Filter für Edges (WP15)
|
||||||
│ │ └── embeddings_client.py
|
│ │ ├── embeddings_client.py# NEU: Async Embeddings (HTTPX)
|
||||||
├── config/
|
│ │ ├── feedback_service.py # Logging (JSONL Writer)
|
||||||
│ ├── types.yaml # Typ-Definitionen (Import-Zeit)
|
│ │ └── discovery.py # NEU: Intelligence Logic (WP11)
|
||||||
│ ├── retriever.yaml # Scoring-Gewichte (Laufzeit)
|
│ ├── frontend/ # NEU (WP10)
|
||||||
│ ├── decision_engine.yaml # Strategien & Keywords (WP06)
|
│ │ └── ui.py # Streamlit Application inkl. Healing Parser
|
||||||
│ └── prompts.yaml # LLM System-Prompts & Templates (WP06)
|
│ └── main.py # Entrypoint der API
|
||||||
|
├── config/ # YAML-Konfigurationen (Single Source of Truth)
|
||||||
|
│ ├── types.yaml # Import-Regeln & Smart-Edge Config
|
||||||
|
│ ├── prompts.yaml # LLM Prompts & Interview Templates (WP06/07)
|
||||||
|
│ ├── decision_engine.yaml # Router-Strategien (Actions only)
|
||||||
|
│ └── retriever.yaml # Scoring-Regeln & Kantengewichte
|
||||||
├── data/
|
├── data/
|
||||||
│ └── logs/ # Lokale JSONL-Logs (WP04c)
|
│ └── logs/ # Lokale Logs (search_history.jsonl, feedback.jsonl)
|
||||||
├── scripts/
|
├── scripts/ # CLI-Tools (Import, Diagnose, Reset)
|
||||||
│ ├── import_markdown.py # Haupt-Importer CLI
|
│ ├── import_markdown.py # Haupt-Importer CLI (Async)
|
||||||
│ ├── payload_dryrun.py # Diagnose: JSON-Generierung ohne DB
|
│ ├── payload_dryrun.py # Diagnose: JSON-Generierung ohne DB
|
||||||
│ └── edges_full_check.py # Diagnose: Graph-Integrität
|
│ └── edges_full_check.py # Diagnose: Graph-Integrität
|
||||||
└── tests/ # Pytest Suite
|
├── tests/ # Pytest Suite & Smoke Scripts
|
||||||
|
└── vault/ # Dein lokaler Markdown-Content (Git-ignored)
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -128,12 +147,14 @@ Repräsentiert die Metadaten einer Datei.
|
|||||||
### 2.2 Chunks Collection (`<prefix>_chunks`)
|
### 2.2 Chunks Collection (`<prefix>_chunks`)
|
||||||
Die atomaren Sucheinheiten.
|
Die atomaren Sucheinheiten.
|
||||||
* **Zweck:** Vektorsuche (Embeddings), Granulares Ergebnis.
|
* **Zweck:** Vektorsuche (Embeddings), Granulares Ergebnis.
|
||||||
|
* **Update v2.4:** Vektor-Dimension ist jetzt **768** (für `nomic-embed-text`).
|
||||||
* **Schema (Payload):**
|
* **Schema (Payload):**
|
||||||
|
|
||||||
| Feld | Datentyp | Beschreibung |
|
| Feld | Datentyp | Beschreibung |
|
||||||
| :--- | :--- | :--- |
|
| :--- | :--- | :--- |
|
||||||
| `chunk_id` | Keyword | Deterministisch: `{note_id}#c{index:02d}`. |
|
| `chunk_id` | Keyword | Deterministisch: `{note_id}#c{index:02d}`. |
|
||||||
| `note_id` | Keyword | Referenz zur Note. |
|
| `note_id` | Keyword | Referenz zur Note. |
|
||||||
|
| `type` | Keyword | **Kopie des Note-Typs** (Denormalisiert für Filter). |
|
||||||
| `text` | Text | **Reiner Inhalt** (ohne Overlap). Anzeige-Text. |
|
| `text` | Text | **Reiner Inhalt** (ohne Overlap). Anzeige-Text. |
|
||||||
| `window` | Text | **Kontext-Fenster** (mit Overlap). Embedding-Basis. |
|
| `window` | Text | **Kontext-Fenster** (mit Overlap). Embedding-Basis. |
|
||||||
| `ord` | Integer | Sortierreihenfolge (1..N). |
|
| `ord` | Integer | Sortierreihenfolge (1..N). |
|
||||||
@@ -157,6 +178,7 @@ Gerichtete Kanten. Massiv erweitert in WP03 für Provenienz-Tracking.
|
|||||||
| `scope` | Keyword | Geltungsbereich. | Immer `"chunk"` (v2.2). |
|
| `scope` | Keyword | Geltungsbereich. | Immer `"chunk"` (v2.2). |
|
||||||
| `rule_id` | Keyword | Herkunftsregel. | `explicit:wikilink`, `inline:rel` |
|
| `rule_id` | Keyword | Herkunftsregel. | `explicit:wikilink`, `inline:rel` |
|
||||||
| `confidence` | Float | Vertrauenswürdigkeit (0.0-1.0). | 1.0, 0.95, 0.7 |
|
| `confidence` | Float | Vertrauenswürdigkeit (0.0-1.0). | 1.0, 0.95, 0.7 |
|
||||||
|
| `provenance` | Keyword | Quelle der Kante (Neu in v2.6). | `explicit`, `rule`, `smart` |
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -167,13 +189,20 @@ Die Logik ist ausgelagert in YAML-Dateien.
|
|||||||
### 3.1 Typ-Registry (`config/types.yaml`)
|
### 3.1 Typ-Registry (`config/types.yaml`)
|
||||||
Steuert den Import-Prozess.
|
Steuert den Import-Prozess.
|
||||||
* **Priorität:** Frontmatter > Pfad > Default.
|
* **Priorität:** Frontmatter > Pfad > Default.
|
||||||
|
* **Neu in v2.6:**
|
||||||
|
* `enable_smart_edge_allocation`: (Bool) Aktiviert den LLM-Filter für diesen Typ.
|
||||||
|
* `detection_keywords`: (List) Keywords für den Hybrid Router ("Objekterkennung").
|
||||||
* **Inhalt (Beispiel):**
|
* **Inhalt (Beispiel):**
|
||||||
|
|
||||||
types:
|
types:
|
||||||
concept:
|
concept:
|
||||||
chunk_profile: medium
|
chunk_profile: sliding_standard
|
||||||
edge_defaults: ["references", "related_to"]
|
edge_defaults: ["references", "related_to"]
|
||||||
retriever_weight: 0.60
|
retriever_weight: 0.60
|
||||||
|
experience:
|
||||||
|
chunk_profile: sliding_smart_edges
|
||||||
|
enable_smart_edge_allocation: true
|
||||||
|
detection_keywords: ["erfahrung", "erlebt"]
|
||||||
|
|
||||||
### 3.2 Retriever-Config (`config/retriever.yaml`)
|
### 3.2 Retriever-Config (`config/retriever.yaml`)
|
||||||
Steuert das Scoring zur Laufzeit (WP04a).
|
Steuert das Scoring zur Laufzeit (WP04a).
|
||||||
@@ -185,47 +214,51 @@ Steuert das Scoring zur Laufzeit (WP04a).
|
|||||||
centrality_weight: 0.5
|
centrality_weight: 0.5
|
||||||
|
|
||||||
### 3.3 Decision Engine (`config/decision_engine.yaml`)
|
### 3.3 Decision Engine (`config/decision_engine.yaml`)
|
||||||
**Neu in WP06:** Steuert den Intent-Router.
|
**Neu in WP06/07:** Steuert den Intent-Router.
|
||||||
* Definiert Strategien (`DECISION`, `EMPATHY`, `CODING`, `FACT`).
|
* Definiert Strategien (`DECISION`, `INTERVIEW`, etc.).
|
||||||
* Definiert `trigger_keywords` und `inject_types` (Late Binding).
|
* **Update v2.6:** Enthält nur noch **Handlungs-Keywords** (Verben wie "neu", "erstellen"). Objektnamen ("Projekt") werden nun über `types.yaml` aufgelöst.
|
||||||
* Definiert LLM-Router-Settings (`llm_fallback_enabled`).
|
* Definiert LLM-Router-Settings (`llm_fallback_enabled`).
|
||||||
|
|
||||||
### 3.4 Prompts (`config/prompts.yaml`)
|
### 3.4 Prompts (`config/prompts.yaml`)
|
||||||
Steuert die LLM-Persönlichkeit und Templates.
|
Steuert die LLM-Persönlichkeit und Templates.
|
||||||
* Enthält Templates für alle Strategien (z.B. `decision_template`, `empathy_template`, `technical_template`).
|
* Enthält Templates für alle Strategien inkl. `interview_template` und neu `router_prompt`.
|
||||||
|
|
||||||
### 3.5 Environment (`.env`)
|
### 3.5 Environment (`.env`)
|
||||||
Erweiterung für LLM-Steuerung:
|
Erweiterung für LLM-Steuerung und Embedding-Modell:
|
||||||
|
|
||||||
MINDNET_LLM_MODEL=phi3:mini
|
MINDNET_LLM_MODEL=phi3:mini
|
||||||
|
MINDNET_EMBEDDING_MODEL=nomic-embed-text # NEU in v2.3.10
|
||||||
MINDNET_OLLAMA_URL=http://127.0.0.1:11434
|
MINDNET_OLLAMA_URL=http://127.0.0.1:11434
|
||||||
MINDNET_LLM_TIMEOUT=300.0 # Neu: Erhöht für CPU-Inference Cold-Starts
|
MINDNET_LLM_TIMEOUT=300.0 # Neu: Erhöht für CPU-Inference Cold-Starts
|
||||||
|
MINDNET_API_TIMEOUT=300.0 # Neu: Timeout für Frontend-API (Smart Edges brauchen Zeit)
|
||||||
MINDNET_DECISION_CONFIG="config/decision_engine.yaml"
|
MINDNET_DECISION_CONFIG="config/decision_engine.yaml"
|
||||||
|
MINDNET_VAULT_ROOT="./vault" # Neu: Pfad für Write-Back
|
||||||
|
MINDNET_LLM_BACKGROUND_LIMIT=2 # Neu: Limit für parallele Hintergrund-Jobs (Traffic Control)
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 4. Import-Pipeline (Markdown → Qdrant)
|
## 4. Import-Pipeline (Markdown → Qdrant)
|
||||||
|
|
||||||
Das Skript `scripts/import_markdown.py` orchestriert den Prozess.
|
Das Skript `scripts/import_markdown.py` orchestriert den Prozess.
|
||||||
|
**Neu in v2.6:** Der Import nutzt `asyncio` und **Traffic Control**, um Ollama nicht zu überlasten.
|
||||||
|
|
||||||
### 4.1 Verarbeitungsschritte
|
### 4.1 Verarbeitungsschritte (Async + Smart)
|
||||||
|
|
||||||
1. **Discovery & Parsing:**
|
1. **Discovery & Parsing:** Hash-Vergleich zur Erkennung von Änderungen.
|
||||||
* Einlesen der `.md` Dateien. Hash-Vergleich (Body/Frontmatter) zur Erkennung von Änderungen.
|
2. **Typauflösung:** Bestimmung des `type` via `types.yaml`.
|
||||||
2. **Typauflösung:**
|
3. **Config Check:** Laden des `chunk_profile` und `enable_smart_edge_allocation`.
|
||||||
* Laden der `types.yaml`. Bestimmen des effektiven Typs und der `edge_defaults`.
|
4. **Chunking & Smart Edges (WP15):**
|
||||||
3. **Chunking:**
|
* Zerlegung des Textes via `chunker.py`.
|
||||||
* Zerlegung via `chunker.py` basierend auf `chunk_profile` (z.B. `by_heading`, `short`, `long`).
|
* Wenn Smart Edges aktiv: Der `SemanticAnalyzer` sendet Chunks an das LLM.
|
||||||
* Trennung von `text` (Kern) und `window` (Embedding-Kontext).
|
* **Traffic Control:** Der Request nutzt `priority="background"`. Die Semaphore (Limit: 2) drosselt die Parallelität.
|
||||||
4. **Kantenableitung (Edge Derivation):**
|
5. **Kantenableitung (Edge Derivation):**
|
||||||
Die `derive_edges.py` erzeugt Kanten in strikter Reihenfolge:
|
* `derive_edges.py` erzeugt Inline-, Callout- und Default-Edges.
|
||||||
1. **Inline-Edges:** `[[rel:depends_on X]]` → `kind=depends_on`, `rule_id=inline:rel`, `conf=0.95`.
|
6. **Embedding (Async):**
|
||||||
2. **Callout-Edges:** `> [!edge] related_to: [[X]]` → `kind=related_to`, `rule_id=callout:edge`, `conf=0.90`.
|
* Der `EmbeddingsClient` (`app/services/embeddings_client.py`) sendet Text-Chunks asynchron an Ollama.
|
||||||
3. **Explizite Referenzen:** `[[X]]` → `kind=references`, `rule_id=explicit:wikilink`, `conf=1.0`.
|
* Modell: `nomic-embed-text` (768d).
|
||||||
4. **Typ-Defaults:** Für jede Referenz werden Zusatzkanten gemäß `edge_defaults` erzeugt (z.B. `project` -> `depends_on`). `rule_id=edge_defaults:...`, `conf=0.7`.
|
7. **Upsert:**
|
||||||
5. **Struktur:** `belongs_to`, `next`, `prev` (automatisch).
|
* Schreiben in Qdrant. Nutzung von `--purge-before-upsert`.
|
||||||
5. **Upsert:**
|
* **Strict Mode:** Der Prozess bricht ab, wenn Embeddings leer sind oder Dimension `0` haben.
|
||||||
* Schreiben in Qdrant. Nutzung von `--purge-before-upsert` für saubere Updates.
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -234,7 +267,7 @@ Das Skript `scripts/import_markdown.py` orchestriert den Prozess.
|
|||||||
Der Retriever (`app/core/retriever.py`) unterstützt zwei Modi. Für den Chat wird **zwingend** der Hybrid-Modus genutzt.
|
Der Retriever (`app/core/retriever.py`) unterstützt zwei Modi. Für den Chat wird **zwingend** der Hybrid-Modus genutzt.
|
||||||
|
|
||||||
### 5.1 Betriebsmodi
|
### 5.1 Betriebsmodi
|
||||||
* **Semantic:** Reine Vektorsuche. Schnell.
|
* **Semantic:** Reine Vektorsuche (768d).
|
||||||
* **Hybrid:** Vektorsuche + Graph-Expansion (Tiefe N) + Re-Ranking.
|
* **Hybrid:** Vektorsuche + Graph-Expansion (Tiefe N) + Re-Ranking.
|
||||||
|
|
||||||
### 5.2 Scoring-Formel (WP04a)
|
### 5.2 Scoring-Formel (WP04a)
|
||||||
@@ -252,70 +285,131 @@ $$
|
|||||||
* **Gewichte ($W$):** Stammen aus `retriever.yaml`.
|
* **Gewichte ($W$):** Stammen aus `retriever.yaml`.
|
||||||
|
|
||||||
### 5.3 Explanation Layer (WP04b)
|
### 5.3 Explanation Layer (WP04b)
|
||||||
Der Retriever kann Ergebnisse erklären (`explain=True`).
|
Der Retriever ist keine Blackbox mehr. Er liefert auf Wunsch (`explain=True`) eine strukturierte Begründung (`Explanation`-Objekt).
|
||||||
* **Logik:**
|
|
||||||
* Berechnung des `ScoreBreakdown` (Anteile von Semantik, Graph, Typ).
|
**Die "Warum"-Logik:**
|
||||||
* Analyse des lokalen Subgraphen mittels `graph_adapter.py`.
|
1. **Semantik:** Prüfung der Cosine-Similarity ("Sehr hohe textuelle Übereinstimmung").
|
||||||
* **Incoming Edges (Authority):** Wer zeigt auf diesen Treffer? (z.B. "Referenziert von...")
|
2. **Typ:** Prüfung des `retriever_weight` ("Bevorzugt, da Entscheidung").
|
||||||
* **Outgoing Edges (Hub):** Worauf zeigt dieser Treffer? (z.B. "Verweist auf...")
|
3. **Graph (Kontext):**
|
||||||
* **Output:** `QueryHit` enthält ein `explanation` Objekt mit menschenlesbaren `reasons` und `related_edges`.
|
* **Hub (Outgoing):** Worauf verweist dieser Treffer? ("Verweist auf Qdrant").
|
||||||
|
* **Authority (Incoming):** Wer verweist auf diesen Treffer? ("Wird referenziert von Projekt Alpha").
|
||||||
|
|
||||||
|
Die API gibt diese Analysen als menschenlesbare Sätze (`reasons`) und als Datenstruktur (`score_breakdown`) zurück.
|
||||||
|
|
||||||
### 5.4 Graph-Expansion
|
### 5.4 Graph-Expansion
|
||||||
Der Hybrid-Modus lädt dynamisch die Nachbarschaft der Top-K Vektor-Treffer ("Seeds") über `graph_adapter.expand`. Dies baut einen temporären `NetworkX`-artigen Graphen im Speicher (Klasse `Subgraph`), auf dem Boni berechnet werden.
|
Der Hybrid-Modus lädt dynamisch die Nachbarschaft der Top-K Vektor-Treffer ("Seeds") über `graph_adapter.expand`. Dies baut einen temporären `NetworkX`-artigen Graphen im Speicher (Klasse `Subgraph`), auf dem Boni berechnet werden.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 6. RAG & Chat Architektur (WP06 Hybrid Router)
|
## 6. RAG & Chat Architektur (WP06 Hybrid Router + WP07 Interview)
|
||||||
|
|
||||||
Der Flow für eine Chat-Anfrage (`/chat`) wurde in WP06 auf eine **Configuration-Driven Architecture** umgestellt. Der `ChatRouter` (`app/routers/chat.py`) fungiert als zentraler Dispatcher.
|
Der Flow für eine Chat-Anfrage (`/chat`) wurde in WP06 auf eine **Configuration-Driven Architecture** umgestellt und in WP15 (v2.6) verfeinert.
|
||||||
|
|
||||||
### 6.1 Architektur-Pattern: Intent Router
|
### 6.1 Architektur-Pattern: Intent Router v5
|
||||||
Die Behandlung einer Anfrage ist nicht mehr hartkodiert, sondern wird dynamisch zur Laufzeit entschieden.
|
Die Behandlung einer Anfrage ist nicht mehr hartkodiert, sondern wird dynamisch zur Laufzeit entschieden.
|
||||||
* **Input:** User Message.
|
* **Input:** User Message.
|
||||||
* **Config:** `config/decision_engine.yaml` (Strategien & Keywords).
|
* **Config:** `decision_engine.yaml` (Strategien) + `types.yaml` (Objekte).
|
||||||
* **Komponenten:**
|
* **Komponenten:**
|
||||||
* **Fast Path:** Keyword Matching (CPU-schonend).
|
* **Traffic Control:** `LLMService` priorisiert Chat-Anfragen.
|
||||||
* **Slow Path:** LLM-basierter Semantic Router (für subtile Intents).
|
* **Question Detection:** Unterscheidung Frage vs. Befehl.
|
||||||
|
|
||||||
### 6.2 Schritt 1: Intent Detection (Hybrid)
|
### 6.2 Traffic Control (Priorisierung)
|
||||||
|
Der `LLMService` implementiert zwei Spuren basierend auf `app/services/llm_service.py` (v2.8.0):
|
||||||
|
* **Realtime (Chat):** `priority="realtime"`. Umgeht die Semaphore. Antwortet sofort.
|
||||||
|
* **Background (Import/Analyse):** `priority="background"`. Wartet in der Semaphore (`asyncio.Semaphore`), die lazy mit `MINDNET_LLM_BACKGROUND_LIMIT` initialisiert wird.
|
||||||
|
|
||||||
|
### 6.3 Schritt 1: Intent Detection (Question vs. Action)
|
||||||
Der Router ermittelt die Absicht (`Intent`) des Nutzers.
|
Der Router ermittelt die Absicht (`Intent`) des Nutzers.
|
||||||
1. **Keyword Scan (Fast Path):**
|
1. **Frage-Check:** Wenn der Input ein `?` enthält oder mit W-Wörtern beginnt, wird der **RAG-Modus** erzwungen (oder LLM-Entscheidung). Interviews werden hier unterdrückt.
|
||||||
* Iteration über alle Strategien in `decision_engine.yaml`.
|
2. **Keyword Scan (Fast Path):**
|
||||||
* Prüfung auf `trigger_keywords`.
|
* Prüfung auf `trigger_keywords` (Handlung) in `decision_engine.yaml`.
|
||||||
* **Best Match:** Bei mehreren Treffern gewinnt das längste/spezifischste Keyword (Robustheit gegen Shadowing).
|
* Prüfung auf `detection_keywords` (Objekt) in `types.yaml`.
|
||||||
2. **LLM Fallback (Slow Path):**
|
* Treffer -> **INTERVIEW Modus** (Erfassen).
|
||||||
* Nur aktiv, wenn `llm_fallback_enabled: true`.
|
3. **LLM Fallback (Slow Path):**
|
||||||
* Greift, wenn keine Keywords gefunden wurden.
|
* Greift, wenn keine Keywords passen. Sendet Query an LLM Router.
|
||||||
* Sendet die Query an das LLM mit einem Klassifizierungs-Prompt (`llm_router_prompt`).
|
|
||||||
* Ergebnis: `EMPATHY`, `DECISION`, `CODING` oder `FACT` (Default).
|
|
||||||
|
|
||||||
### 6.3 Schritt 2: Strategy Resolution (Late Binding)
|
### 6.4 Schritt 2: Strategy Resolution
|
||||||
Basierend auf dem Intent lädt der Router die Parameter:
|
Basierend auf dem Intent lädt der Router die Parameter:
|
||||||
* **inject_types:** Liste der Notiz-Typen, die erzwungen werden sollen (z.B. `["value", "goal"]` bei `DECISION`).
|
* **Bei RAG (FACT/DECISION):** `inject_types` für Strategic Retrieval.
|
||||||
* **prompt_template:** Schlüssel für das Template in `prompts.yaml` (z.B. `decision_template`, `empathy_template`).
|
* **Bei INTERVIEW (WP07):** `schemas` (Pflichtfelder) basierend auf der erkannten Ziel-Entität (`_detect_target_type`).
|
||||||
|
|
||||||
### 6.4 Schritt 3: Multi-Stage Retrieval
|
### 6.5 Schritt 3: Retrieval vs. Extraction
|
||||||
1. **Primary Retrieval:** Hybride Suche nach der User-Query (findet Fakten).
|
Der Router verzweigt hier:
|
||||||
|
|
||||||
|
**A) RAG Modus (FACT, DECISION, EMPATHY):**
|
||||||
|
1. **Primary Retrieval:** Hybride Suche nach der User-Query.
|
||||||
2. **Strategic Retrieval (Conditional):** Wenn `inject_types` definiert sind, erfolgt eine zweite Suche, die explizit auf diese Typen filtert.
|
2. **Strategic Retrieval (Conditional):** Wenn `inject_types` definiert sind, erfolgt eine zweite Suche, die explizit auf diese Typen filtert.
|
||||||
3. **Merge:** Ergebnisse werden dedupliziert zusammengeführt.
|
3. **Merge:** Ergebnisse werden dedupliziert zusammengeführt.
|
||||||
|
|
||||||
### 6.5 Schritt 4: Generation & Response
|
**B) Interview Modus (INTERVIEW):**
|
||||||
* **Context Enrichment:** Metadaten (`[VALUE]`, `[GOAL]`, `[SCORE]`) werden in den Context-String injiziert, um dem LLM die Rolle des Textstücks zu signalisieren.
|
1. **Kein Retrieval:** Der Kontext ist der Chat-Verlauf (oder initial die Query).
|
||||||
|
2. **Schema Injection:** Das Schema für den erkannten Typ (z.B. "Project") wird geladen.
|
||||||
|
3. **Prompt Assembly:** Der `interview_template` Prompt wird mit der Schema-Definition ("Ziel", "Status") gefüllt.
|
||||||
|
|
||||||
|
### 6.6 Schritt 4: Generation & Response
|
||||||
* **Templating:** Das LLM erhält den Prompt basierend auf dem gewählten Template.
|
* **Templating:** Das LLM erhält den Prompt basierend auf dem gewählten Template.
|
||||||
* **Execution:** Der `LLMService` führt den Call aus. Ein konfigurierbarer Timeout (`MINDNET_LLM_TIMEOUT`) fängt Cold-Start-Verzögerungen auf CPU-Hardware ab.
|
* **Execution:** Der `LLMService` führt den Call mit `priority="realtime"` aus.
|
||||||
* **Response:** Rückgabe enthält Antworttext, Quellenliste und den erkannten `intent` (für Debugging/Frontend).
|
* **Response:** Rückgabe enthält Antworttext (im Interview-Modus: Markdown Codeblock), Quellenliste und den erkannten `intent`.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 7. Feedback & Logging Architektur (WP04c)
|
## 7. Frontend Architektur (WP10)
|
||||||
|
|
||||||
|
Das Frontend ist eine **Streamlit-Anwendung** (`app/frontend/ui.py`), die als separater Prozess läuft und via HTTP mit dem Backend kommuniziert.
|
||||||
|
|
||||||
|
### 7.1 Kommunikation
|
||||||
|
* **Backend-URL:** Konfiguriert via `MINDNET_API_URL` (Default: `http://localhost:8002`).
|
||||||
|
* **Endpoints:**
|
||||||
|
* `/chat` (Interaktion)
|
||||||
|
* `/feedback` (Bewertungen)
|
||||||
|
* `/ingest/analyze` (Active Intelligence / Link-Vorschläge)
|
||||||
|
* `/ingest/save` (Persistence / Speichern im Vault)
|
||||||
|
* **Resilienz:** Das Frontend nutzt `MINDNET_API_TIMEOUT` (300s), um auf langsame Backend-Prozesse (Smart Edges) zu warten.
|
||||||
|
|
||||||
|
### 7.2 Features & UI-Logik
|
||||||
|
* **State Management:** Session-State speichert Chat-Verlauf und `query_id`.
|
||||||
|
* **Visualisierung:**
|
||||||
|
* **Intent Badges:** Zeigt Router-Entscheidung (`DECISION`, `INTERVIEW`, etc.).
|
||||||
|
* **Source Expanders:** Zeigt verwendete Chunks inkl. Score und "Why"-Explanation.
|
||||||
|
* **Sidebar:** Zeigt Suchhistorie (Log-basiert) und Konfiguration.
|
||||||
|
|
||||||
|
### 7.3 Draft-Editor & Healing Parser (Neu in WP10a/v2.5)
|
||||||
|
Wenn der Intent `INTERVIEW` ist, rendert die UI statt einer Textblase den **Draft-Editor**.
|
||||||
|
|
||||||
|
1. **Parsing:** Die Funktion `parse_markdown_draft` extrahiert den Codeblock aus der LLM-Antwort.
|
||||||
|
* **Healing:** Erkennt und repariert defekte YAML-Frontmatter (z.B. fehlendes schließendes `---`), falls das LLM unter Last Fehler macht.
|
||||||
|
2. **Sanitization (`normalize_meta_and_body`):**
|
||||||
|
* Prüft den YAML-Frontmatter auf unerlaubte Felder (Halluzinationen des LLMs).
|
||||||
|
* Verschiebt ungültige Felder (z.B. "Situation") in den Body der Notiz.
|
||||||
|
3. **Editor Widget:** `st.text_area` erlaubt das Bearbeiten des Inhalts vor dem Speichern.
|
||||||
|
4. **Save Action:** Speichert über `/ingest/save` atomar in Vault und DB. Erzeugt intelligente Dateinamen via `slugify`.
|
||||||
|
|
||||||
|
### 7.4 State Management (Resurrection Pattern)
|
||||||
|
Um Datenverlust bei Tab-Wechseln (Chat <-> Editor) zu verhindern, nutzt `ui.py` ein Persistenz-Muster:
|
||||||
|
* Daten liegen in `st.session_state[data_key]`.
|
||||||
|
* Widgets liegen in `st.session_state[widget_key]`.
|
||||||
|
* Callbacks (`on_change`) synchronisieren Widget -> Data.
|
||||||
|
* Beim Neu-Rendern wird Widget-State aus Data-State wiederhergestellt.
|
||||||
|
|
||||||
|
### 7.5 Deployment Ports
|
||||||
|
Zur sauberen Trennung von Prod und Dev laufen Frontend und Backend auf dedizierten Ports:
|
||||||
|
|
||||||
|
| Umgebung | Backend (FastAPI) | Frontend (Streamlit) |
|
||||||
|
| :--- | :--- | :--- |
|
||||||
|
| **Production** | 8001 | 8501 |
|
||||||
|
| **Development** | 8002 | 8502 |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 8. Feedback & Logging Architektur (WP04c)
|
||||||
|
|
||||||
Mindnet implementiert ein "Data Flywheel" zur späteren Optimierung (Self-Tuning).
|
Mindnet implementiert ein "Data Flywheel" zur späteren Optimierung (Self-Tuning).
|
||||||
|
|
||||||
### 7.1 Komponenten
|
### 8.1 Komponenten
|
||||||
* **Feedback Service (`app/services/feedback_service.py`):** Kapselt die Schreibzugriffe.
|
* **Feedback Service (`app/services/feedback_service.py`):** Kapselt die Schreibzugriffe.
|
||||||
* **Storage:** Lokales Dateisystem (`data/logs/`), Format JSONL (Line-delimited JSON).
|
* **Storage:** Lokales Dateisystem (`data/logs/`), Format JSONL (Line-delimited JSON).
|
||||||
|
|
||||||
### 7.2 Log-Dateien
|
### 8.2 Log-Dateien
|
||||||
1. **`search_history.jsonl`**:
|
1. **`search_history.jsonl`**:
|
||||||
* Speichert jede Anfrage an `/query` und `/chat`.
|
* Speichert jede Anfrage an `/query` und `/chat`.
|
||||||
* Enthält: `query_id`, `query_text`, `timestamp`, `hits` (inkl. `score_breakdown` Snapshots).
|
* Enthält: `query_id`, `query_text`, `timestamp`, `hits` (inkl. `score_breakdown` Snapshots).
|
||||||
@@ -323,27 +417,28 @@ Mindnet implementiert ein "Data Flywheel" zur späteren Optimierung (Self-Tuning
|
|||||||
2. **`feedback.jsonl`**:
|
2. **`feedback.jsonl`**:
|
||||||
* Speichert User-Reaktionen an `/feedback`.
|
* Speichert User-Reaktionen an `/feedback`.
|
||||||
* Enthält: `query_id`, `node_id`, `score` (1-5), `comment`.
|
* Enthält: `query_id`, `node_id`, `score` (1-5), `comment`.
|
||||||
|
* **Granularität:** Kann sich auf `generated_answer` (Global) oder eine spezifische `node_id` (Quelle) beziehen.
|
||||||
* Zweck: Labels ("War es gut?").
|
* Zweck: Labels ("War es gut?").
|
||||||
|
|
||||||
### 7.3 Traceability
|
### 8.3 Traceability
|
||||||
Die `query_id` (UUIDv4) wird im `/query` Response generiert und muss vom Client beim `/feedback` Aufruf mitgesendet werden. Dies ermöglicht den Join zwischen Snapshot und Bewertung.
|
Die `query_id` (UUIDv4) wird im `/query` Response generiert und muss vom Client beim `/feedback` Aufruf mitgesendet werden. Dies ermöglicht den Join zwischen Snapshot und Bewertung.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 8. Indizes & Performance
|
## 9. Indizes & Performance
|
||||||
|
|
||||||
Damit Qdrant performant bleibt, sind Payload-Indizes essenziell.
|
Damit Qdrant performant bleibt, sind Payload-Indizes essenziell.
|
||||||
|
|
||||||
**Erforderliche Indizes:**
|
**Erforderliche Indizes:**
|
||||||
* **Notes:** `note_id`, `type`, `tags`.
|
* **Notes:** `note_id`, `type`, `tags`.
|
||||||
* **Chunks:** `note_id`, `chunk_id`.
|
* **Chunks:** `note_id`, `chunk_id`, `type`.
|
||||||
* **Edges:** `source_id`, `target_id`, `kind`, `scope`, `note_id`.
|
* **Edges:** `source_id`, `target_id`, `kind`, `scope`, `note_id`.
|
||||||
|
|
||||||
Validierung erfolgt über `tests/ensure_indexes_and_show.py`.
|
Validierung erfolgt über `tests/ensure_indexes_and_show.py`.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 9. Offene Punkte / Known Limitations
|
## 10. Offene Punkte / Known Limitations
|
||||||
|
|
||||||
1. **Multi-Target Inline-Relations:**
|
1. **Multi-Target Inline-Relations:**
|
||||||
* `rel: similar_to [[A]] [[B]]` wird aktuell parser-seitig nicht unterstützt.
|
* `rel: similar_to [[A]] [[B]]` wird aktuell parser-seitig nicht unterstützt.
|
||||||
@@ -351,5 +446,5 @@ Validierung erfolgt über `tests/ensure_indexes_and_show.py`.
|
|||||||
2. **Unresolved Targets:**
|
2. **Unresolved Targets:**
|
||||||
* Kanten zu Notizen, die noch nicht existieren, werden mit `target_id="Titel"` angelegt.
|
* Kanten zu Notizen, die noch nicht existieren, werden mit `target_id="Titel"` angelegt.
|
||||||
* Heilung durch `scripts/resolve_unresolved_references.py` möglich.
|
* Heilung durch `scripts/resolve_unresolved_references.py` möglich.
|
||||||
3. **Vektor-Konfiguration für Edges:**
|
3. **Hardware-Last bei Smart Import:**
|
||||||
* `mindnet_edges` hat aktuell keine Vektoren (`vectors = null`). Eine semantische Suche *auf Kanten* ist noch nicht möglich.
|
* Der "Smart Edge" Import ist rechenintensiv. Trotz Traffic Control kann die Antwortzeit im Chat leicht steigen, wenn die GPU am VRAM-Limit arbeitet.
|
||||||
+113
-45
@@ -1,18 +1,18 @@
|
|||||||
# mindnet v2.2 – Pipeline Playbook
|
# mindnet v2.4 – Pipeline Playbook
|
||||||
**Datei:** `docs/mindnet_pipeline_playbook_v2.2.md`
|
**Datei:** `docs/mindnet_pipeline_playbook_v2.6.md`
|
||||||
**Stand:** 2025-12-09
|
**Stand:** 2025-12-12
|
||||||
**Status:** **FINAL** (Inkl. WP06 Decision Engine)
|
**Status:** **FINAL** (Inkl. Smart Edges & Traffic Control)
|
||||||
**Quellen:** `mindnet_v2_implementation_playbook.md`, `Handbuch.md`, `chunking_strategy.md`, `docs_mindnet_retriever.md`, `mindnet_admin_guide_v2.2.md`.
|
**Quellen:** `mindnet_v2_implementation_playbook.md`, `Handbuch.md`, `chunking_strategy.md`, `docs_mindnet_retriever.md`, `mindnet_admin_guide_v2.4.md`.
|
||||||
|
|
||||||
---
|
---
|
||||||
<details>
|
<details>
|
||||||
<summary>📖 <b>Inhaltsverzeichnis (Klicken zum Öffnen)</b></summary>
|
<summary>📖 <b>Inhaltsverzeichnis (Klicken zum Öffnen)</b></summary>
|
||||||
|
|
||||||
- [mindnet v2.2 – Pipeline Playbook](#mindnet-v22--pipeline-playbook)
|
- [mindnet v2.4 – Pipeline Playbook](#mindnet-v24--pipeline-playbook)
|
||||||
- [](#)
|
- [](#)
|
||||||
- [1. Zweck \& Einordnung](#1-zweck--einordnung)
|
- [1. Zweck \& Einordnung](#1-zweck--einordnung)
|
||||||
- [2. Die Import-Pipeline (Runbook)](#2-die-import-pipeline-runbook)
|
- [2. Die Import-Pipeline (Runbook)](#2-die-import-pipeline-runbook)
|
||||||
- [2.1 Der 12-Schritte-Prozess](#21-der-12-schritte-prozess)
|
- [2.1 Der 13-Schritte-Prozess (Async + Smart)](#21-der-13-schritte-prozess-async--smart)
|
||||||
- [2.2 Standard-Betrieb (Inkrementell)](#22-standard-betrieb-inkrementell)
|
- [2.2 Standard-Betrieb (Inkrementell)](#22-standard-betrieb-inkrementell)
|
||||||
- [2.3 Deployment \& Restart (Systemd)](#23-deployment--restart-systemd)
|
- [2.3 Deployment \& Restart (Systemd)](#23-deployment--restart-systemd)
|
||||||
- [2.4 Full Rebuild (Clean Slate)](#24-full-rebuild-clean-slate)
|
- [2.4 Full Rebuild (Clean Slate)](#24-full-rebuild-clean-slate)
|
||||||
@@ -21,29 +21,32 @@
|
|||||||
- [3.2 Payload-Felder](#32-payload-felder)
|
- [3.2 Payload-Felder](#32-payload-felder)
|
||||||
- [4. Edge-Erzeugung (Die V2-Logik)](#4-edge-erzeugung-die-v2-logik)
|
- [4. Edge-Erzeugung (Die V2-Logik)](#4-edge-erzeugung-die-v2-logik)
|
||||||
- [4.1 Prioritäten \& Provenance](#41-prioritäten--provenance)
|
- [4.1 Prioritäten \& Provenance](#41-prioritäten--provenance)
|
||||||
- [4.2 Typ-Defaults](#42-typ-defaults)
|
- [4.2 Smart Edge Allocation (WP15)](#42-smart-edge-allocation-wp15)
|
||||||
|
- [4.3 Typ-Defaults](#43-typ-defaults)
|
||||||
- [5. Retriever, Chat \& Generation (RAG Pipeline)](#5-retriever-chat--generation-rag-pipeline)
|
- [5. Retriever, Chat \& Generation (RAG Pipeline)](#5-retriever-chat--generation-rag-pipeline)
|
||||||
- [5.1 Retrieval (Hybrid)](#51-retrieval-hybrid)
|
- [5.1 Retrieval (Hybrid)](#51-retrieval-hybrid)
|
||||||
- [5.2 Intent Router (WP06)](#52-intent-router-wp06)
|
- [5.2 Intent Router (WP06/07)](#52-intent-router-wp0607)
|
||||||
- [5.3 Context Enrichment](#53-context-enrichment)
|
- [5.3 Context Enrichment](#53-context-enrichment)
|
||||||
- [5.4 Generation (LLM)](#54-generation-llm)
|
- [5.4 Generation (LLM) mit Traffic Control](#54-generation-llm-mit-traffic-control)
|
||||||
|
- [5.5 Active Intelligence Pipeline (Neu in v2.4)](#55-active-intelligence-pipeline-neu-in-v24)
|
||||||
- [6. Feedback \& Lernen (WP04c)](#6-feedback--lernen-wp04c)
|
- [6. Feedback \& Lernen (WP04c)](#6-feedback--lernen-wp04c)
|
||||||
- [7. Quality Gates \& Tests](#7-quality-gates--tests)
|
- [7. Quality Gates \& Tests](#7-quality-gates--tests)
|
||||||
- [7.1 Pflicht-Tests vor Commit](#71-pflicht-tests-vor-commit)
|
- [7.1 Pflicht-Tests vor Commit](#71-pflicht-tests-vor-commit)
|
||||||
- [7.2 Smoke-Test (E2E)](#72-smoke-test-e2e)
|
- [7.2 Smoke-Test (E2E)](#72-smoke-test-e2e)
|
||||||
- [8. Ausblick \& Roadmap (Technische Skizzen)](#8-ausblick--roadmap-technische-skizzen)
|
- [8. Ausblick \& Roadmap (Technische Skizzen)](#8-ausblick--roadmap-technische-skizzen)
|
||||||
- [8.1 WP-08: Self-Tuning (Skizze)](#81-wp-08-self-tuning-skizze)
|
- [8.1 WP-08: Self-Tuning (Skizze)](#81-wp-08-self-tuning-skizze)
|
||||||
|
- [16. Workpackage Status (v2.6.0)](#16-workpackage-status-v260)
|
||||||
|
|
||||||
</details>
|
</details>
|
||||||
---
|
---
|
||||||
|
|
||||||
## 1. Zweck & Einordnung
|
## 1. Zweck & Einordnung
|
||||||
|
|
||||||
Dieses Playbook ist das zentrale operative Handbuch für die **mindnet-Pipeline**. Es beschreibt, wie Daten vom Markdown-Vault in den Wissensgraphen (Qdrant) gelangen, wie der Retriever betrieben wird und wie die **RAG-Generierung** (inkl. Decision Engine) funktioniert.
|
Dieses Playbook ist das zentrale operative Handbuch für die **mindnet-Pipeline**. Es beschreibt, wie Daten vom Markdown-Vault in den Wissensgraphen (Qdrant) gelangen, wie der Retriever betrieben wird und wie die **RAG-Generierung** (inkl. Decision Engine & Interviewer) funktioniert.
|
||||||
|
|
||||||
**Zielgruppe:** Dev/Ops, Tech-Leads.
|
**Zielgruppe:** Dev/Ops, Tech-Leads.
|
||||||
**Scope:**
|
**Scope:**
|
||||||
* **Ist-Stand (WP01–WP06):** Import, Chunking, Edge-Erzeugung, Hybrider Retriever, RAG-Chat (Hybrid Router), Feedback Loop.
|
* **Ist-Stand (WP01–WP15):** Async Import, Smart Chunking, Edge-Erzeugung, Hybrider Retriever, RAG-Chat (Hybrid Router), Feedback Loop, Frontend, Draft Editor, Active Intelligence.
|
||||||
* **Roadmap (Ausblick):** Technische Skizze für Self-Tuning (WP08).
|
* **Roadmap (Ausblick):** Technische Skizze für Self-Tuning (WP08).
|
||||||
|
|
||||||
---
|
---
|
||||||
@@ -52,21 +55,32 @@ Dieses Playbook ist das zentrale operative Handbuch für die **mindnet-Pipeline*
|
|||||||
|
|
||||||
Der Import ist der kritischste Prozess ("Data Ingestion"). Er muss **deterministisch** und **idempotent** sein. Wir nutzen `scripts/import_markdown.py` als zentralen Entrypoint.
|
Der Import ist der kritischste Prozess ("Data Ingestion"). Er muss **deterministisch** und **idempotent** sein. Wir nutzen `scripts/import_markdown.py` als zentralen Entrypoint.
|
||||||
|
|
||||||
### 2.1 Der 12-Schritte-Prozess
|
### 2.1 Der 13-Schritte-Prozess (Async + Smart)
|
||||||
Gemäß WP03-Spezifikation läuft der Import intern wie folgt ab:
|
Seit v2.6 läuft der Import vollständig asynchron, nutzt intelligente Kantenvalidierung (Smart Edges) und drosselt sich selbst ("Traffic Control").
|
||||||
|
|
||||||
1. **Markdown lesen:** Rekursives Scannen des Vaults.
|
1. **Markdown lesen:** Rekursives Scannen des Vaults.
|
||||||
2. **Frontmatter extrahieren:** Validierung von Pflichtfeldern (`id`, `type`, `title`).
|
2. **Frontmatter extrahieren:** Validierung von Pflichtfeldern (`id`, `type`, `title`).
|
||||||
3. **Typauflösung:** Bestimmung des `type` via `types.yaml` (Prio: Frontmatter > Pfad > Default).
|
3. **Typauflösung:** Bestimmung des `type` via `types.yaml` (Prio: Frontmatter > Pfad > Default).
|
||||||
4. **Note-Payload generieren:** Erstellen des JSON-Objekts für `mindnet_notes`.
|
4. **Note-Payload generieren:** Erstellen des JSON-Objekts für `mindnet_notes`.
|
||||||
5. **Chunking anwenden:** Zerlegung des Textes basierend auf dem `chunk_profile` des Typs.
|
5. **Chunking anwenden:** Zerlegung des Textes basierend auf dem `chunk_profile` des Typs (z.B. `sliding_smart_edges`).
|
||||||
6. **Inline-Kanten finden:** Parsing von `[[rel:...]]` im Fließtext.
|
6. **Smart Edge Allocation (Neu in WP15):**
|
||||||
7. **Callout-Kanten finden:** Parsing von `> [!edge]` Blöcken.
|
* Wenn in `types.yaml` aktiviert (`enable_smart_edge_allocation`):
|
||||||
8. **Default-Edges erzeugen:** Anwendung der `edge_defaults` aus der Typ-Registry.
|
* Der `SemanticAnalyzer` sendet jeden Chunk an das LLM.
|
||||||
9. **Strukturkanten erzeugen:** `belongs_to` (Chunk->Note), `next`/`prev` (Sequenz).
|
* **Resilienz & Traffic Control:**
|
||||||
10. **Chunks upserten:** Schreiben in Qdrant (`mindnet_chunks`).
|
* **Priority:** Der Request nutzt `priority="background"`.
|
||||||
11. **Edges upserten:** Schreiben in Qdrant (`mindnet_edges`).
|
* **Semaphore:** Eine globale Semaphore (Limit: 2, konfigurierbar) verhindert System-Überlastung.
|
||||||
12. **Diagnose:** Automatischer Check der Integrität nach dem Lauf.
|
* **Retry & Backoff:** Bei Fehlern (Timeouts) wird bis zu 5-mal mit exponentieller Wartezeit wiederholt.
|
||||||
|
* **JSON Repair:** Der Analyzer erkennt fehlerhaftes JSON (z.B. Dict statt Liste) und repariert es automatisch.
|
||||||
|
* **Safety Fallback:** Schlagen alle Versuche fehl, werden die Kanten *allen* Chunks zugewiesen, um Datenverlust zu vermeiden.
|
||||||
|
* Ergebnis: Das LLM filtert irrelevante Links aus dem Chunk ("Broadcasting" verhindern).
|
||||||
|
7. **Inline-Kanten finden:** Parsing von `[[rel:...]]` im Fließtext.
|
||||||
|
8. **Callout-Kanten finden:** Parsing von `> [!edge]` Blöcken.
|
||||||
|
9. **Default-Edges erzeugen:** Anwendung der `edge_defaults` aus der Typ-Registry.
|
||||||
|
10. **Strukturkanten erzeugen:** `belongs_to`, `next`, `prev` (Sequenz).
|
||||||
|
11. **Embedding & Upsert (Async):**
|
||||||
|
* Generierung der Vektoren via `nomic-embed-text` (768 Dim).
|
||||||
|
12. **Strict Mode:** Der Prozess bricht sofort ab, wenn ein Embedding leer ist oder die Dimension `0` hat.
|
||||||
|
13. **Diagnose:** Automatischer Check der Integrität nach dem Lauf.
|
||||||
|
|
||||||
### 2.2 Standard-Betrieb (Inkrementell)
|
### 2.2 Standard-Betrieb (Inkrementell)
|
||||||
Für regelmäßige Updates (z.B. Cronjob). Erkennt Änderungen via Hash.
|
Für regelmäßige Updates (z.B. Cronjob). Erkennt Änderungen via Hash.
|
||||||
@@ -88,22 +102,28 @@ Für regelmäßige Updates (z.B. Cronjob). Erkennt Änderungen via Hash.
|
|||||||
* `--sync-deletes`: Entfernt Notizen aus Qdrant, die im Vault gelöscht wurden.
|
* `--sync-deletes`: Entfernt Notizen aus Qdrant, die im Vault gelöscht wurden.
|
||||||
|
|
||||||
### 2.3 Deployment & Restart (Systemd)
|
### 2.3 Deployment & Restart (Systemd)
|
||||||
Nach einem Import oder Code-Update muss der API-Prozess neu gestartet werden.
|
Nach einem Import oder Code-Update müssen die API-Prozesse neu gestartet werden.
|
||||||
|
|
||||||
# Neustart des Produktions-Services
|
# Neustart des Produktions-Services (API + UI)
|
||||||
sudo systemctl restart mindnet-prod
|
sudo systemctl restart mindnet-prod
|
||||||
|
sudo systemctl restart mindnet-ui-prod
|
||||||
|
|
||||||
# Prüfung
|
# Prüfung
|
||||||
sudo systemctl status mindnet-prod
|
sudo systemctl status mindnet-prod
|
||||||
|
|
||||||
### 2.4 Full Rebuild (Clean Slate)
|
### 2.4 Full Rebuild (Clean Slate)
|
||||||
Notwendig bei Änderungen an `types.yaml` (z.B. neue Chunk-Größen) oder Embedding-Modellen.
|
Notwendig bei Änderungen an `types.yaml` (z.B. Smart Edges an/aus) oder beim Wechsel des Embedding-Modells.
|
||||||
|
|
||||||
# 1. Qdrant Collections löschen und neu anlegen (Wipe inkl. Schema)
|
**WICHTIG:** Vorher das Modell pullen, sonst schlägt der Import fehl!
|
||||||
|
|
||||||
|
# 0. Modell sicherstellen (WICHTIG für v2.4+)
|
||||||
|
ollama pull nomic-embed-text
|
||||||
|
|
||||||
|
# 1. Qdrant Collections löschen und neu anlegen (Wipe inkl. Schema 768d)
|
||||||
python3 -m scripts.reset_qdrant --mode wipe --prefix "mindnet" --yes
|
python3 -m scripts.reset_qdrant --mode wipe --prefix "mindnet" --yes
|
||||||
|
|
||||||
# 2. Vollständiger Import aller Dateien
|
# 2. Vollständiger Import aller Dateien
|
||||||
python3 -m scripts.import_markdown --vault ./vault --prefix "mindnet" --apply
|
python3 -m scripts.import_markdown --vault ./vault --prefix "mindnet" --apply --force
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -113,10 +133,10 @@ Das Chunking ist profilbasiert und typgesteuert.
|
|||||||
|
|
||||||
### 3.1 Chunk-Profile
|
### 3.1 Chunk-Profile
|
||||||
In `types.yaml` definiert. Standard-Profile (in `chunk_config.py` implementiert):
|
In `types.yaml` definiert. Standard-Profile (in `chunk_config.py` implementiert):
|
||||||
* `short`: Max 128 Tokens (z.B. für Logs, Chats).
|
* `sliding_short`: Max 128 Tokens (z.B. für Logs, Chats).
|
||||||
* `medium`: Max 256 Tokens (z.B. für Konzepte).
|
* `sliding_standard`: Max 512 Tokens (Standard für Massendaten).
|
||||||
* `long`: Max 512 Tokens (z.B. für Essays, Projekte).
|
* `sliding_smart_edges`: Sliding Window, optimiert für LLM-Analyse (Fließtext).
|
||||||
* `by_heading`: Trennt strikt an Überschriften.
|
* `structured_smart_edges`: Trennt strikt an Überschriften (für strukturierte Daten).
|
||||||
|
|
||||||
### 3.2 Payload-Felder
|
### 3.2 Payload-Felder
|
||||||
Jeder Chunk erhält zwei Text-Felder:
|
Jeder Chunk erhält zwei Text-Felder:
|
||||||
@@ -127,7 +147,7 @@ Jeder Chunk erhält zwei Text-Felder:
|
|||||||
|
|
||||||
## 4. Edge-Erzeugung (Die V2-Logik)
|
## 4. Edge-Erzeugung (Die V2-Logik)
|
||||||
|
|
||||||
In v2.2 entstehen Kanten nach strenger Priorität.
|
In v2.6 entstehen Kanten nach strenger Priorität.
|
||||||
|
|
||||||
### 4.1 Prioritäten & Provenance
|
### 4.1 Prioritäten & Provenance
|
||||||
Der Importer setzt `provenance`, `rule_id` und `confidence` automatisch:
|
Der Importer setzt `provenance`, `rule_id` und `confidence` automatisch:
|
||||||
@@ -137,10 +157,17 @@ Der Importer setzt `provenance`, `rule_id` und `confidence` automatisch:
|
|||||||
| **1** | Inline | `[[rel:depends_on X]]` | `inline:rel` | ~0.95 |
|
| **1** | Inline | `[[rel:depends_on X]]` | `inline:rel` | ~0.95 |
|
||||||
| **2** | Callout | `> [!edge] related_to: [[X]]` | `callout:edge` | ~0.90 |
|
| **2** | Callout | `> [!edge] related_to: [[X]]` | `callout:edge` | ~0.90 |
|
||||||
| **3** | Wikilink | `[[X]]` | `explicit:wikilink` | 1.00 |
|
| **3** | Wikilink | `[[X]]` | `explicit:wikilink` | 1.00 |
|
||||||
| **4** | Default | *(via types.yaml)* | `edge_defaults:...` | ~0.70 |
|
| **4** | Smart | *(via LLM Filter)* | `smart:llm_filter` | 0.90 |
|
||||||
| **5** | Struktur | *(automatisch)* | `structure:...` | 1.00 |
|
| **5** | Default | *(via types.yaml)* | `edge_defaults:...` | ~0.70 |
|
||||||
|
| **6** | Struktur | *(automatisch)* | `structure:...` | 1.00 |
|
||||||
|
|
||||||
### 4.2 Typ-Defaults
|
### 4.2 Smart Edge Allocation (WP15)
|
||||||
|
Dieser Mechanismus löst das Problem, dass Chunks sonst alle Links der Note erben.
|
||||||
|
* **Prozess:** Der `SemanticAnalyzer` prüft jeden Chunk: "Ist Link X im Kontext von Chunk Y relevant?"
|
||||||
|
* **Ergebnis:** Kanten werden präzise an den Chunk gebunden, nicht global an die Note.
|
||||||
|
* **Steuerung:** Das Feature wird in `types.yaml` per Typ aktiviert (`enable_smart_edge_allocation: true`).
|
||||||
|
|
||||||
|
### 4.3 Typ-Defaults
|
||||||
Wenn in `types.yaml` für einen Typ `edge_defaults` definiert sind, werden diese **additiv** zu expliziten Links erzeugt.
|
Wenn in `types.yaml` für einen Typ `edge_defaults` definiert sind, werden diese **additiv** zu expliziten Links erzeugt.
|
||||||
* *Beispiel:* Note Typ `project` verlinkt `[[Tool A]]`.
|
* *Beispiel:* Note Typ `project` verlinkt `[[Tool A]]`.
|
||||||
* *Ergebnis:* Kante `references` (explizit) UND Kante `depends_on` (Default).
|
* *Ergebnis:* Kante `references` (explizit) UND Kante `depends_on` (Default).
|
||||||
@@ -154,22 +181,35 @@ Der Datenfluss endet nicht beim Finden. Er geht weiter bis zur Antwort.
|
|||||||
### 5.1 Retrieval (Hybrid)
|
### 5.1 Retrieval (Hybrid)
|
||||||
Der `/chat` Endpunkt nutzt **Hybrid Retrieval** (Semantic + Graph), um auch logisch verbundene, aber textlich unterschiedliche Notizen zu finden (z.B. Decisions zu einem Projekt).
|
Der `/chat` Endpunkt nutzt **Hybrid Retrieval** (Semantic + Graph), um auch logisch verbundene, aber textlich unterschiedliche Notizen zu finden (z.B. Decisions zu einem Projekt).
|
||||||
|
|
||||||
### 5.2 Intent Router (WP06)
|
### 5.2 Intent Router (WP06/07)
|
||||||
Der Request durchläuft den **Hybrid Router**:
|
Der Request durchläuft den **Hybrid Router v5**:
|
||||||
1. **Fast Path:** Prüfung auf `trigger_keywords` aus `decision_engine.yaml`.
|
1. **Question Detection:** Ist es eine Frage (`?`, W-Wörter)? -> RAG Modus. Interviews werden hier blockiert.
|
||||||
2. **Slow Path:** Falls kein Keyword matched und `llm_fallback_enabled=true`, klassifiziert das LLM den Intent (`DECISION`, `EMPATHY`, `FACT`, `CODING`).
|
2. **Keyword Scan:** Enthält es Keywords aus `types.yaml` (Objekt, z.B. "Projekt") oder `decision_engine.yaml` (Action, z.B. "erstellen")? -> INTERVIEW Modus.
|
||||||
3. **Result:** Auswahl der Strategie und der `inject_types` (z.B. Values & Goals).
|
3. **LLM Fallback:** Wenn unklar, entscheidet das LLM.
|
||||||
|
|
||||||
### 5.3 Context Enrichment
|
### 5.3 Context Enrichment
|
||||||
Der Router (`chat.py`) reichert die gefundenen Chunks mit Metadaten an:
|
Der Router (`chat.py`) reichert die gefundenen Chunks mit Metadaten an:
|
||||||
* **Typ-Injection:** `[DECISION]`, `[PROJECT]`.
|
* **Typ-Injection:** `[DECISION]`, `[PROJECT]`.
|
||||||
* **Reasoning-Infos:** `(Score: 0.75)`.
|
* **Reasoning-Infos:** `(Score: 0.75)`.
|
||||||
* **Zweck:** Ermöglicht kleinen Modellen (Phi-3) das Erkennen von logischen Rollen ("Warum?" vs "Was?").
|
|
||||||
|
|
||||||
### 5.4 Generation (LLM)
|
### 5.4 Generation (LLM) mit Traffic Control
|
||||||
* **Engine:** Ollama (lokal).
|
* **Engine:** Ollama (lokal).
|
||||||
* **Modell:** `phi3:mini` (Standard).
|
* **Modell:** `phi3:mini` (Standard).
|
||||||
* **Prompting:** Template wird basierend auf Intent gewählt (`decision_template` vs `empathy_template`).
|
* **Prompting:** Template wird basierend auf Intent gewählt (`decision_template`, `interview_template` etc.).
|
||||||
|
* **Traffic Control:** Der `LLMService` unterscheidet:
|
||||||
|
* **Chat-Requests** (`priority="realtime"`) -> Sofortige Ausführung.
|
||||||
|
* **Import-Requests** (`priority="background"`) -> Gedrosselt durch Semaphore (Standard: 2).
|
||||||
|
|
||||||
|
### 5.5 Active Intelligence Pipeline (Neu in v2.4)
|
||||||
|
Ein paralleler Datenfluss im Frontend ("Draft Editor") zur Unterstützung des Autors.
|
||||||
|
1. **Trigger:** User klickt "Analyse starten" oder tippt.
|
||||||
|
2. **Service:** `ingest/analyze` (Backend).
|
||||||
|
3. **Discovery:**
|
||||||
|
* **Sliding Window:** Zerlegt Text in Abschnitte.
|
||||||
|
* **Embedding:** Vektorisiert Abschnitte via Nomic (Async).
|
||||||
|
* **Exact Match:** Sucht nach Aliases ("KI-Gedächtnis").
|
||||||
|
* **Matrix Logic:** Bestimmt Kanten-Typ (`experience` -> `based_on` -> `value`).
|
||||||
|
4. **Feedback:** UI zeigt Vorschläge (`[[rel:...]]`) zum Einfügen an.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -203,7 +243,10 @@ Prüft am laufenden System (Prod oder Dev), ob Semantik, Graph und Feedback funk
|
|||||||
# Retriever Test
|
# Retriever Test
|
||||||
python scripts/test_retriever_smoke.py --mode hybrid --top-k 5
|
python scripts/test_retriever_smoke.py --mode hybrid --top-k 5
|
||||||
|
|
||||||
# Chat / Decision Engine Test (Neu WP06)
|
# Intelligence Test (WP11)
|
||||||
|
curl -X POST "http://localhost:8002/ingest/analyze" -d '{"text": "mindnet", "type": "journal"}'
|
||||||
|
|
||||||
|
# Decision Engine Test (WP06)
|
||||||
python tests/test_wp06_decision.py -p 8002 -e EMPATHY -q "Alles ist grau"
|
python tests/test_wp06_decision.py -p 8002 -e EMPATHY -q "Alles ist grau"
|
||||||
|
|
||||||
# Feedback Test
|
# Feedback Test
|
||||||
@@ -220,4 +263,29 @@ Wie entwickeln wir die Pipeline weiter?
|
|||||||
**Ansatz:** Ein Offline-Learning-Skript `scripts/optimize_weights.py`.
|
**Ansatz:** Ein Offline-Learning-Skript `scripts/optimize_weights.py`.
|
||||||
1. **Load:** Liest `search_history.jsonl` und joint mit `feedback.jsonl` via `query_id`.
|
1. **Load:** Liest `search_history.jsonl` und joint mit `feedback.jsonl` via `query_id`.
|
||||||
2. **Analyze:** Korrelation Scores vs. User-Rating.
|
2. **Analyze:** Korrelation Scores vs. User-Rating.
|
||||||
3. **Optimize:** Vorschlag neuer Gewichte für `retriever.yaml`.
|
3. **Optimize:** Vorschlag neuer Gewichte für `retriever.yaml`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 16. Workpackage Status (v2.6.0)
|
||||||
|
|
||||||
|
Aktueller Implementierungsstand der Module.
|
||||||
|
|
||||||
|
| WP | Titel | Status | Anmerkung |
|
||||||
|
| :--- | :--- | :--- | :--- |
|
||||||
|
| **WP01** | Knowledge Design | 🟢 Live | Typen, Frontmatter definiert. |
|
||||||
|
| **WP02** | Chunking Strategy | 🟢 Live | Profilbasiertes Chunking aktiv. |
|
||||||
|
| **WP03** | Edge Logic / Import | 🟢 Live | Neue Importer-Pipeline mit Provenance. |
|
||||||
|
| **WP04a**| Retriever Scoring | 🟢 Live | Hybrider Score (Semantik + Graph). |
|
||||||
|
| **WP04b**| Explanation Layer | 🟢 Live | API liefert Reasons & Breakdown. |
|
||||||
|
| **WP04c**| Feedback Loop | 🟢 Live | Logging (JSONL) & Traceability aktiv. |
|
||||||
|
| **WP05** | Persönlichkeit / Chat | 🟢 Live | RAG-Integration mit Context Enrichment. |
|
||||||
|
| **WP06** | Decision Engine | 🟢 Live | Hybrid Router, Strategic Retrieval. |
|
||||||
|
| **WP07** | Interview Assistent | 🟢 Live | **One-Shot Extractor & Schemas aktiv.** |
|
||||||
|
| **WP08** | Self-Tuning | 🔴 Geplant | Auto-Adjustment der Gewichte. |
|
||||||
|
| **WP10** | Chat Interface | 🟢 Live | Web-Interface (Streamlit). |
|
||||||
|
| **WP10a**| Draft Editor | 🟢 Live | **Interaktives UI für WP07 Drafts.** |
|
||||||
|
| **WP11** | Backend Intelligence | 🟢 Live | **Async Ingestion, Nomic Embeddings, Matrix Logic.** |
|
||||||
|
| **WP15** | Smart Edge Allocation | 🟢 Live | **LLM-Filter & Traffic Control aktiv.** |
|
||||||
|
| **WP16** | Auto-Discovery | 🟡 Geplant | UX & Retrieval Tuning. |
|
||||||
|
| **WP17** | Conversational Memory | 🟡 Geplant | Dialog-Gedächtnis. |
|
||||||
+97
-66
@@ -1,11 +1,11 @@
|
|||||||
# Mindnet v2.2 – User Guide
|
# Mindnet v2.4 – User Guide
|
||||||
**Datei:** `docs/mindnet_user_guide_v2.2.md`
|
**Datei:** `docs/mindnet_user_guide_v2.6.md`
|
||||||
**Stand:** 2025-12-09
|
**Stand:** 2025-12-12
|
||||||
**Status:** **FINAL** (Inkl. RAG & Multi-Personality Chat)
|
**Status:** **FINAL** (Inkl. Smart Edges, Hybrid Router v5 & Healing UI)
|
||||||
**Quellen:** `knowledge_design.md`, `wp04_retriever_scoring.md`, `Programmplan_V2.2.md`, `Handbuch.md`.
|
**Quellen:** `knowledge_design.md`, `wp04_retriever_scoring.md`, `Programmplan_V2.2.md`, `Handbuch.md`.
|
||||||
|
|
||||||
> **Willkommen bei Mindnet.**
|
> **Willkommen bei Mindnet.**
|
||||||
> Dies ist dein persönliches Wissensnetzwerk und dein Digitaler Zwilling. Es hilft dir beim Erinnern, beim Entscheiden und beim Reflektieren.
|
> Dies ist dein persönliches Wissensnetzwerk und dein Digitaler Zwilling. Es hilft dir beim Erinnern, beim Entscheiden, beim Reflektieren und beim **Erstellen von Inhalten**.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -18,91 +18,122 @@ Wenn du nach "Projekt Alpha" suchst, findet Mindnet nicht nur das Dokument. Es f
|
|||||||
* **Abhängigkeiten:** "Technologie X wird benötigt".
|
* **Abhängigkeiten:** "Technologie X wird benötigt".
|
||||||
* **Entscheidungen:** "Warum nutzen wir X?".
|
* **Entscheidungen:** "Warum nutzen wir X?".
|
||||||
* **Ähnliches:** "Projekt Beta war ähnlich".
|
* **Ähnliches:** "Projekt Beta war ähnlich".
|
||||||
|
* **Neu in v2.6 (Smart Edges):** Mindnet zeigt dir präzise Verknüpfungen an, die für den spezifischen Textabschnitt relevant sind, statt pauschal alle Links der Notiz anzuzeigen.
|
||||||
|
|
||||||
### 1.2 Der Zwilling (Die Personas)
|
### 1.2 Der Zwilling (Die Personas)
|
||||||
Seit Version 2.3.1 passt Mindnet seinen Charakter dynamisch an deine Frage an:
|
Mindnet passt seinen Charakter dynamisch an deine Frage an:
|
||||||
1. **Der Bibliothekar (FACT):** Liefert präzise Fakten und Definitionen.
|
1. **Der Bibliothekar (FACT):** Liefert präzise Fakten und Definitionen.
|
||||||
2. **Der Berater (DECISION):** Hilft dir beim Abwägen, basierend auf deinen Werten und Zielen.
|
2. **Der Berater (DECISION):** Hilft dir beim Abwägen, basierend auf deinen Werten und Zielen.
|
||||||
3. **Der Spiegel (EMPATHY):** Hört zu und antwortet basierend auf deinen Erfahrungen ("Ich"-Perspektive).
|
3. **Der Spiegel (EMPATHY):** Hört zu und antwortet basierend auf deinen Erfahrungen ("Ich"-Perspektive).
|
||||||
4. **Der Coder (CODING):** Liefert technische Schnipsel ohne Smalltalk.
|
4. **Der Analyst (INTERVIEW):** Hilft dir, neue Notizen zu entwerfen und strukturiert zu erfassen.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 2. Den Chat steuern (Intents)
|
## 2. Die Oberfläche (Web UI)
|
||||||
|
|
||||||
Du steuerst die Persönlichkeit von Mindnet durch deine Wortwahl. Das System nutzt einen **Hybrid Router**, der sowohl auf Schlüsselwörter als auch auf die Bedeutung achtet.
|
Seit Version 2.3.1 bedienst du Mindnet über eine grafische Oberfläche im Browser.
|
||||||
|
|
||||||
### 2.1 Modus: Entscheidung ("Der Berater")
|
### 2.1 Der Chat-Bereich
|
||||||
Wenn du vor einer Wahl stehst, hilft Mindnet dir, konform zu deinen Prinzipien zu bleiben.
|
* **Eingabe:** Unten findest du das Textfeld.
|
||||||
|
* **Intent-Badge:** Über jeder Antwort zeigt ein kleines Label (z.B. **⚖️ Intent: DECISION**), in welchem Modus das System arbeitet und ob dies durch ein Schlüsselwort oder die KI erkannt wurde.
|
||||||
|
* **Quellen-Karten:** Unter der Antwort findest du ausklappbare Karten ("Expanders").
|
||||||
|
* **Grüner Punkt:** Hohe Relevanz (Score > 0.8).
|
||||||
|
* **Gelber Punkt:** Mittlere Relevanz.
|
||||||
|
* **Klick darauf:** Zeigt den Textauszug und die **Begründung** ("Warum wurde das gefunden?").
|
||||||
|
|
||||||
* **Auslöser (Keywords):** "Soll ich...", "Was ist deine Meinung?", "Strategie für...", "Vor- und Nachteile".
|
### 2.2 Die Sidebar (Einstellungen & Verlauf)
|
||||||
* **Was passiert:** Mindnet lädt deine **Werte** (`type: value`) und **Ziele** (`type: goal`) in den Kontext und prüft die Fakten dagegen.
|
* **Modus-Wahl:** Umschalten zwischen "💬 Chat" und "📝 Manueller Editor".
|
||||||
* **Beispiel-Dialog:**
|
* *Neu in v2.4:* Der manuelle Editor speichert deine Eingaben auch beim Wechseln der Tabs ("State Resurrection").
|
||||||
* *Du:* "Soll ich Tool X nutzen?"
|
* **Verlauf:** Die letzten Suchanfragen sind hier gelistet. Ein Klick führt die Suche erneut aus.
|
||||||
* *Mindnet:* "Nein. Tool X speichert Daten in den USA. Das verstößt gegen dein Prinzip 'Privacy First' und dein Ziel 'Digitale Autarkie'."
|
* **Settings:**
|
||||||
|
* **Top-K:** Wie viele Quellen sollen gelesen werden? (Standard: 5).
|
||||||
### 2.2 Modus: Empathie ("Der Spiegel")
|
* **Explanation Layer:** Schaltet die "Warum"-Erklärungen an/aus.
|
||||||
Wenn du frustriert bist oder reflektieren willst, wechselt Mindnet in den "Ich"-Modus.
|
|
||||||
|
|
||||||
* **Auslöser (Keywords & Semantik):** "Ich fühle mich...", "Traurig", "Gestresst", "Alles ist sinnlos", "Ich bin überfordert".
|
|
||||||
* **Was passiert:** Mindnet lädt deine **Erfahrungen** (`type: experience`) und **Glaubenssätze** (`type: belief`). Es antwortet verständnisvoll und zitiert deine eigenen Lektionen.
|
|
||||||
* **Beispiel-Dialog:**
|
|
||||||
* *Du:* "Ich bin total überfordert, nichts funktioniert."
|
|
||||||
* *Mindnet:* "Das Gefühl kenne ich. Erinnere dich an die Situation im Projekt X ('Der Durchbruch nach der Krise'). Damals hat uns das Mantra 'Einfach weitermachen, der Nebel lichtet sich' geholfen."
|
|
||||||
|
|
||||||
### 2.3 Modus: Coding ("Der Techniker")
|
|
||||||
* **Auslöser:** "Code", "Python", "Funktion", "Syntax".
|
|
||||||
* **Was passiert:** Mindnet antwortet kurz, prägnant und liefert Code-Blöcke. Smalltalk wird reduziert.
|
|
||||||
|
|
||||||
### 2.4 Modus: Fakten (Standard)
|
|
||||||
* **Auslöser:** Alles andere. "Was ist Qdrant?", "Zusammenfassung von X".
|
|
||||||
* **Was passiert:** Standard-Suche nach Wissen ohne spezielle Filter.
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 3. Ergebnisse interpretieren (Explanation Layer)
|
## 3. Den Chat steuern (Intents)
|
||||||
|
|
||||||
|
Du steuerst die Persönlichkeit von Mindnet durch deine Wortwahl. Das System nutzt einen **Hybrid Router v5**, der intelligent zwischen Frage und Befehl unterscheidet.
|
||||||
|
|
||||||
|
### 3.1 Frage-Modus (Wissen abrufen)
|
||||||
|
Sobald du ein Fragezeichen `?` benutzt oder Wörter wie "Wer", "Wie", "Was", "Soll ich" verwendest, sucht Mindnet nach Antworten (**RAG**).
|
||||||
|
|
||||||
|
* **Entscheidung ("Soll ich?"):** Mindnet lädt deine **Werte** (`type: value`) und **Ziele** (`type: goal`) in den Kontext und prüft die Fakten dagegen.
|
||||||
|
* *Beispiel:* "Soll ich Tool X nutzen?" -> "Nein, Tool X speichert Daten in den USA. Das verstößt gegen dein Prinzip 'Privacy First' und dein Ziel 'Digitale Autarkie'."
|
||||||
|
* **Empathie ("Ich fühle..."):** Mindnet lädt deine **Erfahrungen** (`type: experience`) und **Glaubenssätze** (`type: belief`). Es antwortet verständnisvoll und zitiert deine eigenen Lektionen.
|
||||||
|
* *Beispiel:* "Ich bin frustriert." -> "Das erinnert mich an Projekt Y, da ging es uns ähnlich..."
|
||||||
|
|
||||||
|
### 3.2 Befehls-Modus (Wissen erfassen / Interview)
|
||||||
|
Wenn du keine Frage stellst, sondern eine Absicht äußerst, wechselt Mindnet in den **Interview-Modus**.
|
||||||
|
|
||||||
|
* **Auslöser:** "Neues Projekt", "Notiz erstellen", "Ich will etwas festhalten", "Neue Entscheidung dokumentieren".
|
||||||
|
* **Was passiert:** Mindnet sucht nicht im Archiv, sondern öffnet den **Draft-Editor**.
|
||||||
|
* **Beispiel:** "Neue Erfahrung: Streit am Recyclinghof." -> Das System erstellt sofort eine strukturierte Notiz mit den Feldern "Situation", "Reaktion" und "Learning".
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. Ergebnisse interpretieren (Explanation Layer)
|
||||||
|
|
||||||
Mindnet liefert nicht einfach nur Treffer. Es liefert eine **Begründung** (Explanation), warum es etwas gefunden hat.
|
Mindnet liefert nicht einfach nur Treffer. Es liefert eine **Begründung** (Explanation), warum es etwas gefunden hat.
|
||||||
|
|
||||||
### 3.1 Die Gründe ("Reasons")
|
### 4.1 Die Gründe ("Reasons")
|
||||||
Das System sagt dir in natürlicher Sprache, warum ein Treffer relevant ist:
|
Öffne eine Quellen-Karte, um zu sehen:
|
||||||
* *"Hohe textuelle Übereinstimmung."* (Semantik)
|
* *"Hohe textuelle Übereinstimmung."* (Semantik)
|
||||||
* *"Bevorzugt aufgrund des Typs 'decision'."* (Wichtigkeit)
|
* *"Bevorzugt aufgrund des Typs 'decision'."* (Wichtigkeit)
|
||||||
* *"Verweist auf 'Projekt X' via 'depends_on'."* (Graph-Kontext)
|
* *"Verweist auf 'Projekt X' via 'depends_on'."* (Graph-Kontext)
|
||||||
|
|
||||||
### 3.2 Der Score Breakdown
|
|
||||||
Wenn du es genau wissen willst, schau auf die Aufschlüsselung:
|
|
||||||
|
|
||||||
Score = (Text) + (Typ-Bonus) + (Vernetzungs-Bonus)
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 4. Neues Wissen beisteuern (Authoring)
|
|
||||||
|
|
||||||
Mindnet lebt von deinem Input. Du musst kein Techniker sein, um gutes Wissen zu designen. Siehe dazu das **Knowledge Design Manual** für Details.
|
|
||||||
|
|
||||||
### 4.1 Die Goldene Regel: "Verlinke semantisch"
|
|
||||||
Statt einfach nur `[[Link]]` zu schreiben, versuche zu sagen, *wie* es zusammenhängt.
|
|
||||||
* Hängt es davon ab? -> `[[rel:depends_on Ziel]]`
|
|
||||||
* Ist es ähnlich? -> `[[rel:similar_to Ziel]]`
|
|
||||||
|
|
||||||
### 4.2 Typen nutzen (Wichtig!)
|
|
||||||
Setze im Frontmatter deiner Notizen den richtigen Typ. Das ist der wichtigste Hebel für den Chat:
|
|
||||||
* Willst du, dass Mindnet etwas als **Regel** nutzt? -> `type: principle`
|
|
||||||
* Willst du, dass Mindnet dich an eine **Lektion** erinnert? -> `type: experience`
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 5. Feedback & Lernen
|
## 5. Feedback & Lernen
|
||||||
|
|
||||||
Mindnet wird schlauer, wenn du es pflegst.
|
Mindnet wird schlauer, wenn du es pflegst. Nutze die Feedback-Funktionen im Chat:
|
||||||
|
|
||||||
### 5.1 Feedback geben (Data Flywheel)
|
### 5.1 Globales Feedback (Antwort-Qualität)
|
||||||
Das System zeichnet auf, welche Ergebnisse es liefert. Du kannst Treffer bewerten (geplant für WP-10 UI).
|
* **Wie:** Klicke auf die **Sterne (1-5)** unter der Antwort.
|
||||||
In Zukunft analysiert das System diese Daten, um seine Gewichte selbstständig anzupassen (Self-Tuning).
|
* **Bedeutung:** Bewertet, wie gut die generierte Antwort war (Prompting, Tonfall).
|
||||||
|
|
||||||
### 5.2 Ergebnis fehlt? Troubleshooting
|
### 5.2 Granulares Feedback (Quellen-Relevanz)
|
||||||
Wenn Mindnet etwas nicht findet:
|
* **Wie:** Klicke innerhalb einer Quellen-Karte auf die **Smileys (Faces)**.
|
||||||
1. **Existiert** die Notiz im Vault? (Dateiname korrekt?)
|
* **Bedeutung:**
|
||||||
2. **Typ korrekt?** (Eine Erfahrung als `concept` getaggt wird im Empathie-Modus vielleicht übersehen).
|
* 😞 (Sad): Diese Quelle ist irrelevant/falsch. (Senkt zukünftig das Gewicht).
|
||||||
3. **Keywords?** (Wenn du "grau" sagst, aber in der Notiz nur "schlecht" steht, füge das Wort "grau" zur Notiz hinzu).
|
* 😐 (Neutral): Okay, aber nicht entscheidend.
|
||||||
|
* 😀 (Grin): Das ist der perfekte Treffer! (Stärkt diesen Typ/Kante).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. Neues Wissen beisteuern (Authoring)
|
||||||
|
|
||||||
|
Mindnet lebt von deinem Input. Du musst kein Techniker sein, um gutes Wissen zu designen. Siehe dazu das **Knowledge Design Manual** für Details.
|
||||||
|
|
||||||
|
### 6.1 Die Goldene Regel: "Verlinke semantisch"
|
||||||
|
Statt einfach nur `[[Link]]` zu schreiben, versuche zu sagen, *wie* es zusammenhängt.
|
||||||
|
* Hängt es davon ab? -> `[[rel:depends_on Ziel]]`
|
||||||
|
* Ist es ähnlich? -> `[[rel:similar_to Ziel]]`
|
||||||
|
|
||||||
|
### 6.2 Typen nutzen (Wichtig!)
|
||||||
|
Setze im Frontmatter deiner Notizen den richtigen Typ. Das ist der wichtigste Hebel für den Chat:
|
||||||
|
* Willst du, dass Mindnet etwas als **Regel** nutzt? -> `type: principle`
|
||||||
|
* Willst du, dass Mindnet dich an eine **Lektion** erinnert? -> `type: experience`
|
||||||
|
|
||||||
|
### 6.3 Der Interview-Assistent (Drafting)
|
||||||
|
Mindnet kann dir helfen, Markdown-Notizen zu schreiben.
|
||||||
|
|
||||||
|
1. **Start:** Schreibe im Chat: *"Ich möchte ein neues Projekt 'Apollo' starten, Ziel ist die Mondlandung."*
|
||||||
|
2. **Generierung:** Mindnet erkennt den Wunsch (`INTERVIEW`), analysiert den Satz und erstellt **sofort** einen Entwurf.
|
||||||
|
3. **Editor:** Die UI wechselt von der Chat-Blase zu einem **Draft-Editor**.
|
||||||
|
* Du siehst das generierte Frontmatter (`type: project`, `status: draft`).
|
||||||
|
* **Healing UI (v2.5):** Falls das LLM Syntax-Fehler gemacht hat (z.B. fehlendes `---`), hat der Editor das bereits automatisch repariert.
|
||||||
|
* Du siehst den Body-Text mit Platzhaltern (`[TODO]`), wo Infos fehlten (z.B. Stakeholder).
|
||||||
|
4. **Finalisierung:** Ergänze die fehlenden Infos direkt im Editor und klicke auf **Download** oder **Kopieren**.
|
||||||
|
5. **Speichern:** Klicke auf "💾 Speichern". Die Notiz landet sofort im Vault und im Index.
|
||||||
|
|
||||||
|
### 6.4 Der Intelligence-Workflow (Neu in v2.4)
|
||||||
|
Wenn du Texte im **manuellen Editor** schreibst, unterstützt dich Mindnet aktiv bei der Vernetzung:
|
||||||
|
|
||||||
|
1. **Schreiben:** Tippe deinen Text im Tab **"✏️ Inhalt"**.
|
||||||
|
2. **Analysieren:** Wechsle zum Tab **"🧠 Intelligence"** und klicke auf **"🔍 Analyse starten"**. Das System scannt deinen Text (Vektor-Suche & Exact Match).
|
||||||
|
3. **Vorschläge nutzen:**
|
||||||
|
* **Exakte Treffer:** Das System erkennt Begriffe wie "KI-Gedächtnis" automatisch als Alias für "Mindnet (System)".
|
||||||
|
* **Semantische Treffer:** Das System findet inhaltlich verwandte Notizen.
|
||||||
|
* **Klick auf "➕ Einfügen":** Fügt den Link (z.B. `[[rel:related_to Mindnet]]`) an der Cursor-Position oder am Ende ein.
|
||||||
|
4. **Speichern:** Klicke auf "💾 Speichern & Indizieren". Der Text wird sofort in den Vault geschrieben und in Qdrant indiziert.
|
||||||
+4
-6
@@ -11,25 +11,23 @@ qdrant-client>=1.15.1
|
|||||||
pydantic>=2.11.7
|
pydantic>=2.11.7
|
||||||
numpy>=2.3.2
|
numpy>=2.3.2
|
||||||
|
|
||||||
# --- Markdown & Parsing (Hier fehlten Pakete!) ---
|
# --- Markdown & Parsing ---
|
||||||
python-frontmatter>=1.1.0
|
python-frontmatter>=1.1.0
|
||||||
# WICHTIG: Das fehlte und verursachte den Fehler
|
|
||||||
markdown-it-py>=3.0.0
|
markdown-it-py>=3.0.0
|
||||||
# WICHTIG: Für types.yaml und retriever.yaml
|
|
||||||
PyYAML>=6.0.2
|
PyYAML>=6.0.2
|
||||||
python-slugify>=8.0.4
|
python-slugify>=8.0.4
|
||||||
|
|
||||||
# --- KI & Embeddings ---
|
# --- KI & Embeddings ---
|
||||||
sentence-transformers>=5.1.0
|
sentence-transformers>=5.1.0
|
||||||
# Torch wird meist durch sentence-transformers geholt,
|
|
||||||
# aber wir listen es explizit für Stabilität
|
|
||||||
torch>=2.0.0
|
torch>=2.0.0
|
||||||
|
|
||||||
# --- Utilities ---
|
# --- Utilities ---
|
||||||
# WICHTIG: Damit .env Dateien gelesen werden
|
|
||||||
python-dotenv>=1.1.1
|
python-dotenv>=1.1.1
|
||||||
requests>=2.32.5
|
requests>=2.32.5
|
||||||
tqdm>=4.67.1
|
tqdm>=4.67.1
|
||||||
|
|
||||||
# --- Testing ---
|
# --- Testing ---
|
||||||
pytest>=8.4.2
|
pytest>=8.4.2
|
||||||
|
|
||||||
|
# --- Frontend (WP-10) ---
|
||||||
|
streamlit>=1.39.0
|
||||||
+82
-568
@@ -1,593 +1,107 @@
|
|||||||
#!/usr/bin/env python3
|
#!/usr/bin/env python3
|
||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""
|
"""
|
||||||
scripts/import_markdown.py
|
scripts/import_markdown.py
|
||||||
|
CLI-Tool zum Importieren von Markdown-Dateien in Qdrant.
|
||||||
Zweck
|
Updated for Mindnet v2.3.6 (Async Ingestion Support).
|
||||||
-----
|
|
||||||
- Liest Markdown-Notizen aus einem Vault ein
|
|
||||||
- Erzeugt Note-Payload, Chunk-Payloads (+ optionale Embeddings) und Edges
|
|
||||||
- Schreibt alles idempotent in Qdrant (Notes, Chunks, Edges)
|
|
||||||
- Integriert eine optionale Type-Registry (types.yaml), um z. B. chunk_profile
|
|
||||||
und retriever_weight pro Notiz-Typ zu steuern.
|
|
||||||
|
|
||||||
Wesentliche Fixes ggü. vorherigen fehlerhaften Ständen
|
|
||||||
------------------------------------------------------
|
|
||||||
- `embed_texts` wird optional importiert und defensiv geprüft (kein NameError mehr)
|
|
||||||
- `effective_chunk_profile` / `effective_retriever_weight` und Registry-Helfer
|
|
||||||
sind VOR `main()` definiert (kein NameError mehr)
|
|
||||||
- `retriever_weight` wird in Note- und Chunk-Payload zuverlässig gesetzt
|
|
||||||
- Robuste Kantenbildung; Fehler bei Edges blockieren Notes/Chunks nicht
|
|
||||||
- Korrekte Verwendung von `scroll_filter` beim Qdrant-Client
|
|
||||||
- `--purge-before-upsert` entfernt alte Chunks/Edges einer Note vor dem Upsert
|
|
||||||
|
|
||||||
Qdrant / ENV
|
|
||||||
------------
|
|
||||||
- QDRANT_URL | QDRANT_HOST/QDRANT_PORT | QDRANT_API_KEY
|
|
||||||
- COLLECTION_PREFIX (Default: mindnet), via --prefix überschreibbar
|
|
||||||
- VECTOR_DIM (Default: 384)
|
|
||||||
- MINDNET_NOTE_SCOPE_REFS: true|false (Default: false)
|
|
||||||
- MINDNET_TYPES_FILE: Pfad zu types.yaml (optional; Default: ./types.yaml)
|
|
||||||
|
|
||||||
Beispiele
|
|
||||||
---------
|
|
||||||
# Standard (Body, parsed, canonical)
|
|
||||||
python3 -m scripts.import_markdown --vault ./vault
|
|
||||||
|
|
||||||
# Erstimport nach truncate (Create-Fall)
|
|
||||||
python3 -m scripts.import_markdown --vault ./vault --apply --purge-before-upsert
|
|
||||||
|
|
||||||
# Nur eine Datei (Diagnose)
|
|
||||||
python3 -m scripts.import_markdown --vault ./vault --only-path ./vault/30_projects/project-demo.md --apply
|
|
||||||
|
|
||||||
# Sync-Deletes (Dry-Run → Apply)
|
|
||||||
python3 -m scripts.import_markdown --vault ./vault --sync-deletes
|
|
||||||
python3 -m scripts.import_markdown --vault ./vault --sync-deletes --apply
|
|
||||||
"""
|
"""
|
||||||
from __future__ import annotations
|
import asyncio
|
||||||
|
|
||||||
import argparse
|
|
||||||
import json
|
|
||||||
import os
|
import os
|
||||||
import sys
|
import argparse
|
||||||
from typing import Dict, List, Optional, Tuple, Any, Set
|
import logging
|
||||||
|
from pathlib import Path
|
||||||
from dotenv import load_dotenv
|
from dotenv import load_dotenv
|
||||||
from qdrant_client.http import models as rest
|
|
||||||
|
|
||||||
# --- Projekt-Imports ---
|
import logging
|
||||||
from app.core.parser import (
|
# Setzt das Level global auf INFO, damit Sie den Fortschritt sehen
|
||||||
read_markdown,
|
logging.basicConfig(level=logging.INFO, format='%(asctime)s [%(levelname)s] %(message)s')
|
||||||
normalize_frontmatter,
|
|
||||||
validate_required_frontmatter,
|
|
||||||
)
|
|
||||||
from app.core.note_payload import make_note_payload
|
|
||||||
from app.core.chunker import assemble_chunks
|
|
||||||
from app.core.chunk_payload import make_chunk_payloads
|
|
||||||
try:
|
|
||||||
from app.core.derive_edges import build_edges_for_note
|
|
||||||
except Exception: # pragma: no cover
|
|
||||||
from app.core.edges import build_edges_for_note # type: ignore
|
|
||||||
from app.core.qdrant import (
|
|
||||||
QdrantConfig,
|
|
||||||
get_client,
|
|
||||||
ensure_collections,
|
|
||||||
ensure_payload_indexes,
|
|
||||||
)
|
|
||||||
from app.core.qdrant_points import (
|
|
||||||
points_for_chunks,
|
|
||||||
points_for_note,
|
|
||||||
points_for_edges,
|
|
||||||
upsert_batch,
|
|
||||||
)
|
|
||||||
|
|
||||||
# embeddings sind optional (z. B. im reinen Payload-Backfill)
|
# Wenn Sie TIEFE Einblicke wollen, setzen Sie den SemanticAnalyzer spezifisch auf DEBUG:
|
||||||
try:
|
logging.getLogger("app.services.semantic_analyzer").setLevel(logging.DEBUG)
|
||||||
from app.core.embed import embed_texts # optional
|
|
||||||
except Exception: # pragma: no cover
|
|
||||||
embed_texts = None
|
|
||||||
|
|
||||||
|
# Importiere den neuen Async Service
|
||||||
|
# Stellen wir sicher, dass der Pfad stimmt (Pythonpath)
|
||||||
|
import sys
|
||||||
|
sys.path.append(os.getcwd())
|
||||||
|
|
||||||
# ---------------------------------------------------------------------
|
from app.core.ingestion import IngestionService
|
||||||
# Type-Registry (types.yaml) – Helper (robust, optional)
|
|
||||||
# ---------------------------------------------------------------------
|
|
||||||
|
|
||||||
def _env(name: str, default: Optional[str] = None) -> Optional[str]:
|
logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s")
|
||||||
v = os.getenv(name)
|
logger = logging.getLogger("importer")
|
||||||
return v if v is not None else default
|
|
||||||
|
|
||||||
def _load_json_or_yaml(path: str) -> dict:
|
async def main_async(args):
|
||||||
import io
|
vault_path = Path(args.vault).resolve()
|
||||||
data: dict = {}
|
if not vault_path.exists():
|
||||||
if not path or not os.path.exists(path):
|
logger.error(f"Vault path does not exist: {vault_path}")
|
||||||
return data
|
return
|
||||||
try:
|
|
||||||
import yaml # type: ignore
|
|
||||||
with io.open(path, "r", encoding="utf-8") as f:
|
|
||||||
data = yaml.safe_load(f) or {}
|
|
||||||
if not isinstance(data, dict):
|
|
||||||
return {}
|
|
||||||
return data
|
|
||||||
except Exception:
|
|
||||||
# YAML evtl. nicht installiert – versuche JSON
|
|
||||||
try:
|
|
||||||
with io.open(path, "r", encoding="utf-8") as f:
|
|
||||||
data = json.load(f)
|
|
||||||
if not isinstance(data, dict):
|
|
||||||
return {}
|
|
||||||
return data
|
|
||||||
except Exception:
|
|
||||||
return {}
|
|
||||||
|
|
||||||
def load_type_registry() -> dict:
|
# Service initialisieren (startet Async Clients)
|
||||||
# Reihenfolge: ENV > ./types.yaml (im aktuellen Arbeitsverzeichnis)
|
logger.info(f"Initializing IngestionService (Prefix: {args.prefix})")
|
||||||
p = _env("MINDNET_TYPES_FILE", None)
|
service = IngestionService(collection_prefix=args.prefix)
|
||||||
if p and os.path.exists(p):
|
|
||||||
return _load_json_or_yaml(p)
|
logger.info(f"Scanning {vault_path}...")
|
||||||
fallback = os.path.abspath("./config/types.yaml") if os.path.exists("./config/types.yaml") else os.path.abspath("./types.yaml")
|
files = list(vault_path.rglob("*.md"))
|
||||||
return _load_json_or_yaml(fallback)
|
# Exclude .obsidian folder if present
|
||||||
|
files = [f for f in files if ".obsidian" not in str(f)]
|
||||||
|
files.sort()
|
||||||
|
|
||||||
|
logger.info(f"Found {len(files)} markdown files.")
|
||||||
|
|
||||||
def get_type_config(note_type: Optional[str], reg: dict) -> dict:
|
stats = {"processed": 0, "skipped": 0, "errors": 0}
|
||||||
if not reg or not isinstance(reg, dict):
|
|
||||||
return {}
|
|
||||||
types = reg.get("types", {}) if isinstance(reg.get("types"), dict) else {}
|
|
||||||
if note_type and isinstance(note_type, str) and note_type in types:
|
|
||||||
return types[note_type] or {}
|
|
||||||
# Fallback: concept
|
|
||||||
return types.get("concept", {}) or {}
|
|
||||||
|
|
||||||
def resolve_note_type(requested: Optional[str], reg: dict) -> str:
|
# Wir nutzen eine Semaphore, um nicht zu viele Files gleichzeitig zu öffnen/embedden
|
||||||
if requested and isinstance(requested, str):
|
sem = asyncio.Semaphore(5) # Max 5 concurrent files to avoid OOM or Rate Limit
|
||||||
return requested
|
|
||||||
# Fallback wenn nichts gesetzt ist
|
|
||||||
types = reg.get("types", {}) if isinstance(reg.get("types"), dict) else {}
|
|
||||||
return "concept" if "concept" in types else (requested or "concept")
|
|
||||||
|
|
||||||
def effective_chunk_profile(note_type: str, reg: dict) -> Optional[str]:
|
async def process_with_limit(f_path):
|
||||||
"""Resolve chunk_profile for type or from defaults/global.
|
async with sem:
|
||||||
Accepts symbolic profiles: short|medium|long|default.
|
|
||||||
"""
|
|
||||||
cfg = get_type_config(note_type, reg)
|
|
||||||
prof = (cfg.get("chunk_profile") if isinstance(cfg, dict) else None)
|
|
||||||
if isinstance(prof, str) and prof:
|
|
||||||
return prof
|
|
||||||
# defaults fallbacks
|
|
||||||
for key in ("defaults", "default", "global"):
|
|
||||||
dcfg = reg.get(key) if isinstance(reg, dict) else None
|
|
||||||
if isinstance(dcfg, dict):
|
|
||||||
dprof = dcfg.get("chunk_profile")
|
|
||||||
if isinstance(dprof, str) and dprof:
|
|
||||||
return dprof
|
|
||||||
return "default"
|
|
||||||
|
|
||||||
def effective_retriever_weight(note_type: str, reg: dict) -> Optional[float]:
|
|
||||||
"""Resolve retriever_weight for type or defaults; returns float.
|
|
||||||
"""
|
|
||||||
cfg = get_type_config(note_type, reg)
|
|
||||||
w = (cfg.get("retriever_weight") if isinstance(cfg, dict) else None)
|
|
||||||
try:
|
|
||||||
if w is not None:
|
|
||||||
return float(w)
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
# defaults fallbacks
|
|
||||||
for key in ("defaults", "default", "global"):
|
|
||||||
dcfg = reg.get(key) if isinstance(reg, dict) else None
|
|
||||||
if isinstance(dcfg, dict):
|
|
||||||
dw = dcfg.get("retriever_weight")
|
|
||||||
try:
|
try:
|
||||||
if dw is not None:
|
res = await service.process_file(
|
||||||
return float(dw)
|
file_path=str(f_path),
|
||||||
except Exception:
|
vault_root=str(vault_path),
|
||||||
pass
|
force_replace=args.force,
|
||||||
return 1.0
|
apply=args.apply,
|
||||||
|
purge_before=True
|
||||||
|
|
||||||
# ---------------------------------------------------------------------
|
|
||||||
# Sonstige Helper
|
|
||||||
# ---------------------------------------------------------------------
|
|
||||||
|
|
||||||
def iter_md(root: str) -> List[str]:
|
|
||||||
out: List[str] = []
|
|
||||||
for dirpath, _, filenames in os.walk(root):
|
|
||||||
for fn in filenames:
|
|
||||||
if not fn.lower().endswith(".md"):
|
|
||||||
continue
|
|
||||||
p = os.path.join(dirpath, fn)
|
|
||||||
pn = p.replace("\\", "/")
|
|
||||||
if any(ex in pn for ex in ["/.obsidian/", "/_backup_frontmatter/", "/_imported/"]):
|
|
||||||
continue
|
|
||||||
out.append(p)
|
|
||||||
return sorted(out)
|
|
||||||
|
|
||||||
def collections(prefix: str) -> Tuple[str, str, str]:
|
|
||||||
return f"{prefix}_notes", f"{prefix}_chunks", f"{prefix}_edges"
|
|
||||||
|
|
||||||
def fetch_existing_note_payload(client, prefix: str, note_id: str) -> Optional[Dict]:
|
|
||||||
notes_col, _, _ = collections(prefix)
|
|
||||||
f = rest.Filter(must=[rest.FieldCondition(key="note_id", match=rest.MatchValue(value=note_id))])
|
|
||||||
points, _ = client.scroll(
|
|
||||||
collection_name=notes_col,
|
|
||||||
scroll_filter=f, # wichtig: scroll_filter (nicht: filter)
|
|
||||||
with_payload=True,
|
|
||||||
with_vectors=False,
|
|
||||||
limit=1,
|
|
||||||
)
|
|
||||||
if not points:
|
|
||||||
return None
|
|
||||||
return points[0].payload or {}
|
|
||||||
|
|
||||||
def list_qdrant_note_ids(client, prefix: str) -> Set[str]:
|
|
||||||
notes_col, _, _ = collections(prefix)
|
|
||||||
out: Set[str] = set()
|
|
||||||
next_page = None
|
|
||||||
while True:
|
|
||||||
pts, next_page = client.scroll(
|
|
||||||
collection_name=notes_col,
|
|
||||||
with_payload=True,
|
|
||||||
with_vectors=False,
|
|
||||||
limit=256,
|
|
||||||
offset=next_page,
|
|
||||||
)
|
|
||||||
if not pts:
|
|
||||||
break
|
|
||||||
for p in pts:
|
|
||||||
pl = p.payload or {}
|
|
||||||
nid = pl.get("note_id")
|
|
||||||
if isinstance(nid, str):
|
|
||||||
out.add(nid)
|
|
||||||
if next_page is None:
|
|
||||||
break
|
|
||||||
return out
|
|
||||||
|
|
||||||
def purge_note_artifacts(client, prefix: str, note_id: str) -> None:
|
|
||||||
_, chunks_col, edges_col = collections(prefix)
|
|
||||||
filt = rest.Filter(must=[rest.FieldCondition(key="note_id", match=rest.MatchValue(value=note_id))])
|
|
||||||
for col in (chunks_col, edges_col):
|
|
||||||
try:
|
|
||||||
client.delete(
|
|
||||||
collection_name=col,
|
|
||||||
points_selector=rest.FilterSelector(filter=filt),
|
|
||||||
wait=True
|
|
||||||
)
|
|
||||||
except Exception as e:
|
|
||||||
print(json.dumps({"note_id": note_id, "warn": f"delete in {col} via filter failed: {e}"}))
|
|
||||||
|
|
||||||
def delete_note_everywhere(client, prefix: str, note_id: str) -> None:
|
|
||||||
notes_col, chunks_col, edges_col = collections(prefix)
|
|
||||||
filt = rest.Filter(must=[rest.FieldCondition(key="note_id", match=rest.MatchValue(value=note_id))])
|
|
||||||
for col in (edges_col, chunks_col, notes_col):
|
|
||||||
try:
|
|
||||||
client.delete(
|
|
||||||
collection_name=col,
|
|
||||||
points_selector=rest.FilterSelector(filter=filt),
|
|
||||||
wait=True
|
|
||||||
)
|
|
||||||
except Exception as e:
|
|
||||||
print(json.dumps({"note_id": note_id, "warn": f"delete in {col} failed: {e}"}))
|
|
||||||
|
|
||||||
|
|
||||||
# --- Neu: Existenz-Checks für Artefakte (fehlertoleranter Rebuild) ---
|
|
||||||
|
|
||||||
def _has_any_point(client, collection: str, note_id: str) -> bool:
|
|
||||||
"""Prüft, ob es mind. einen Punkt mit note_id in der Collection gibt."""
|
|
||||||
filt = rest.Filter(must=[rest.FieldCondition(key="note_id", match=rest.MatchValue(value=note_id))])
|
|
||||||
pts, _ = client.scroll(
|
|
||||||
collection_name=collection,
|
|
||||||
scroll_filter=filt,
|
|
||||||
with_payload=False,
|
|
||||||
with_vectors=False,
|
|
||||||
limit=1,
|
|
||||||
)
|
|
||||||
return bool(pts)
|
|
||||||
|
|
||||||
def artifacts_missing(client, prefix: str, note_id: str) -> Tuple[bool, bool]:
|
|
||||||
"""Gibt (chunks_missing, edges_missing) zurück."""
|
|
||||||
_, chunks_col, edges_col = collections(prefix)
|
|
||||||
chunks_missing = not _has_any_point(client, chunks_col, note_id)
|
|
||||||
edges_missing = not _has_any_point(client, edges_col, note_id)
|
|
||||||
return chunks_missing, edges_missing
|
|
||||||
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------------
|
|
||||||
# Main
|
|
||||||
# ---------------------------------------------------------------------
|
|
||||||
|
|
||||||
def _resolve_mode(m: Optional[str]) -> str:
|
|
||||||
m = (m or "body").strip().lower()
|
|
||||||
return m if m in {"body", "frontmatter", "full"} else "body"
|
|
||||||
|
|
||||||
def main() -> None:
|
|
||||||
load_dotenv()
|
|
||||||
|
|
||||||
ap = argparse.ArgumentParser(
|
|
||||||
prog="scripts.import_markdown",
|
|
||||||
description="Importiert Markdown-Notizen in Qdrant (Notes/Chunks/Edges)."
|
|
||||||
)
|
|
||||||
ap.add_argument("--vault", required=True, help="Pfad zum Vault (Ordner mit .md-Dateien)")
|
|
||||||
ap.add_argument("--only-path", help="Nur diese Datei verarbeiten (absolut oder relativ)")
|
|
||||||
ap.add_argument("--apply", action="store_true", help="Schreibt nach Qdrant (sonst Dry-Run)")
|
|
||||||
ap.add_argument("--purge-before-upsert", action="store_true", help="Alte Chunks/Edges der Note vorher löschen")
|
|
||||||
ap.add_argument("--force-replace", action="store_true", help="Note/Chunks/Edges unabhängig von Hash neu schreiben")
|
|
||||||
ap.add_argument("--note-id", help="Nur Notes mit dieser ID verarbeiten (Filter)")
|
|
||||||
ap.add_argument("--note-scope-refs", action="store_true", help="Note-scope References/Backlinks erzeugen")
|
|
||||||
ap.add_argument("--hash-mode", help="body|frontmatter|full (Default body)")
|
|
||||||
ap.add_argument("--hash-source", help="parsed|raw (Default parsed)")
|
|
||||||
ap.add_argument("--hash-normalize", help="canonical|none (Default canonical)")
|
|
||||||
ap.add_argument("--compare-text", action="store_true", help="Parsed fulltext zusätzlich direkt vergleichen")
|
|
||||||
ap.add_argument("--baseline-modes", action="store_true", help="Fehlende Hash-Varianten still nachtragen (Notes)")
|
|
||||||
ap.add_argument("--sync-deletes", action="store_true", help="Qdrant->Vault Lösch-Sync (Dry-Run; mit --apply ausführen)")
|
|
||||||
ap.add_argument("--prefix", help="Collection-Prefix (überschreibt ENV COLLECTION_PREFIX)")
|
|
||||||
args = ap.parse_args()
|
|
||||||
|
|
||||||
mode = _resolve_mode(args.hash_mode) # body|frontmatter|full
|
|
||||||
src = _env("MINDNET_HASH_SOURCE", args.hash_source or "parsed") # parsed|raw
|
|
||||||
norm = _env("MINDNET_HASH_NORMALIZE", args.hash_normalize or "canonical") # canonical|none
|
|
||||||
note_scope_refs_env = (_env("MINDNET_NOTE_SCOPE_REFS", "false") == "true")
|
|
||||||
note_scope_refs = args.note_scope_refs or note_scope_refs_env
|
|
||||||
compare_text = args.compare_text or (_env("MINDNET_COMPARE_TEXT", "false") == "true")
|
|
||||||
|
|
||||||
# Qdrant
|
|
||||||
cfg = QdrantConfig.from_env()
|
|
||||||
if args.prefix:
|
|
||||||
cfg.prefix = args.prefix.strip()
|
|
||||||
client = get_client(cfg)
|
|
||||||
ensure_collections(client, cfg.prefix, cfg.dim)
|
|
||||||
ensure_payload_indexes(client, cfg.prefix)
|
|
||||||
|
|
||||||
# Type-Registry laden (optional)
|
|
||||||
reg = load_type_registry()
|
|
||||||
|
|
||||||
root = os.path.abspath(args.vault)
|
|
||||||
|
|
||||||
# Dateiliste
|
|
||||||
if args.only_path:
|
|
||||||
only = os.path.abspath(args.only_path)
|
|
||||||
files = [only]
|
|
||||||
else:
|
|
||||||
files = iter_md(root)
|
|
||||||
if not files:
|
|
||||||
print("Keine Markdown-Dateien gefunden.", file=sys.stderr)
|
|
||||||
sys.exit(2)
|
|
||||||
|
|
||||||
# Optional: Sync-Deletes vorab
|
|
||||||
if args.sync_deletes:
|
|
||||||
vault_note_ids: Set[str] = set()
|
|
||||||
for path in files:
|
|
||||||
try:
|
|
||||||
parsed = read_markdown(path)
|
|
||||||
if not parsed:
|
|
||||||
continue
|
|
||||||
fm = normalize_frontmatter(parsed.frontmatter)
|
|
||||||
nid = fm.get("id")
|
|
||||||
if isinstance(nid, str):
|
|
||||||
vault_note_ids.add(nid)
|
|
||||||
except Exception:
|
|
||||||
continue
|
|
||||||
qdrant_note_ids = list_qdrant_note_ids(client, cfg.prefix)
|
|
||||||
to_delete = sorted(qdrant_note_ids - vault_note_ids)
|
|
||||||
print(json.dumps({
|
|
||||||
"action": "sync-deletes",
|
|
||||||
"prefix": cfg.prefix,
|
|
||||||
"qdrant_total": len(qdrant_note_ids),
|
|
||||||
"vault_total": len(vault_note_ids),
|
|
||||||
"to_delete_count": len(to_delete),
|
|
||||||
"to_delete": to_delete[:50] + (["…"] if len(to_delete) > 50 else [])
|
|
||||||
}, ensure_ascii=False))
|
|
||||||
if args.apply and to_delete:
|
|
||||||
for nid in to_delete:
|
|
||||||
print(json.dumps({"action": "delete", "note_id": nid, "decision": "apply"}))
|
|
||||||
delete_note_everywhere(client, cfg.prefix, nid)
|
|
||||||
|
|
||||||
key_current = f"{mode}:{src}:{norm}"
|
|
||||||
|
|
||||||
processed = 0
|
|
||||||
for path in files:
|
|
||||||
try:
|
|
||||||
parsed = read_markdown(path)
|
|
||||||
if not parsed:
|
|
||||||
continue
|
|
||||||
except Exception as e:
|
|
||||||
print(json.dumps({"path": path, "error": f"read_markdown failed: {type(e).__name__}: {e}"}))
|
|
||||||
continue
|
|
||||||
|
|
||||||
# --- Frontmatter prüfen ---
|
|
||||||
try:
|
|
||||||
fm = normalize_frontmatter(parsed.frontmatter)
|
|
||||||
validate_required_frontmatter(fm)
|
|
||||||
except Exception as e:
|
|
||||||
print(json.dumps({"path": path, "error": f"Frontmatter invalid: {type(e).__name__}: {e}"}))
|
|
||||||
continue
|
|
||||||
|
|
||||||
if args.note_id and not args.only_path and fm.get("id") != args.note_id:
|
|
||||||
continue
|
|
||||||
|
|
||||||
processed += 1
|
|
||||||
|
|
||||||
# --- Type-Registry anwenden (chunk_profile / retriever_weight) ---
|
|
||||||
try:
|
|
||||||
note_type = resolve_note_type(fm.get("type"), reg)
|
|
||||||
except Exception:
|
|
||||||
note_type = (fm.get("type") or "concept")
|
|
||||||
fm["type"] = note_type or fm.get("type") or "concept"
|
|
||||||
|
|
||||||
prof = effective_chunk_profile(note_type, reg)
|
|
||||||
if prof:
|
|
||||||
fm["chunk_profile"] = prof
|
|
||||||
|
|
||||||
weight = effective_retriever_weight(note_type, reg)
|
|
||||||
if weight is not None:
|
|
||||||
try:
|
|
||||||
fm["retriever_weight"] = float(weight)
|
|
||||||
except Exception:
|
|
||||||
pass # falls FM string-inkonsistent ist
|
|
||||||
|
|
||||||
# --- Payload aufbauen (inkl. Hashes) ---
|
|
||||||
try:
|
|
||||||
note_pl = make_note_payload(
|
|
||||||
parsed,
|
|
||||||
vault_root=root,
|
|
||||||
hash_mode=mode,
|
|
||||||
hash_normalize=norm,
|
|
||||||
hash_source=src,
|
|
||||||
file_path=path,
|
|
||||||
)
|
|
||||||
except Exception as e:
|
|
||||||
print(json.dumps({"path": path, "error": f"make_note_payload failed: {type(e).__name__}: {e}"}))
|
|
||||||
continue
|
|
||||||
|
|
||||||
if not note_pl.get("fulltext"):
|
|
||||||
note_pl["fulltext"] = getattr(parsed, "body", "") or ""
|
|
||||||
|
|
||||||
# retriever_weight sicher in Note-Payload spiegeln (für spätere Filter)
|
|
||||||
if "retriever_weight" not in note_pl and fm.get("retriever_weight") is not None:
|
|
||||||
try:
|
|
||||||
note_pl["retriever_weight"] = float(fm.get("retriever_weight"))
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
|
|
||||||
note_id = note_pl.get("note_id") or fm.get("id")
|
|
||||||
if not note_id:
|
|
||||||
print(json.dumps({"path": path, "error": "Missing note_id after payload build"}))
|
|
||||||
continue
|
|
||||||
|
|
||||||
# --- bestehenden Payload laden (zum Diff) ---
|
|
||||||
old_payload = None if args.force_replace else fetch_existing_note_payload(client, cfg.prefix, note_id)
|
|
||||||
has_old = old_payload is not None
|
|
||||||
|
|
||||||
old_hashes = (old_payload or {}).get("hashes") or {}
|
|
||||||
old_hash_exact = old_hashes.get(key_current)
|
|
||||||
new_hash_exact = (note_pl.get("hashes") or {}).get(key_current)
|
|
||||||
needs_baseline = (old_hash_exact is None)
|
|
||||||
|
|
||||||
hash_changed = (old_hash_exact is not None and new_hash_exact is not None and old_hash_exact != new_hash_exact)
|
|
||||||
|
|
||||||
text_changed = False
|
|
||||||
if compare_text:
|
|
||||||
old_text = (old_payload or {}).get("fulltext") or ""
|
|
||||||
new_text = note_pl.get("fulltext") or ""
|
|
||||||
text_changed = (old_text != new_text)
|
|
||||||
|
|
||||||
changed = args.force_replace or (not has_old) or hash_changed or text_changed
|
|
||||||
do_baseline_only = (args.baseline_modes and has_old and needs_baseline and not changed)
|
|
||||||
|
|
||||||
# --- Chunks + Embeddings vorbereiten ---
|
|
||||||
try:
|
|
||||||
body_text = getattr(parsed, "body", "") or ""
|
|
||||||
chunks = assemble_chunks(fm["id"], body_text, fm.get("type", "concept"))
|
|
||||||
chunk_pls: List[Dict[str, Any]] = make_chunk_payloads(fm, note_pl["path"], chunks, note_text=body_text)
|
|
||||||
except Exception as e:
|
|
||||||
print(json.dumps({"path": path, "note_id": note_id, "error": f"chunk build failed: {type(e).__name__}: {e}"}))
|
|
||||||
continue
|
|
||||||
|
|
||||||
# retriever_weight auf Chunk-Payload spiegeln
|
|
||||||
if fm.get("retriever_weight") is not None:
|
|
||||||
try:
|
|
||||||
rw = float(fm.get("retriever_weight"))
|
|
||||||
for pl in chunk_pls:
|
|
||||||
# Feld nur setzen, wenn noch nicht vorhanden
|
|
||||||
if "retriever_weight" not in pl:
|
|
||||||
pl["retriever_weight"] = rw
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
|
|
||||||
# Embeddings (fallback: Nullvektoren)
|
|
||||||
vecs: List[List[float]] = [[0.0] * int(cfg.dim) for _ in chunk_pls]
|
|
||||||
if embed_texts and chunk_pls:
|
|
||||||
try:
|
|
||||||
texts_for_embed = [(pl.get("window") or pl.get("text") or "") for pl in chunk_pls]
|
|
||||||
vecs = embed_texts(texts_for_embed)
|
|
||||||
except Exception as e:
|
|
||||||
print(json.dumps({"path": path, "note_id": note_id, "warn": f"embed_texts failed, using zeros: {e}"}))
|
|
||||||
|
|
||||||
# --- Fehlende Artefakte in Qdrant ermitteln ---
|
|
||||||
chunks_missing, edges_missing = artifacts_missing(client, cfg.prefix, note_id)
|
|
||||||
|
|
||||||
# --- Edges (robust) ---
|
|
||||||
edges: List[Dict[str, Any]] = []
|
|
||||||
edges_failed = False
|
|
||||||
should_build_edges = (changed and (not do_baseline_only)) or edges_missing
|
|
||||||
if should_build_edges:
|
|
||||||
try:
|
|
||||||
note_refs = note_pl.get("references") or []
|
|
||||||
edges = build_edges_for_note(
|
|
||||||
note_id,
|
|
||||||
chunk_pls,
|
|
||||||
note_level_references=note_refs,
|
|
||||||
include_note_scope_refs=note_scope_refs,
|
|
||||||
)
|
)
|
||||||
|
return res
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
edges_failed = True
|
return {"status": "error", "error": str(e), "path": str(f_path)}
|
||||||
edges = []
|
|
||||||
print(json.dumps({"path": path, "note_id": note_id, "warn": f"build_edges_for_note failed, skipping edges: {type(e).__name__}: {e}"}))
|
|
||||||
|
|
||||||
# --- Summary (stdout) ---
|
# Batch Processing
|
||||||
summary = {
|
# Wir verarbeiten in Chunks, um den Progress zu sehen
|
||||||
"note_id": note_id,
|
batch_size = 20
|
||||||
"title": fm.get("title"),
|
for i in range(0, len(files), batch_size):
|
||||||
"chunks": len(chunk_pls),
|
batch = files[i:i+batch_size]
|
||||||
"edges": len(edges),
|
logger.info(f"Processing batch {i} to {i+len(batch)}...")
|
||||||
"edges_failed": edges_failed,
|
|
||||||
"changed": changed,
|
tasks = [process_with_limit(f) for f in batch]
|
||||||
"chunks_missing": chunks_missing,
|
results = await asyncio.gather(*tasks)
|
||||||
"edges_missing": edges_missing,
|
|
||||||
"needs_baseline_for_mode": needs_baseline,
|
for res in results:
|
||||||
"decision": ("baseline-only" if args.apply and do_baseline_only else
|
if res.get("status") == "success":
|
||||||
"apply" if args.apply and (changed or chunks_missing or edges_missing) else
|
stats["processed"] += 1
|
||||||
"apply-skip-unchanged" if args.apply and not (changed or chunks_missing or edges_missing) else
|
elif res.get("status") == "error":
|
||||||
"dry-run"),
|
stats["errors"] += 1
|
||||||
"path": note_pl["path"],
|
logger.error(f"Error in {res.get('path')}: {res.get('error')}")
|
||||||
"hash_mode": mode,
|
else:
|
||||||
"hash_normalize": norm,
|
stats["skipped"] += 1
|
||||||
"hash_source": src,
|
|
||||||
"prefix": cfg.prefix,
|
|
||||||
}
|
|
||||||
print(json.dumps(summary, ensure_ascii=False))
|
|
||||||
|
|
||||||
# --- Writes ---
|
logger.info(f"Done. Stats: {stats}")
|
||||||
if not args.apply:
|
if not args.apply:
|
||||||
continue
|
logger.info("DRY RUN. Use --apply to write to DB.")
|
||||||
|
|
||||||
if do_baseline_only:
|
def main():
|
||||||
merged_hashes = {}
|
load_dotenv()
|
||||||
merged_hashes.update(old_hashes)
|
default_prefix = os.getenv("COLLECTION_PREFIX", "mindnet")
|
||||||
merged_hashes.update(note_pl.get("hashes") or {})
|
|
||||||
if old_payload:
|
|
||||||
note_pl["hash_fulltext"] = old_payload.get("hash_fulltext", note_pl.get("hash_fulltext"))
|
|
||||||
note_pl["hash_signature"] = old_payload.get("hash_signature", note_pl.get("hash_signature"))
|
|
||||||
note_pl["hashes"] = merged_hashes
|
|
||||||
notes_name, note_pts = points_for_note(cfg.prefix, note_pl, None, cfg.dim)
|
|
||||||
upsert_batch(client, notes_name, note_pts)
|
|
||||||
continue
|
|
||||||
|
|
||||||
# Wenn nichts geändert und keine Artefakte fehlen → nichts zu tun
|
|
||||||
if not changed and not (chunks_missing or edges_missing):
|
|
||||||
continue
|
|
||||||
|
|
||||||
# Purge nur bei echten Änderungen (unverändert + fehlende Artefakte ≠ Purge)
|
|
||||||
if args.purge_before_upsert and has_old and changed:
|
|
||||||
try:
|
|
||||||
purge_note_artifacts(client, cfg.prefix, note_id)
|
|
||||||
except Exception as e:
|
|
||||||
print(json.dumps({"path": path, "note_id": note_id, "warn": f"purge failed: {e}"}))
|
|
||||||
|
|
||||||
# Note nur bei Änderungen neu schreiben
|
|
||||||
if changed:
|
|
||||||
notes_name, note_pts = points_for_note(cfg.prefix, note_pl, None, cfg.dim)
|
|
||||||
upsert_batch(client, notes_name, note_pts)
|
|
||||||
|
|
||||||
# Chunks schreiben, wenn geändert ODER vorher fehlend
|
|
||||||
if chunk_pls and (changed or chunks_missing):
|
|
||||||
chunks_name, chunk_pts = points_for_chunks(cfg.prefix, chunk_pls, vecs)
|
|
||||||
upsert_batch(client, chunks_name, chunk_pts)
|
|
||||||
|
|
||||||
# Edges schreiben, wenn vorhanden und (geändert ODER vorher fehlend)
|
|
||||||
if edges and (changed or edges_missing):
|
|
||||||
edges_name, edge_pts = points_for_edges(cfg.prefix, edges)
|
|
||||||
upsert_batch(client, edges_name, edge_pts)
|
|
||||||
|
|
||||||
print(f"Done. Processed notes: {processed}")
|
|
||||||
|
|
||||||
|
parser = argparse.ArgumentParser(description="Import Vault to Qdrant (Async)")
|
||||||
|
parser.add_argument("--vault", default="./vault", help="Path to vault root")
|
||||||
|
parser.add_argument("--prefix", default=default_prefix, help="Collection prefix")
|
||||||
|
parser.add_argument("--force", action="store_true", help="Force re-index all files")
|
||||||
|
parser.add_argument("--apply", action="store_true", help="Perform writes to Qdrant")
|
||||||
|
|
||||||
|
args = parser.parse_args()
|
||||||
|
|
||||||
|
# Starte den Async Loop
|
||||||
|
asyncio.run(main_async(args))
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
main()
|
main()
|
||||||
+13
-2
@@ -2,7 +2,7 @@
|
|||||||
# -*- coding: utf-8 -*-
|
# -*- coding: utf-8 -*-
|
||||||
"""
|
"""
|
||||||
Name: scripts/reset_qdrant.py
|
Name: scripts/reset_qdrant.py
|
||||||
Version: v1.2.0 (2025-11-11)
|
Version: v1.2.1 (2025-12-11)
|
||||||
Kurzbeschreibung:
|
Kurzbeschreibung:
|
||||||
Sicheres Zurücksetzen der Qdrant-Collections für EIN Projektpräfix. Das Skript
|
Sicheres Zurücksetzen der Qdrant-Collections für EIN Projektpräfix. Das Skript
|
||||||
ermittelt zunächst die tatsächlich betroffenen Collections und zeigt eine
|
ermittelt zunächst die tatsächlich betroffenen Collections und zeigt eine
|
||||||
@@ -39,6 +39,7 @@ Exitcodes:
|
|||||||
0 = OK, 1 = abgebrochen/keine Aktion, 2 = Verbindungs-/Konfigurationsfehler
|
0 = OK, 1 = abgebrochen/keine Aktion, 2 = Verbindungs-/Konfigurationsfehler
|
||||||
|
|
||||||
Changelog:
|
Changelog:
|
||||||
|
v1.2.1: Fix: load_dotenv() hinzugefügt, damit VECTOR_DIM aus .env gelesen wird.
|
||||||
v1.2.0: ensure_payload_indexes() nach wipe/truncate standardmäßig ausführen (idempotent); --no-indexes Flag ergänzt.
|
v1.2.0: ensure_payload_indexes() nach wipe/truncate standardmäßig ausführen (idempotent); --no-indexes Flag ergänzt.
|
||||||
v1.1.1: Stabilisierung & Preview (2025-09-05).
|
v1.1.1: Stabilisierung & Preview (2025-09-05).
|
||||||
v1.1.0: Interaktive Bestätigung, --yes/--dry-run hinzugefügt, Preview der betroffenen Collections.
|
v1.1.0: Interaktive Bestätigung, --yes/--dry-run hinzugefügt, Preview der betroffenen Collections.
|
||||||
@@ -50,6 +51,9 @@ import os
|
|||||||
import sys
|
import sys
|
||||||
from typing import List
|
from typing import List
|
||||||
|
|
||||||
|
# FIX: Dotenv laden
|
||||||
|
from dotenv import load_dotenv
|
||||||
|
|
||||||
from qdrant_client import QdrantClient
|
from qdrant_client import QdrantClient
|
||||||
from qdrant_client.http import models as rest
|
from qdrant_client.http import models as rest
|
||||||
|
|
||||||
@@ -124,6 +128,9 @@ def wipe_collections(client: QdrantClient, all_col_names: List[str], existing: L
|
|||||||
|
|
||||||
|
|
||||||
def main():
|
def main():
|
||||||
|
# FIX: Umgebungsvariablen aus .env laden
|
||||||
|
load_dotenv()
|
||||||
|
|
||||||
ap = argparse.ArgumentParser(description="Wipe oder truncate mindnet-Collections in Qdrant (mit Bestätigung & Index-Setup).")
|
ap = argparse.ArgumentParser(description="Wipe oder truncate mindnet-Collections in Qdrant (mit Bestätigung & Index-Setup).")
|
||||||
ap.add_argument("--mode", choices=["wipe", "truncate"], required=True,
|
ap.add_argument("--mode", choices=["wipe", "truncate"], required=True,
|
||||||
help="wipe = Collections löschen & neu anlegen; truncate = nur Inhalte löschen")
|
help="wipe = Collections löschen & neu anlegen; truncate = nur Inhalte löschen")
|
||||||
@@ -135,6 +142,7 @@ def main():
|
|||||||
|
|
||||||
# Qdrant-Konfiguration
|
# Qdrant-Konfiguration
|
||||||
try:
|
try:
|
||||||
|
# Hier wird jetzt VECTOR_DIM=768 korrekt berücksichtigt
|
||||||
cfg = QdrantConfig.from_env()
|
cfg = QdrantConfig.from_env()
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(f"Konfigurationsfehler: {e}", file=sys.stderr)
|
print(f"Konfigurationsfehler: {e}", file=sys.stderr)
|
||||||
@@ -156,6 +164,9 @@ def main():
|
|||||||
existing = resolve_existing_collections(client, cfg.prefix)
|
existing = resolve_existing_collections(client, cfg.prefix)
|
||||||
nonexisting = [c for c in all_col_names if c not in existing]
|
nonexisting = [c for c in all_col_names if c not in existing]
|
||||||
|
|
||||||
|
# Debug-Info zur Dimension
|
||||||
|
print(f"Info: Nutze Vektor-Dimension: {cfg.dim}")
|
||||||
|
|
||||||
# Preview & Bestätigung
|
# Preview & Bestätigung
|
||||||
if not confirm_or_abort(args.mode, existing, nonexisting, args.yes):
|
if not confirm_or_abort(args.mode, existing, nonexisting, args.yes):
|
||||||
print("Abgebrochen – keine Änderungen vorgenommen.")
|
print("Abgebrochen – keine Änderungen vorgenommen.")
|
||||||
@@ -188,4 +199,4 @@ def main():
|
|||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
main()
|
main()
|
||||||
@@ -0,0 +1,105 @@
|
|||||||
|
import unittest
|
||||||
|
import asyncio
|
||||||
|
import os
|
||||||
|
import shutil
|
||||||
|
from pathlib import Path
|
||||||
|
from app.routers.ingest import save_note, SaveRequest
|
||||||
|
from app.core.ingestion import IngestionService
|
||||||
|
|
||||||
|
# Wir simulieren den API-Aufruf direkt
|
||||||
|
class TestDialogFullFlow(unittest.IsolatedAsyncioTestCase):
|
||||||
|
|
||||||
|
def setUp(self):
|
||||||
|
# Test Vault definieren
|
||||||
|
self.test_vault = os.path.abspath("./vault_test_dialog")
|
||||||
|
os.environ["MINDNET_VAULT_ROOT"] = self.test_vault
|
||||||
|
|
||||||
|
# Sicherstellen, dass das Verzeichnis existiert
|
||||||
|
if not os.path.exists(self.test_vault):
|
||||||
|
os.makedirs(self.test_vault)
|
||||||
|
|
||||||
|
def tearDown(self):
|
||||||
|
# Cleanup nach dem Test (optional, zum Debuggen auskommentieren)
|
||||||
|
if os.path.exists(self.test_vault):
|
||||||
|
shutil.rmtree(self.test_vault)
|
||||||
|
|
||||||
|
async def test_a_save_journal_entry(self):
|
||||||
|
"""
|
||||||
|
Testet den 'Fast Path' (Journal) -> sliding_short.
|
||||||
|
Erwartung: Sehr schnell, keine LLM-Warnungen im Log.
|
||||||
|
"""
|
||||||
|
print("\n--- TEST A: Journal Save (Fast Path) ---")
|
||||||
|
|
||||||
|
content = """---
|
||||||
|
type: journal
|
||||||
|
status: active
|
||||||
|
title: Test Journal Entry
|
||||||
|
---
|
||||||
|
# Daily Log
|
||||||
|
Heute haben wir das Chunking-System getestet.
|
||||||
|
Es lief alles sehr schnell durch.
|
||||||
|
"""
|
||||||
|
req = SaveRequest(
|
||||||
|
markdown_content=content,
|
||||||
|
filename="2025-12-12-test-journal.md",
|
||||||
|
folder="00_Inbox"
|
||||||
|
)
|
||||||
|
|
||||||
|
# Rufe die API-Funktion auf (simuliert Frontend "Save")
|
||||||
|
response = await save_note(req)
|
||||||
|
|
||||||
|
# Checks
|
||||||
|
self.assertEqual(response.status, "success")
|
||||||
|
self.assertTrue(response.stats['chunks'] > 0, "Keine Chunks erstellt!")
|
||||||
|
|
||||||
|
# File Check
|
||||||
|
file_path = Path(response.file_path)
|
||||||
|
self.assertTrue(file_path.exists(), "Datei wurde nicht geschrieben!")
|
||||||
|
print(f"✅ Journal gespeichert: {response.note_id}")
|
||||||
|
|
||||||
|
async def test_b_save_project_entry(self):
|
||||||
|
"""
|
||||||
|
Testet den 'Smart Path' (Project) -> sliding_smart_edges.
|
||||||
|
Erwartung: Smart Edge Allocation läuft (LLM Aufruf), dauert etwas länger.
|
||||||
|
"""
|
||||||
|
print("\n--- TEST B: Project Save (Smart Path) ---")
|
||||||
|
|
||||||
|
# Ein Text mit expliziten Kanten, um den Smart Chunker zu triggern
|
||||||
|
content = """---
|
||||||
|
type: project
|
||||||
|
status: active
|
||||||
|
title: Test Projekt Smart Chunking
|
||||||
|
---
|
||||||
|
# Mission
|
||||||
|
Wir wollen [[leitbild-werte#Integrität]] sicherstellen.
|
||||||
|
Das System muss stabil sein.
|
||||||
|
|
||||||
|
# Status
|
||||||
|
Wir nutzen [[rel:uses|Ollama]] für die Intelligenz.
|
||||||
|
"""
|
||||||
|
req = SaveRequest(
|
||||||
|
markdown_content=content,
|
||||||
|
filename="Test_Projekt_Smart.md",
|
||||||
|
folder="Projects"
|
||||||
|
)
|
||||||
|
|
||||||
|
# API Call
|
||||||
|
response = await save_note(req)
|
||||||
|
|
||||||
|
# Checks
|
||||||
|
self.assertEqual(response.status, "success")
|
||||||
|
self.assertTrue(response.stats['chunks'] > 0)
|
||||||
|
self.assertTrue(response.stats['edges'] > 0, "Kanten sollten gefunden werden (mind. structure edges)")
|
||||||
|
|
||||||
|
print(f"✅ Projekt gespeichert: {response.note_id}")
|
||||||
|
|
||||||
|
# Optional: Prüfen ob Qdrant Daten hat (via IngestionService Helper)
|
||||||
|
service = IngestionService()
|
||||||
|
chunks_missing, edges_missing = service._artifacts_missing(response.note_id)
|
||||||
|
|
||||||
|
self.assertFalse(chunks_missing, "Chunks fehlen in Qdrant!")
|
||||||
|
self.assertFalse(edges_missing, "Edges fehlen in Qdrant!")
|
||||||
|
print("✅ Qdrant Persistenz verifiziert.")
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
unittest.main()
|
||||||
@@ -0,0 +1,110 @@
|
|||||||
|
# tests/test_final_wp15_validation.py
|
||||||
|
|
||||||
|
import asyncio
|
||||||
|
import unittest
|
||||||
|
from typing import List, Dict, Any
|
||||||
|
import re
|
||||||
|
from pathlib import Path
|
||||||
|
import sys
|
||||||
|
|
||||||
|
# --- PFAD-KORREKTUR ---
|
||||||
|
ROOT_DIR = Path(__file__).resolve().parent.parent
|
||||||
|
sys.path.insert(0, str(ROOT_DIR))
|
||||||
|
|
||||||
|
from app.core import chunker
|
||||||
|
from app.services.semantic_analyzer import SemanticAnalyzer
|
||||||
|
|
||||||
|
def get_config_for_test(strategy: str, enable_smart_edge: bool) -> Dict[str, Any]:
|
||||||
|
cfg = chunker.get_chunk_config("concept")
|
||||||
|
cfg['strategy'] = strategy
|
||||||
|
cfg['enable_smart_edge_allocation'] = enable_smart_edge
|
||||||
|
# WICHTIG: Setze sehr kleine Werte, um Split bei kurzem Text zu erzwingen
|
||||||
|
cfg['target'] = 50
|
||||||
|
cfg['max'] = 100
|
||||||
|
return cfg
|
||||||
|
|
||||||
|
TEST_NOTE_ID_SMART = "20251212-test-smart"
|
||||||
|
TEST_NOTE_ID_LEGACY = "20251212-test-legacy"
|
||||||
|
|
||||||
|
TEST_MARKDOWN_SMART = """
|
||||||
|
---
|
||||||
|
id: 20251212-test-smart
|
||||||
|
title: Integrationstest - Smart Edges
|
||||||
|
type: concept
|
||||||
|
status: active
|
||||||
|
---
|
||||||
|
# Teil 1: Wichtige Definition
|
||||||
|
Die Mission ist: präsent sein.
|
||||||
|
Dies entspricht unseren Werten [[leitbild-werte#Integrität]].
|
||||||
|
|
||||||
|
## Teil 2: Konflikt
|
||||||
|
Der Konflikt zwischen [[leitbild-rollen#Vater]] und [[leitbild-rollen#Beruf]].
|
||||||
|
Lösung: [[rel:depends_on leitbild-review#Weekly Review]].
|
||||||
|
"""
|
||||||
|
|
||||||
|
# Verlängerter Text, um Split > 1 zu erzwingen (bei Target 50)
|
||||||
|
TEST_MARKDOWN_SLIDING = """
|
||||||
|
---
|
||||||
|
id: 20251212-test-legacy
|
||||||
|
title: Fließtext Protokoll
|
||||||
|
type: journal
|
||||||
|
status: active
|
||||||
|
---
|
||||||
|
Dies ist der erste Absatz. Er muss lang genug sein, damit der Chunker ihn schneidet.
|
||||||
|
Wir schreiben hier über Rituale wie [[leitbild-rituale-system]] und viele andere Dinge.
|
||||||
|
Das Wetter ist schön und die Programmierung läuft gut. Dies sind Füllsätze für Länge.
|
||||||
|
|
||||||
|
Dies ist der zweite Absatz. Er ist durch eine Leerzeile getrennt und sollte einen neuen Kontext bilden.
|
||||||
|
Auch hier schreiben wir viel Text, damit die Token-Anzahl die Grenze von 50 Tokens überschreitet.
|
||||||
|
Das System muss hier splitten.
|
||||||
|
"""
|
||||||
|
|
||||||
|
class TestFinalWP15Integration(unittest.TestCase):
|
||||||
|
|
||||||
|
_analyzer_instance = None
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def setUpClass(cls):
|
||||||
|
cls._analyzer_instance = SemanticAnalyzer()
|
||||||
|
chunker._semantic_analyzer_instance = cls._analyzer_instance
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def tearDownClass(cls):
|
||||||
|
# FIX: Kein explizites Loop-Closing hier, um RuntimeError zu vermeiden
|
||||||
|
pass
|
||||||
|
|
||||||
|
def test_a_smart_edge_allocation(self):
|
||||||
|
"""A: Prüft Smart Edge Allocation (LLM-Filter)."""
|
||||||
|
config = get_config_for_test('by_heading', enable_smart_edge=True)
|
||||||
|
|
||||||
|
chunks = asyncio.run(chunker.assemble_chunks(
|
||||||
|
note_id=TEST_NOTE_ID_SMART,
|
||||||
|
md_text=TEST_MARKDOWN_SMART,
|
||||||
|
note_type='concept',
|
||||||
|
config=config
|
||||||
|
))
|
||||||
|
|
||||||
|
self.assertTrue(len(chunks) >= 2, f"A1 Fehler: Erwartete >= 2 Chunks, bekam {len(chunks)}")
|
||||||
|
print(f" -> Chunks generiert (Smart): {len(chunks)}")
|
||||||
|
|
||||||
|
def test_b_backward_compatibility(self):
|
||||||
|
"""B: Prüft Sliding Window (Legacy)."""
|
||||||
|
config = get_config_for_test('sliding_window', enable_smart_edge=False)
|
||||||
|
|
||||||
|
chunks = asyncio.run(chunker.assemble_chunks(
|
||||||
|
note_id=TEST_NOTE_ID_LEGACY,
|
||||||
|
md_text=TEST_MARKDOWN_SLIDING,
|
||||||
|
note_type='journal',
|
||||||
|
config=config
|
||||||
|
))
|
||||||
|
|
||||||
|
# Sliding Window muss bei diesem langen Text > 1 Chunk liefern
|
||||||
|
self.assertTrue(len(chunks) >= 2, f"B1 Fehler: Sliding Window lieferte nur {len(chunks)} Chunk(s). Split defekt.")
|
||||||
|
|
||||||
|
# Check: Keine LLM Kanten (da deaktiviert)
|
||||||
|
injected = re.search(r'\[\[rel:', chunks[0].text)
|
||||||
|
self.assertIsNone(injected, "B2 Fehler: LLM-Kanten trotz Deaktivierung gefunden!")
|
||||||
|
print(f" -> Chunks generiert (Legacy): {len(chunks)}")
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
unittest.main()
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
import requests
|
||||||
|
import sys
|
||||||
|
|
||||||
|
API_URL = "http://localhost:8002/chat/"
|
||||||
|
|
||||||
|
def test_intent(message):
|
||||||
|
print(f"📡 Sende: '{message}' ...")
|
||||||
|
payload = {
|
||||||
|
"message": message,
|
||||||
|
"top_k": 0,
|
||||||
|
"explain": False
|
||||||
|
}
|
||||||
|
|
||||||
|
try:
|
||||||
|
# Timeout nach 30 Sekunden erzwingen
|
||||||
|
response = requests.post(API_URL, json=payload, timeout=30)
|
||||||
|
|
||||||
|
if response.status_code != 200:
|
||||||
|
print(f"❌ Server Error {response.status_code}: {response.text}")
|
||||||
|
return
|
||||||
|
|
||||||
|
data = response.json()
|
||||||
|
intent = data.get("intent")
|
||||||
|
source = data.get("intent_source")
|
||||||
|
answer = data.get("answer")
|
||||||
|
|
||||||
|
print(f"✅ Ergebnis erhalten:")
|
||||||
|
print(f" Intent: {intent} (Quelle: {source})")
|
||||||
|
print(f" Antwort: {answer[:100]}...") # Nur die ersten 100 Zeichen
|
||||||
|
print("-" * 40)
|
||||||
|
|
||||||
|
except requests.exceptions.Timeout:
|
||||||
|
print("❌ TIMEOUT: Das Backend antwortet nicht innerhalb von 30 Sekunden.")
|
||||||
|
print(" -> Prüfe das Terminal, wo uvicorn läuft. Gibt es dort Fehlermeldungen?")
|
||||||
|
except Exception as e:
|
||||||
|
print(f"❌ Fehler: {e}")
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
# Testfall: Muss INTERVIEW auslösen
|
||||||
|
test_intent("Ich möchte ein neues Projekt anlegen")
|
||||||
@@ -0,0 +1,147 @@
|
|||||||
|
# tests/test_smart_chunking_integration.py (Letzte Korrektur zur Umgehung des AsyncIO-Fehlers)
|
||||||
|
|
||||||
|
import asyncio
|
||||||
|
import unittest
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import List, Dict
|
||||||
|
|
||||||
|
# --- PFAD-KORREKTUR ---
|
||||||
|
ROOT_DIR = Path(__file__).resolve().parent.parent
|
||||||
|
sys.path.insert(0, str(ROOT_DIR))
|
||||||
|
# ----------------------
|
||||||
|
|
||||||
|
# Import der Kernkomponenten
|
||||||
|
from app.core import chunker
|
||||||
|
from app.core import derive_edges
|
||||||
|
from app.services.semantic_analyzer import SemanticAnalyzer
|
||||||
|
|
||||||
|
|
||||||
|
# 1. Definieren der Test-Note (Simuliert eine journal.md Datei)
|
||||||
|
TEST_NOTE_ID = "20251211-journal-sem-test"
|
||||||
|
TEST_NOTE_TYPE = "journal"
|
||||||
|
|
||||||
|
TEST_MARKDOWN = """
|
||||||
|
---
|
||||||
|
id: 20251211-journal-sem-test
|
||||||
|
title: Tägliches Log - Semantischer Test
|
||||||
|
type: journal
|
||||||
|
status: active
|
||||||
|
created: 2025-12-11
|
||||||
|
tags: [test, daily-log]
|
||||||
|
---
|
||||||
|
# Log-Eintrag 2025-12-11
|
||||||
|
|
||||||
|
Heute war ein guter Tag. Zuerst habe ich mit der R1 Meditation begonnen, um meinen Nordstern Fokus zu klären. Das Ritual [[leitbild-rituale-system]] hat mir geholfen, ruhig in den Tag zu starten. Ich habe gespürt, wie wichtig meine [[leitbild-werte#Integrität]] für meine Entscheidungen ist. Das ist das Fundament.
|
||||||
|
|
||||||
|
Am Nachmittag gab es einen Konflikt bei der Karate-Trainer-Ausbildung. Ein Schüler war uneinsichtig. Ich habe die Situation nach [[leitbild-prinzipien#P4 Gerechtigkeit & Fairness]] behandelt und beide Seiten gehört (Steelman). Das war anstrengend, aber ich habe meine [[leitbild-rollen#Karate-Trainer]] Mission erfüllt. Die Konsequenz war klar und ruhig.
|
||||||
|
|
||||||
|
Abends habe ich den wöchentlichen Load-Check mit meinem Partner gemacht. Das Paar-Ritual [[leitbild-rituale-system#R5]] hilft, das Ziel [[leitbild-ziele-portfolio#Nordstern Partner]] aktiv zu verfolgen. Es ist der operative Rhythmus für uns beide.
|
||||||
|
"""
|
||||||
|
|
||||||
|
# --- ENTFERNEN DER KOMPLEXEN TEARDOWN-HILFEN ---
|
||||||
|
# Wir entfernen die fehleranfällige asynchrone Schließungslogik.
|
||||||
|
|
||||||
|
|
||||||
|
class TestSemanticChunking(unittest.TestCase):
|
||||||
|
|
||||||
|
_analyzer_instance = None
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def setUpClass(cls):
|
||||||
|
"""Initialisiert den SemanticAnalyzer einmalig."""
|
||||||
|
cls._analyzer_instance = SemanticAnalyzer()
|
||||||
|
# Stellt sicher, dass der Chunker diese Singleton-Instanz verwendet
|
||||||
|
chunker._semantic_analyzer_instance = cls._analyzer_instance
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def tearDownClass(cls):
|
||||||
|
"""
|
||||||
|
PRAGMATISCHE LÖSUNG: Überspringe das explizite Aclose() im Teardown,
|
||||||
|
um den Event Loop Konflikt zu vermeiden. Die GC wird die Verbindung schließen.
|
||||||
|
"""
|
||||||
|
pass
|
||||||
|
|
||||||
|
def setUp(self):
|
||||||
|
self.config = chunker.get_chunk_config(TEST_NOTE_TYPE)
|
||||||
|
|
||||||
|
def test_a_strategy_selection(self):
|
||||||
|
"""Prüft, ob die Strategie 'semantic_llm' für den Typ 'journal' gewählt wird."""
|
||||||
|
self.assertEqual(self.config['strategy'], 'semantic_llm',
|
||||||
|
"Fehler: 'journal' sollte die Strategie 'semantic_llm' nutzen.")
|
||||||
|
|
||||||
|
def test_b_llm_chunking_and_injection(self):
|
||||||
|
"""
|
||||||
|
Prüft den gesamten End-to-End-Flow: 1. LLM-Chunking, 2. Kanten-Injektion, 3. Kanten-Erkennung.
|
||||||
|
"""
|
||||||
|
|
||||||
|
# --- 1. Chunking (Asynchron) ---
|
||||||
|
chunks = asyncio.run(chunker.assemble_chunks(
|
||||||
|
note_id=TEST_NOTE_ID,
|
||||||
|
md_text=TEST_MARKDOWN,
|
||||||
|
note_type=TEST_NOTE_TYPE
|
||||||
|
))
|
||||||
|
|
||||||
|
print(f"\n--- LLM Chunker Output: {len(chunks)} Chunks ---")
|
||||||
|
|
||||||
|
# Assertion B1: Zerlegung (Das LLM muss mehr als 1 Chunk liefern)
|
||||||
|
self.assertTrue(len(chunks) > 1,
|
||||||
|
"Assertion B1 Fehler: LLM hat nicht zerlegt (Fallback aktiv). Prüfe LLM-Stabilität.")
|
||||||
|
|
||||||
|
# --- 2. Injektion prüfen ---
|
||||||
|
chunk_1_text = chunks[0].text
|
||||||
|
self.assertIn("[[rel:", chunk_1_text,
|
||||||
|
"Assertion B2 Fehler: Der Chunk-Text muss die injizierte [[rel: Kante enthalten.")
|
||||||
|
|
||||||
|
# --- 3. Kanten-Derivation (Synchron) ---
|
||||||
|
edges = derive_edges.build_edges_for_note(
|
||||||
|
note_id=TEST_NOTE_ID,
|
||||||
|
chunks=[c.__dict__ for c in chunks]
|
||||||
|
)
|
||||||
|
|
||||||
|
print(f"--- Edge Derivation Output: {len(edges)} Kanten ---")
|
||||||
|
|
||||||
|
# Assertion B3: Mindestens 3 LLM-Kanten (inline:rel)
|
||||||
|
llm_generated_edges = [
|
||||||
|
e for e in edges
|
||||||
|
if e.get('rule_id') == 'inline:rel' and e.get('source_id').startswith(TEST_NOTE_ID + '#sem')
|
||||||
|
]
|
||||||
|
|
||||||
|
self.assertTrue(len(llm_generated_edges) >= 3,
|
||||||
|
"Assertion B3 Fehler: Es wurden weniger als 3 semantische Kanten gefunden.")
|
||||||
|
|
||||||
|
# Assertion B4: Check für die Matrix-Logik / Werte-Kante
|
||||||
|
has_matrix_kante = any(
|
||||||
|
e['target_id'].startswith('leitbild-werte') and e['kind'] in ['based_on', 'derived_from']
|
||||||
|
for e in llm_generated_edges
|
||||||
|
)
|
||||||
|
self.assertTrue(has_matrix_kante,
|
||||||
|
"Assertion B4 Fehler: Die Matrix-Logik / Werte-Kante wurde nicht erkannt.")
|
||||||
|
|
||||||
|
print("\n✅ Integrationstest für Semantic Chunking erfolgreich.")
|
||||||
|
|
||||||
|
def test_c_draft_status_prevention(self):
|
||||||
|
"""Prüft, ob 'draft' Status semantic_llm auf by_heading überschreibt."""
|
||||||
|
|
||||||
|
DRAFT_MARKDOWN = TEST_MARKDOWN.replace("status: active", "status: draft")
|
||||||
|
|
||||||
|
# 1. Chunking mit Draft Status
|
||||||
|
chunks = asyncio.run(chunker.assemble_chunks(
|
||||||
|
note_id=TEST_NOTE_ID,
|
||||||
|
md_text=DRAFT_MARKDOWN,
|
||||||
|
note_type=TEST_NOTE_TYPE
|
||||||
|
))
|
||||||
|
|
||||||
|
# 2. Prüfen der Chunker-IDs
|
||||||
|
self.assertFalse(chunks[0].id.startswith(TEST_NOTE_ID + '#sem'),
|
||||||
|
"Assertion C1 Fehler: LLM-Chunking wurde für den Status 'draft' nicht verhindert.")
|
||||||
|
|
||||||
|
self.assertTrue(chunks[0].id.startswith(TEST_NOTE_ID + '#c'),
|
||||||
|
"Assertion C2 Fehler: Fallback-Strategie 'by_heading' wurde nicht korrekt ausgeführt.")
|
||||||
|
|
||||||
|
print(f"\n✅ Prevention Test: Draft-Status hat LLM-Chunking verhindert (Fallback ID: {chunks[0].id}).")
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
print("Starte den Semantic Chunking Integrationstest.")
|
||||||
|
unittest.main()
|
||||||
+29
-10
@@ -1,6 +1,10 @@
|
|||||||
"""
|
"""
|
||||||
tests/test_wp06_decision.py — Flexibler Integrationstest für WP-06
|
tests/test_wp06_decision.py — Flexibler Integrationstest für WP-06
|
||||||
Update: Timeout auf 300s erhöht für CPU-Inference Cold-Starts.
|
Update:
|
||||||
|
- Timeout 300s.
|
||||||
|
- Zeigt Intent Source an.
|
||||||
|
- Payload/Source Fallback für Metadaten.
|
||||||
|
- Debug-Dump bei unknown Type.
|
||||||
"""
|
"""
|
||||||
import requests
|
import requests
|
||||||
import json
|
import json
|
||||||
@@ -22,7 +26,7 @@ def test_decision_engine(query: str, port: int, expected_intent: str):
|
|||||||
print(f"FRAGE: '{query}'")
|
print(f"FRAGE: '{query}'")
|
||||||
print("... warte auf LLM (kann auf CPU >120s dauern) ...")
|
print("... warte auf LLM (kann auf CPU >120s dauern) ...")
|
||||||
|
|
||||||
# FIX: Timeout auf 300 erhöht, passend zur Server-Config
|
# FIX: Timeout auf 300 erhöht
|
||||||
response = requests.post(f"{api_url}/chat/", json=payload, timeout=300)
|
response = requests.post(f"{api_url}/chat/", json=payload, timeout=300)
|
||||||
response.raise_for_status()
|
response.raise_for_status()
|
||||||
data = response.json()
|
data = response.json()
|
||||||
@@ -31,9 +35,14 @@ def test_decision_engine(query: str, port: int, expected_intent: str):
|
|||||||
|
|
||||||
# 1. Intent Check
|
# 1. Intent Check
|
||||||
intent = data.get("intent", "UNKNOWN")
|
intent = data.get("intent", "UNKNOWN")
|
||||||
match = intent == expected_intent
|
source_method = data.get("intent_source", "Unknown Source")
|
||||||
|
|
||||||
|
match = intent.upper() == expected_intent.upper()
|
||||||
|
|
||||||
print(f"\n1. INTENT DETECTION: [{'✅' if match else '❌'}]")
|
print(f"\n1. INTENT DETECTION: [{'✅' if match else '❌'}]")
|
||||||
print(f" Erkannt: {intent} (Erwartet: {expected_intent})")
|
print(f" Erkannt: {intent}")
|
||||||
|
print(f" Erwartet: {expected_intent}")
|
||||||
|
print(f" Methode: {source_method}")
|
||||||
|
|
||||||
# 2. Source Check (Strategic Retrieval)
|
# 2. Source Check (Strategic Retrieval)
|
||||||
sources = data.get("sources", [])
|
sources = data.get("sources", [])
|
||||||
@@ -44,18 +53,28 @@ def test_decision_engine(query: str, port: int, expected_intent: str):
|
|||||||
if not sources:
|
if not sources:
|
||||||
print(" (Keine Quellen gefunden)")
|
print(" (Keine Quellen gefunden)")
|
||||||
|
|
||||||
|
debug_printed = False
|
||||||
|
|
||||||
for i, source in enumerate(sources):
|
for i, source in enumerate(sources):
|
||||||
# Safe access auf Source-Dict
|
# --- FIX: Robusterer Zugriff auf Metadaten ---
|
||||||
src_meta = source.get("source", {})
|
src_meta = source.get("payload") or source.get("source") or {}
|
||||||
|
|
||||||
node_type = src_meta.get("type", "unknown")
|
node_type = src_meta.get("type", "unknown")
|
||||||
title = source.get("note_id", "Unknown")
|
title = source.get("note_id", "Unknown")
|
||||||
score = source.get("total_score", 0.0)
|
score = source.get("total_score", 0.0)
|
||||||
|
|
||||||
|
# DEBUG: Wenn Typ unknown ist, dumpen wir das erste Objekt
|
||||||
|
if node_type == "unknown" and not debug_printed:
|
||||||
|
print(f"\n 🔴 DEBUG: Raw Data von Quelle {i+1} (da Typ unknown):")
|
||||||
|
print(json.dumps(source, indent=2, ensure_ascii=False))
|
||||||
|
print(" ------------------------------------------------")
|
||||||
|
debug_printed = True
|
||||||
|
|
||||||
# Marker für Ausgabe
|
# Marker für Ausgabe
|
||||||
marker = " "
|
marker = " "
|
||||||
if node_type in ["value", "principle", "goal", "experience", "belief", "profile"]:
|
if node_type in ["value", "principle", "goal", "experience", "belief", "profile", "decision"]:
|
||||||
marker = "🎯" # Strategischer Treffer
|
marker = "🎯" # Strategischer Treffer
|
||||||
strategic_hits.append(title)
|
strategic_hits.append(f"{title} ({node_type})")
|
||||||
else:
|
else:
|
||||||
marker = "📄"
|
marker = "📄"
|
||||||
fact_hits.append(title)
|
fact_hits.append(title)
|
||||||
@@ -77,7 +96,7 @@ def test_decision_engine(query: str, port: int, expected_intent: str):
|
|||||||
|
|
||||||
except requests.exceptions.ReadTimeout:
|
except requests.exceptions.ReadTimeout:
|
||||||
print(f"\n❌ TIMEOUT: Der Server hat nicht innerhalb von 300s geantwortet.")
|
print(f"\n❌ TIMEOUT: Der Server hat nicht innerhalb von 300s geantwortet.")
|
||||||
print(" Tipp: Prüfe die Server-Logs. Lädt er noch das Modell?")
|
print(" Tipp: Prüfe die Server-Logs (Terminal 1). Lädt er noch das Modell?")
|
||||||
sys.exit(1)
|
sys.exit(1)
|
||||||
except requests.exceptions.ConnectionError:
|
except requests.exceptions.ConnectionError:
|
||||||
print(f"\n❌ FEHLER: Keine Verbindung zu {api_url}. Läuft der Server?")
|
print(f"\n❌ FEHLER: Keine Verbindung zu {api_url}. Läuft der Server?")
|
||||||
@@ -96,7 +115,7 @@ if __name__ == "__main__":
|
|||||||
help="Der Port der API (Default: 8002 für Dev).")
|
help="Der Port der API (Default: 8002 für Dev).")
|
||||||
parser.add_argument("--expect", "-e", type=str,
|
parser.add_argument("--expect", "-e", type=str,
|
||||||
default="DECISION",
|
default="DECISION",
|
||||||
help="Der erwartete Intent (z.B. DECISION, EMPATHY).")
|
help="Der erwartete Intent (z.B. DECISION, EMPATHY, FACT).")
|
||||||
|
|
||||||
args = parser.parse_args()
|
args = parser.parse_args()
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,76 @@
|
|||||||
|
import unittest
|
||||||
|
import asyncio
|
||||||
|
from unittest.mock import MagicMock, patch
|
||||||
|
from app.core import chunker
|
||||||
|
|
||||||
|
class TestWP15Orchestration(unittest.TestCase):
|
||||||
|
|
||||||
|
def setUp(self):
|
||||||
|
# Basis Config
|
||||||
|
self.config = {
|
||||||
|
"strategy": "sliding_window",
|
||||||
|
"enable_smart_edge_allocation": True,
|
||||||
|
"target": 100, "max": 200
|
||||||
|
}
|
||||||
|
|
||||||
|
@patch("app.core.chunker.get_semantic_analyzer")
|
||||||
|
@patch("app.core.chunker.build_edges_for_note")
|
||||||
|
def test_smart_allocation_flow(self, mock_build_edges, mock_get_analyzer):
|
||||||
|
"""
|
||||||
|
Prüft, ob Kanten gefunden, gefiltert und injiziert werden.
|
||||||
|
"""
|
||||||
|
# 1. Mock Edge Discovery (Simuliert derive_edges.py)
|
||||||
|
# Wir simulieren, dass im Text 2 Kanten gefunden wurden.
|
||||||
|
mock_build_edges.return_value = [
|
||||||
|
{"kind": "uses", "target_id": "tool_a"},
|
||||||
|
{"kind": "references", "target_id": "doc_b"}
|
||||||
|
]
|
||||||
|
|
||||||
|
# 2. Mock LLM Analyzer (Simuliert semantic_analyzer.py)
|
||||||
|
mock_analyzer_instance = MagicMock()
|
||||||
|
mock_get_analyzer.return_value = mock_analyzer_instance
|
||||||
|
|
||||||
|
# Simuliere LLM Antwort: Chunk 1 bekommt "tool_a", Chunk 2 bekommt nichts.
|
||||||
|
async def mock_assign(text, candidates, type):
|
||||||
|
if "Tool A" in text:
|
||||||
|
return ["uses:tool_a"]
|
||||||
|
return []
|
||||||
|
|
||||||
|
mock_analyzer_instance.assign_edges_to_chunk.side_effect = mock_assign
|
||||||
|
|
||||||
|
# 3. Run Chunker
|
||||||
|
md_text = """
|
||||||
|
# Intro
|
||||||
|
Hier nutzen wir Tool A für Tests.
|
||||||
|
|
||||||
|
# Outro
|
||||||
|
Hier ist nur Text ohne Tool.
|
||||||
|
"""
|
||||||
|
|
||||||
|
# Wir führen assemble_chunks aus (im Event Loop des Tests)
|
||||||
|
chunks = asyncio.run(chunker.assemble_chunks(
|
||||||
|
"test_note", md_text, "concept", config=self.config
|
||||||
|
))
|
||||||
|
|
||||||
|
# 4. Assertions
|
||||||
|
|
||||||
|
# Check: Wurde derive_edges aufgerufen?
|
||||||
|
mock_build_edges.assert_called_once()
|
||||||
|
|
||||||
|
# Check: Wurde LLM Analyzer aufgerufen?
|
||||||
|
self.assertTrue(mock_analyzer_instance.assign_edges_to_chunk.called)
|
||||||
|
|
||||||
|
# Check: Injection in Chunk 1 (Tool A Text)
|
||||||
|
chunk_with_tool = next((c for c in chunks if "Tool A" in c.text), None)
|
||||||
|
self.assertIsNotNone(chunk_with_tool)
|
||||||
|
self.assertIn("[[rel:uses|tool_a]]", chunk_with_tool.text, "Kante wurde nicht injiziert!")
|
||||||
|
|
||||||
|
# Check: Fallback (Die Kante 'references:doc_b' wurde vom LLM nirgends zugeordnet)
|
||||||
|
# Sie sollte also in ALLEN Chunks als Fallback landen.
|
||||||
|
for c in chunks:
|
||||||
|
self.assertIn("[[rel:references|doc_b]]", c.text, "Fallback-Kante fehlt!")
|
||||||
|
|
||||||
|
print("✅ WP-15 Logic Test passed.")
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
unittest.main()
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
---
|
||||||
|
id: leitbild-ops-guide
|
||||||
|
title: Leitbild – Leitfaden (Betrieb & Rhythmus)
|
||||||
|
type: concept
|
||||||
|
status: active
|
||||||
|
created: 2025-10-31
|
||||||
|
tags: [leitbild, operating-guide, habits]
|
||||||
|
lang: de
|
||||||
|
---
|
||||||
|
# Leitbild – Operations Manual (TL;DR)
|
||||||
|
|
||||||
|
Dieses Dokument beschreibt die operative Nutzung des Systems.
|
||||||
|
Es steuert die Anwendung von [[rel:uses leitbild-rituale-system]] und [[rel:uses leitbild-review]].
|
||||||
|
|
||||||
|
## 1) Karte – „Welche Datei wofür?“
|
||||||
|
* **Kompass:** [[rel:references leitbild-text]] (Wofür stehe ich?)
|
||||||
|
* **System:** [[rel:references leitbild-rituale-system]] (Trigger & Fallbacks).
|
||||||
|
* **Steuerung:** [[rel:references leitbild-review]] (Weekly/Monthly).
|
||||||
|
* **Strategie:** [[rel:references leitbild-ziele-portfolio]] (Nordsterne).
|
||||||
|
* **Identität:** [[rel:references leitbild-rollen]] (Kontext).
|
||||||
|
* **Ethik:** [[rel:references leitbild-prinzipien]] (Wächterfragen).
|
||||||
|
|
||||||
|
## 2) Dein Tag (Mikro-Anker)
|
||||||
|
* **Morgens:** R1 (Meditation) + Nordstern-Fokus.
|
||||||
|
* **Mittags:** R2 (Mobility).
|
||||||
|
* **Abends:** R6 (Rohan) + R3 (Journal).
|
||||||
|
|
||||||
|
## 3) Weekly Review SOP
|
||||||
|
Der Prozess für [[rel:related_to leitbild-review#Weekly Review]].
|
||||||
|
1. Scoreboard füllen.
|
||||||
|
2. Reflexion (Wirksamkeit, Repair).
|
||||||
|
3. **Decision Note** erstellen.
|
||||||
|
|
||||||
|
## 6) Decision & Deviation
|
||||||
|
Wie man Entscheidungen dokumentiert (siehe [[rel:related_to leitbild-prinzipien#P1 Integrität]]):
|
||||||
|
* **Decision Note:** Für echte Wahlmöglichkeiten.
|
||||||
|
* **Deviation Note:** Für Abweichungen ("Schuldschein").
|
||||||
|
|
||||||
|
## 10) Emergency Mode
|
||||||
|
Wenn Energie knapp ist:
|
||||||
|
* **Weniger, dafür besser:** Fallbacks aus [[rel:uses leitbild-rituale-system]] nutzen.
|
||||||
|
* **Repair first:** Konflikte bereinigen.
|
||||||
@@ -0,0 +1,60 @@
|
|||||||
|
---
|
||||||
|
id: leitbild-prinzipien
|
||||||
|
title: Leitbild – Prinzipien
|
||||||
|
type: principle
|
||||||
|
status: active
|
||||||
|
created: 2025-10-30
|
||||||
|
updated: 2025-10-30
|
||||||
|
tags: [topic/prinzipien, method/values-to-principles]
|
||||||
|
lang: de
|
||||||
|
---
|
||||||
|
# Handlungsprinzipien
|
||||||
|
|
||||||
|
> Diese Prinzipien sind abgeleitet aus [[rel:derived_from leitbild-wertekompass]].
|
||||||
|
> Sie steuern das Verhalten in allen Rollen ([[rel:guides leitbild-rollen]]).
|
||||||
|
|
||||||
|
## P1 – Integrität
|
||||||
|
**Satz:** *Ich spiegele jede wichtige Entscheidung am Werte-Modell und dokumentiere Abweichungen.*
|
||||||
|
**Verbindung:** Basiert auf Wert [[rel:derived_from leitbild-wertekompass#Integrität]].
|
||||||
|
**Signal:** Decision Note („Schuldschein“) binnen 24h erstellt.
|
||||||
|
|
||||||
|
## P2 – Vertrauenswürdigkeit & Ehrlichkeit
|
||||||
|
**Satz:** *Ich kündige drohende Abweichungen proaktiv an und verhandle Alternativen.*
|
||||||
|
**Verbindung:** Basiert auf Wert [[rel:derived_from leitbild-wertekompass#Vertrauenswürdigkeit]].
|
||||||
|
**Signal:** Info *vor* Fristende.
|
||||||
|
|
||||||
|
## P3 – Disziplin (Selbstführung)
|
||||||
|
**Satz:** *Ich bin mir selbst konsequent; Unangenehmes gehe ich rechtzeitig an.*
|
||||||
|
**Verbindung:** Basiert auf Wert [[rel:derived_from leitbild-wertekompass#Disziplin]].
|
||||||
|
|
||||||
|
### P3a – Disziplin in der Familie
|
||||||
|
**Satz:** *Ich setze wenige Regeln ruhig durch, nachdem ich Bedürfnisse geprüft habe.*
|
||||||
|
**Signal:** Angekündigte Konsequenzen werden umgesetzt.
|
||||||
|
|
||||||
|
## P4 – Gerechtigkeit & Fairness
|
||||||
|
**Satz:** *Ich entscheide nach transparenten Maßstäben und höre beide Seiten (Steelman).*
|
||||||
|
**Verbindung:** Basiert auf Wert [[rel:derived_from leitbild-wertekompass#Gerechtigkeit]].
|
||||||
|
|
||||||
|
## P5 – Respekt
|
||||||
|
**Satz:** *Ich antworte erst, wenn ich verstanden habe.*
|
||||||
|
**Verbindung:** Basiert auf Wert [[rel:derived_from leitbild-wertekompass#Respekt]].
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Tier 2 – Mikro-Prinzipien
|
||||||
|
|
||||||
|
### MP1 – Fürsorge (Familie)
|
||||||
|
*Ich schenke tägliche Präsenz und schütze Familienzeit.*
|
||||||
|
(Siehe Ritual [[rel:enforced_by leitbild-rituale-system#R6]]).
|
||||||
|
|
||||||
|
### MP2 – Klarheit (Struktur)
|
||||||
|
*Wer macht was bis wann.*
|
||||||
|
|
||||||
|
### MP3 – Lernorientierung
|
||||||
|
*Ich wähle ein Deep-Dive-Thema und teile Wissen.*
|
||||||
|
|
||||||
|
### MP4 – Großzügigkeit
|
||||||
|
*Ich teile Zeit/Wissen ohne Bilanzdenken.*
|
||||||
|
|
||||||
|
### MP5 – Mut
|
||||||
|
*Ich spreche Unangenehmes früh an.*
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
---
|
||||||
|
id: leitbild-review
|
||||||
|
title: Leitbild – Review-System (Weekly · Monthly · Quarterly)
|
||||||
|
type: concept
|
||||||
|
status: active
|
||||||
|
created: 2025-10-31
|
||||||
|
tags: [review, scoreboard, retro, process]
|
||||||
|
lang: de
|
||||||
|
---
|
||||||
|
# Zweck
|
||||||
|
Das Betriebssystem zur Steuerung der Nordsterne.
|
||||||
|
Es verarbeitet Daten aus [[rel:analyzes leitbild-rituale-system]] und prüft [[rel:analyzes leitbild-ziele-portfolio]].
|
||||||
|
|
||||||
|
## 0) Cadence
|
||||||
|
* **Weekly:** Scoreboard & Decision Note.
|
||||||
|
* **Monthly:** Strategie-Check.
|
||||||
|
* **Quarterly:** Meilensteine.
|
||||||
|
|
||||||
|
## 1) Weekly Review (SOP)
|
||||||
|
1. **Scoreboard:** Fakten eintragen.
|
||||||
|
2. **Reflexion:** Wirksamkeit prüfen.
|
||||||
|
3. **Output:** Erstellung einer **Decision Note** (`type: decision`).
|
||||||
|
|
||||||
|
## 2) Monthly & Quarterly
|
||||||
|
* **Monthly:** Roll-up der KPIs.
|
||||||
|
* **Quarterly:** Validierung der Ziele in [[rel:validates leitbild-ziele-portfolio]].
|
||||||
|
|
||||||
|
## Templates (Copy-Paste)
|
||||||
|
|
||||||
|
### Decision Note
|
||||||
|
Nutze dies für Richtungsentscheidungen. Erzeugt `type: decision`.
|
||||||
|
> Siehe [[rel:related_to leitbild-ops-guide]].
|
||||||
|
|
||||||
|
### Deviation Note (Schuldschein)
|
||||||
|
Nutze dies bei Abweichung von Werten.
|
||||||
|
> Referenziert [[rel:checks_compliance_of leitbild-werte]].
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
---
|
||||||
|
id: leitbild-rituale-system
|
||||||
|
title: Leitbild – Rituale & Systeme
|
||||||
|
type: concept
|
||||||
|
status: active
|
||||||
|
created: 2025-10-31
|
||||||
|
updated: 2025-10-31
|
||||||
|
tags: [rituale, habits, recovery, system-design]
|
||||||
|
lang: de
|
||||||
|
---
|
||||||
|
# Ziel
|
||||||
|
Das Betriebssystem für Recovery & Alltag.
|
||||||
|
Es operationalisiert die Ziele aus [[rel:solves leitbild-ziele-portfolio]] und sichert die Prinzipien aus [[rel:enforces leitbild-prinzipien]].
|
||||||
|
|
||||||
|
## DAILY RITUALE
|
||||||
|
|
||||||
|
### R1 – Meditation (Zazen) · 20 Minuten
|
||||||
|
* **Trigger:** Erster ruhiger 30′-Block.
|
||||||
|
* **Aktion:** Zazen (Atem zählen 1-10).
|
||||||
|
* **Zweck:** Dient dem Ziel [[rel:contributes_to leitbild-ziele-portfolio#Nordstern Ich-Pflege]].
|
||||||
|
|
||||||
|
### R2 – Flexibilität/Mobility · 10 Minuten
|
||||||
|
* **Trigger:** Mittagspause Start.
|
||||||
|
* **Aktion:** Mobility Flow.
|
||||||
|
|
||||||
|
### R3 – Abendliches Journal
|
||||||
|
* **Trigger:** Licht aus.
|
||||||
|
* **Aktion:** 3 Zeilen (Gut, Gelernt, Fokus).
|
||||||
|
* **Datenfluss:** Speist Daten in [[rel:feeds leitbild-review]].
|
||||||
|
|
||||||
|
### R6 – 1:1 mit Rohan
|
||||||
|
* **Trigger:** Nach Abendessen.
|
||||||
|
* **Aktion:** Bindungs-Check.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## PERIODISCHE RITUALE
|
||||||
|
|
||||||
|
### R5 – Paar-Ritual Tanzen (Weekly)
|
||||||
|
Stärkt die Rolle [[rel:related_to leitbild-rollen#Partner]].
|
||||||
|
|
||||||
|
### R7 – 1:1 mit Rouven (Weekly)
|
||||||
|
Walk & Talk.
|
||||||
|
|
||||||
|
### R4 – Familienrat light (14-tägig)
|
||||||
|
Klärt Regeln und Standards.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## MESSUNG & ZIELE
|
||||||
|
* **KPIs:** R1-R3 ≥6/7.
|
||||||
|
* **Relapse-Shield:** Mini-Reset ≤24 h.
|
||||||
|
* **Tracking:** Siehe [[rel:related_to leitbild-review]].
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
---
|
||||||
|
id: leitbild-rollen
|
||||||
|
title: Leitbild – Rollenlandkarte
|
||||||
|
type: profile
|
||||||
|
status: active
|
||||||
|
created: 2025-10-30
|
||||||
|
updated: 2025-10-31
|
||||||
|
tags: [topic/rollen, identity, persona]
|
||||||
|
lang: de
|
||||||
|
---
|
||||||
|
# Rollenlandkarte
|
||||||
|
|
||||||
|
Diese Rollen definieren meine Identität und verfolgen die Strategien in [[rel:pursues leitbild-ziele-portfolio]].
|
||||||
|
|
||||||
|
## Vater
|
||||||
|
**Mission:** Verlässlich präsent, ruhige Führung, Stärkung der Selbstwirksamkeit.
|
||||||
|
**Ziele:** Siehe [[rel:pursues leitbild-ziele-portfolio#Nordstern Vater]].
|
||||||
|
**Qualitätskriterien:**
|
||||||
|
* Nähe & Präsenz (Täglich 1:1).
|
||||||
|
* Faire Führung (Bedürfnis-Check vor Konsequenz).
|
||||||
|
* Ordnung (Küche morgens sauber).
|
||||||
|
|
||||||
|
## Partner
|
||||||
|
**Mission:** Team-Alltag, faire Lastverteilung, zärtliche Präsenz.
|
||||||
|
**Ziele:** Siehe [[rel:pursues leitbild-ziele-portfolio#Nordstern Partner]].
|
||||||
|
**Qualitätskriterien:**
|
||||||
|
* Weekly Load-Check.
|
||||||
|
* Energie schützen (Ruhefenster vor Terminen).
|
||||||
|
|
||||||
|
## Berufsrolle (Umbrella)
|
||||||
|
**Mission:** Evidenzbasiert, wertorientiert, menschenzentriert.
|
||||||
|
**Ziele:** Siehe [[rel:pursues leitbild-ziele-portfolio#Nordstern Beruf]].
|
||||||
|
**Sub-Rollen:**
|
||||||
|
1. **A1 Research Lead:** Insight/Monat, Deep-Dive/Quartal.
|
||||||
|
2. **A2 IT-Kosten:** Playbooks, Savings-Pipeline.
|
||||||
|
3. **A3 Ausbilder:** Lernkurven, Placement-Rate.
|
||||||
|
|
||||||
|
## Karate- & Gewaltschutztrainer
|
||||||
|
**Mission:** Budo-Werte, Kinderschutz, Trainer-Multiplikation.
|
||||||
|
**Ziele:** Siehe [[rel:pursues leitbild-ziele-portfolio#Nordstern Karate]].
|
||||||
|
**Qualitätskriterien:**
|
||||||
|
* Sichere Progression (Reifegradpfade).
|
||||||
|
* Trainer-Pipeline (S1 Shadowing → S4 Lead).
|
||||||
|
|
||||||
|
## Freund
|
||||||
|
**Mission:** Verlässlich, loyal, Kontakt auf Augenhöhe.
|
||||||
|
**Ziele:** Siehe [[rel:pursues leitbild-ziele-portfolio#Nordstern Freund]].
|
||||||
|
**Qualitätskriterien:**
|
||||||
|
* Kontakt-Cadence (1 Ping/Monat).
|
||||||
|
* Kein Gossip, keine Rettung ohne Kapazität.
|
||||||
|
|
||||||
|
## Ich-Pflege
|
||||||
|
**Mission:** Körper, Geist und Herz gesund halten.
|
||||||
|
**Ziele:** Siehe [[rel:pursues leitbild-ziele-portfolio#Nordstern Ich-Pflege]].
|
||||||
|
**Guardrails:** Kein Training durch Schmerz.
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
---
|
||||||
|
id: leitbild-scope
|
||||||
|
title: Leitbild – Scope (Session 0, final)
|
||||||
|
type: concept
|
||||||
|
status: active
|
||||||
|
created: 2025-10-30
|
||||||
|
tags: [topic/leitbild, history, scope]
|
||||||
|
lang: de
|
||||||
|
---
|
||||||
|
# Schlüsselpunkte (Session 0 – Konstitution)
|
||||||
|
|
||||||
|
Dieses Dokument definiert den Kontext für das Projekt [[rel:defines_scope_for leitbild-text]].
|
||||||
|
|
||||||
|
## 1. Auslöser & Kontext
|
||||||
|
Ursprung: Schicksalsschlag (Glioblastom). Dies führte zu einer Neuausrichtung der Prioritäten.
|
||||||
|
Neue Rollen: Research-Lead, IT-Cost, Ausbilder (siehe [[rel:related_to leitbild-rollen]]).
|
||||||
|
|
||||||
|
## 2. Familienphase
|
||||||
|
Fokus auf Bindung und Halt für die Söhne (18 & 15).
|
||||||
|
|
||||||
|
## 3. Zweck
|
||||||
|
Strategischer Kompass, keine operative Checkliste.
|
||||||
|
|
||||||
|
## 8. Wertekern
|
||||||
|
Fokus auf **Integrität** und **Vertrauen** (definiert in [[rel:related_to leitbild-wertekompass]]).
|
||||||
|
|
||||||
|
## 13. 90-Tage-Checks
|
||||||
|
Initiale Metriken für den Start (mittlerweile abgelöst durch [[rel:replaced_by leitbild-review]]).
|
||||||
|
|
||||||
|
### Kompass-Formel
|
||||||
|
„Ich spiegle jede wichtige Entscheidung am Werte-Modell.“
|
||||||
|
Dies ist die Basis für das Prinzip [[rel:leads_to leitbild-prinzipien#P1 Integrität]].
|
||||||
@@ -0,0 +1,80 @@
|
|||||||
|
---
|
||||||
|
id: leitbild-text
|
||||||
|
title: Persönliches Leitbild (2025–2029)
|
||||||
|
type: concept
|
||||||
|
status: active
|
||||||
|
created: 2025-10-31
|
||||||
|
updated: 2025-10-31
|
||||||
|
tags: [leitbild, werte, prinzipien, rollen, nordsterne, ich-perspektive]
|
||||||
|
lang: de
|
||||||
|
---
|
||||||
|
# Wer ich bin
|
||||||
|
Ich bin Lars. Ich stehe für Verlässlichkeit, klare Haltung und freundliche Konsequenz.
|
||||||
|
Schicksalsschläge haben mich geerdet. Ich wähle bewusst: **präsent sein, fair handeln, vorleben statt fordern**.
|
||||||
|
Dieser Text ist die narrative Klammer um [[rel:summarizes leitbild-scope]].
|
||||||
|
|
||||||
|
# Wofür ich jeden Morgen aufstehe
|
||||||
|
Ich baue ein Zuhause für meine Kinder. Ich pflege meine Partnerschaft.
|
||||||
|
Ich diene als Trainer und Ausbilder: **ideenreich, integer, wirksam**.
|
||||||
|
Dies definiert meine Identität in [[rel:defined_by leitbild-rollen]].
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Meine Kernwerte (kompakt)
|
||||||
|
Das Fundament für alle Entscheidungen (siehe [[rel:based_on leitbild-werte]]):
|
||||||
|
|
||||||
|
* **Integrität** – Wort = Verpflichtung.
|
||||||
|
* **Disziplin (mit Menschlichkeit)** – Konsequent, aber fair.
|
||||||
|
* **Respekt** – Jeder Mensch ist gleichwürdig.
|
||||||
|
|
||||||
|
**Ergänzende Leitwerte:** Fürsorge, Klarheit, Lernorientierung (siehe [[rel:related_to leitbild-wertekompass]]).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Handlungsprinzipien (Auszug)
|
||||||
|
Konkrete Regeln aus [[rel:derived_from leitbild-prinzipien]]:
|
||||||
|
* **Vorbild vor Anspruch.**
|
||||||
|
* **Verstehen vor Antworten.**
|
||||||
|
* **Repair first.**
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Rollen & Missionen
|
||||||
|
Zusammenfassung der Profile aus [[rel:summarizes leitbild-rollen]]:
|
||||||
|
|
||||||
|
### Vater
|
||||||
|
Präsent, fair, verlässlich. Stärkt Bindung und Selbstwirksamkeit.
|
||||||
|
|
||||||
|
### Partner
|
||||||
|
Zugewandt, klar, Lasten teilend.
|
||||||
|
|
||||||
|
### Berufsrolle (AI-first)
|
||||||
|
Research-Tiefe, IT-Kostensenkung, Ausbildung.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Nordsterne (2025–2029)
|
||||||
|
Die strategischen Ziele aus [[rel:summarizes leitbild-ziele-portfolio]]:
|
||||||
|
1. **Vater:** Starke Bindung, klare Standards.
|
||||||
|
2. **Ich-Pflege:** Ruhe, Beweglichkeit.
|
||||||
|
3. **Karate:** Sicheres Lernökosystem.
|
||||||
|
4. **Partner:** Nähe als Team.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Rituale als Systeme
|
||||||
|
Umsetzung via [[rel:uses leitbild-rituale-system]]:
|
||||||
|
* **R1** Meditation
|
||||||
|
* **R3** Journal
|
||||||
|
* **R4** Familienrat light
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Standards & Grenzen
|
||||||
|
Abweichungen werden dokumentiert via [[rel:uses leitbild-review]] (Decision Notes).
|
||||||
|
* **Zuhause:** Ablagen frei, Küche sauber.
|
||||||
|
* **Nein-Liste:** Keine Verwässerung der Nordsterne.
|
||||||
|
|
||||||
|
> [!edge]
|
||||||
|
> derived_from: [[leitbild-werte]], [[leitbild-rollen]]
|
||||||
|
> guides: [[leitbild-ops-guide]]
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
---
|
||||||
|
id: leitbild-werte
|
||||||
|
title: Leitbild – Werte (Top-5)
|
||||||
|
type: value
|
||||||
|
status: active
|
||||||
|
created: 2025-10-30
|
||||||
|
updated: 2025-10-30
|
||||||
|
tags: [topic/werte, method/values-inventory, core-values]
|
||||||
|
lang: de
|
||||||
|
---
|
||||||
|
# Werte – Top-5 (Priorität für 12 Monate)
|
||||||
|
|
||||||
|
> **Decision Engine Hinweis:** Diese Werte haben Priorität 1. Bei Konflikten schlagen sie andere Erwägungen.
|
||||||
|
> Sie sind das Fundament für [[rel:leads_to leitbild-prinzipien]].
|
||||||
|
|
||||||
|
## 1) Integrität
|
||||||
|
**Definition:** Ich handle **vorhersagbar principled**; **mein Wort gilt**.
|
||||||
|
**Anker:** Entscheidungen am Werte-Modell spiegeln.
|
||||||
|
**Anti-Pattern:** Rigidität.
|
||||||
|
|
||||||
|
## 2) Vertrauenswürdigkeit & Ehrlichkeit
|
||||||
|
**Definition:** **Wort gilt**; Abweichungen offen ansprechen.
|
||||||
|
**Anker:** 24h-Reparatur bei Verstößen.
|
||||||
|
|
||||||
|
## 3) Disziplin
|
||||||
|
**Definition:** Ich halte zugesagte Standards und Regeln verlässlich ein.
|
||||||
|
**Anker:** Wenige klare Regeln, ruhig durchgesetzt.
|
||||||
|
**Bezug:** Ermöglicht das System [[rel:enables leitbild-rituale-system]].
|
||||||
|
|
||||||
|
## 4) Gerechtigkeit & Fairness
|
||||||
|
**Definition:** Transparente Maßstäbe für alle.
|
||||||
|
**Anker:** Keine Impuls-Strafen; Steelman-Argumentation.
|
||||||
|
|
||||||
|
## 5) Respekt
|
||||||
|
**Definition:** Ich erkenne jeden Menschen als gleichwertig an.
|
||||||
|
**Anker:** Sprache ohne Abwertung; erst verstehen, dann antworten.
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
---
|
||||||
|
id: leitbild-wertekompass
|
||||||
|
title: Leitbild – Wertekompass (vollständig)
|
||||||
|
type: value
|
||||||
|
status: active
|
||||||
|
created: 2025-10-30
|
||||||
|
updated: 2025-10-30
|
||||||
|
tags: [topic/werte, method/values-inventory]
|
||||||
|
lang: de
|
||||||
|
---
|
||||||
|
# Wertekompass – vollständige Übersicht
|
||||||
|
|
||||||
|
> Zweck: Arbeitsinventar aller relevanten Werte.
|
||||||
|
> Dieser Kompass definiert die Basis für [[rel:derived_from leitbild-werte]] (Top-5) und stützt die Prinzipien in [[rel:supports leitbild-prinzipien]].
|
||||||
|
|
||||||
|
## Tier 1 – Kernwerte (Top-5, verbindlich)
|
||||||
|
1. **Integrität** – Ich handle vorhersagbar principled; mein Wort gilt.
|
||||||
|
2. **Vertrauenswürdigkeit & Ehrlichkeit** – Zusagen sind verlässlich.
|
||||||
|
3. **Disziplin** – Ich halte zugesagte Standards.
|
||||||
|
4. **Gerechtigkeit & Fairness** – Klare Maßstäbe für alle.
|
||||||
|
5. **Respekt** – Würdigung von Mensch und Prozess.
|
||||||
|
|
||||||
|
> Details und Verhaltensanker findest du im verkürzten Dokument [[rel:related_to leitbild-werte]].
|
||||||
|
|
||||||
|
## Tier 2 – Unterstützungswerte **on deck** (12 Monate)
|
||||||
|
Diese Werte dienen als Reserve und Nuance für Entscheidungen.
|
||||||
|
|
||||||
|
### Fürsorge & Familienbindung
|
||||||
|
* **Kurz:** Ich bin ansprechbar und stärke Bindung aktiv.
|
||||||
|
* **Anker:** Wöchentliche Qualitätszeit.
|
||||||
|
* **Bezug:** Stützt die Rolle [[rel:supports leitbild-rollen#Vater]].
|
||||||
|
|
||||||
|
### Klarheit & Struktur
|
||||||
|
* **Kurz:** Wenige Regeln, klare Zuständigkeiten.
|
||||||
|
* **Anker:** „Wer macht was bis wann“.
|
||||||
|
|
||||||
|
### Lernorientierung
|
||||||
|
* **Kurz:** Neugierig bleiben, Lerngewinne teilen.
|
||||||
|
* **Anker:** „Teach-back“ als Standard.
|
||||||
|
* **Bezug:** Stützt die Rolle [[rel:supports leitbild-rollen#Berufsrolle]].
|
||||||
|
|
||||||
|
### Großzügigkeit
|
||||||
|
* **Kurz:** Zeit/Wissen teilen, ohne sich zu verbrennen.
|
||||||
|
|
||||||
|
### Mut
|
||||||
|
* **Kurz:** Unangenehmes respektvoll ansprechen.
|
||||||
|
|
||||||
|
## Arbeitsregeln
|
||||||
|
* **Konflikte:** Tier 1 schlägt Tier 2.
|
||||||
|
* **Ausnahmen:** Dokumentation via `type: decision` (Schuldschein).
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
---
|
||||||
|
id: leitbild-ziele-portfolio
|
||||||
|
title: Leitbild – Ziele-Portfolio (Nordsterne komplett)
|
||||||
|
type: goal
|
||||||
|
status: active
|
||||||
|
created: 2025-10-30
|
||||||
|
updated: 2025-10-31
|
||||||
|
tags: [topic/ziele, method/objectives, scope/nordsterne]
|
||||||
|
lang: de
|
||||||
|
---
|
||||||
|
# Ziele-Portfolio (Nordsterne)
|
||||||
|
|
||||||
|
Diese Datei definiert die strategischen Outcomes 2026–2029.
|
||||||
|
Der Fortschritt wird überwacht durch [[rel:measured_by leitbild-review]].
|
||||||
|
|
||||||
|
## Nordstern: Vater
|
||||||
|
**Ziel:** Verlässlich präsent, ruhig und gerecht.
|
||||||
|
**Strategie:** Tägliche Nähe, faire Führung.
|
||||||
|
**Bezug:** Definiert Erfolg für [[rel:defines_success_for leitbild-rollen#Vater]].
|
||||||
|
**KPIs:** 1:1 ≥5 Tage/W; Konsequenzen-Quote ≥90%.
|
||||||
|
|
||||||
|
## Nordstern: Ich-Pflege
|
||||||
|
**Ziel:** Belastbar, schmerzfrei trainierbar.
|
||||||
|
**Strategie:** Reha-Bridge, Zazen, Ernährung.
|
||||||
|
**KPIs:** Kraft ≥2×/W; Mobility ≥4×/W.
|
||||||
|
|
||||||
|
## Nordstern: Karate & Gewaltschutz
|
||||||
|
**Ziel:** Sicheres Lernökosystem & Traineraufbau.
|
||||||
|
**Bezug:** Definiert Erfolg für [[rel:defines_success_for leitbild-rollen#Karate-Trainer]].
|
||||||
|
**KPIs:** ≥2 neue Leads/Jahr.
|
||||||
|
|
||||||
|
## Nordstern: Partner
|
||||||
|
**Ziel:** Alltag als Team, faire Lastverteilung.
|
||||||
|
**Strategie:** Weekly Load-Check, Paar-Ritual.
|
||||||
|
**KPIs:** Konflikte ≤48h geklärt.
|
||||||
|
|
||||||
|
## Nordstern: Freund (Neuaufbau)
|
||||||
|
**Ziel:** Neuer Kreis auf Augenhöhe.
|
||||||
|
**Strategie:** Mikro-Events, 90-Tage-Pipeline.
|
||||||
|
|
||||||
|
## Nordstern: Berufsrolle (AI-first)
|
||||||
|
**Ziel:** Evidenzbasiert, IT-Kostensenkung, Assetisierung.
|
||||||
|
**Bezug:** Definiert Erfolg für [[rel:defines_success_for leitbild-rollen#Berufsrolle]].
|
||||||
|
**Strategie:** AI-OS v1, Reuse-Quote ≥50%.
|
||||||
Reference in new issue
Block a user