Compare commits
221
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f6f3213b84 | ||
|
|
e5db7011f3 | ||
|
|
b0bc8518ed | ||
|
|
046b648286 | ||
|
|
e04aecb0c5 | ||
|
|
d64ba06809 | ||
|
|
b0d73cb053 | ||
|
|
5213d262a2 | ||
|
|
2985f5288b | ||
|
|
27b404560c | ||
|
|
16e128668c | ||
|
|
ecfdc67485 | ||
|
|
c9cf1b7e4c | ||
|
|
fa6eb0795a | ||
|
|
4ac504a4ae | ||
|
|
56dd1bcd84 | ||
|
|
b4a07a05af | ||
|
|
5c55229376 | ||
|
|
f3fd71b828 | ||
|
|
079cf174d4 | ||
|
|
4ab44e36a2 | ||
|
|
5278c75ac1 | ||
|
|
a908853c30 | ||
|
|
867a7a8b44 | ||
|
|
2c073c7d3c | ||
|
|
0157faab89 | ||
|
|
f1bfa40b5b | ||
|
|
dcc3083455 | ||
|
|
a5b4dfb31f | ||
|
|
a733212c0f | ||
|
|
49b454d2ec | ||
|
|
18780e5330 | ||
|
|
36fb27edf0 | ||
|
|
c60aba63a4 | ||
|
|
2a98c37ca1 | ||
|
|
0ac8a14ea7 | ||
|
|
234949800b | ||
|
|
c68c7404cf | ||
|
|
f8ed7bb62e | ||
|
|
81d005d969 | ||
|
|
99482ad65a | ||
|
|
2d43e0596c | ||
|
|
74cac7e16c | ||
|
|
0c2dc61cb5 | ||
|
|
97c3461685 | ||
|
|
41e7a49d52 | ||
|
|
725dc6bda4 | ||
|
|
5da8eb6543 | ||
|
|
4f2296b9b0 | ||
|
|
cb9addb1b6 | ||
|
|
c5198a80d8 | ||
|
|
0df266b2e9 | ||
|
|
444f64e94c | ||
|
|
59bcd227f9 | ||
|
|
7f707cffb9 | ||
|
|
a50c4494c6 | ||
|
|
418612cd10 | ||
|
|
828fe1f8ce | ||
|
|
c184c3cae2 | ||
|
|
2cd3605017 | ||
|
|
0d71f41a13 | ||
|
|
f5bfb0cfb4 | ||
|
|
f7ab32ebf4 | ||
|
|
64dbd57fc5 | ||
|
|
ba46957556 | ||
|
|
33b0c83c87 | ||
|
|
5dd58f49f0 | ||
|
|
cc12dcf993 | ||
|
|
cbfdd96152 | ||
|
|
babab3167b | ||
|
|
c61d9c8236 | ||
|
|
e47241740d | ||
|
|
6db1714449 | ||
|
|
136c3bb43f | ||
|
|
2c3ee8efd6 | ||
|
|
48729e6f5d | ||
|
|
3eac646cb6 | ||
|
|
9a18f3cc8b | ||
|
|
5dd20d683f | ||
|
|
8af744fc97 | ||
|
|
342d3e5103 | ||
|
|
7f7d8c87db | ||
|
|
43f695de54 | ||
|
|
20b219d86c | ||
|
|
0ff39d7b14 | ||
|
|
e2ee5df815 | ||
|
|
77a6db7e92 | ||
|
|
d53912a8f1 | ||
|
|
cdcaff184f | ||
|
|
25ec3880bb | ||
|
|
edbd8f0ca8 | ||
|
|
a4272c17a9 | ||
|
|
c8cdf218f2 | ||
|
|
b3833f2051 | ||
|
|
a272c39613 | ||
|
|
6df9b54626 | ||
|
|
156c2c2fd5 | ||
|
|
6011b96fc1 | ||
|
|
7639bb8472 | ||
|
|
c61b66b49d | ||
|
|
cf49715c66 | ||
|
|
bf8a814c58 | ||
|
|
8fadec5c2c | ||
|
|
7263fee4c7 | ||
|
|
4204c2c974 | ||
|
|
9372cfb8ca | ||
|
|
179949b289 | ||
|
|
cd3946bd11 | ||
|
|
12e374bc05 | ||
|
|
fd2fac7112 | ||
|
|
60092b378b | ||
|
|
9025af62f0 | ||
|
|
83bb18b6a7 | ||
|
|
ec759dd1dc | ||
|
|
c454fc40bb | ||
|
|
bfb42cfc24 | ||
|
|
49dd91fee0 | ||
|
|
56c1862205 | ||
|
|
dbefd30dce | ||
|
|
bc06ce5b90 | ||
|
|
b26d9fd10e | ||
|
|
909ee338d2 | ||
|
|
84e319a42f | ||
|
|
efd9c74cd3 | ||
|
|
eccdf43cd3 | ||
|
|
9e25e5b26b | ||
|
|
cee8fc05c2 | ||
|
|
9a55d45832 | ||
|
|
48de6aed8c | ||
|
|
8772271648 | ||
|
|
0cb216c2bc | ||
|
|
eb45d78c47 | ||
|
|
582aed61ec | ||
|
|
0294414d26 | ||
|
|
3a2a78e0fd | ||
|
|
245a96809a | ||
|
|
bb41b11cce | ||
|
|
af73ab9371 | ||
|
|
cba1337066 | ||
|
|
d50ed70467 | ||
|
|
f313f0873b | ||
|
|
f7a4dab707 | ||
|
|
3861246ac6 | ||
|
|
053c22bc15 | ||
|
|
bbfa2049eb | ||
|
|
0b47ffdcb6 | ||
|
|
cf91730e45 | ||
|
|
ae0768e4de | ||
|
|
ccc848f2e2 | ||
|
|
c6ccad1d18 | ||
|
|
4e8512c812 | ||
|
|
f1bcbb1543 | ||
|
|
537a2883bf | ||
|
|
72a3988e49 | ||
|
|
93b8bc48e4 | ||
|
|
19f8d76e21 | ||
|
|
772a202d6e | ||
|
|
dc16bbf8a4 | ||
|
|
028ad7e941 | ||
|
|
620858a575 | ||
|
|
0bb5f57cc6 | ||
|
|
0a4374dc8c | ||
|
|
8afa402118 | ||
|
|
1eee189a49 | ||
|
|
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 |
No files matched your search
@@ -1,4 +1,3 @@
|
|||||||
|
|
||||||
# mindnet API (bundle)
|
# mindnet API (bundle)
|
||||||
|
|
||||||
This bundle provides a minimal FastAPI app for embeddings and Qdrant upserts/queries plus a Markdown importer.
|
This bundle provides a minimal FastAPI app for embeddings and Qdrant upserts/queries plus a Markdown importer.
|
||||||
@@ -35,5 +34,5 @@ python3 scripts/import_markdown.py --vault /path/to/Obsidian
|
|||||||
See `scripts/quick_test.sh` for a runnable example.
|
See `scripts/quick_test.sh` for a runnable example.
|
||||||
|
|
||||||
>Anmerkung:
|
>Anmerkung:
|
||||||
Diese Datei ist veraltet
|
Diese Datei ist veraltet und muss auf Stand 2.6.0 gebracht werden
|
||||||
|
|
||||||
+6
-13
@@ -1,17 +1,10 @@
|
|||||||
"""
|
"""
|
||||||
app — mindnet API package
|
FILE: app/__init__.py
|
||||||
|
DESCRIPTION: Paket-Initialisierung.
|
||||||
Zweck:
|
VERSION: 0.1.0
|
||||||
Markiert 'app/' als Python-Paket, damit 'from app.main import create_app'
|
STATUS: Active
|
||||||
in Tests und Skripten funktioniert.
|
DEPENDENCIES: None
|
||||||
Kompatibilität:
|
LAST_ANALYSIS: 2025-12-15
|
||||||
Python 3.12+
|
|
||||||
Version:
|
|
||||||
0.1.0 (Erstanlage)
|
|
||||||
Stand:
|
|
||||||
2025-10-07
|
|
||||||
Hinweise:
|
|
||||||
Keine Logik – nur Paketinitialisierung.
|
|
||||||
"""
|
"""
|
||||||
|
|
||||||
__version__ = "0.1.0"
|
__version__ = "0.1.0"
|
||||||
+50
-11
@@ -1,36 +1,74 @@
|
|||||||
"""
|
"""
|
||||||
app/config.py — zentrale Konfiguration
|
FILE: app/config.py
|
||||||
Version: 0.4.0 (WP-06 Complete)
|
DESCRIPTION: Zentrale Pydantic-Konfiguration.
|
||||||
|
WP-20: Hybrid-Cloud Modus Support (OpenRouter/Gemini/Ollama).
|
||||||
|
FIX: Einführung von Parametern zur intelligenten Rate-Limit Steuerung (429 Handling).
|
||||||
|
VERSION: 0.6.7
|
||||||
|
STATUS: Active
|
||||||
|
DEPENDENCIES: os, functools, pathlib, python-dotenv
|
||||||
"""
|
"""
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
import os
|
import os
|
||||||
from functools import lru_cache
|
from functools import lru_cache
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
from dotenv import load_dotenv
|
||||||
|
|
||||||
|
# WP-20: Lade Umgebungsvariablen aus der .env Datei
|
||||||
|
# override=True garantiert, dass Änderungen in der .env immer Vorrang haben.
|
||||||
|
load_dotenv(override=True)
|
||||||
|
|
||||||
class Settings:
|
class Settings:
|
||||||
# Qdrant
|
# --- Qdrant Datenbank ---
|
||||||
QDRANT_URL: str = os.getenv("QDRANT_URL", "http://127.0.0.1:6333")
|
QDRANT_URL: str = os.getenv("QDRANT_URL", "http://127.0.0.1:6333")
|
||||||
QDRANT_API_KEY: str | None = os.getenv("QDRANT_API_KEY")
|
QDRANT_API_KEY: str | None = os.getenv("QDRANT_API_KEY")
|
||||||
COLLECTION_PREFIX: str = os.getenv("MINDNET_PREFIX", "mindnet")
|
COLLECTION_PREFIX: str = os.getenv("MINDNET_PREFIX", "mindnet_dev")
|
||||||
VECTOR_SIZE: int = int(os.getenv("MINDNET_VECTOR_SIZE", "384"))
|
|
||||||
|
# WP-22: Vektor-Dimension für das Embedding-Modell (nomic)
|
||||||
|
VECTOR_SIZE: int = int(os.getenv("VECTOR_DIM", "768"))
|
||||||
DISTANCE: str = os.getenv("MINDNET_DISTANCE", "Cosine")
|
DISTANCE: str = os.getenv("MINDNET_DISTANCE", "Cosine")
|
||||||
|
|
||||||
# Embeddings
|
# --- Lokale Embeddings (Ollama & Sentence-Transformers) ---
|
||||||
|
EMBEDDING_MODEL: str = os.getenv("MINDNET_EMBEDDING_MODEL", "nomic-embed-text")
|
||||||
MODEL_NAME: str = os.getenv("MINDNET_MODEL", "sentence-transformers/all-MiniLM-L6-v2")
|
MODEL_NAME: str = os.getenv("MINDNET_MODEL", "sentence-transformers/all-MiniLM-L6-v2")
|
||||||
|
|
||||||
# WP-05 LLM / Ollama
|
# --- WP-20 Hybrid LLM Provider ---
|
||||||
|
# Erlaubt: "ollama" | "gemini" | "openrouter"
|
||||||
|
MINDNET_LLM_PROVIDER: str = os.getenv("MINDNET_LLM_PROVIDER", "openrouter").lower()
|
||||||
|
|
||||||
|
# Google AI Studio (2025er Lite-Modell für höhere Kapazität)
|
||||||
|
GOOGLE_API_KEY: str | None = os.getenv("GOOGLE_API_KEY")
|
||||||
|
GEMINI_MODEL: str = os.getenv("MINDNET_GEMINI_MODEL", "gemini-2.5-flash-lite")
|
||||||
|
|
||||||
|
# OpenRouter Integration (Verfügbares Free-Modell 2025)
|
||||||
|
OPENROUTER_API_KEY: str | None = os.getenv("OPENROUTER_API_KEY")
|
||||||
|
OPENROUTER_MODEL: str = os.getenv("OPENROUTER_MODEL", "mistralai/mistral-7b-instruct:free")
|
||||||
|
|
||||||
|
LLM_FALLBACK_ENABLED: bool = os.getenv("MINDNET_LLM_FALLBACK", "true").lower() == "true"
|
||||||
|
|
||||||
|
# --- NEU: Intelligente Rate-Limit Steuerung ---
|
||||||
|
# Dauer der Wartezeit in Sekunden, wenn ein HTTP 429 (Rate Limit) auftritt
|
||||||
|
LLM_RATE_LIMIT_WAIT: float = float(os.getenv("MINDNET_LLM_RATE_LIMIT_WAIT", "60.0"))
|
||||||
|
# Anzahl der Cloud-Retries bei 429, bevor Ollama-Fallback greift
|
||||||
|
LLM_RATE_LIMIT_RETRIES: int = int(os.getenv("MINDNET_LLM_RATE_LIMIT_RETRIES", "3"))
|
||||||
|
|
||||||
|
# --- WP-05 Lokales LLM (Ollama) ---
|
||||||
OLLAMA_URL: str = os.getenv("MINDNET_OLLAMA_URL", "http://127.0.0.1:11434")
|
OLLAMA_URL: str = os.getenv("MINDNET_OLLAMA_URL", "http://127.0.0.1:11434")
|
||||||
LLM_MODEL: str = os.getenv("MINDNET_LLM_MODEL", "phi3:mini")
|
LLM_MODEL: str = os.getenv("MINDNET_LLM_MODEL", "phi3:mini")
|
||||||
PROMPTS_PATH: str = os.getenv("MINDNET_PROMPTS_PATH", "config/prompts.yaml")
|
PROMPTS_PATH: str = os.getenv("MINDNET_PROMPTS_PATH", "config/prompts.yaml")
|
||||||
|
|
||||||
# NEU für WP-06
|
# --- WP-06 / WP-14 Performance & Last-Steuerung ---
|
||||||
LLM_TIMEOUT: float = float(os.getenv("MINDNET_LLM_TIMEOUT", "120.0"))
|
LLM_TIMEOUT: float = float(os.getenv("MINDNET_LLM_TIMEOUT", "300.0"))
|
||||||
DECISION_CONFIG_PATH: str = os.getenv("MINDNET_DECISION_CONFIG", "config/decision_engine.yaml")
|
DECISION_CONFIG_PATH: str = os.getenv("MINDNET_DECISION_CONFIG", "config/decision_engine.yaml")
|
||||||
|
BACKGROUND_LIMIT: int = int(os.getenv("MINDNET_LLM_BACKGROUND_LIMIT", "2"))
|
||||||
|
|
||||||
# API
|
# --- System-Pfade & Ingestion-Logik ---
|
||||||
DEBUG: bool = os.getenv("DEBUG", "false").lower() == "true"
|
DEBUG: bool = os.getenv("DEBUG", "false").lower() == "true"
|
||||||
|
MINDNET_VAULT_ROOT: str = os.getenv("MINDNET_VAULT_ROOT", "./vault_master")
|
||||||
|
MINDNET_TYPES_FILE: str = os.getenv("MINDNET_TYPES_FILE", "config/types.yaml")
|
||||||
|
MINDNET_VOCAB_PATH: str = os.getenv("MINDNET_VOCAB_PATH", "/mindnet/vault/mindnet/_system/dictionary/edge_vocabulary.md")
|
||||||
|
CHANGE_DETECTION_MODE: str = os.getenv("MINDNET_CHANGE_DETECTION_MODE", "full")
|
||||||
|
|
||||||
# WP-04 Retriever Defaults
|
# --- WP-04 Retriever Gewichte ---
|
||||||
RETRIEVER_W_SEM: float = float(os.getenv("MINDNET_WP04_W_SEM", "0.70"))
|
RETRIEVER_W_SEM: float = float(os.getenv("MINDNET_WP04_W_SEM", "0.70"))
|
||||||
RETRIEVER_W_EDGE: float = float(os.getenv("MINDNET_WP04_W_EDGE", "0.25"))
|
RETRIEVER_W_EDGE: float = float(os.getenv("MINDNET_WP04_W_EDGE", "0.25"))
|
||||||
RETRIEVER_W_CENT: float = float(os.getenv("MINDNET_WP04_W_CENT", "0.05"))
|
RETRIEVER_W_CENT: float = float(os.getenv("MINDNET_WP04_W_CENT", "0.05"))
|
||||||
@@ -40,4 +78,5 @@ class Settings:
|
|||||||
|
|
||||||
@lru_cache
|
@lru_cache
|
||||||
def get_settings() -> Settings:
|
def get_settings() -> Settings:
|
||||||
|
"""Gibt die zentralen Einstellungen als Singleton zurück."""
|
||||||
return Settings()
|
return Settings()
|
||||||
@@ -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)
|
|
||||||
+76
-36
@@ -1,11 +1,13 @@
|
|||||||
#!/usr/bin/env python3
|
|
||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""
|
"""
|
||||||
app/core/chunk_payload.py (Mindnet V2 — types.yaml authoritative)
|
FILE: app/core/chunk_payload.py
|
||||||
- neighbors_prev / neighbors_next sind Listen ([], [id]).
|
DESCRIPTION: Baut das JSON-Objekt für 'mindnet_chunks'.
|
||||||
- retriever_weight / chunk_profile kommen aus types.yaml (Frontmatter wird ignoriert).
|
FEATURES:
|
||||||
- Fallbacks: defaults.* in types.yaml; sonst 1.0 / "default".
|
- Inkludiert Nachbarschafts-IDs (prev/next) und Titel.
|
||||||
- WP-11 Update: Injects 'title' into chunk payload for Discovery Service.
|
- FIX 3: Robuste Erkennung des Inputs (Frontmatter-Dict vs. Note-Objekt), damit Overrides ankommen.
|
||||||
|
VERSION: 2.3.0
|
||||||
|
STATUS: Active
|
||||||
|
DEPENDENCIES: yaml, os
|
||||||
|
EXTERNAL_CONFIG: config/types.yaml
|
||||||
"""
|
"""
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
from typing import Any, Dict, List, Optional
|
from typing import Any, Dict, List, Optional
|
||||||
@@ -36,42 +38,48 @@ def _get_defaults(reg: dict) -> dict:
|
|||||||
return {}
|
return {}
|
||||||
|
|
||||||
def _as_float(x: Any):
|
def _as_float(x: Any):
|
||||||
try:
|
try: return float(x)
|
||||||
return float(x)
|
except Exception: return None
|
||||||
except Exception:
|
|
||||||
return None
|
|
||||||
|
|
||||||
def _resolve_chunk_profile(note_type: str, reg: dict) -> str:
|
def _resolve_chunk_profile_from_config(note_type: str, reg: dict) -> Optional[str]:
|
||||||
|
# 1. Type Level
|
||||||
types = _get_types_map(reg)
|
types = _get_types_map(reg)
|
||||||
if isinstance(types, dict):
|
if isinstance(types, dict):
|
||||||
t = types.get(note_type, {})
|
t = types.get(note_type, {})
|
||||||
if isinstance(t, dict) and isinstance(t.get("chunk_profile"), str):
|
if isinstance(t, dict):
|
||||||
return t["chunk_profile"]
|
cp = t.get("chunking_profile") or t.get("chunk_profile")
|
||||||
|
if isinstance(cp, str) and cp: return cp
|
||||||
|
# 2. Defaults Level
|
||||||
defs = _get_defaults(reg)
|
defs = _get_defaults(reg)
|
||||||
if isinstance(defs, dict) and isinstance(defs.get("chunk_profile"), str):
|
if isinstance(defs, dict):
|
||||||
return defs["chunk_profile"]
|
cp = defs.get("chunking_profile") or defs.get("chunk_profile")
|
||||||
return "default"
|
if isinstance(cp, str) and cp: return cp
|
||||||
|
return None
|
||||||
|
|
||||||
def _resolve_retriever_weight(note_type: str, reg: dict) -> float:
|
def _resolve_retriever_weight_from_config(note_type: str, reg: dict) -> float:
|
||||||
|
"""
|
||||||
|
Liest Weight nur aus Config (Type > Default).
|
||||||
|
Wird aufgerufen, wenn im Frontmatter nichts steht.
|
||||||
|
"""
|
||||||
|
# 1. Type Level
|
||||||
types = _get_types_map(reg)
|
types = _get_types_map(reg)
|
||||||
if isinstance(types, dict):
|
if isinstance(types, dict):
|
||||||
t = types.get(note_type, {})
|
t = types.get(note_type, {})
|
||||||
if isinstance(t, dict) and (t.get("retriever_weight") is not None):
|
if isinstance(t, dict) and (t.get("retriever_weight") is not None):
|
||||||
v = _as_float(t.get("retriever_weight"))
|
v = _as_float(t.get("retriever_weight"))
|
||||||
if v is not None:
|
if v is not None: return float(v)
|
||||||
return float(v)
|
|
||||||
|
# 2. Defaults Level
|
||||||
defs = _get_defaults(reg)
|
defs = _get_defaults(reg)
|
||||||
if isinstance(defs, dict) and (defs.get("retriever_weight") is not None):
|
if isinstance(defs, dict) and (defs.get("retriever_weight") is not None):
|
||||||
v = _as_float(defs.get("retriever_weight"))
|
v = _as_float(defs.get("retriever_weight"))
|
||||||
if v is not None:
|
if v is not None: return float(v)
|
||||||
return float(v)
|
|
||||||
return 1.0
|
return 1.0
|
||||||
|
|
||||||
def _as_list(x):
|
def _as_list(x):
|
||||||
if x is None:
|
if x is None: return []
|
||||||
return []
|
if isinstance(x, list): return x
|
||||||
if isinstance(x, list):
|
|
||||||
return x
|
|
||||||
return [x]
|
return [x]
|
||||||
|
|
||||||
def make_chunk_payloads(note: Dict[str, Any],
|
def make_chunk_payloads(note: Dict[str, Any],
|
||||||
@@ -81,18 +89,49 @@ def make_chunk_payloads(note: Dict[str, Any],
|
|||||||
note_text: str = "",
|
note_text: str = "",
|
||||||
types_cfg: Optional[dict] = None,
|
types_cfg: Optional[dict] = None,
|
||||||
file_path: Optional[str] = None) -> List[Dict[str, Any]]:
|
file_path: Optional[str] = None) -> List[Dict[str, Any]]:
|
||||||
fm = (note or {}).get("frontmatter", {}) or {}
|
"""
|
||||||
|
Erstellt die Payloads für die Chunks.
|
||||||
|
|
||||||
|
Argument 'note' kann sein:
|
||||||
|
A) Ein komplexes Objekt/Dict mit Key "frontmatter" (Legacy / Tests)
|
||||||
|
B) Direkt das Frontmatter-Dictionary (Call aus ingestion.py)
|
||||||
|
"""
|
||||||
|
|
||||||
|
# --- FIX 3: Intelligente Erkennung der Input-Daten ---
|
||||||
|
# Wir prüfen: Ist 'note' ein Container MIT 'frontmatter', oder IST es das 'frontmatter'?
|
||||||
|
if isinstance(note, dict) and "frontmatter" in note and isinstance(note["frontmatter"], dict):
|
||||||
|
# Fall A: Container (wir müssen auspacken)
|
||||||
|
fm = note["frontmatter"]
|
||||||
|
else:
|
||||||
|
# Fall B: Direktes Dict (so ruft ingestion.py es auf!)
|
||||||
|
fm = note 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
|
# Title Extraction (Fallback Chain)
|
||||||
# Wir holen den Titel aus Frontmatter oder Fallback ID/Untitled
|
|
||||||
title = fm.get("title") or note.get("title") or fm.get("id") or "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
|
# --- Profil-Ermittlung ---
|
||||||
cp = _resolve_chunk_profile(note_type, reg)
|
# Da wir 'fm' jetzt korrekt haben, funktionieren diese lookups:
|
||||||
rw = _resolve_retriever_weight(note_type, reg)
|
cp = fm.get("chunking_profile") or fm.get("chunk_profile")
|
||||||
|
|
||||||
|
if not cp:
|
||||||
|
cp = _resolve_chunk_profile_from_config(note_type, reg)
|
||||||
|
if not cp:
|
||||||
|
cp = "sliding_standard"
|
||||||
|
|
||||||
|
# --- Retriever Weight Ermittlung ---
|
||||||
|
rw = fm.get("retriever_weight")
|
||||||
|
|
||||||
|
if rw is None:
|
||||||
|
rw = _resolve_retriever_weight_from_config(note_type, reg)
|
||||||
|
|
||||||
|
try:
|
||||||
|
rw = float(rw)
|
||||||
|
except Exception:
|
||||||
|
rw = 1.0
|
||||||
|
|
||||||
tags = fm.get("tags") or []
|
tags = fm.get("tags") or []
|
||||||
if isinstance(tags, str):
|
if isinstance(tags, str):
|
||||||
@@ -100,7 +139,7 @@ def make_chunk_payloads(note: Dict[str, Any],
|
|||||||
|
|
||||||
out: List[Dict[str, Any]] = []
|
out: List[Dict[str, Any]] = []
|
||||||
for idx, ch in enumerate(chunks_from_chunker):
|
for idx, ch in enumerate(chunks_from_chunker):
|
||||||
# Attribute oder Keys (Chunk-Objekt oder Dict)
|
# Attribute extrahieren
|
||||||
cid = getattr(ch, "id", None) or (ch.get("id") if isinstance(ch, dict) else None)
|
cid = getattr(ch, "id", None) or (ch.get("id") if isinstance(ch, dict) else None)
|
||||||
nid = getattr(ch, "note_id", None) or (ch.get("note_id") if isinstance(ch, dict) else fm.get("id"))
|
nid = getattr(ch, "note_id", None) or (ch.get("note_id") if isinstance(ch, dict) else fm.get("id"))
|
||||||
index = getattr(ch, "index", None) or (ch.get("index") if isinstance(ch, dict) else idx)
|
index = getattr(ch, "index", None) or (ch.get("index") if isinstance(ch, dict) else idx)
|
||||||
@@ -112,7 +151,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
|
"title": title,
|
||||||
"index": int(index),
|
"index": int(index),
|
||||||
"ord": int(index) + 1,
|
"ord": int(index) + 1,
|
||||||
"type": note_type,
|
"type": note_type,
|
||||||
@@ -125,9 +164,10 @@ def make_chunk_payloads(note: Dict[str, Any],
|
|||||||
"path": note_path,
|
"path": note_path,
|
||||||
"source_path": file_path or note_path,
|
"source_path": file_path or note_path,
|
||||||
"retriever_weight": float(rw),
|
"retriever_weight": float(rw),
|
||||||
"chunk_profile": cp,
|
"chunk_profile": cp, # Jetzt endlich mit dem Override-Wert!
|
||||||
}
|
}
|
||||||
# Aufräumen von Alt-Feldern
|
|
||||||
|
# Cleanup
|
||||||
for alias in ("chunk_num", "Chunk_Number"):
|
for alias in ("chunk_num", "Chunk_Number"):
|
||||||
pl.pop(alias, None)
|
pl.pop(alias, None)
|
||||||
|
|
||||||
|
|||||||
+429
-181
@@ -1,226 +1,474 @@
|
|||||||
|
"""
|
||||||
|
FILE: app/core/chunker.py
|
||||||
|
DESCRIPTION: Zerlegt Texte in Chunks (Sliding Window oder nach Headings).
|
||||||
|
Orchestriert die Smart-Edge-Allocation via SemanticAnalyzer.
|
||||||
|
FIX V3: Support für mehrzeilige Callouts und Section-Propagation.
|
||||||
|
VERSION: 3.1.0 (Full Compatibility Merge)
|
||||||
|
"""
|
||||||
|
|
||||||
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
|
||||||
from markdown_it import MarkdownIt
|
import yaml
|
||||||
from markdown_it.token import Token
|
from pathlib import Path
|
||||||
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
|
||||||
|
# Wir importieren build_edges_for_note nur, um kompatibel zur Signatur zu bleiben
|
||||||
|
# oder für den Fallback.
|
||||||
|
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"
|
||||||
|
# Fallback Default, falls types.yaml fehlt
|
||||||
|
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]:
|
||||||
|
"""
|
||||||
|
Lädt die Chunking-Strategie basierend auf dem Note-Type aus types.yaml.
|
||||||
|
Dies sichert die Kompatibilität zu WP-15 (Profile).
|
||||||
|
"""
|
||||||
|
full_config = _load_yaml_config()
|
||||||
|
profiles = full_config.get("chunking_profiles", {})
|
||||||
|
type_def = full_config.get("types", {}).get(note_type.lower(), {})
|
||||||
|
|
||||||
|
# Welches Profil nutzt dieser Typ? (z.B. 'sliding_smart_edges')
|
||||||
|
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()
|
||||||
|
|
||||||
|
# Tupel-Konvertierung für Overlap (YAML liest oft Listen)
|
||||||
|
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 & TEXT TOOLS
|
||||||
|
# ==========================================
|
||||||
|
|
||||||
|
_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
|
||||||
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).
|
||||||
|
Wichtig für die Strategie 'by_heading'.
|
||||||
|
"""
|
||||||
|
blocks = []
|
||||||
|
h1_title = "Dokument"
|
||||||
section_path = "/"
|
section_path = "/"
|
||||||
cur_text = []
|
current_h2 = None
|
||||||
cur_kind = None
|
|
||||||
|
|
||||||
def push(kind: str, txt: str, lvl: Optional[int]):
|
fm, text_without_fm = extract_frontmatter_from_text(md_text)
|
||||||
nonlocal section_path
|
|
||||||
txt = txt.strip()
|
|
||||||
if not txt:
|
|
||||||
return
|
|
||||||
title = None
|
|
||||||
if kind == "heading" and lvl:
|
|
||||||
title = txt
|
|
||||||
blocks.append(RawBlock(kind=kind, text=txt, level=lvl, section_path=section_path))
|
|
||||||
|
|
||||||
i = 0
|
h1_match = re.search(r'^#\s+(.*)', text_without_fm, re.MULTILINE)
|
||||||
while i < len(tokens):
|
if h1_match:
|
||||||
t = tokens[i]
|
h1_title = h1_match.group(1).strip()
|
||||||
if t.type == "heading_open":
|
|
||||||
lvl = int(t.tag[1])
|
|
||||||
# Sammle heading inline
|
|
||||||
i += 1
|
|
||||||
title_txt = ""
|
|
||||||
while i < len(tokens) and tokens[i].type != "heading_close":
|
|
||||||
if tokens[i].type == "inline":
|
|
||||||
title_txt += tokens[i].content
|
|
||||||
i += 1
|
|
||||||
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"):
|
lines = text_without_fm.split('\n')
|
||||||
# Codeblock hat eigenen content im selben Token
|
buffer = []
|
||||||
content = t.content or ""
|
|
||||||
push(kind, content, None)
|
for line in lines:
|
||||||
|
stripped = line.strip()
|
||||||
|
if stripped.startswith('# '):
|
||||||
|
continue
|
||||||
|
elif stripped.startswith('## '):
|
||||||
|
if buffer:
|
||||||
|
content = "\n".join(buffer).strip()
|
||||||
|
if content:
|
||||||
|
blocks.append(RawBlock("paragraph", content, None, section_path, current_h2))
|
||||||
|
buffer = []
|
||||||
|
current_h2 = stripped[3:].strip()
|
||||||
|
section_path = f"/{current_h2}"
|
||||||
|
blocks.append(RawBlock("heading", stripped, 2, section_path, current_h2))
|
||||||
|
elif not stripped:
|
||||||
|
if buffer:
|
||||||
|
content = "\n".join(buffer).strip()
|
||||||
|
if content:
|
||||||
|
blocks.append(RawBlock("paragraph", content, None, section_path, current_h2))
|
||||||
|
buffer = []
|
||||||
else:
|
else:
|
||||||
# inline sammeln bis close
|
buffer.append(line)
|
||||||
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
|
if buffer:
|
||||||
|
content = "\n".join(buffer).strip()
|
||||||
|
if content:
|
||||||
|
blocks.append(RawBlock("paragraph", content, None, section_path, current_h2))
|
||||||
|
|
||||||
def assemble_chunks(note_id: str, md_text: str, note_type: str) -> List[Chunk]:
|
return blocks, h1_title
|
||||||
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)
|
def _strategy_sliding_window(blocks: List[RawBlock], config: Dict[str, Any], note_id: str, doc_title: str = "", context_prefix: str = "") -> List[Chunk]:
|
||||||
|
"""
|
||||||
|
Die Standard-Strategie aus WP-15.
|
||||||
|
Fasst Blöcke zusammen und schneidet bei 'target' Tokens (mit Satz-Rücksicht).
|
||||||
|
"""
|
||||||
|
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 = []
|
||||||
|
|
||||||
chunks: List[Chunk] = []
|
def _create_chunk(txt, win, sec, path):
|
||||||
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:
|
|
||||||
_emit(text)
|
|
||||||
buf = []
|
|
||||||
|
|
||||||
def _emit(text_block: str):
|
|
||||||
nonlocal chunks, char_pos
|
|
||||||
idx = len(chunks)
|
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(
|
chunks.append(Chunk(
|
||||||
id=chunk_id,
|
id=f"{note_id}#c{idx:02d}", note_id=note_id, index=idx,
|
||||||
note_id=note_id,
|
text=txt, window=win, token_count=estimate_tokens(txt),
|
||||||
index=idx,
|
section_title=sec, section_path=path, neighbors_prev=None, neighbors_next=None,
|
||||||
text=text_block,
|
suggested_edges=[]
|
||||||
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
|
def flush_buffer():
|
||||||
cur_sec_title = None
|
nonlocal buf
|
||||||
|
if not buf: return
|
||||||
|
|
||||||
|
text_body = "\n\n".join([b.text for b in buf])
|
||||||
|
sec_title = buf[-1].section_title if buf else None
|
||||||
|
sec_path = buf[-1].section_path if buf else "/"
|
||||||
|
|
||||||
|
# Context Prefix (z.B. H1) voranstellen für Embedding-Qualität
|
||||||
|
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, sec_title, sec_path)
|
||||||
|
else:
|
||||||
|
# Zu groß -> Satzweiser Split
|
||||||
|
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, sec_title, sec_path)
|
||||||
|
|
||||||
|
# Overlap für nächsten Chunk
|
||||||
|
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
|
||||||
|
|
||||||
|
# Rest
|
||||||
|
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, sec_title, sec_path)
|
||||||
|
|
||||||
|
buf = []
|
||||||
|
|
||||||
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:
|
||||||
|
flush_buffer()
|
||||||
|
|
||||||
|
flush_buffer()
|
||||||
|
return chunks
|
||||||
|
|
||||||
|
def _strategy_by_heading(blocks: List[RawBlock], config: Dict[str, Any], note_id: str, doc_title: str = "") -> List[Chunk]:
|
||||||
|
"""
|
||||||
|
Strategie für strukturierte Daten (Profile, Werte).
|
||||||
|
Nutzt sliding_window, forciert aber Schnitte an Headings (via parse_blocks Vorarbeit).
|
||||||
|
"""
|
||||||
|
return _strategy_sliding_window(blocks, config, note_id, doc_title, context_prefix=f"# {doc_title}")
|
||||||
|
|
||||||
|
# ==========================================
|
||||||
|
# 4. ROBUST EDGE PARSING & PROPAGATION (NEU)
|
||||||
|
# ==========================================
|
||||||
|
|
||||||
|
def _parse_edges_robust(text: str) -> Set[str]:
|
||||||
|
"""
|
||||||
|
NEU: Findet Kanten im Text, auch wenn sie mehrzeilig oder 'kaputt' formatiert sind.
|
||||||
|
Erkennt:
|
||||||
|
> [!edge] type
|
||||||
|
> [[Link]]
|
||||||
|
Returns: Set von Strings "kind:target"
|
||||||
|
"""
|
||||||
|
found_edges = set()
|
||||||
|
|
||||||
|
# A. Inline [[rel:type|target]] (Standard)
|
||||||
|
inlines = re.findall(r'\[\[rel:([^\|\]]+)\|?([^\]]*)\]\]', text)
|
||||||
|
for kind, target in inlines:
|
||||||
|
k = kind.strip()
|
||||||
|
t = target.strip()
|
||||||
|
if k and t: found_edges.add(f"{k}:{t}")
|
||||||
|
|
||||||
|
# B. Multiline Callouts Parsing (Der Fix für dein Problem)
|
||||||
|
lines = text.split('\n')
|
||||||
|
current_edge_type = None
|
||||||
|
|
||||||
|
for line in lines:
|
||||||
|
stripped = line.strip()
|
||||||
|
|
||||||
|
# 1. Start Blockquote: > [!edge] type
|
||||||
|
# (Erlaubt optionalen Doppelpunkt)
|
||||||
|
callout_match = re.match(r'>\s*\[!edge\]\s*([^:\s]+)', stripped)
|
||||||
|
if callout_match:
|
||||||
|
current_edge_type = callout_match.group(1).strip()
|
||||||
|
|
||||||
|
# Check: Sind Links noch in der GLEICHEN Zeile?
|
||||||
|
links = re.findall(r'\[\[([^\]]+)\]\]', stripped)
|
||||||
|
for l in links:
|
||||||
|
if "rel:" not in l:
|
||||||
|
found_edges.add(f"{current_edge_type}:{l}")
|
||||||
continue
|
continue
|
||||||
|
|
||||||
txt = b.text.strip()
|
# 2. Continuation Line: > [[Target]]
|
||||||
if not txt:
|
# Wenn wir noch im 'edge mode' sind und die Zeile ein Zitat ist
|
||||||
continue
|
if current_edge_type and stripped.startswith('>'):
|
||||||
|
links = re.findall(r'\[\[([^\]]+)\]\]', stripped)
|
||||||
|
for l in links:
|
||||||
|
if "rel:" not in l:
|
||||||
|
found_edges.add(f"{current_edge_type}:{l}")
|
||||||
|
|
||||||
tentative = "\n\n".join([*(x[0] for x in buf), txt]).strip()
|
# 3. End of Blockquote (kein '>') -> Reset Type
|
||||||
if estimate_tokens(tentative) > max(get_sizes(note_type)["target"]):
|
elif not stripped.startswith('>'):
|
||||||
# weicher Schnitt vor Hinzufügen
|
current_edge_type = None
|
||||||
flush_buffer()
|
|
||||||
buf.append((txt, cur_sec_title, b.section_path))
|
|
||||||
|
|
||||||
# bei Erreichen ~Target flushen
|
return found_edges
|
||||||
if estimate_tokens("\n\n".join([x[0] for x in buf])) >= target:
|
|
||||||
flush_buffer()
|
|
||||||
|
|
||||||
flush_buffer(force=True)
|
def _propagate_section_edges(chunks: List[Chunk]) -> List[Chunk]:
|
||||||
|
"""
|
||||||
|
NEU: Verteilt Kanten innerhalb einer Sektion.
|
||||||
|
Löst das Problem: Callout steht oben im Kapitel, gilt aber für alle Chunks darunter.
|
||||||
|
"""
|
||||||
|
# Step 1: Sammeln pro Sektion
|
||||||
|
section_map = {} # path -> set(kind:target)
|
||||||
|
|
||||||
# neighbors setzen
|
for ch in chunks:
|
||||||
|
# Root-Level "/" ignorieren wir meist, da zu global
|
||||||
|
if not ch.section_path or ch.section_path == "/": continue
|
||||||
|
|
||||||
|
edges = _parse_edges_robust(ch.text)
|
||||||
|
if edges:
|
||||||
|
if ch.section_path not in section_map:
|
||||||
|
section_map[ch.section_path] = set()
|
||||||
|
section_map[ch.section_path].update(edges)
|
||||||
|
|
||||||
|
# Step 2: Injizieren (Broadcasting)
|
||||||
|
for ch in chunks:
|
||||||
|
if ch.section_path in section_map:
|
||||||
|
edges_to_add = section_map[ch.section_path]
|
||||||
|
if not edges_to_add: continue
|
||||||
|
|
||||||
|
injections = []
|
||||||
|
for e_str in edges_to_add:
|
||||||
|
kind, target = e_str.split(':', 1)
|
||||||
|
# Check: Kante schon im Text?
|
||||||
|
token = f"[[rel:{kind}|{target}]]"
|
||||||
|
if token not in ch.text:
|
||||||
|
injections.append(token)
|
||||||
|
|
||||||
|
if injections:
|
||||||
|
# Wir schreiben die Kanten "hart" in den Text.
|
||||||
|
# Damit findet sie derive_edges.py später garantiert.
|
||||||
|
block = "\n\n\n" + " ".join(injections)
|
||||||
|
ch.text += block
|
||||||
|
# Auch ins Window schreiben für Embedding-Kontext
|
||||||
|
ch.window += block
|
||||||
|
|
||||||
|
return chunks
|
||||||
|
|
||||||
|
# ==========================================
|
||||||
|
# 5. ORCHESTRATION (ASYNC)
|
||||||
|
# ==========================================
|
||||||
|
|
||||||
|
async def assemble_chunks(note_id: str, md_text: str, note_type: str, config: Optional[Dict] = None) -> List[Chunk]:
|
||||||
|
"""
|
||||||
|
Hauptfunktion. Verbindet Parsing, Splitting und Edge-Allocation.
|
||||||
|
"""
|
||||||
|
# 1. Config laden (WP-15 Kompatibilität)
|
||||||
|
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)
|
||||||
|
|
||||||
|
# Drafts skippen LLM um Kosten/Zeit zu sparen
|
||||||
|
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
|
||||||
|
|
||||||
|
# 2. Parsing & Splitting
|
||||||
|
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 []
|
||||||
|
|
||||||
|
# 3. NEU: Propagation VOR Smart Edge Allocation
|
||||||
|
# Das repariert die fehlenden Kanten aus deinen Callouts.
|
||||||
|
chunks = _propagate_section_edges(chunks)
|
||||||
|
|
||||||
|
# 4. Smart Edges (LLM)
|
||||||
|
if enable_smart_edges:
|
||||||
|
chunks = await _run_smart_edge_allocation(chunks, md_text, note_id, note_type)
|
||||||
|
|
||||||
|
# 5. Linking
|
||||||
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
|
||||||
|
|
||||||
|
def _extract_all_edges_from_md(md_text: str, note_id: str, note_type: str) -> List[str]:
|
||||||
|
"""
|
||||||
|
Hilfsfunktion: Sammelt ALLE Kanten für den LLM-Kandidaten-Pool.
|
||||||
|
"""
|
||||||
|
# A. Via derive_edges (Standard)
|
||||||
|
dummy_chunk = {
|
||||||
|
"chunk_id": f"{note_id}#full",
|
||||||
|
"text": md_text,
|
||||||
|
"content": md_text,
|
||||||
|
"window": md_text,
|
||||||
|
"type": note_type
|
||||||
|
}
|
||||||
|
# Signatur-Anpassung beachten (WP-15 Fix)
|
||||||
|
raw_edges = build_edges_for_note(
|
||||||
|
note_id,
|
||||||
|
[dummy_chunk],
|
||||||
|
note_level_references=None,
|
||||||
|
include_note_scope_refs=False
|
||||||
|
)
|
||||||
|
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}")
|
||||||
|
|
||||||
|
# B. Via Robust Parser (NEU) - fängt die multiline Callouts
|
||||||
|
robust_edges = _parse_edges_robust(md_text)
|
||||||
|
all_candidates.update(robust_edges)
|
||||||
|
|
||||||
|
return list(all_candidates)
|
||||||
|
|
||||||
|
async def _run_smart_edge_allocation(chunks: List[Chunk], full_text: str, note_id: str, note_type: str) -> List[Chunk]:
|
||||||
|
"""
|
||||||
|
Der LLM-Schritt (WP-15). Filtert irrelevante Kanten.
|
||||||
|
"""
|
||||||
|
analyzer = get_semantic_analyzer()
|
||||||
|
candidate_list = _extract_all_edges_from_md(full_text, note_id, note_type)
|
||||||
|
|
||||||
|
if not candidate_list:
|
||||||
|
return chunks
|
||||||
|
|
||||||
|
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)
|
||||||
|
|
||||||
|
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:
|
||||||
|
# Wir schreiben auch Smart Edges hart in den Text
|
||||||
|
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
|
||||||
|
|
||||||
|
# Fallback für Kanten, die das LLM nirgendwo zugeordnet hat
|
||||||
|
# (Damit nichts verloren geht -> Safety Fallback)
|
||||||
|
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
|
return chunks
|
||||||
@@ -1,26 +1,11 @@
|
|||||||
#!/usr/bin/env python3
|
|
||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""
|
"""
|
||||||
Modul: app/core/derive_edges.py
|
FILE: app/core/derive_edges.py
|
||||||
Zweck:
|
DESCRIPTION: Extrahiert Graph-Kanten aus Text. Unterstützt Wikilinks, Inline-Relations ([[rel:type|target]]) und Obsidian Callouts.
|
||||||
- Bewahrt bestehende Edgelogik (belongs_to, prev/next, references, backlink)
|
VERSION: 2.0.0
|
||||||
- Ergänzt typenbasierte Default-Kanten (edge_defaults aus config/types.yaml)
|
STATUS: Active
|
||||||
- Unterstützt "typed inline relations":
|
DEPENDENCIES: re, os, yaml, typing
|
||||||
* [[rel:KIND | Target]]
|
EXTERNAL_CONFIG: config/types.yaml
|
||||||
* [[rel:KIND Target]]
|
LAST_ANALYSIS: 2025-12-15
|
||||||
* rel: KIND [[Target]]
|
|
||||||
- Unterstützt Obsidian-Callouts:
|
|
||||||
* > [!edge] KIND: [[Target]] [[Target2]] ...
|
|
||||||
Kompatibilität:
|
|
||||||
- build_edges_for_note(...) Signatur unverändert
|
|
||||||
- rule_id Werte:
|
|
||||||
* structure:belongs_to
|
|
||||||
* structure:order
|
|
||||||
* explicit:wikilink
|
|
||||||
* inline:rel
|
|
||||||
* callout:edge
|
|
||||||
* edge_defaults:<type>:<relation>
|
|
||||||
* derived:backlink
|
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|||||||
@@ -1,296 +0,0 @@
|
|||||||
#!/usr/bin/env python3
|
|
||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""
|
|
||||||
Modul: app/core/edges.py
|
|
||||||
Version: 2.0.0 (V2‑superset, rückwärtskompatibel zu v1 vom 2025‑09‑09)
|
|
||||||
|
|
||||||
Zweck
|
|
||||||
-----
|
|
||||||
Bewahrt die bestehende Edgelogik (belongs_to, prev/next, references, backlink)
|
|
||||||
und ergänzt V2‑Felder + Typ‑Default‑Kanten gemäß config/types.yaml (edge_defaults).
|
|
||||||
Die Funktion ist **idempotent** und **rückwärtskompatibel** zur bisherigen Signatur.
|
|
||||||
|
|
||||||
Kompatibilitätsgarantien (gegenüber v1):
|
|
||||||
- **Input**: akzeptiert identische Chunk‑Payloads wie v1:
|
|
||||||
* `id` (Chunk‑ID), `note_id` (Owner), `neighbors.prev|next` (optional),
|
|
||||||
`references: [{target_id: ...}]` (optional),
|
|
||||||
alternativ: `chunk_id`, `chunk_index|ord`, `window|text`
|
|
||||||
- **Output (v1‑Felder)**: `kind`, `source_id`, `target_id`, `scope`, `note_id`, `edge_id`
|
|
||||||
- **Neu (v2‑Felder)**: `relation`, `src_note_id`, `src_chunk_id?`, `dst_note_id`, `dst_chunk_id?`,
|
|
||||||
`provenance` (`explicit|rule`), `rule_id?`, `confidence?`
|
|
||||||
|
|
||||||
Regeln
|
|
||||||
------
|
|
||||||
- Deduplizierungsschlüssel: (source_id, target_id, relation, rule_id)
|
|
||||||
- Strukturkanten:
|
|
||||||
* belongs_to: 1× pro Chunk
|
|
||||||
* next/prev: Sequenz der Chunks; nutzt bevorzugt neighbors; sonst ord/chunk_index
|
|
||||||
- Explizite Referenzen:
|
|
||||||
* aus Chunk: `references[].target_id` (falls vorhanden)
|
|
||||||
* Fallback: Wikilinks in `window|text`: [[Some Title|some-id]] oder [[some-id]]
|
|
||||||
- Note‑Scope:
|
|
||||||
* backlink immer; references nur, wenn include_note_scope_refs=True
|
|
||||||
- Typ‑Defaults (edge_defaults aus config/types.yaml des **Quell‑Notiztyps**):
|
|
||||||
* Für jede explizite Referenz wird je default‑Relation eine Regel‑Kante erzeugt
|
|
||||||
* rule_id: "type_default:{note_type}:{relation}:v1", provenance="rule"
|
|
||||||
|
|
||||||
Konfiguration
|
|
||||||
-------------
|
|
||||||
- ENV MINDNET_TYPES_FILE (Default: ./config/types.yaml)
|
|
||||||
|
|
||||||
Lizenz/Autor
|
|
||||||
------------
|
|
||||||
- Erstimplementierung v1 (2025‑09‑09) — Projekt Mindnet
|
|
||||||
- Erweiterung v2 (2025‑11‑11) — kompatible Superset‑Implementierung
|
|
||||||
"""
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
import os
|
|
||||||
import re
|
|
||||||
from typing import Dict, Iterable, List, Optional, Tuple, Set
|
|
||||||
|
|
||||||
try:
|
|
||||||
import yaml # optional, nur für types.yaml
|
|
||||||
except Exception: # pragma: no cover
|
|
||||||
yaml = None
|
|
||||||
|
|
||||||
# ------------------------------------------------------------
|
|
||||||
# Hilfen: types.yaml laden (edge_defaults)
|
|
||||||
# ------------------------------------------------------------
|
|
||||||
|
|
||||||
def _types_path() -> str:
|
|
||||||
return os.getenv("MINDNET_TYPES_FILE") or "./config/types.yaml"
|
|
||||||
|
|
||||||
def _load_types() -> Dict[str, dict]:
|
|
||||||
p = _types_path()
|
|
||||||
if not os.path.isfile(p) or yaml is None:
|
|
||||||
return {}
|
|
||||||
try:
|
|
||||||
with open(p, "r", encoding="utf-8") as f:
|
|
||||||
data = yaml.safe_load(f) or {}
|
|
||||||
if isinstance(data, dict) and "types" in data and isinstance(data["types"], dict):
|
|
||||||
return data["types"]
|
|
||||||
return data if isinstance(data, dict) else {}
|
|
||||||
except Exception:
|
|
||||||
return {}
|
|
||||||
|
|
||||||
def _edge_defaults_for(note_type: Optional[str]) -> List[str]:
|
|
||||||
types = _load_types()
|
|
||||||
t = (note_type or "").strip().lower()
|
|
||||||
cfg = types.get(t) or {}
|
|
||||||
defaults = cfg.get("edge_defaults") or []
|
|
||||||
if isinstance(defaults, str):
|
|
||||||
defaults = [defaults]
|
|
||||||
return [str(x) for x in defaults if isinstance(x, (str, int, float))]
|
|
||||||
|
|
||||||
# ------------------------------------------------------------
|
|
||||||
# Wikilink‑Parser (Fallback, wenn ch["references"] fehlt)
|
|
||||||
# ------------------------------------------------------------
|
|
||||||
|
|
||||||
_WIKILINK_RE = re.compile(r"\[\[(?:[^\|\]]+\|)?([a-zA-Z0-9_\-#:. ]+)\]\]")
|
|
||||||
|
|
||||||
def _extract_wikilinks(text: str) -> List[str]:
|
|
||||||
ids: List[str] = []
|
|
||||||
for m in _WIKILINK_RE.finditer(text or ""):
|
|
||||||
ids.append(m.group(1).strip())
|
|
||||||
return ids
|
|
||||||
|
|
||||||
# ------------------------------------------------------------
|
|
||||||
# Utility
|
|
||||||
# ------------------------------------------------------------
|
|
||||||
|
|
||||||
def _mk_edge_id(kind: str, s: str, t: str, scope: str, rule_id: Optional[str] = None) -> str:
|
|
||||||
base = f"{kind}:{s}->{t}#{scope}"
|
|
||||||
if rule_id:
|
|
||||||
base += f"|{rule_id}"
|
|
||||||
try:
|
|
||||||
import hashlib
|
|
||||||
return hashlib.blake2s(base.encode("utf-8"), digest_size=12).hexdigest()
|
|
||||||
except Exception: # pragma: no cover
|
|
||||||
return base
|
|
||||||
|
|
||||||
def _dedupe(edges: List[Dict]) -> List[Dict]:
|
|
||||||
seen: Set[Tuple[str,str,str,str]] = set()
|
|
||||||
out: List[Dict] = []
|
|
||||||
for e in edges:
|
|
||||||
s = str(e.get("source_id") or "")
|
|
||||||
t = str(e.get("target_id") or "")
|
|
||||||
rel = str(e.get("relation") or e.get("kind") or "edge")
|
|
||||||
rule = str(e.get("rule_id") or "")
|
|
||||||
key = (s, t, rel, rule)
|
|
||||||
if key in seen:
|
|
||||||
continue
|
|
||||||
seen.add(key)
|
|
||||||
out.append(e)
|
|
||||||
return out
|
|
||||||
|
|
||||||
def _first(v: dict, *keys, default=None):
|
|
||||||
for k in keys:
|
|
||||||
if k in v and v[k] is not None:
|
|
||||||
return v[k]
|
|
||||||
return default
|
|
||||||
|
|
||||||
# ------------------------------------------------------------
|
|
||||||
# Hauptfunktion
|
|
||||||
# ------------------------------------------------------------
|
|
||||||
|
|
||||||
def build_edges_for_note(
|
|
||||||
note_id: str,
|
|
||||||
chunk_payloads: List[Dict],
|
|
||||||
note_level_refs: Optional[List[str]] = None,
|
|
||||||
*,
|
|
||||||
include_note_scope_refs: bool = False,
|
|
||||||
) -> List[Dict]:
|
|
||||||
edges: List[Dict] = []
|
|
||||||
chunks = list(chunk_payloads or [])
|
|
||||||
# Notiztyp aus erstem Chunk ableiten (kompatibel zu existierenden Payloads)
|
|
||||||
note_type = (chunks[0].get("type") if chunks else None) or (chunks[0].get("note_type") if chunks else None)
|
|
||||||
|
|
||||||
# --- Strukturkanten ------------------------------------------------------
|
|
||||||
# belongs_to
|
|
||||||
for ch in chunks:
|
|
||||||
cid = _first(ch, "id", "chunk_id")
|
|
||||||
if not cid:
|
|
||||||
continue
|
|
||||||
owner = ch.get("note_id") or note_id
|
|
||||||
e = {
|
|
||||||
"edge_id": _mk_edge_id("belongs_to", cid, note_id, "chunk", "structure:belongs_to:v1"),
|
|
||||||
"kind": "belongs_to",
|
|
||||||
"relation": "belongs_to",
|
|
||||||
"scope": "chunk",
|
|
||||||
"source_id": cid,
|
|
||||||
"target_id": note_id,
|
|
||||||
"note_id": owner, # v1-Kompat
|
|
||||||
# v2
|
|
||||||
"src_note_id": owner,
|
|
||||||
"src_chunk_id": cid,
|
|
||||||
"dst_note_id": note_id,
|
|
||||||
"provenance": "rule",
|
|
||||||
"rule_id": "structure:belongs_to:v1",
|
|
||||||
"confidence": 1.0,
|
|
||||||
}
|
|
||||||
edges.append(e)
|
|
||||||
|
|
||||||
# next/prev — bevorzugt neighbors.prev/next; sonst via ord/chunk_index
|
|
||||||
# Map der Chunks nach Index
|
|
||||||
ordered = list(chunks)
|
|
||||||
def _idx(c):
|
|
||||||
return _first(c, "chunk_index", "ord", default=0)
|
|
||||||
ordered.sort(key=_idx)
|
|
||||||
|
|
||||||
for i, ch in enumerate(ordered):
|
|
||||||
cid = _first(ch, "id", "chunk_id")
|
|
||||||
if not cid:
|
|
||||||
continue
|
|
||||||
owner = ch.get("note_id") or note_id
|
|
||||||
nb = ch.get("neighbors") or {}
|
|
||||||
prev_id = nb.get("prev")
|
|
||||||
next_id = nb.get("next")
|
|
||||||
# Fallback-Reihenfolge
|
|
||||||
if prev_id is None and i > 0:
|
|
||||||
prev_id = _first(ordered[i-1], "id", "chunk_id")
|
|
||||||
if next_id is None and i+1 < len(ordered):
|
|
||||||
next_id = _first(ordered[i+1], "id", "chunk_id")
|
|
||||||
|
|
||||||
if prev_id:
|
|
||||||
edges.append({
|
|
||||||
"edge_id": _mk_edge_id("prev", cid, prev_id, "chunk", "structure:order:v1"),
|
|
||||||
"kind": "prev", "relation": "prev", "scope": "chunk",
|
|
||||||
"source_id": cid, "target_id": prev_id, "note_id": owner,
|
|
||||||
"src_note_id": owner, "src_chunk_id": cid,
|
|
||||||
"dst_note_id": owner, "dst_chunk_id": prev_id,
|
|
||||||
"provenance": "rule", "rule_id": "structure:order:v1", "confidence": 0.95,
|
|
||||||
})
|
|
||||||
edges.append({
|
|
||||||
"edge_id": _mk_edge_id("next", prev_id, cid, "chunk", "structure:order:v1"),
|
|
||||||
"kind": "next", "relation": "next", "scope": "chunk",
|
|
||||||
"source_id": prev_id, "target_id": cid, "note_id": owner,
|
|
||||||
"src_note_id": owner, "src_chunk_id": prev_id,
|
|
||||||
"dst_note_id": owner, "dst_chunk_id": cid,
|
|
||||||
"provenance": "rule", "rule_id": "structure:order:v1", "confidence": 0.95,
|
|
||||||
})
|
|
||||||
|
|
||||||
# --- Explizite Referenzen (Chunk‑Scope) ---------------------------------
|
|
||||||
explicit_refs: List[Dict] = []
|
|
||||||
for ch in chunks:
|
|
||||||
cid = _first(ch, "id", "chunk_id")
|
|
||||||
if not cid:
|
|
||||||
continue
|
|
||||||
owner = ch.get("note_id") or note_id
|
|
||||||
# 1) bevorzugt vorhandene ch["references"]
|
|
||||||
refs = ch.get("references") or []
|
|
||||||
targets = [r.get("target_id") for r in refs if isinstance(r, dict) and r.get("target_id")]
|
|
||||||
# 2) Fallback: Wikilinks aus Text
|
|
||||||
if not targets:
|
|
||||||
text = _first(ch, "window", "text", default="") or ""
|
|
||||||
targets = _extract_wikilinks(text)
|
|
||||||
for tid in targets:
|
|
||||||
if not isinstance(tid, str) or not tid.strip():
|
|
||||||
continue
|
|
||||||
e = {
|
|
||||||
"edge_id": _mk_edge_id("references", cid, tid, "chunk"),
|
|
||||||
"kind": "references",
|
|
||||||
"relation": "references",
|
|
||||||
"scope": "chunk",
|
|
||||||
"source_id": cid,
|
|
||||||
"target_id": tid,
|
|
||||||
"note_id": owner,
|
|
||||||
# v2
|
|
||||||
"src_note_id": owner,
|
|
||||||
"src_chunk_id": cid,
|
|
||||||
"dst_note_id": tid,
|
|
||||||
"provenance": "explicit",
|
|
||||||
"rule_id": "",
|
|
||||||
"confidence": 1.0,
|
|
||||||
}
|
|
||||||
edges.append(e)
|
|
||||||
explicit_refs.append(e)
|
|
||||||
|
|
||||||
# --- Note‑Scope: references (optional) + backlink (immer) ----------------
|
|
||||||
unique_refs = []
|
|
||||||
if note_level_refs:
|
|
||||||
seen = set()
|
|
||||||
for tid in note_level_refs:
|
|
||||||
if isinstance(tid, str) and tid.strip() and tid not in seen:
|
|
||||||
unique_refs.append(tid); seen.add(tid)
|
|
||||||
|
|
||||||
for tid in unique_refs:
|
|
||||||
if include_note_scope_refs:
|
|
||||||
edges.append({
|
|
||||||
"edge_id": _mk_edge_id("references", note_id, tid, "note"),
|
|
||||||
"kind": "references", "relation": "references", "scope": "note",
|
|
||||||
"source_id": note_id, "target_id": tid, "note_id": note_id,
|
|
||||||
"src_note_id": note_id, "dst_note_id": tid,
|
|
||||||
"provenance": "explicit", "rule_id": "", "confidence": 1.0,
|
|
||||||
})
|
|
||||||
edges.append({
|
|
||||||
"edge_id": _mk_edge_id("backlink", tid, note_id, "note", "derived:backlink:v1"),
|
|
||||||
"kind": "backlink", "relation": "backlink", "scope": "note",
|
|
||||||
"source_id": tid, "target_id": note_id, "note_id": note_id,
|
|
||||||
"src_note_id": tid, "dst_note_id": note_id,
|
|
||||||
"provenance": "rule", "rule_id": "derived:backlink:v1", "confidence": 0.9,
|
|
||||||
})
|
|
||||||
|
|
||||||
# --- Type‑Defaults je expliziter Referenz --------------------------------
|
|
||||||
defaults = [d for d in _edge_defaults_for(note_type) if d and d != "references"]
|
|
||||||
if defaults:
|
|
||||||
for e in explicit_refs + ([ ] if not include_note_scope_refs else []):
|
|
||||||
# wir nutzen die bereits erzeugten explicit‑Edges als Vorlage
|
|
||||||
src = e["source_id"]; tgt = e["target_id"]
|
|
||||||
scope = e.get("scope", "chunk")
|
|
||||||
s_note = e.get("src_note_id") or note_id
|
|
||||||
s_chunk = e.get("src_chunk_id")
|
|
||||||
t_note = e.get("dst_note_id") or tgt
|
|
||||||
for rel in defaults:
|
|
||||||
rule_id = f"type_default:{(note_type or 'unknown')}:{rel}:v1"
|
|
||||||
edges.append({
|
|
||||||
"edge_id": _mk_edge_id(rel, src, tgt, scope, rule_id),
|
|
||||||
"kind": rel, "relation": rel, "scope": scope,
|
|
||||||
"source_id": src, "target_id": tgt, "note_id": s_note,
|
|
||||||
"src_note_id": s_note, "src_chunk_id": s_chunk,
|
|
||||||
"dst_note_id": t_note,
|
|
||||||
"provenance": "rule", "rule_id": rule_id, "confidence": 0.7,
|
|
||||||
})
|
|
||||||
|
|
||||||
# --- Dedupe & Return -----------------------------------------------------
|
|
||||||
return _dedupe(edges)
|
|
||||||
@@ -1,94 +0,0 @@
|
|||||||
# app/core/edges_writer.py
|
|
||||||
from __future__ import annotations
|
|
||||||
import hashlib
|
|
||||||
from typing import Dict, List, Iterable, Tuple
|
|
||||||
|
|
||||||
try:
|
|
||||||
# Dein Modul mit der Schemadefinition und der Builder-Funktion
|
|
||||||
from app.core.edges import build_edges_for_note # noqa: F401
|
|
||||||
except Exception as e:
|
|
||||||
raise RuntimeError("Konnte app.core.edges nicht importieren. "
|
|
||||||
"Bitte sicherstellen, dass app/core/edges.py vorhanden ist.") from e
|
|
||||||
|
|
||||||
def _edge_uid(kind: str, source_id: str, target_id: str, scope: str) -> str:
|
|
||||||
"""
|
|
||||||
Deterministische, kurze ID für eine Edge.
|
|
||||||
Kollisionen sind praktisch ausgeschlossen (BLAKE2s über den Kanonischen Schlüssel).
|
|
||||||
"""
|
|
||||||
key = f"{kind}|{source_id}|{target_id}|{scope}"
|
|
||||||
return hashlib.blake2s(key.encode("utf-8"), digest_size=12).hexdigest()
|
|
||||||
|
|
||||||
def ensure_edges_collection(qdrant_client, collection: str) -> None:
|
|
||||||
"""
|
|
||||||
Legt die Edge-Collection an, falls sie nicht existiert.
|
|
||||||
Minimal: 1D-Vector (Dummy), Cosine. Payload-only-Collections sind je nach Qdrant-Version heikel.
|
|
||||||
"""
|
|
||||||
from qdrant_client.http import models as qm
|
|
||||||
|
|
||||||
existing = [c.name for c in qdrant_client.get_collections().collections]
|
|
||||||
if collection in existing:
|
|
||||||
return
|
|
||||||
|
|
||||||
qdrant_client.recreate_collection(
|
|
||||||
collection_name=collection,
|
|
||||||
vectors_config=qm.VectorParams(size=1, distance=qm.Distance.COSINE),
|
|
||||||
on_disk_payload=True,
|
|
||||||
)
|
|
||||||
|
|
||||||
def edges_from_note(
|
|
||||||
note_id: str,
|
|
||||||
chunk_payloads: List[Dict],
|
|
||||||
note_level_refs: Iterable[str] | None,
|
|
||||||
*,
|
|
||||||
include_note_scope_refs: bool = False,
|
|
||||||
) -> List[Dict]:
|
|
||||||
"""
|
|
||||||
Ruft deinen Edge-Builder auf und gibt die (deduplizierten) Edge-Payloads zurück.
|
|
||||||
Keine Schemaänderung – exakt das aus app/core/edges.py.
|
|
||||||
"""
|
|
||||||
return build_edges_for_note(
|
|
||||||
note_id=note_id,
|
|
||||||
chunk_payloads=chunk_payloads,
|
|
||||||
note_level_refs=list(note_level_refs or []),
|
|
||||||
include_note_scope_refs=include_note_scope_refs,
|
|
||||||
)
|
|
||||||
|
|
||||||
def upsert_edges(
|
|
||||||
qdrant_client,
|
|
||||||
collection: str,
|
|
||||||
edge_payloads: List[Dict],
|
|
||||||
) -> Tuple[int, int]:
|
|
||||||
"""
|
|
||||||
Schreibt Edges als Points in Qdrant.
|
|
||||||
- id: deterministisch aus (kind, source_id, target_id, scope)
|
|
||||||
- vector: [0.0] Dummy
|
|
||||||
- payload: Edge-Dict (unverändert, siehe Schema in app/core/edges.py)
|
|
||||||
Gibt (anzahl_points, anzahl_unique_keys) zurück.
|
|
||||||
"""
|
|
||||||
from qdrant_client.models import PointStruct
|
|
||||||
|
|
||||||
if not edge_payloads:
|
|
||||||
return 0, 0
|
|
||||||
|
|
||||||
points = []
|
|
||||||
seen = set()
|
|
||||||
for e in edge_payloads:
|
|
||||||
key = (e.get("kind"), e.get("source_id"), e.get("target_id"), e.get("scope"))
|
|
||||||
if key in seen:
|
|
||||||
continue
|
|
||||||
seen.add(key)
|
|
||||||
eid = _edge_uid(*key)
|
|
||||||
points.append(
|
|
||||||
PointStruct(
|
|
||||||
id=eid,
|
|
||||||
vector=[0.0],
|
|
||||||
payload=e,
|
|
||||||
)
|
|
||||||
)
|
|
||||||
|
|
||||||
if not points:
|
|
||||||
return 0, 0
|
|
||||||
|
|
||||||
ensure_edges_collection(qdrant_client, collection)
|
|
||||||
qdrant_client.upsert(collection_name=collection, points=points)
|
|
||||||
return len(points), len(seen)
|
|
||||||
@@ -1,82 +0,0 @@
|
|||||||
from __future__ import annotations
|
|
||||||
import os, time, json
|
|
||||||
import urllib.request
|
|
||||||
from typing import List, Dict, Any
|
|
||||||
|
|
||||||
# Backend-Auswahl:
|
|
||||||
# - EMBED_BACKEND=ollama -> EMBED_URL=/api/embeddings (Ollama), EMBED_MODEL=z.B. nomic-embed-text
|
|
||||||
# - EMBED_BACKEND=mini -> EMBED_URL=/embed (unser MiniLM-Server), EMBED_MODEL=minilm-384
|
|
||||||
EMBED_BACKEND = os.getenv("EMBED_BACKEND", "mini").lower()
|
|
||||||
EMBED_URL = os.getenv("EMBED_URL", "http://127.0.0.1:8990/embed")
|
|
||||||
EMBED_MODEL = os.getenv("EMBED_MODEL", "minilm-384")
|
|
||||||
EMBED_BATCH = int(os.getenv("EMBED_BATCH", "64"))
|
|
||||||
TIMEOUT = 60
|
|
||||||
|
|
||||||
class EmbedError(RuntimeError): ...
|
|
||||||
|
|
||||||
def _post_json(url: str, payload: Dict[str, Any]) -> Dict[str, Any]:
|
|
||||||
data = json.dumps(payload).encode("utf-8")
|
|
||||||
req = urllib.request.Request(url, data=data, headers={"Content-Type": "application/json"})
|
|
||||||
with urllib.request.urlopen(req, timeout=TIMEOUT) as resp:
|
|
||||||
return json.loads(resp.read().decode("utf-8"))
|
|
||||||
|
|
||||||
def _embed_mini(inputs: List[str], model: str, batch: int) -> List[List[float]]:
|
|
||||||
out: List[List[float]] = []
|
|
||||||
i = 0
|
|
||||||
while i < len(inputs):
|
|
||||||
chunk = inputs[i:i+batch]
|
|
||||||
# einfache Retries
|
|
||||||
for attempt in range(5):
|
|
||||||
try:
|
|
||||||
resp = _post_json(EMBED_URL, {"model": model, "inputs": chunk})
|
|
||||||
vecs = resp.get("embeddings") or resp.get("vectors") or resp.get("data")
|
|
||||||
if not isinstance(vecs, list):
|
|
||||||
raise EmbedError(f"Bad embed response keys: {list(resp.keys())}")
|
|
||||||
out.extend(vecs)
|
|
||||||
break
|
|
||||||
except Exception:
|
|
||||||
if attempt == 4:
|
|
||||||
raise
|
|
||||||
time.sleep(1.5 * (attempt + 1))
|
|
||||||
i += batch
|
|
||||||
return out
|
|
||||||
|
|
||||||
def _embed_ollama(inputs: List[str], model: str, batch: int) -> List[List[float]]:
|
|
||||||
# Ollama /api/embeddings akzeptiert "input" als String ODER Array.
|
|
||||||
# Die Response enthält:
|
|
||||||
# - für single input: {"embedding":[...], "model":"...", ...}
|
|
||||||
# - für array input: {"embeddings":[[...],[...],...], "model":"...", ...} (je nach Version)
|
|
||||||
# Um maximal kompatibel zu sein, rufen wir pro Text einzeln auf.
|
|
||||||
out: List[List[float]] = []
|
|
||||||
for text in inputs:
|
|
||||||
# Retries
|
|
||||||
for attempt in range(5):
|
|
||||||
try:
|
|
||||||
resp = _post_json(EMBED_URL, {"model": model, "input": text})
|
|
||||||
if "embedding" in resp and isinstance(resp["embedding"], list):
|
|
||||||
out.append(resp["embedding"])
|
|
||||||
elif "embeddings" in resp and isinstance(resp["embeddings"], list):
|
|
||||||
# Falls Server array zurückgibt, nimm das erste Element
|
|
||||||
vecs = resp["embeddings"]
|
|
||||||
out.append(vecs[0] if vecs else [])
|
|
||||||
else:
|
|
||||||
raise EmbedError(f"Ollama response unexpected keys: {list(resp.keys())}")
|
|
||||||
break
|
|
||||||
except Exception:
|
|
||||||
if attempt == 4:
|
|
||||||
raise
|
|
||||||
time.sleep(1.5 * (attempt + 1))
|
|
||||||
return out
|
|
||||||
|
|
||||||
def embed_texts(texts: List[str], model: str | None = None, batch_size: int | None = None) -> List[List[float]]:
|
|
||||||
model = model or EMBED_MODEL
|
|
||||||
batch = batch_size or EMBED_BATCH
|
|
||||||
if not texts:
|
|
||||||
return []
|
|
||||||
if EMBED_BACKEND == "ollama":
|
|
||||||
return _embed_ollama(texts, model, batch)
|
|
||||||
# default: mini
|
|
||||||
return _embed_mini(texts, model, batch)
|
|
||||||
|
|
||||||
def embed_one(text: str, model: str | None = None) -> List[float]:
|
|
||||||
return embed_texts([text], model=model, batch_size=1)[0]
|
|
||||||
@@ -1,103 +0,0 @@
|
|||||||
#!/usr/bin/env python3
|
|
||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""
|
|
||||||
Datei: app/core/env_vars.py
|
|
||||||
Version: 1.1.0 (2025-11-08)
|
|
||||||
|
|
||||||
Zweck
|
|
||||||
Einheitliche Auflösung von ENV-Variablen (Prefix, Qdrant, Embeddings, Hashing)
|
|
||||||
mit Abwärtskompatibilität.
|
|
||||||
|
|
||||||
Grundsatz
|
|
||||||
- Für Qdrant-Funktionen ist 'COLLECTION_PREFIX' der Primärschlüssel.
|
|
||||||
- 'MINDNET_PREFIX' bleibt für App-/UI-/Exporter-Kontexte nutzbar.
|
|
||||||
- Fallbacks sorgen dafür, dass ältere Umgebungen weiter funktionieren.
|
|
||||||
|
|
||||||
Wichtig
|
|
||||||
- Lädt optional eine .env (wenn python-dotenv verfügbar ist).
|
|
||||||
- Überschreibt keine bereits gesetzten OS-Variablen (override=False).
|
|
||||||
"""
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
import os
|
|
||||||
from typing import Optional, Dict
|
|
||||||
|
|
||||||
# Optional: .env automatisch laden (ohne Hard-Fail, falls nicht vorhanden)
|
|
||||||
try:
|
|
||||||
from dotenv import load_dotenv, find_dotenv # type: ignore
|
|
||||||
_p = find_dotenv()
|
|
||||||
if _p:
|
|
||||||
load_dotenv(_p, override=False)
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
|
|
||||||
# -------- Prefix-Auflösung --------
|
|
||||||
|
|
||||||
def get_collection_prefix(cli_override: Optional[str] = None) -> str:
|
|
||||||
"""
|
|
||||||
Für Qdrant-relevante Funktionen:
|
|
||||||
1) CLI-Override (--prefix)
|
|
||||||
2) ENV COLLECTION_PREFIX
|
|
||||||
3) ENV MINDNET_PREFIX (Fallback)
|
|
||||||
4) 'mindnet' (Default)
|
|
||||||
"""
|
|
||||||
if cli_override and str(cli_override).strip():
|
|
||||||
return str(cli_override).strip()
|
|
||||||
return (
|
|
||||||
os.getenv("COLLECTION_PREFIX")
|
|
||||||
or os.getenv("MINDNET_PREFIX")
|
|
||||||
or "mindnet"
|
|
||||||
)
|
|
||||||
|
|
||||||
def get_mindnet_prefix(cli_override: Optional[str] = None) -> str:
|
|
||||||
"""
|
|
||||||
Für App-/UI-/Exporter-Kontexte:
|
|
||||||
1) CLI-Override (--prefix)
|
|
||||||
2) ENV MINDNET_PREFIX
|
|
||||||
3) ENV COLLECTION_PREFIX (Fallback)
|
|
||||||
4) 'mindnet'
|
|
||||||
"""
|
|
||||||
if cli_override and str(cli_override).strip():
|
|
||||||
return str(cli_override).strip()
|
|
||||||
return (
|
|
||||||
os.getenv("MINDNET_PREFIX")
|
|
||||||
or os.getenv("COLLECTION_PREFIX")
|
|
||||||
or "mindnet"
|
|
||||||
)
|
|
||||||
|
|
||||||
def get_prefix(cli_override: Optional[str] = None, target: str = "qdrant") -> str:
|
|
||||||
"""
|
|
||||||
Universelle Hülle (abwärtskompatibel):
|
|
||||||
target='qdrant' -> get_collection_prefix
|
|
||||||
target='app' -> get_mindnet_prefix
|
|
||||||
"""
|
|
||||||
if target.lower() == "app":
|
|
||||||
return get_mindnet_prefix(cli_override)
|
|
||||||
return get_collection_prefix(cli_override)
|
|
||||||
|
|
||||||
# -------- Qdrant / Embeddings / Hashing --------
|
|
||||||
|
|
||||||
def get_qdrant_url(default: str = "http://127.0.0.1:6333") -> str:
|
|
||||||
return os.getenv("QDRANT_URL", default)
|
|
||||||
|
|
||||||
def get_qdrant_api_key(default: str = "") -> str:
|
|
||||||
return os.getenv("QDRANT_API_KEY", default)
|
|
||||||
|
|
||||||
def get_vector_dim(default: int = 384) -> int:
|
|
||||||
try:
|
|
||||||
return int(os.getenv("VECTOR_DIM", str(default)))
|
|
||||||
except Exception:
|
|
||||||
return default
|
|
||||||
|
|
||||||
def get_embed_url(default: Optional[str] = None) -> Optional[str]:
|
|
||||||
return os.getenv("EMBED_URL", default)
|
|
||||||
|
|
||||||
def get_hash_env() -> Dict[str, str]:
|
|
||||||
"""
|
|
||||||
Liefert die Hash-Konfiguration (nur Aggregation; die Auswertung bleibt in den Skripten).
|
|
||||||
"""
|
|
||||||
return {
|
|
||||||
"MINDNET_HASH_COMPARE": os.getenv("MINDNET_HASH_COMPARE", ""),
|
|
||||||
"MINDNET_HASH_SOURCE": os.getenv("MINDNET_HASH_SOURCE", ""),
|
|
||||||
"MINDNET_HASH_NORMALIZE": os.getenv("MINDNET_HASH_NORMALIZE", ""),
|
|
||||||
}
|
|
||||||
@@ -1,17 +1,10 @@
|
|||||||
#!/usr/bin/env python3
|
|
||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""
|
"""
|
||||||
app/core/graph_adapter.py — Adjazenzaufbau & Subgraph-Expansion
|
FILE: app/core/graph_adapter.py
|
||||||
|
DESCRIPTION: Lädt Kanten aus Qdrant und baut einen In-Memory Subgraphen für Scoring (Centrality) und Explanation.
|
||||||
Zweck:
|
VERSION: 0.4.0
|
||||||
Baut aus Qdrant-Edges (Collection: *_edges) einen leichten In-Memory-Graph.
|
STATUS: Active
|
||||||
|
DEPENDENCIES: qdrant_client, app.core.qdrant
|
||||||
Kompatibilität:
|
LAST_ANALYSIS: 2025-12-15
|
||||||
- WP-04a: Liefert Scores (edge_bonus, centrality).
|
|
||||||
- WP-04b: Liefert jetzt auch Struktur-Daten für Erklärungen (Reverse-Lookup).
|
|
||||||
|
|
||||||
Version:
|
|
||||||
0.4.0 (Update für WP-04b: Reverse Adjacency für Explainability)
|
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|||||||
+259
-212
@@ -1,14 +1,21 @@
|
|||||||
"""
|
"""
|
||||||
app/core/ingestion.py
|
FILE: app/core/ingestion.py
|
||||||
|
DESCRIPTION: Haupt-Ingestion-Logik. Transformiert Markdown in den Graphen.
|
||||||
Zentraler Service für die Transformation von Markdown-Dateien in Qdrant-Objekte (Notes, Chunks, Edges).
|
WP-20: Optimiert für OpenRouter (mistralai/mistral-7b-instruct:free).
|
||||||
Dient als Shared Logic für:
|
WP-22: Content Lifecycle, Edge Registry Validation & Multi-Hash.
|
||||||
1. CLI-Imports (scripts/import_markdown.py)
|
FIX: Deep Fallback Logic (v2.11.14). Erkennt Policy Violations auch in validen
|
||||||
2. API-Uploads (WP-11)
|
JSON-Objekten und erzwingt den lokalen Ollama-Sprung, um Kantenverlust
|
||||||
Refactored for Async Embedding Support.
|
bei umfangreichen Protokollen zu verhindern.
|
||||||
|
VERSION: 2.11.14
|
||||||
|
STATUS: Active
|
||||||
|
DEPENDENCIES: app.core.parser, app.core.note_payload, app.core.chunker, app.services.llm_service, app.services.edge_registry
|
||||||
"""
|
"""
|
||||||
import os
|
import os
|
||||||
|
import json
|
||||||
|
import re
|
||||||
import logging
|
import logging
|
||||||
|
import asyncio
|
||||||
|
import time
|
||||||
from typing import Dict, List, Optional, Tuple, Any
|
from typing import Dict, List, Optional, Tuple, Any
|
||||||
|
|
||||||
# Core Module Imports
|
# Core Module Imports
|
||||||
@@ -16,23 +23,16 @@ from app.core.parser import (
|
|||||||
read_markdown,
|
read_markdown,
|
||||||
normalize_frontmatter,
|
normalize_frontmatter,
|
||||||
validate_required_frontmatter,
|
validate_required_frontmatter,
|
||||||
|
extract_edges_with_context,
|
||||||
)
|
)
|
||||||
from app.core.note_payload import make_note_payload
|
from app.core.note_payload import make_note_payload
|
||||||
from app.core.chunker import assemble_chunks
|
from app.core.chunker import assemble_chunks, get_chunk_config
|
||||||
from app.core.chunk_payload import make_chunk_payloads
|
from app.core.chunk_payload import make_chunk_payloads
|
||||||
|
|
||||||
# Fallback für Edges Import (Robustheit)
|
# Fallback für Edges
|
||||||
try:
|
try:
|
||||||
from app.core.derive_edges import build_edges_for_note
|
from app.core.derive_edges import build_edges_for_note
|
||||||
except ImportError:
|
except ImportError:
|
||||||
try:
|
|
||||||
from app.core.derive_edges import derive_edges_for_note as build_edges_for_note
|
|
||||||
except ImportError:
|
|
||||||
try:
|
|
||||||
from app.core.edges import build_edges_for_note
|
|
||||||
except ImportError:
|
|
||||||
# Fallback Mock
|
|
||||||
logging.warning("Could not import edge derivation logic. Edges will be empty.")
|
|
||||||
def build_edges_for_note(*args, **kwargs): return []
|
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 import QdrantConfig, get_client, ensure_collections, ensure_payload_indexes
|
||||||
@@ -43,146 +43,240 @@ from app.core.qdrant_points import (
|
|||||||
upsert_batch,
|
upsert_batch,
|
||||||
)
|
)
|
||||||
|
|
||||||
# WICHTIG: Wir nutzen den API-Client für Embeddings (Async Support)
|
|
||||||
from app.services.embeddings_client import EmbeddingsClient
|
from app.services.embeddings_client import EmbeddingsClient
|
||||||
|
from app.services.edge_registry import registry as edge_registry
|
||||||
|
from app.services.llm_service import LLMService
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
# --- Helper für Type-Registry ---
|
# --- Global Helpers ---
|
||||||
def load_type_registry(custom_path: Optional[str] = None) -> dict:
|
def extract_json_from_response(text: str) -> Any:
|
||||||
import yaml
|
"""
|
||||||
path = custom_path or os.getenv("MINDNET_TYPES_FILE", "config/types.yaml")
|
Extrahiert JSON-Daten und bereinigt LLM-Steuerzeichen (Mistral/Llama).
|
||||||
if not os.path.exists(path):
|
Entfernt <s>, [OUT], [/OUT] und Markdown-Blöcke für maximale Robustheit.
|
||||||
if os.path.exists("types.yaml"):
|
"""
|
||||||
path = "types.yaml"
|
if not text or not isinstance(text, str):
|
||||||
else:
|
return []
|
||||||
return {}
|
|
||||||
|
# 1. Entferne Mistral/Llama Steuerzeichen und Tags
|
||||||
|
clean = text.replace("<s>", "").replace("</s>", "")
|
||||||
|
clean = clean.replace("[OUT]", "").replace("[/OUT]", "")
|
||||||
|
clean = clean.strip()
|
||||||
|
|
||||||
|
# 2. Suche nach Markdown JSON-Blöcken (```json ... ```)
|
||||||
|
match = re.search(r"```(?:json)?\s*(.*?)\s*```", clean, re.DOTALL)
|
||||||
|
payload = match.group(1) if match else clean
|
||||||
|
|
||||||
try:
|
try:
|
||||||
with open(path, "r", encoding="utf-8") as f:
|
return json.loads(payload.strip())
|
||||||
return yaml.safe_load(f) or {}
|
except json.JSONDecodeError:
|
||||||
except Exception:
|
# 3. Recovery: Suche nach der ersten [ und letzten ] (Liste)
|
||||||
return {}
|
start = payload.find('[')
|
||||||
|
end = payload.rfind(']') + 1
|
||||||
|
if start != -1 and end > start:
|
||||||
|
try:
|
||||||
|
return json.loads(payload[start:end])
|
||||||
|
except: pass
|
||||||
|
|
||||||
def resolve_note_type(requested: Optional[str], reg: dict) -> str:
|
# 4. Zweite Recovery: Suche nach der ersten { und letzten } (Objekt)
|
||||||
types = reg.get("types", {})
|
start_obj = payload.find('{')
|
||||||
if requested and requested in types:
|
end_obj = payload.rfind('}') + 1
|
||||||
return requested
|
if start_obj != -1 and end_obj > start_obj:
|
||||||
return "concept"
|
try:
|
||||||
|
return json.loads(payload[start_obj:end_obj])
|
||||||
|
except: pass
|
||||||
|
|
||||||
def effective_chunk_profile(note_type: str, reg: dict) -> str:
|
return []
|
||||||
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))
|
|
||||||
|
|
||||||
|
def load_type_registry(custom_path: Optional[str] = None) -> dict:
|
||||||
|
"""Lädt die types.yaml zur Steuerung der typ-spezifischen Ingestion."""
|
||||||
|
import yaml
|
||||||
|
from app.config import get_settings
|
||||||
|
settings = get_settings()
|
||||||
|
path = custom_path or settings.MINDNET_TYPES_FILE
|
||||||
|
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 {}
|
||||||
|
|
||||||
|
# --- Service Class ---
|
||||||
class IngestionService:
|
class IngestionService:
|
||||||
def __init__(self, collection_prefix: str = None):
|
def __init__(self, collection_prefix: str = None):
|
||||||
# Prefix Logik vereinheitlichen
|
from app.config import get_settings
|
||||||
env_prefix = os.getenv("COLLECTION_PREFIX", "mindnet")
|
self.settings = get_settings()
|
||||||
self.prefix = collection_prefix or env_prefix
|
|
||||||
|
|
||||||
|
self.prefix = collection_prefix or self.settings.COLLECTION_PREFIX
|
||||||
self.cfg = QdrantConfig.from_env()
|
self.cfg = QdrantConfig.from_env()
|
||||||
self.cfg.prefix = self.prefix
|
self.cfg.prefix = self.prefix
|
||||||
self.client = get_client(self.cfg)
|
self.client = get_client(self.cfg)
|
||||||
self.dim = self.cfg.dim
|
self.dim = self.settings.VECTOR_SIZE
|
||||||
|
|
||||||
# Registry laden
|
|
||||||
self.registry = load_type_registry()
|
self.registry = load_type_registry()
|
||||||
|
|
||||||
# Embedding Service initialisieren (Async Client)
|
|
||||||
self.embedder = EmbeddingsClient()
|
self.embedder = EmbeddingsClient()
|
||||||
|
self.llm = LLMService()
|
||||||
|
|
||||||
|
self.active_hash_mode = self.settings.CHANGE_DETECTION_MODE
|
||||||
|
|
||||||
# Init DB Checks (Fehler abfangen, falls DB nicht erreichbar)
|
|
||||||
try:
|
try:
|
||||||
ensure_collections(self.client, self.prefix, self.dim)
|
ensure_collections(self.client, self.prefix, self.dim)
|
||||||
ensure_payload_indexes(self.client, self.prefix)
|
ensure_payload_indexes(self.client, self.prefix)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.warning(f"DB initialization warning: {e}")
|
logger.warning(f"DB init warning: {e}")
|
||||||
|
|
||||||
|
def _resolve_note_type(self, requested: Optional[str]) -> str:
|
||||||
|
"""Bestimmt den finalen Notiz-Typ (Fallback auf 'concept')."""
|
||||||
|
types = self.registry.get("types", {})
|
||||||
|
if requested and requested in types: return requested
|
||||||
|
return "concept"
|
||||||
|
|
||||||
|
def _get_chunk_config_by_profile(self, profile_name: str, note_type: str) -> Dict[str, Any]:
|
||||||
|
"""Holt die Chunker-Parameter für ein spezifisches Profil aus der Registry."""
|
||||||
|
profiles = self.registry.get("chunking_profiles", {})
|
||||||
|
if profile_name in profiles:
|
||||||
|
cfg = profiles[profile_name].copy()
|
||||||
|
if "overlap" in cfg and isinstance(cfg["overlap"], list):
|
||||||
|
cfg["overlap"] = tuple(cfg["overlap"])
|
||||||
|
return cfg
|
||||||
|
return get_chunk_config(note_type)
|
||||||
|
|
||||||
|
async def _perform_smart_edge_allocation(self, text: str, note_id: str) -> List[Dict]:
|
||||||
|
"""
|
||||||
|
KI-Extraktion mit Deep-Fallback Logik.
|
||||||
|
Erzwingt den lokalen Ollama-Sprung, wenn die Cloud-Antwort keine verwertbaren
|
||||||
|
Kanten liefert (häufig bei Policy Violations auf OpenRouter).
|
||||||
|
"""
|
||||||
|
provider = self.settings.MINDNET_LLM_PROVIDER
|
||||||
|
model = self.settings.OPENROUTER_MODEL if provider == "openrouter" else self.settings.GEMINI_MODEL
|
||||||
|
|
||||||
|
logger.info(f"🚀 [Ingestion] Turbo-Mode: Extracting edges for '{note_id}' using {model} on {provider}")
|
||||||
|
|
||||||
|
edge_registry.ensure_latest()
|
||||||
|
valid_types_str = ", ".join(sorted(list(edge_registry.valid_types)))
|
||||||
|
|
||||||
|
template = self.llm.get_prompt("edge_extraction", provider)
|
||||||
|
|
||||||
|
try:
|
||||||
|
try:
|
||||||
|
# Wir begrenzen den Kontext auf 6000 Zeichen (ca. 1500 Token)
|
||||||
|
prompt = template.format(
|
||||||
|
text=text[:6000],
|
||||||
|
note_id=note_id,
|
||||||
|
valid_types=valid_types_str
|
||||||
|
)
|
||||||
|
except KeyError as ke:
|
||||||
|
logger.error(f"❌ [Ingestion] Prompt-Template Fehler (Variable {ke} fehlt).")
|
||||||
|
return []
|
||||||
|
|
||||||
|
# 1. Versuch: Anfrage an den primären Cloud-Provider
|
||||||
|
response_json = await self.llm.generate_raw_response(
|
||||||
|
prompt=prompt, priority="background", force_json=True,
|
||||||
|
provider=provider, model_override=model
|
||||||
|
)
|
||||||
|
|
||||||
|
# Initiales Parsing
|
||||||
|
raw_data = extract_json_from_response(response_json)
|
||||||
|
|
||||||
|
# 2. Dictionary Recovery (Versuche Liste aus Dict zu extrahieren)
|
||||||
|
candidates = []
|
||||||
|
if isinstance(raw_data, list):
|
||||||
|
candidates = raw_data
|
||||||
|
elif isinstance(raw_data, dict):
|
||||||
|
logger.info(f"ℹ️ [Ingestion] LLM returned dict, checking for embedded lists in {note_id}")
|
||||||
|
for k in ["edges", "links", "results", "kanten", "matches", "edge_list"]:
|
||||||
|
if k in raw_data and isinstance(raw_data[k], list):
|
||||||
|
candidates = raw_data[k]
|
||||||
|
break
|
||||||
|
# Wenn immer noch keine Liste gefunden, versuche Key-Value Paare (Dict Recovery)
|
||||||
|
if not candidates:
|
||||||
|
for k, v in raw_data.items():
|
||||||
|
if isinstance(v, str): candidates.append(f"{k}:{v}")
|
||||||
|
elif isinstance(v, list): [candidates.append(f"{k}:{i}") for i in v if isinstance(i, str)]
|
||||||
|
|
||||||
|
# 3. DEEP FALLBACK: Wenn nach allen Recovery-Versuchen die Liste leer ist UND wir in der Cloud waren
|
||||||
|
# Triggert den Fallback bei "Data Policy Violations" (leere oder Fehler-JSONs).
|
||||||
|
if not candidates and provider != "ollama" and self.settings.LLM_FALLBACK_ENABLED:
|
||||||
|
logger.warning(
|
||||||
|
f"🛑 [Ingestion] Cloud-Antwort für {note_id} lieferte keine verwertbaren Kanten. "
|
||||||
|
f"Mögliche Policy Violation oder Refusal. Erzwinge LOKALEN FALLBACK via Ollama..."
|
||||||
|
)
|
||||||
|
response_json_local = await self.llm.generate_raw_response(
|
||||||
|
prompt=prompt, priority="background", force_json=True, provider="ollama"
|
||||||
|
)
|
||||||
|
raw_data_local = extract_json_from_response(response_json_local)
|
||||||
|
|
||||||
|
# Wiederhole Recovery für lokale Antwort
|
||||||
|
if isinstance(raw_data_local, list):
|
||||||
|
candidates = raw_data_local
|
||||||
|
elif isinstance(raw_data_local, dict):
|
||||||
|
for k in ["edges", "links", "results"]:
|
||||||
|
if k in raw_data_local and isinstance(raw_data_local[k], list):
|
||||||
|
candidates = raw_data_local[k]; break
|
||||||
|
|
||||||
|
if not candidates:
|
||||||
|
logger.warning(f"⚠️ [Ingestion] Auch nach Fallback keine extrahierbaren Kanten für {note_id}")
|
||||||
|
return []
|
||||||
|
|
||||||
|
processed = []
|
||||||
|
for item in candidates:
|
||||||
|
if isinstance(item, dict) and "to" in item:
|
||||||
|
item["provenance"] = "semantic_ai"
|
||||||
|
item["line"] = f"ai-{provider}"
|
||||||
|
processed.append(item)
|
||||||
|
elif isinstance(item, str) and ":" in item:
|
||||||
|
parts = item.split(":", 1)
|
||||||
|
processed.append({
|
||||||
|
"to": parts[1].strip(),
|
||||||
|
"kind": parts[0].strip(),
|
||||||
|
"provenance": "semantic_ai",
|
||||||
|
"line": f"ai-{provider}"
|
||||||
|
})
|
||||||
|
return processed
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
logger.warning(f"⚠️ [Ingestion] Smart Edge Allocation failed for {note_id}: {e}")
|
||||||
|
return []
|
||||||
|
|
||||||
async def process_file(
|
async def process_file(
|
||||||
self,
|
self, file_path: str, vault_root: str,
|
||||||
file_path: str,
|
force_replace: bool = False, apply: bool = False, purge_before: bool = False,
|
||||||
vault_root: str,
|
note_scope_refs: bool = False, hash_source: str = "parsed", hash_normalize: str = "canonical"
|
||||||
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]:
|
) -> Dict[str, Any]:
|
||||||
"""
|
"""Transformiert eine Markdown-Datei in den Graphen (Notes, Chunks, Edges)."""
|
||||||
Verarbeitet eine einzelne Datei (ASYNC Version).
|
result = {"path": file_path, "status": "skipped", "changed": False, "error": None}
|
||||||
"""
|
|
||||||
result = {
|
|
||||||
"path": file_path,
|
|
||||||
"status": "skipped",
|
|
||||||
"changed": False,
|
|
||||||
"error": None
|
|
||||||
}
|
|
||||||
|
|
||||||
# 1. Parse & Frontmatter
|
# 1. Parse & Lifecycle Gate
|
||||||
try:
|
try:
|
||||||
parsed = read_markdown(file_path)
|
parsed = read_markdown(file_path)
|
||||||
if not parsed:
|
if not parsed: return {**result, "error": "Empty file"}
|
||||||
return {**result, "error": "Empty or unreadable file"}
|
|
||||||
|
|
||||||
fm = normalize_frontmatter(parsed.frontmatter)
|
fm = normalize_frontmatter(parsed.frontmatter)
|
||||||
validate_required_frontmatter(fm)
|
validate_required_frontmatter(fm)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"Validation failed for {file_path}: {e}")
|
|
||||||
return {**result, "error": f"Validation failed: {str(e)}"}
|
return {**result, "error": f"Validation failed: {str(e)}"}
|
||||||
|
|
||||||
# 2. Type & Config Resolution
|
# WP-22: Filter für Systemdateien und Entwürfe
|
||||||
note_type = resolve_note_type(fm.get("type"), self.registry)
|
status = fm.get("status", "draft").lower().strip()
|
||||||
|
if status in ["system", "template", "archive", "hidden"]:
|
||||||
|
return {**result, "status": "skipped", "reason": f"lifecycle_{status}"}
|
||||||
|
|
||||||
|
# 2. Config Resolution & Payload Construction
|
||||||
|
note_type = self._resolve_note_type(fm.get("type"))
|
||||||
fm["type"] = note_type
|
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:
|
try:
|
||||||
note_pl = make_note_payload(
|
note_pl = make_note_payload(parsed, vault_root=vault_root, hash_normalize=hash_normalize, hash_source=hash_source, file_path=file_path)
|
||||||
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"]
|
note_id = note_pl["note_id"]
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"Payload build failed: {e}")
|
return {**result, "error": f"Payload failed: {str(e)}"}
|
||||||
return {**result, "error": f"Payload build failed: {str(e)}"}
|
|
||||||
|
|
||||||
# 4. Change Detection
|
# 3. Change Detection (Strikte DoD Umsetzung)
|
||||||
old_payload = None
|
old_payload = None if force_replace else self._fetch_note_payload(note_id)
|
||||||
if not force_replace:
|
check_key = f"{self.active_hash_mode}:{hash_source}:{hash_normalize}"
|
||||||
old_payload = self._fetch_note_payload(note_id)
|
old_hash = (old_payload or {}).get("hashes", {}).get(check_key)
|
||||||
|
new_hash = note_pl.get("hashes", {}).get(check_key)
|
||||||
|
|
||||||
has_old = old_payload is not None
|
# Prüfung auf fehlende Artefakte in Qdrant
|
||||||
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)
|
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
|
should_write = force_replace or (not old_payload) or (old_hash != new_hash) or chunks_missing or edges_missing
|
||||||
|
|
||||||
if not should_write:
|
if not should_write:
|
||||||
return {**result, "status": "unchanged", "note_id": note_id}
|
return {**result, "status": "unchanged", "note_id": note_id}
|
||||||
@@ -190,60 +284,58 @@ class IngestionService:
|
|||||||
if not apply:
|
if not apply:
|
||||||
return {**result, "status": "dry-run", "changed": True, "note_id": note_id}
|
return {**result, "status": "dry-run", "changed": True, "note_id": note_id}
|
||||||
|
|
||||||
# 5. Processing (Chunking, Embedding, Edges)
|
# 4. Processing (Chunking, Embedding, AI Edges)
|
||||||
try:
|
try:
|
||||||
body_text = getattr(parsed, "body", "") or ""
|
body_text = getattr(parsed, "body", "") or ""
|
||||||
chunks = assemble_chunks(fm["id"], body_text, fm["type"])
|
edge_registry.ensure_latest()
|
||||||
|
|
||||||
|
# Profil-gesteuertes Chunking
|
||||||
|
profile = fm.get("chunk_profile") or fm.get("chunking_profile") or "sliding_standard"
|
||||||
|
chunk_cfg = self._get_chunk_config_by_profile(profile, note_type)
|
||||||
|
chunks = await assemble_chunks(fm["id"], body_text, fm["type"], config=chunk_cfg)
|
||||||
chunk_pls = make_chunk_payloads(fm, note_pl["path"], chunks, note_text=body_text)
|
chunk_pls = make_chunk_payloads(fm, note_pl["path"], chunks, note_text=body_text)
|
||||||
|
|
||||||
# --- EMBEDDING FIX (ASYNC) ---
|
# Vektorisierung
|
||||||
vecs = []
|
vecs = []
|
||||||
if chunk_pls:
|
if chunk_pls:
|
||||||
texts = [c.get("window") or c.get("text") or "" for c in chunk_pls]
|
texts = [c.get("window") or c.get("text") or "" for c in chunk_pls]
|
||||||
try:
|
|
||||||
# Async Aufruf des Embedders (via Batch oder Loop)
|
|
||||||
if hasattr(self.embedder, 'embed_documents'):
|
|
||||||
vecs = await self.embedder.embed_documents(texts)
|
vecs = await self.embedder.embed_documents(texts)
|
||||||
else:
|
|
||||||
# Fallback Loop falls Client kein Batch unterstützt
|
|
||||||
for t in texts:
|
|
||||||
v = await self.embedder.embed_query(t)
|
|
||||||
vecs.append(v)
|
|
||||||
|
|
||||||
# Validierung der Dimensionen
|
# Kanten-Extraktion
|
||||||
if vecs and len(vecs) > 0:
|
edges = []
|
||||||
dim_got = len(vecs[0])
|
context = {"file": file_path, "note_id": note_id}
|
||||||
if dim_got != self.dim:
|
|
||||||
# Wirf keinen Fehler, aber logge Warnung. Qdrant Upsert wird failen wenn 0.
|
|
||||||
logger.warning(f"Vector dimension mismatch. Expected {self.dim}, got {dim_got}")
|
|
||||||
if dim_got == 0:
|
|
||||||
raise ValueError("Embedding returned empty vectors (Dim 0)")
|
|
||||||
except Exception as e:
|
|
||||||
logger.error(f"Embedding generation failed: {e}")
|
|
||||||
raise RuntimeError(f"Embedding failed: {e}")
|
|
||||||
|
|
||||||
# Edges
|
# A. Explizite Kanten (User / Wikilinks)
|
||||||
note_refs = note_pl.get("references") or []
|
for e in extract_edges_with_context(parsed):
|
||||||
# Versuche flexible Signatur für Edges (V1 vs V2)
|
e["kind"] = edge_registry.resolve(edge_type=e["kind"], provenance="explicit", context={**context, "line": e.get("line")})
|
||||||
|
edges.append(e)
|
||||||
|
|
||||||
|
# B. KI Kanten (Turbo Mode mit v2.11.14 Fallback)
|
||||||
|
ai_edges = await self._perform_smart_edge_allocation(body_text, note_id)
|
||||||
|
for e in ai_edges:
|
||||||
|
valid_kind = edge_registry.resolve(edge_type=e.get("kind"), provenance="semantic_ai", context={**context, "line": e.get("line")})
|
||||||
|
e["kind"] = valid_kind
|
||||||
|
edges.append(e)
|
||||||
|
|
||||||
|
# C. System Kanten (Struktur)
|
||||||
try:
|
try:
|
||||||
edges = build_edges_for_note(
|
sys_edges = build_edges_for_note(note_id, chunk_pls, note_level_references=note_pl.get("references", []), include_note_scope_refs=note_scope_refs)
|
||||||
note_id,
|
except:
|
||||||
chunk_pls,
|
sys_edges = build_edges_for_note(note_id, chunk_pls)
|
||||||
note_level_references=note_refs,
|
|
||||||
include_note_scope_refs=note_scope_refs
|
for e in sys_edges:
|
||||||
)
|
valid_kind = edge_registry.resolve(edge_type=e.get("kind", "belongs_to"), provenance="structure", context={**context, "line": "system"})
|
||||||
except TypeError:
|
if valid_kind:
|
||||||
# Fallback für ältere Signatur
|
e["kind"] = valid_kind
|
||||||
edges = build_edges_for_note(note_id, chunk_pls)
|
edges.append(e)
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"Processing failed: {e}", exc_info=True)
|
logger.error(f"Processing failed for {file_path}: {e}", exc_info=True)
|
||||||
return {**result, "error": f"Processing failed: {str(e)}"}
|
return {**result, "error": f"Processing failed: {str(e)}"}
|
||||||
|
|
||||||
# 6. Upsert Action
|
# 5. DB Upsert
|
||||||
try:
|
try:
|
||||||
if purge_before and has_old:
|
if purge_before and old_payload: self._purge_artifacts(note_id)
|
||||||
self._purge_artifacts(note_id)
|
|
||||||
|
|
||||||
n_name, n_pts = points_for_note(self.prefix, note_pl, None, self.dim)
|
n_name, n_pts = points_for_note(self.prefix, note_pl, None, self.dim)
|
||||||
upsert_batch(self.client, n_name, n_pts)
|
upsert_batch(self.client, n_name, n_pts)
|
||||||
@@ -256,88 +348,43 @@ class IngestionService:
|
|||||||
e_name, e_pts = points_for_edges(self.prefix, edges)
|
e_name, e_pts = points_for_edges(self.prefix, edges)
|
||||||
upsert_batch(self.client, e_name, e_pts)
|
upsert_batch(self.client, e_name, e_pts)
|
||||||
|
|
||||||
return {
|
return {"path": file_path, "status": "success", "changed": True, "note_id": note_id, "chunks_count": len(chunk_pls), "edges_count": len(edges)}
|
||||||
"path": file_path,
|
|
||||||
"status": "success",
|
|
||||||
"changed": True,
|
|
||||||
"note_id": note_id,
|
|
||||||
"chunks_count": len(chunk_pls),
|
|
||||||
"edges_count": len(edges)
|
|
||||||
}
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"Upsert failed: {e}", exc_info=True)
|
|
||||||
return {**result, "error": f"DB Upsert failed: {e}"}
|
return {**result, "error": f"DB Upsert failed: {e}"}
|
||||||
|
|
||||||
# --- Interne Qdrant Helper ---
|
|
||||||
|
|
||||||
def _fetch_note_payload(self, note_id: str) -> Optional[dict]:
|
def _fetch_note_payload(self, note_id: str) -> Optional[dict]:
|
||||||
|
"""Holt die Metadaten einer Note aus Qdrant."""
|
||||||
from qdrant_client.http import models as rest
|
from qdrant_client.http import models as rest
|
||||||
col = f"{self.prefix}_notes"
|
|
||||||
try:
|
try:
|
||||||
f = rest.Filter(must=[rest.FieldCondition(key="note_id", match=rest.MatchValue(value=note_id))])
|
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)
|
pts, _ = self.client.scroll(collection_name=f"{self.prefix}_notes", scroll_filter=f, limit=1, with_payload=True)
|
||||||
return pts[0].payload if pts else None
|
return pts[0].payload if pts else None
|
||||||
except: return None
|
except: return None
|
||||||
|
|
||||||
def _artifacts_missing(self, note_id: str) -> Tuple[bool, bool]:
|
def _artifacts_missing(self, note_id: str) -> Tuple[bool, bool]:
|
||||||
|
"""Prüft Qdrant aktiv auf vorhandene Chunks und Edges."""
|
||||||
from qdrant_client.http import models as rest
|
from qdrant_client.http import models as rest
|
||||||
c_col = f"{self.prefix}_chunks"
|
|
||||||
e_col = f"{self.prefix}_edges"
|
|
||||||
try:
|
try:
|
||||||
f = rest.Filter(must=[rest.FieldCondition(key="note_id", match=rest.MatchValue(value=note_id))])
|
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)
|
c_pts, _ = self.client.scroll(collection_name=f"{self.prefix}_chunks", scroll_filter=f, limit=1)
|
||||||
e_pts, _ = self.client.scroll(collection_name=e_col, scroll_filter=f, limit=1)
|
e_pts, _ = self.client.scroll(collection_name=f"{self.prefix}_edges", scroll_filter=f, limit=1)
|
||||||
return (not bool(c_pts)), (not bool(e_pts))
|
return (not bool(c_pts)), (not bool(e_pts))
|
||||||
except: return True, True
|
except: return True, True
|
||||||
|
|
||||||
def _purge_artifacts(self, note_id: str):
|
def _purge_artifacts(self, note_id: str):
|
||||||
|
"""Löscht verwaiste Chunks/Edges vor einem Re-Import."""
|
||||||
from qdrant_client.http import models as rest
|
from qdrant_client.http import models as rest
|
||||||
f = rest.Filter(must=[rest.FieldCondition(key="note_id", match=rest.MatchValue(value=note_id))])
|
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"]:
|
for suffix in ["chunks", "edges"]:
|
||||||
try:
|
try: self.client.delete(collection_name=f"{self.prefix}_{suffix}", points_selector=rest.FilterSelector(filter=f))
|
||||||
self.client.delete(collection_name=f"{self.prefix}_{suffix}", points_selector=selector)
|
except: pass
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
|
|
||||||
async def create_from_text(
|
async def create_from_text(self, markdown_content: str, filename: str, vault_root: str, folder: str = "00_Inbox") -> Dict[str, Any]:
|
||||||
self,
|
"""Hilfsmethode zur Erstellung einer Note aus einem Textstream."""
|
||||||
markdown_content: str,
|
|
||||||
filename: str,
|
|
||||||
vault_root: str,
|
|
||||||
folder: str = "00_Inbox"
|
|
||||||
) -> Dict[str, Any]:
|
|
||||||
"""
|
|
||||||
WP-11 Persistence API Entrypoint.
|
|
||||||
Schreibt Text in Vault und indiziert ihn sofort.
|
|
||||||
"""
|
|
||||||
# 1. Zielordner
|
|
||||||
target_dir = os.path.join(vault_root, folder)
|
target_dir = os.path.join(vault_root, folder)
|
||||||
try:
|
|
||||||
os.makedirs(target_dir, exist_ok=True)
|
os.makedirs(target_dir, exist_ok=True)
|
||||||
except Exception as e:
|
file_path = os.path.join(target_dir, filename)
|
||||||
return {"status": "error", "error": f"Could not create folder {target_dir}: {e}"}
|
|
||||||
|
|
||||||
# 2. Dateiname
|
|
||||||
safe_filename = os.path.basename(filename)
|
|
||||||
if not safe_filename.endswith(".md"):
|
|
||||||
safe_filename += ".md"
|
|
||||||
file_path = os.path.join(target_dir, safe_filename)
|
|
||||||
|
|
||||||
# 3. Schreiben
|
|
||||||
try:
|
|
||||||
with open(file_path, "w", encoding="utf-8") as f:
|
with open(file_path, "w", encoding="utf-8") as f:
|
||||||
f.write(markdown_content)
|
f.write(markdown_content)
|
||||||
logger.info(f"Written file to {file_path}")
|
await asyncio.sleep(0.1)
|
||||||
except Exception as e:
|
return await self.process_file(file_path=file_path, vault_root=vault_root, apply=True, force_replace=True, purge_before=True)
|
||||||
return {"status": "error", "error": f"Disk write failed at {file_path}: {str(e)}"}
|
|
||||||
|
|
||||||
# 4. Indizieren (Async Aufruf!)
|
|
||||||
# Wir rufen process_file auf, das jetzt ASYNC ist
|
|
||||||
return await self.process_file(
|
|
||||||
file_path=file_path,
|
|
||||||
vault_root=vault_root,
|
|
||||||
apply=True,
|
|
||||||
force_replace=True,
|
|
||||||
purge_before=True
|
|
||||||
)
|
|
||||||
+83
-51
@@ -1,17 +1,13 @@
|
|||||||
#!/usr/bin/env python3
|
|
||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""
|
"""
|
||||||
Modul: app/core/note_payload.py
|
FILE: app/core/note_payload.py
|
||||||
Version: 2.1.0 (WP-11 Update: Aliases support)
|
DESCRIPTION: Baut das JSON-Objekt.
|
||||||
|
FEATURES:
|
||||||
Zweck
|
1. Multi-Hash: Berechnet immer 'body' AND 'full' Hashes für flexible Change Detection.
|
||||||
-----
|
2. Config-Fix: Liest korrekt 'chunking_profile' aus types.yaml (statt Legacy 'chunk_profile').
|
||||||
Erzeugt ein robustes Note-Payload. Werte wie `retriever_weight`, `chunk_profile`
|
VERSION: 2.3.0
|
||||||
und `edge_defaults` werden in folgender Priorität bestimmt:
|
STATUS: Active
|
||||||
1) Frontmatter (Note)
|
DEPENDENCIES: yaml, os, json, pathlib, hashlib
|
||||||
2) Typ-Registry (config/types.yaml: types.<type>.*)
|
EXTERNAL_CONFIG: config/types.yaml
|
||||||
3) Registry-Defaults (config/types.yaml: defaults.*)
|
|
||||||
4) ENV-Defaults (MINDNET_DEFAULT_RETRIEVER_WEIGHT / MINDNET_DEFAULT_CHUNK_PROFILE)
|
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
@@ -20,6 +16,7 @@ from typing import Any, Dict, Tuple, Optional
|
|||||||
import os
|
import os
|
||||||
import json
|
import json
|
||||||
import pathlib
|
import pathlib
|
||||||
|
import hashlib
|
||||||
|
|
||||||
try:
|
try:
|
||||||
import yaml # type: ignore
|
import yaml # type: ignore
|
||||||
@@ -37,7 +34,6 @@ def _as_dict(x) -> Dict[str, Any]:
|
|||||||
return dict(x)
|
return dict(x)
|
||||||
|
|
||||||
out: Dict[str, Any] = {}
|
out: Dict[str, Any] = {}
|
||||||
# bekannte Attribute übernehmen, sofern vorhanden
|
|
||||||
for attr in (
|
for attr in (
|
||||||
"frontmatter",
|
"frontmatter",
|
||||||
"body",
|
"body",
|
||||||
@@ -56,7 +52,6 @@ def _as_dict(x) -> Dict[str, Any]:
|
|||||||
if val is not None:
|
if val is not None:
|
||||||
out[attr] = val
|
out[attr] = val
|
||||||
|
|
||||||
# Fallback: wenn immer noch leer, raw speichern
|
|
||||||
if not out:
|
if not out:
|
||||||
out["raw"] = str(x)
|
out["raw"] = str(x)
|
||||||
|
|
||||||
@@ -64,14 +59,12 @@ def _as_dict(x) -> Dict[str, Any]:
|
|||||||
|
|
||||||
|
|
||||||
def _pick_args(*args, **kwargs) -> Tuple[Optional[str], Optional[dict]]:
|
def _pick_args(*args, **kwargs) -> Tuple[Optional[str], Optional[dict]]:
|
||||||
"""Extrahiert optionale Zusatzargumente wie path und types_cfg."""
|
|
||||||
path = kwargs.get("path") or (args[0] if args else None)
|
path = kwargs.get("path") or (args[0] if args else None)
|
||||||
types_cfg = kwargs.get("types_cfg") or kwargs.get("types") or None
|
types_cfg = kwargs.get("types_cfg") or kwargs.get("types") or None
|
||||||
return path, types_cfg
|
return path, types_cfg
|
||||||
|
|
||||||
|
|
||||||
def _env_float(name: str, default: float) -> float:
|
def _env_float(name: str, default: float) -> float:
|
||||||
"""Liest einen Float-Wert aus der Umgebung, mit robustem Fallback."""
|
|
||||||
try:
|
try:
|
||||||
return float(os.environ.get(name, default))
|
return float(os.environ.get(name, default))
|
||||||
except Exception:
|
except Exception:
|
||||||
@@ -79,7 +72,6 @@ def _env_float(name: str, default: float) -> float:
|
|||||||
|
|
||||||
|
|
||||||
def _ensure_list(x) -> list:
|
def _ensure_list(x) -> list:
|
||||||
"""Garantiert eine String-Liste."""
|
|
||||||
if x is None:
|
if x is None:
|
||||||
return []
|
return []
|
||||||
if isinstance(x, list):
|
if isinstance(x, list):
|
||||||
@@ -88,13 +80,44 @@ def _ensure_list(x) -> list:
|
|||||||
return [str(i) for i in x]
|
return [str(i) for i in x]
|
||||||
return [str(x)]
|
return [str(x)]
|
||||||
|
|
||||||
|
# --- Hash Logic ---
|
||||||
|
def _compute_hash(content: str) -> str:
|
||||||
|
"""Berechnet einen SHA-256 Hash für den gegebenen String."""
|
||||||
|
if not content:
|
||||||
|
return ""
|
||||||
|
return hashlib.sha256(content.encode("utf-8")).hexdigest()
|
||||||
|
|
||||||
|
def _get_hash_source_content(n: Dict[str, Any], mode: str) -> str:
|
||||||
|
"""
|
||||||
|
Stellt den String zusammen, der gehasht werden soll.
|
||||||
|
"""
|
||||||
|
body = str(n.get("body") or "")
|
||||||
|
|
||||||
|
if mode == "body":
|
||||||
|
return body
|
||||||
|
|
||||||
|
if mode == "full":
|
||||||
|
fm = n.get("frontmatter") or {}
|
||||||
|
# Wichtig: Sortierte Keys für deterministisches Verhalten!
|
||||||
|
# Wir nehmen alle steuernden Metadaten auf
|
||||||
|
meta_parts = []
|
||||||
|
# Hier checken wir keys, die eine Neu-Indizierung rechtfertigen würden
|
||||||
|
for k in sorted(["title", "type", "status", "tags", "chunking_profile", "chunk_profile", "retriever_weight"]):
|
||||||
|
val = fm.get(k)
|
||||||
|
if val is not None:
|
||||||
|
meta_parts.append(f"{k}:{val}")
|
||||||
|
|
||||||
|
meta_str = "|".join(meta_parts)
|
||||||
|
return f"{meta_str}||{body}"
|
||||||
|
|
||||||
|
return body
|
||||||
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
# Type-Registry laden
|
# Type-Registry laden
|
||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
def _load_types_config(explicit_cfg: Optional[dict] = None) -> dict:
|
def _load_types_config(explicit_cfg: Optional[dict] = None) -> dict:
|
||||||
"""Lädt die Type-Registry aus YAML/JSON oder nutzt ein explizit übergebenes Dict."""
|
|
||||||
if explicit_cfg and isinstance(explicit_cfg, dict):
|
if explicit_cfg and isinstance(explicit_cfg, dict):
|
||||||
return explicit_cfg
|
return explicit_cfg
|
||||||
|
|
||||||
@@ -111,7 +134,6 @@ def _load_types_config(explicit_cfg: Optional[dict] = None) -> dict:
|
|||||||
|
|
||||||
|
|
||||||
def _cfg_for_type(note_type: str, reg: dict) -> dict:
|
def _cfg_for_type(note_type: str, reg: dict) -> dict:
|
||||||
"""Liefert die Konfiguration für einen konkreten Notiztyp aus der Registry."""
|
|
||||||
if not isinstance(reg, dict):
|
if not isinstance(reg, dict):
|
||||||
return {}
|
return {}
|
||||||
types = reg.get("types") if isinstance(reg.get("types"), dict) else reg
|
types = reg.get("types") if isinstance(reg.get("types"), dict) else reg
|
||||||
@@ -119,7 +141,6 @@ def _cfg_for_type(note_type: str, reg: dict) -> dict:
|
|||||||
|
|
||||||
|
|
||||||
def _cfg_defaults(reg: dict) -> dict:
|
def _cfg_defaults(reg: dict) -> dict:
|
||||||
"""Liefert den Default-Block aus der Registry (defaults/global)."""
|
|
||||||
if not isinstance(reg, dict):
|
if not isinstance(reg, dict):
|
||||||
return {}
|
return {}
|
||||||
for key in ("defaults", "default", "global"):
|
for key in ("defaults", "default", "global"):
|
||||||
@@ -136,21 +157,16 @@ def _cfg_defaults(reg: dict) -> dict:
|
|||||||
def make_note_payload(note: Any, *args, **kwargs) -> Dict[str, Any]:
|
def make_note_payload(note: Any, *args, **kwargs) -> Dict[str, Any]:
|
||||||
"""
|
"""
|
||||||
Baut das Note-Payload für mindnet_notes auf.
|
Baut das Note-Payload für mindnet_notes auf.
|
||||||
|
Inkludiert Hash-Berechnung (Body & Full) und korrigierte Config-Lookups.
|
||||||
Erwartete Felder im Payload:
|
|
||||||
- note_id: stabile ID aus Frontmatter (id) oder Note-Objekt
|
|
||||||
- title: Titel der Notiz
|
|
||||||
- type: Notiztyp (z. B. concept, project, journal, ...)
|
|
||||||
- path: Pfad im Vault
|
|
||||||
- retriever_weight: effektives Gewicht für den Retriever
|
|
||||||
- chunk_profile: Profil für Chunking (short|medium|long|default|...)
|
|
||||||
- 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)
|
||||||
reg = _load_types_config(types_cfg_explicit)
|
reg = _load_types_config(types_cfg_explicit)
|
||||||
|
|
||||||
|
# Hash Config (Parameter für Source/Normalize, Mode ist hardcoded auf 'beide')
|
||||||
|
hash_source = kwargs.get("hash_source", "parsed")
|
||||||
|
hash_normalize = kwargs.get("hash_normalize", "canonical")
|
||||||
|
|
||||||
fm = n.get("frontmatter") or {}
|
fm = n.get("frontmatter") or {}
|
||||||
fm_type = fm.get("type") or n.get("type") or "concept"
|
fm_type = fm.get("type") or n.get("type") or "concept"
|
||||||
note_type = str(fm_type)
|
note_type = str(fm_type)
|
||||||
@@ -158,7 +174,7 @@ def make_note_payload(note: Any, *args, **kwargs) -> Dict[str, Any]:
|
|||||||
cfg_type = _cfg_for_type(note_type, reg)
|
cfg_type = _cfg_for_type(note_type, reg)
|
||||||
cfg_def = _cfg_defaults(reg)
|
cfg_def = _cfg_defaults(reg)
|
||||||
|
|
||||||
# --- retriever_weight: Frontmatter > Typ-Config > Registry-Defaults > ENV ---
|
# --- retriever_weight ---
|
||||||
default_rw = _env_float("MINDNET_DEFAULT_RETRIEVER_WEIGHT", 1.0)
|
default_rw = _env_float("MINDNET_DEFAULT_RETRIEVER_WEIGHT", 1.0)
|
||||||
retriever_weight = fm.get("retriever_weight")
|
retriever_weight = fm.get("retriever_weight")
|
||||||
if retriever_weight is None:
|
if retriever_weight is None:
|
||||||
@@ -171,20 +187,23 @@ def make_note_payload(note: Any, *args, **kwargs) -> Dict[str, Any]:
|
|||||||
except Exception:
|
except Exception:
|
||||||
retriever_weight = default_rw
|
retriever_weight = default_rw
|
||||||
|
|
||||||
# --- chunk_profile: Frontmatter > Typ-Config > Registry-Defaults > ENV ---
|
# --- chunk_profile (FIXED LOGIC) ---
|
||||||
chunk_profile = fm.get("chunk_profile")
|
# 1. Frontmatter Override (beide Schreibweisen erlaubt)
|
||||||
if chunk_profile is None:
|
chunk_profile = fm.get("chunking_profile") or fm.get("chunk_profile")
|
||||||
chunk_profile = cfg_type.get(
|
|
||||||
"chunk_profile",
|
|
||||||
cfg_def.get(
|
|
||||||
"chunk_profile",
|
|
||||||
os.environ.get("MINDNET_DEFAULT_CHUNK_PROFILE", "medium"),
|
|
||||||
),
|
|
||||||
)
|
|
||||||
if not isinstance(chunk_profile, str):
|
|
||||||
chunk_profile = "medium"
|
|
||||||
|
|
||||||
# --- edge_defaults: Frontmatter > Typ-Config > Registry-Defaults ---
|
# 2. Type Config (Korrekter Key 'chunking_profile' aus types.yaml)
|
||||||
|
if chunk_profile is None:
|
||||||
|
chunk_profile = cfg_type.get("chunking_profile")
|
||||||
|
|
||||||
|
# 3. Default Config (Fallback auf sliding_standard statt medium)
|
||||||
|
if chunk_profile is None:
|
||||||
|
chunk_profile = cfg_def.get("chunking_profile", "sliding_standard")
|
||||||
|
|
||||||
|
# 4. Safety Fallback
|
||||||
|
if not isinstance(chunk_profile, str) or not chunk_profile:
|
||||||
|
chunk_profile = "sliding_standard"
|
||||||
|
|
||||||
|
# --- edge_defaults ---
|
||||||
edge_defaults = fm.get("edge_defaults")
|
edge_defaults = fm.get("edge_defaults")
|
||||||
if edge_defaults is None:
|
if edge_defaults is None:
|
||||||
edge_defaults = cfg_type.get(
|
edge_defaults = cfg_type.get(
|
||||||
@@ -193,7 +212,7 @@ def make_note_payload(note: Any, *args, **kwargs) -> Dict[str, Any]:
|
|||||||
)
|
)
|
||||||
edge_defaults = _ensure_list(edge_defaults)
|
edge_defaults = _ensure_list(edge_defaults)
|
||||||
|
|
||||||
# --- Basis-Metadaten (IDs, Titel, Pfad) ---
|
# --- Basis-Metadaten ---
|
||||||
note_id = n.get("note_id") or n.get("id") or fm.get("id")
|
note_id = n.get("note_id") or n.get("id") or fm.get("id")
|
||||||
title = n.get("title") or fm.get("title") or ""
|
title = n.get("title") or fm.get("title") or ""
|
||||||
path = n.get("path") or path_arg
|
path = n.get("path") or path_arg
|
||||||
@@ -208,29 +227,42 @@ def make_note_payload(note: Any, *args, **kwargs) -> Dict[str, Any]:
|
|||||||
"retriever_weight": retriever_weight,
|
"retriever_weight": retriever_weight,
|
||||||
"chunk_profile": chunk_profile,
|
"chunk_profile": chunk_profile,
|
||||||
"edge_defaults": edge_defaults,
|
"edge_defaults": edge_defaults,
|
||||||
|
"hashes": {} # Init Hash Dict
|
||||||
}
|
}
|
||||||
|
|
||||||
# Tags / Keywords übernehmen
|
# --- MULTI-HASH CALCULATION (Strategy Decoupling) ---
|
||||||
|
# Wir berechnen immer BEIDE Strategien und speichern sie.
|
||||||
|
# ingestion.py entscheidet dann anhand der ENV-Variable, welcher verglichen wird.
|
||||||
|
modes_to_calc = ["body", "full"]
|
||||||
|
|
||||||
|
for mode in modes_to_calc:
|
||||||
|
content_to_hash = _get_hash_source_content(n, mode)
|
||||||
|
computed_hash = _compute_hash(content_to_hash)
|
||||||
|
# Key Schema: mode:source:normalize (z.B. "full:parsed:canonical")
|
||||||
|
key = f"{mode}:{hash_source}:{hash_normalize}"
|
||||||
|
payload["hashes"][key] = computed_hash
|
||||||
|
|
||||||
|
# Tags / Keywords
|
||||||
tags = fm.get("tags") or fm.get("keywords") or n.get("tags")
|
tags = fm.get("tags") or fm.get("keywords") or n.get("tags")
|
||||||
if tags:
|
if tags:
|
||||||
payload["tags"] = _ensure_list(tags)
|
payload["tags"] = _ensure_list(tags)
|
||||||
|
|
||||||
# WP-11: Aliases übernehmen (für Discovery Service)
|
# Aliases
|
||||||
aliases = fm.get("aliases")
|
aliases = fm.get("aliases")
|
||||||
if aliases:
|
if aliases:
|
||||||
payload["aliases"] = _ensure_list(aliases)
|
payload["aliases"] = _ensure_list(aliases)
|
||||||
|
|
||||||
# Zeitliche Metadaten (sofern vorhanden)
|
# Zeit
|
||||||
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)
|
# Fulltext
|
||||||
if "body" in n and n["body"]:
|
if "body" in n and n["body"]:
|
||||||
payload["fulltext"] = str(n["body"])
|
payload["fulltext"] = str(n["body"])
|
||||||
|
|
||||||
# JSON-Roundtrip zur harten Validierung (ASCII beibehalten)
|
# JSON Validation
|
||||||
json.loads(json.dumps(payload, ensure_ascii=False))
|
json.loads(json.dumps(payload, ensure_ascii=False))
|
||||||
|
|
||||||
return payload
|
return payload
|
||||||
+52
-61
@@ -1,43 +1,11 @@
|
|||||||
#!/usr/bin/env python3
|
|
||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""
|
"""
|
||||||
Modul: app/core/parser.py
|
FILE: app/core/parser.py
|
||||||
Version: 1.7.1 (fault-tolerant, API-kompatibel)
|
DESCRIPTION: Liest Markdown-Dateien fehlertolerant (Encoding-Fallback). Trennt Frontmatter (YAML) vom Body.
|
||||||
Datum: 2025-10-01
|
WP-22 Erweiterung: Kanten-Extraktion mit Zeilennummern für die EdgeRegistry.
|
||||||
|
VERSION: 1.8.0
|
||||||
Zweck
|
STATUS: Active
|
||||||
-----
|
DEPENDENCIES: yaml, re, dataclasses, json, io, os
|
||||||
Fehlertolerantes Einlesen von Markdown-Dateien mit YAML-Frontmatter.
|
LAST_ANALYSIS: 2025-12-23
|
||||||
Kompatibel zur bisherigen Parser-API, aber robust gegenüber Nicht-UTF-8-Dateien:
|
|
||||||
- Versucht nacheinander: utf-8 → utf-8-sig → cp1252 → latin-1.
|
|
||||||
- Bei Fallback wird ein JSON-Warnhinweis auf stdout ausgegeben; der Import bricht NICHT ab.
|
|
||||||
- YAML-Frontmatter wird mit '---' am Anfang und '---' als Abschluss erkannt.
|
|
||||||
- extract_wikilinks() normalisiert [[id#anchor|label]] → 'id'.
|
|
||||||
|
|
||||||
Öffentliche API (kompatibel):
|
|
||||||
- class ParsedNote(frontmatter: dict, body: str, path: str)
|
|
||||||
- read_markdown(path) -> ParsedNote | None
|
|
||||||
- normalize_frontmatter(fm) -> dict
|
|
||||||
- validate_required_frontmatter(fm, required: tuple[str,...]=("id","title")) -> None
|
|
||||||
- extract_wikilinks(text) -> list[str]
|
|
||||||
- FRONTMATTER_RE (Kompatibilitäts-Konstante; Regex für '---'-Zeilen)
|
|
||||||
|
|
||||||
Beispiele
|
|
||||||
---------
|
|
||||||
from app.core.parser import read_markdown, normalize_frontmatter, validate_required_frontmatter
|
|
||||||
parsed = read_markdown("./vault/30_projects/project-demo.md")
|
|
||||||
fm = normalize_frontmatter(parsed.frontmatter)
|
|
||||||
validate_required_frontmatter(fm)
|
|
||||||
body = parsed.body
|
|
||||||
|
|
||||||
from app.core.parser import extract_wikilinks
|
|
||||||
links = extract_wikilinks(body)
|
|
||||||
|
|
||||||
Abhängigkeiten
|
|
||||||
--------------
|
|
||||||
- PyYAML (yaml)
|
|
||||||
|
|
||||||
Lizenz: MIT (projektintern)
|
|
||||||
"""
|
"""
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
@@ -171,13 +139,7 @@ def _read_text_with_fallback(path: str) -> Tuple[str, str, bool]:
|
|||||||
|
|
||||||
def read_markdown(path: str) -> Optional[ParsedNote]:
|
def read_markdown(path: str) -> Optional[ParsedNote]:
|
||||||
"""
|
"""
|
||||||
Liest eine Markdown-Datei fehlertolerant:
|
Liest eine Markdown-Datei fehlertolerant.
|
||||||
- Erlaubt verschiedene Encodings (UTF-8 bevorzugt, cp1252/latin-1 als Fallback).
|
|
||||||
- Schlägt NICHT mit UnicodeDecodeError fehl.
|
|
||||||
- Gibt ParsedNote(frontmatter, body, path) zurück oder None, falls die Datei nicht existiert.
|
|
||||||
|
|
||||||
Bei Decoding-Fallback wird ein JSON-Warnhinweis geloggt:
|
|
||||||
{"path": "...", "warn": "encoding_fallback_used", "used": "cp1252"}
|
|
||||||
"""
|
"""
|
||||||
if not os.path.exists(path):
|
if not os.path.exists(path):
|
||||||
return None
|
return None
|
||||||
@@ -194,10 +156,6 @@ def validate_required_frontmatter(fm: Dict[str, Any],
|
|||||||
required: Tuple[str, ...] = ("id", "title")) -> None:
|
required: Tuple[str, ...] = ("id", "title")) -> None:
|
||||||
"""
|
"""
|
||||||
Prüft, ob alle Pflichtfelder vorhanden sind.
|
Prüft, ob alle Pflichtfelder vorhanden sind.
|
||||||
Default-kompatibel: ('id', 'title'), kann aber vom Aufrufer erweitert werden, z. B.:
|
|
||||||
validate_required_frontmatter(fm, required=("id","title","type","status","created"))
|
|
||||||
|
|
||||||
Hebt ValueError, falls Felder fehlen oder leer sind.
|
|
||||||
"""
|
"""
|
||||||
if fm is None:
|
if fm is None:
|
||||||
fm = {}
|
fm = {}
|
||||||
@@ -211,17 +169,13 @@ def validate_required_frontmatter(fm: Dict[str, Any],
|
|||||||
if missing:
|
if missing:
|
||||||
raise ValueError(f"Missing required frontmatter fields: {', '.join(missing)}")
|
raise ValueError(f"Missing required frontmatter fields: {', '.join(missing)}")
|
||||||
|
|
||||||
# Plausibilitäten: 'tags' sollte eine Liste sein, wenn vorhanden
|
|
||||||
if "tags" in fm and fm["tags"] not in (None, "") and not isinstance(fm["tags"], (list, tuple)):
|
if "tags" in fm and fm["tags"] not in (None, "") and not isinstance(fm["tags"], (list, tuple)):
|
||||||
raise ValueError("frontmatter 'tags' must be a list of strings")
|
raise ValueError("frontmatter 'tags' must be a list of strings")
|
||||||
|
|
||||||
|
|
||||||
def normalize_frontmatter(fm: Dict[str, Any]) -> Dict[str, Any]:
|
def normalize_frontmatter(fm: Dict[str, Any]) -> Dict[str, Any]:
|
||||||
"""
|
"""
|
||||||
Sanfte Normalisierung ohne Semantikänderung:
|
Normalisierung von Tags und anderen Feldern.
|
||||||
- 'tags' → Liste von Strings (Trim)
|
|
||||||
- 'embedding_exclude' → bool
|
|
||||||
- andere Felder unverändert
|
|
||||||
"""
|
"""
|
||||||
out = dict(fm or {})
|
out = dict(fm or {})
|
||||||
if "tags" in out:
|
if "tags" in out:
|
||||||
@@ -238,15 +192,12 @@ def normalize_frontmatter(fm: Dict[str, Any]) -> Dict[str, Any]:
|
|||||||
|
|
||||||
# ------------------------------ Wikilinks ---------------------------- #
|
# ------------------------------ Wikilinks ---------------------------- #
|
||||||
|
|
||||||
# Basismuster für [[...]]; die Normalisierung (id vor '#', vor '|') macht extract_wikilinks
|
|
||||||
_WIKILINK_RE = re.compile(r"\[\[([^\]]+)\]\]")
|
_WIKILINK_RE = re.compile(r"\[\[([^\]]+)\]\]")
|
||||||
|
|
||||||
|
|
||||||
def extract_wikilinks(text: str) -> List[str]:
|
def extract_wikilinks(text: str) -> List[str]:
|
||||||
"""
|
"""
|
||||||
Extrahiert Wikilinks wie [[id]], [[id#anchor]], [[id|label]], [[id#anchor|label]].
|
Extrahiert Wikilinks als einfache Liste von IDs.
|
||||||
Rückgabe sind NUR die Ziel-IDs (ohne Anchor/Label), führend/folgend getrimmt.
|
|
||||||
Keine aggressive Slug-Normalisierung (die kann später im Resolver erfolgen).
|
|
||||||
"""
|
"""
|
||||||
if not text:
|
if not text:
|
||||||
return []
|
return []
|
||||||
@@ -255,12 +206,52 @@ def extract_wikilinks(text: str) -> List[str]:
|
|||||||
raw = (m.group(1) or "").strip()
|
raw = (m.group(1) or "").strip()
|
||||||
if not raw:
|
if not raw:
|
||||||
continue
|
continue
|
||||||
# Split an Pipe (Label) → links vor '|'
|
|
||||||
if "|" in raw:
|
if "|" in raw:
|
||||||
raw = raw.split("|", 1)[0].strip()
|
raw = raw.split("|", 1)[0].strip()
|
||||||
# Split an Anchor
|
|
||||||
if "#" in raw:
|
if "#" in raw:
|
||||||
raw = raw.split("#", 1)[0].strip()
|
raw = raw.split("#", 1)[0].strip()
|
||||||
if raw:
|
if raw:
|
||||||
out.append(raw)
|
out.append(raw)
|
||||||
return out
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def extract_edges_with_context(parsed: ParsedNote) -> List[Dict[str, Any]]:
|
||||||
|
"""
|
||||||
|
WP-22: Extrahiert Wikilinks [[Ziel|Typ]] aus dem Body und speichert die Zeilennummer.
|
||||||
|
Gibt eine Liste von Dictionaries zurück, die direkt von der Ingestion verarbeitet werden können.
|
||||||
|
"""
|
||||||
|
edges = []
|
||||||
|
if not parsed or not parsed.body:
|
||||||
|
return edges
|
||||||
|
|
||||||
|
# Wir nutzen splitlines(True), um Zeilenumbrüche für die Positionsberechnung zu erhalten,
|
||||||
|
# oder einfaches splitlines() für die reine Zeilennummerierung.
|
||||||
|
lines = parsed.body.splitlines()
|
||||||
|
|
||||||
|
for line_num, line_content in enumerate(lines, 1):
|
||||||
|
for match in _WIKILINK_RE.finditer(line_content):
|
||||||
|
raw = (match.group(1) or "").strip()
|
||||||
|
if not raw:
|
||||||
|
continue
|
||||||
|
|
||||||
|
# Syntax: [[Ziel|Typ]]
|
||||||
|
if "|" in raw:
|
||||||
|
parts = raw.split("|", 1)
|
||||||
|
target = parts[0].strip()
|
||||||
|
kind = parts[1].strip()
|
||||||
|
else:
|
||||||
|
target = raw.strip()
|
||||||
|
kind = "related_to" # Default-Typ
|
||||||
|
|
||||||
|
# Anchor (#) entfernen, da Relationen auf Notiz-Ebene (ID) basieren
|
||||||
|
if "#" in target:
|
||||||
|
target = target.split("#", 1)[0].strip()
|
||||||
|
|
||||||
|
if target:
|
||||||
|
edges.append({
|
||||||
|
"to": target,
|
||||||
|
"kind": kind,
|
||||||
|
"line": line_num,
|
||||||
|
"provenance": "explicit"
|
||||||
|
})
|
||||||
|
return edges
|
||||||
+6
-24
@@ -1,28 +1,10 @@
|
|||||||
#!/usr/bin/env python3
|
|
||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""
|
"""
|
||||||
app/core/qdrant.py
|
FILE: app/core/qdrant.py
|
||||||
Version: 2.2.0 (2025-11-11)
|
DESCRIPTION: Qdrant-Client Factory und Schema-Management. Erstellt Collections und Payload-Indizes.
|
||||||
|
VERSION: 2.2.0
|
||||||
Aufgabe
|
STATUS: Active
|
||||||
-------
|
DEPENDENCIES: qdrant_client, dataclasses, os
|
||||||
- Zentraler Qdrant-Zugriff (Client, Config)
|
LAST_ANALYSIS: 2025-12-15
|
||||||
- Collection-Anlage (notes/chunks/edges)
|
|
||||||
- **Payload-Indizes sicherstellen** (idempotent)
|
|
||||||
|
|
||||||
Hinweis
|
|
||||||
-------
|
|
||||||
Diese Datei ist als Drop-in-Ersatz gedacht, falls in deinem Projekt noch keine
|
|
||||||
robuste ensure_payload_indexes()-Implementierung vorliegt. Die Signaturen
|
|
||||||
bleiben kompatibel zu scripts.import_markdown und scripts.reset_qdrant.
|
|
||||||
|
|
||||||
API-Notizen
|
|
||||||
-----------
|
|
||||||
- Payload-Indizes werden mit `create_payload_index` angelegt.
|
|
||||||
- Typen stammen aus `qdrant_client.http.models.PayloadSchemaType`:
|
|
||||||
KEYWORD | TEXT | INTEGER | FLOAT | BOOL | GEO | DATETIME
|
|
||||||
- Für häufige Filterfelder (note_id, kind, scope, type, tags, ...) legen wir
|
|
||||||
Indizes an. Das ist laut Qdrant-Doku Best Practice für performante Filter.
|
|
||||||
"""
|
"""
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
|
|||||||
@@ -1,18 +1,10 @@
|
|||||||
#!/usr/bin/env python3
|
|
||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""
|
"""
|
||||||
app/core/qdrant_points.py - robust points helpers for Qdrant
|
FILE: app/core/qdrant_points.py
|
||||||
|
DESCRIPTION: Object-Mapper für Qdrant. Konvertiert JSON-Payloads (Notes, Chunks, Edges) in PointStructs und generiert deterministische UUIDs.
|
||||||
- Single source of truth for building PointStruct for notes/chunks/edges
|
VERSION: 1.5.0
|
||||||
- Backward-compatible payloads for edges
|
STATUS: Active
|
||||||
- Handles both Single-Vector and Named-Vector collections
|
DEPENDENCIES: qdrant_client, uuid, os
|
||||||
- Deterministic overrides via ENV to avoid auto-detection traps:
|
LAST_ANALYSIS: 2025-12-15
|
||||||
* NOTES_VECTOR_NAME, CHUNKS_VECTOR_NAME, EDGES_VECTOR_NAME
|
|
||||||
* MINDNET_VECTOR_NAME (fallback)
|
|
||||||
> Set to a concrete name (e.g. "text") to force Named-Vector with that name
|
|
||||||
> Set to "__single__" (or "single") to force Single-Vector
|
|
||||||
|
|
||||||
Version: 1.5.0 (2025-11-08)
|
|
||||||
"""
|
"""
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
import os
|
import os
|
||||||
|
|||||||
@@ -1,56 +0,0 @@
|
|||||||
"""
|
|
||||||
app/core/ranking.py — Kombiniertes Scoring (WP-04)
|
|
||||||
|
|
||||||
Zweck:
|
|
||||||
Zusammenführen von semantischem Score (normalisiert), Edge-Bonus und
|
|
||||||
Centrality-Bonus in einen Gesamtscore für die Ergebnisreihung.
|
|
||||||
Kompatibilität:
|
|
||||||
Python 3.12+
|
|
||||||
Version:
|
|
||||||
0.1.0 (Erstanlage)
|
|
||||||
Stand:
|
|
||||||
2025-10-07
|
|
||||||
Bezug:
|
|
||||||
WP-04 Ranking-Formel (w_sem, w_edge, w_cent)
|
|
||||||
Nutzung:
|
|
||||||
from app.core.ranking import combine_scores
|
|
||||||
Änderungsverlauf:
|
|
||||||
0.1.0 (2025-10-07) – Erstanlage.
|
|
||||||
"""
|
|
||||||
|
|
||||||
from __future__ import annotations
|
|
||||||
from typing import List, Tuple, Dict
|
|
||||||
|
|
||||||
|
|
||||||
def normalize_scores(values: List[float]) -> List[float]:
|
|
||||||
"""Min-Max-Normalisierung über die Kandidatenmenge (Fallback 0.5 bei Konstanz)."""
|
|
||||||
if not values:
|
|
||||||
return values
|
|
||||||
lo, hi = min(values), max(values)
|
|
||||||
if hi - lo < 1e-9:
|
|
||||||
return [0.5] * len(values)
|
|
||||||
return [(v - lo) / (hi - lo) for v in values]
|
|
||||||
|
|
||||||
|
|
||||||
def combine_scores(
|
|
||||||
hits: List[Tuple[str, float, dict]], # (id, semantic_score, payload)
|
|
||||||
edge_bonus_map: Dict[str, float],
|
|
||||||
centrality_map: Dict[str, float],
|
|
||||||
w_sem: float = 0.70,
|
|
||||||
w_edge: float = 0.25,
|
|
||||||
w_cent: float = 0.05,
|
|
||||||
) -> List[Tuple[str, float, float, float, float]]:
|
|
||||||
"""
|
|
||||||
Liefert Liste von (point_id, total_score, edge_bonus, centrality_bonus, raw_semantic_score),
|
|
||||||
absteigend nach total_score sortiert.
|
|
||||||
"""
|
|
||||||
sem = [h[1] for h in hits]
|
|
||||||
sem_n = normalize_scores(sem)
|
|
||||||
out = []
|
|
||||||
for (pid, s, payload), s_norm in zip(hits, sem_n):
|
|
||||||
e = edge_bonus_map.get(pid, 0.0)
|
|
||||||
c = centrality_map.get(pid, 0.0)
|
|
||||||
total = w_sem * s_norm + w_edge * e + w_cent * c
|
|
||||||
out.append((pid, total, e, c, s))
|
|
||||||
out.sort(key=lambda t: t[1], reverse=True)
|
|
||||||
return out
|
|
||||||
+190
-216
@@ -1,82 +1,63 @@
|
|||||||
"""
|
"""
|
||||||
app/core/retriever.py — Hybrider Such-Algorithmus
|
FILE: app/core/retriever.py
|
||||||
|
DESCRIPTION: Haupt-Schnittstelle für die Suche. Orchestriert Vektorsuche und Graph-Expansion.
|
||||||
Version:
|
Nutzt retriever_scoring.py für die WP-22 Logik.
|
||||||
0.5.3 (WP-06 Fix: Populate 'payload' in QueryHit for meta-data access)
|
FIX: TypeError in embed_text (model_name) behoben.
|
||||||
|
FIX: Pydantic ValidationError (Target/Source) behoben.
|
||||||
|
VERSION: 0.6.15 (WP-22 Full & Stable)
|
||||||
|
STATUS: Active
|
||||||
|
DEPENDENCIES: app.config, app.models.dto, app.core.qdrant*, app.core.graph_adapter, app.core.retriever_scoring
|
||||||
"""
|
"""
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import os
|
import os
|
||||||
import time
|
import time
|
||||||
from functools import lru_cache
|
import logging
|
||||||
from typing import Any, Dict, List, Tuple, Iterable, Optional
|
from typing import Any, Dict, List, Tuple, Iterable, Optional
|
||||||
|
|
||||||
from app.config import get_settings
|
from app.config import get_settings
|
||||||
from app.models.dto import (
|
from app.models.dto import (
|
||||||
QueryRequest,
|
QueryRequest, QueryResponse, QueryHit,
|
||||||
QueryResponse,
|
Explanation, ScoreBreakdown, Reason, EdgeDTO
|
||||||
QueryHit,
|
|
||||||
Explanation,
|
|
||||||
ScoreBreakdown,
|
|
||||||
Reason,
|
|
||||||
EdgeDTO
|
|
||||||
)
|
)
|
||||||
import app.core.qdrant as qdr
|
import app.core.qdrant as qdr
|
||||||
import app.core.qdrant_points as qp
|
import app.core.qdrant_points as qp
|
||||||
import app.services.embeddings_client as ec
|
import app.services.embeddings_client as ec
|
||||||
import app.core.graph_adapter as ga
|
import app.core.graph_adapter as ga
|
||||||
|
|
||||||
try:
|
# Mathematische Engine importieren
|
||||||
import yaml # type: ignore[import]
|
from app.core.retriever_scoring import get_weights, compute_wp22_score
|
||||||
except Exception: # pragma: no cover
|
|
||||||
yaml = None # type: ignore[assignment]
|
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
@lru_cache
|
# ==============================================================================
|
||||||
def _get_scoring_weights() -> Tuple[float, float, float]:
|
# 1. CORE HELPERS & CONFIG LOADERS
|
||||||
"""Liefert (semantic_weight, edge_weight, centrality_weight) für den Retriever."""
|
# ==============================================================================
|
||||||
settings = get_settings()
|
|
||||||
sem = float(getattr(settings, "RETRIEVER_W_SEM", 1.0))
|
|
||||||
edge = float(getattr(settings, "RETRIEVER_W_EDGE", 0.0))
|
|
||||||
cent = float(getattr(settings, "RETRIEVER_W_CENT", 0.0))
|
|
||||||
|
|
||||||
config_path = os.getenv("MINDNET_RETRIEVER_CONFIG", "config/retriever.yaml")
|
|
||||||
if yaml is None:
|
|
||||||
return sem, edge, cent
|
|
||||||
try:
|
|
||||||
if os.path.exists(config_path):
|
|
||||||
with open(config_path, "r", encoding="utf-8") as f:
|
|
||||||
data = yaml.safe_load(f) or {}
|
|
||||||
scoring = data.get("scoring", {}) or {}
|
|
||||||
sem = float(scoring.get("semantic_weight", sem))
|
|
||||||
edge = float(scoring.get("edge_weight", edge))
|
|
||||||
cent = float(scoring.get("centrality_weight", cent))
|
|
||||||
except Exception:
|
|
||||||
return sem, edge, cent
|
|
||||||
return sem, edge, cent
|
|
||||||
|
|
||||||
|
|
||||||
def _get_client_and_prefix() -> Tuple[Any, str]:
|
def _get_client_and_prefix() -> Tuple[Any, str]:
|
||||||
"""Liefert (QdrantClient, prefix)."""
|
"""Initialisiert Qdrant Client und lädt Collection-Prefix."""
|
||||||
cfg = qdr.QdrantConfig.from_env()
|
cfg = qdr.QdrantConfig.from_env()
|
||||||
client = qdr.get_client(cfg)
|
return qdr.get_client(cfg), cfg.prefix
|
||||||
return client, cfg.prefix
|
|
||||||
|
|
||||||
|
|
||||||
def _get_query_vector(req: QueryRequest) -> List[float]:
|
def _get_query_vector(req: QueryRequest) -> List[float]:
|
||||||
"""Liefert den Query-Vektor aus dem Request."""
|
"""
|
||||||
|
Vektorisiert die Anfrage.
|
||||||
|
FIX: Enthält try-except Block für unterschiedliche Signaturen von ec.embed_text.
|
||||||
|
"""
|
||||||
if req.query_vector:
|
if req.query_vector:
|
||||||
return list(req.query_vector)
|
return list(req.query_vector)
|
||||||
|
|
||||||
if not req.query:
|
if not req.query:
|
||||||
raise ValueError("QueryRequest benötigt entweder query oder query_vector")
|
raise ValueError("Kein Text oder Vektor für die Suche angegeben.")
|
||||||
|
|
||||||
settings = get_settings()
|
settings = get_settings()
|
||||||
model_name = settings.MODEL_NAME
|
|
||||||
|
|
||||||
try:
|
try:
|
||||||
return ec.embed_text(req.query, model_name=model_name)
|
# Versuch mit modernem Interface (WP-03 kompatibel)
|
||||||
|
return ec.embed_text(req.query, model_name=settings.MODEL_NAME)
|
||||||
except TypeError:
|
except TypeError:
|
||||||
|
# Fallback für Signaturen, die 'model_name' nicht als Keyword akzeptieren
|
||||||
|
logger.debug("ec.embed_text does not accept 'model_name' keyword. Falling back.")
|
||||||
return ec.embed_text(req.query)
|
return ec.embed_text(req.query)
|
||||||
|
|
||||||
|
|
||||||
@@ -85,138 +66,116 @@ def _semantic_hits(
|
|||||||
prefix: str,
|
prefix: str,
|
||||||
vector: List[float],
|
vector: List[float],
|
||||||
top_k: int,
|
top_k: int,
|
||||||
filters: Dict[str, Any] | None = None,
|
filters: Optional[Dict] = None
|
||||||
) -> List[Tuple[str, float, Dict[str, Any]]]:
|
) -> List[Tuple[str, float, Dict[str, Any]]]:
|
||||||
"""Führt eine semantische Suche aus."""
|
"""Führt die Vektorsuche durch und konvertiert Qdrant-Points in ein einheitliches Format."""
|
||||||
flt = filters or None
|
raw_hits = qp.search_chunks_by_vector(client, prefix, vector, top=top_k, filters=filters)
|
||||||
raw_hits = qp.search_chunks_by_vector(client, prefix, vector, top=top_k, filters=flt)
|
# Strikte Typkonvertierung für Stabilität
|
||||||
results: List[Tuple[str, float, Dict[str, Any]]] = []
|
return [(str(hit[0]), float(hit[1]), dict(hit[2] or {})) for hit in raw_hits]
|
||||||
for pid, score, payload in raw_hits:
|
|
||||||
results.append((str(pid), float(score), dict(payload or {})))
|
|
||||||
return results
|
|
||||||
|
|
||||||
|
# ==============================================================================
|
||||||
def _compute_total_score(
|
# 2. EXPLANATION LAYER (DEBUG & VERIFIABILITY)
|
||||||
semantic_score: float,
|
# ==============================================================================
|
||||||
payload: Dict[str, Any],
|
|
||||||
edge_bonus: float = 0.0,
|
|
||||||
cent_bonus: float = 0.0,
|
|
||||||
) -> Tuple[float, float, float]:
|
|
||||||
"""Berechnet total_score."""
|
|
||||||
raw_weight = payload.get("retriever_weight", 1.0)
|
|
||||||
try:
|
|
||||||
weight = float(raw_weight)
|
|
||||||
except (TypeError, ValueError):
|
|
||||||
weight = 1.0
|
|
||||||
if weight < 0.0:
|
|
||||||
weight = 0.0
|
|
||||||
|
|
||||||
sem_w, edge_w, cent_w = _get_scoring_weights()
|
|
||||||
total = (sem_w * float(semantic_score) * weight) + (edge_w * edge_bonus) + (cent_w * cent_bonus)
|
|
||||||
return float(total), float(edge_bonus), float(cent_bonus)
|
|
||||||
|
|
||||||
|
|
||||||
# --- WP-04b Explanation Logic ---
|
|
||||||
|
|
||||||
def _build_explanation(
|
def _build_explanation(
|
||||||
semantic_score: float,
|
semantic_score: float,
|
||||||
payload: Dict[str, Any],
|
payload: Dict[str, Any],
|
||||||
edge_bonus: float,
|
scoring_debug: Dict[str, Any],
|
||||||
cent_bonus: float,
|
|
||||||
subgraph: Optional[ga.Subgraph],
|
subgraph: Optional[ga.Subgraph],
|
||||||
node_key: Optional[str]
|
target_note_id: Optional[str],
|
||||||
|
applied_boosts: Optional[Dict[str, float]] = None
|
||||||
) -> Explanation:
|
) -> Explanation:
|
||||||
"""Erstellt ein Explanation-Objekt."""
|
"""
|
||||||
sem_w, _edge_w, _cent_w = _get_scoring_weights()
|
Transformiert mathematische Scores und Graph-Signale in eine menschenlesbare Erklärung.
|
||||||
# Scoring weights erneut laden für Reason-Details
|
Behebt Pydantic ValidationErrors durch explizite String-Sicherung.
|
||||||
_, edge_w_cfg, cent_w_cfg = _get_scoring_weights()
|
"""
|
||||||
|
_, edge_w_cfg, _ = get_weights()
|
||||||
try:
|
base_val = scoring_debug["base_val"]
|
||||||
type_weight = float(payload.get("retriever_weight", 1.0))
|
|
||||||
except (TypeError, ValueError):
|
|
||||||
type_weight = 1.0
|
|
||||||
|
|
||||||
note_type = payload.get("type", "unknown")
|
|
||||||
|
|
||||||
|
# 1. Detaillierter mathematischer Breakdown
|
||||||
breakdown = ScoreBreakdown(
|
breakdown = ScoreBreakdown(
|
||||||
semantic_contribution=(sem_w * semantic_score * type_weight),
|
semantic_contribution=base_val,
|
||||||
edge_contribution=(edge_w_cfg * edge_bonus),
|
edge_contribution=base_val * scoring_debug["edge_impact_final"],
|
||||||
centrality_contribution=(cent_w_cfg * cent_bonus),
|
centrality_contribution=base_val * scoring_debug["cent_impact_final"],
|
||||||
raw_semantic=semantic_score,
|
raw_semantic=semantic_score,
|
||||||
raw_edge_bonus=edge_bonus,
|
raw_edge_bonus=scoring_debug["edge_bonus"],
|
||||||
raw_centrality=cent_bonus,
|
raw_centrality=scoring_debug["cent_bonus"],
|
||||||
node_weight=type_weight
|
node_weight=float(payload.get("retriever_weight", 1.0)),
|
||||||
|
status_multiplier=scoring_debug["status_multiplier"],
|
||||||
|
graph_boost_factor=scoring_debug["graph_boost_factor"]
|
||||||
)
|
)
|
||||||
|
|
||||||
reasons: List[Reason] = []
|
reasons: List[Reason] = []
|
||||||
edges_dto: List[EdgeDTO] = []
|
edges_dto: List[EdgeDTO] = []
|
||||||
|
|
||||||
|
# 2. Gründe für Semantik hinzufügen
|
||||||
if semantic_score > 0.85:
|
if semantic_score > 0.85:
|
||||||
reasons.append(Reason(kind="semantic", message="Sehr hohe textuelle Übereinstimmung.", score_impact=breakdown.semantic_contribution))
|
reasons.append(Reason(kind="semantic", message="Sehr hohe textuelle Übereinstimmung.", score_impact=base_val))
|
||||||
elif semantic_score > 0.70:
|
elif semantic_score > 0.70:
|
||||||
reasons.append(Reason(kind="semantic", message="Gute textuelle Übereinstimmung.", score_impact=breakdown.semantic_contribution))
|
reasons.append(Reason(kind="semantic", message="Inhaltliche Übereinstimmung.", score_impact=base_val))
|
||||||
|
|
||||||
|
# 3. Gründe für Typ und Lifecycle
|
||||||
|
type_weight = float(payload.get("retriever_weight", 1.0))
|
||||||
if type_weight != 1.0:
|
if type_weight != 1.0:
|
||||||
msg = "Bevorzugt" if type_weight > 1.0 else "Leicht abgewertet"
|
msg = "Bevorzugt" if type_weight > 1.0 else "De-priorisiert"
|
||||||
reasons.append(Reason(kind="type", message=f"{msg} aufgrund des Typs '{note_type}'.", score_impact=(sem_w * semantic_score * (type_weight - 1.0))))
|
reasons.append(Reason(kind="type", message=f"{msg} durch Typ-Profil.", score_impact=base_val * (type_weight - 1.0)))
|
||||||
|
|
||||||
if subgraph and node_key and edge_bonus > 0:
|
|
||||||
if hasattr(subgraph, "get_outgoing_edges"):
|
|
||||||
outgoing = subgraph.get_outgoing_edges(node_key)
|
|
||||||
for edge in outgoing:
|
|
||||||
target = edge.get("target", "Unknown")
|
|
||||||
kind = edge.get("kind", "edge")
|
|
||||||
weight = edge.get("weight", 0.0)
|
|
||||||
if weight > 0.05:
|
|
||||||
edges_dto.append(EdgeDTO(id=f"{node_key}->{target}:{kind}", kind=kind, source=node_key, target=target, weight=weight, direction="out"))
|
|
||||||
|
|
||||||
|
# 4. Kanten-Verarbeitung (Graph-Intelligence)
|
||||||
|
if subgraph and target_note_id and scoring_debug["edge_bonus"] > 0:
|
||||||
|
raw_edges = []
|
||||||
if hasattr(subgraph, "get_incoming_edges"):
|
if hasattr(subgraph, "get_incoming_edges"):
|
||||||
incoming = subgraph.get_incoming_edges(node_key)
|
raw_edges.extend(subgraph.get_incoming_edges(target_note_id) or [])
|
||||||
for edge in incoming:
|
if hasattr(subgraph, "get_outgoing_edges"):
|
||||||
src = edge.get("source", "Unknown")
|
raw_edges.extend(subgraph.get_outgoing_edges(target_note_id) or [])
|
||||||
kind = edge.get("kind", "edge")
|
|
||||||
weight = edge.get("weight", 0.0)
|
|
||||||
if weight > 0.05:
|
|
||||||
edges_dto.append(EdgeDTO(id=f"{src}->{node_key}:{kind}", kind=kind, source=src, target=node_key, weight=weight, direction="in"))
|
|
||||||
|
|
||||||
all_edges = sorted(edges_dto, key=lambda e: e.weight, reverse=True)
|
for edge in raw_edges:
|
||||||
for top_edge in all_edges[:3]:
|
# FIX: Zwingende String-Konvertierung für Pydantic-Stabilität
|
||||||
impact = edge_w_cfg * top_edge.weight
|
src = str(edge.get("source") or "note_root")
|
||||||
dir_txt = "Verweist auf" if top_edge.direction == "out" else "Referenziert von"
|
tgt = str(edge.get("target") or target_note_id or "unknown_target")
|
||||||
tgt_txt = top_edge.target if top_edge.direction == "out" else top_edge.source
|
kind = str(edge.get("kind", "related_to"))
|
||||||
reasons.append(Reason(kind="edge", message=f"{dir_txt} '{tgt_txt}' via '{top_edge.kind}'", score_impact=impact, details={"kind": top_edge.kind}))
|
prov = str(edge.get("provenance", "rule"))
|
||||||
|
conf = float(edge.get("confidence", 1.0))
|
||||||
|
|
||||||
if cent_bonus > 0.01:
|
direction = "in" if tgt == target_note_id else "out"
|
||||||
reasons.append(Reason(kind="centrality", message="Knoten liegt zentral im Kontext.", score_impact=breakdown.centrality_contribution))
|
|
||||||
|
|
||||||
return Explanation(breakdown=breakdown, reasons=reasons, related_edges=edges_dto if edges_dto else None)
|
edge_obj = EdgeDTO(
|
||||||
|
id=f"{src}->{tgt}:{kind}",
|
||||||
|
kind=kind,
|
||||||
|
source=src,
|
||||||
|
target=tgt,
|
||||||
|
weight=conf,
|
||||||
|
direction=direction,
|
||||||
|
provenance=prov,
|
||||||
|
confidence=conf
|
||||||
|
)
|
||||||
|
edges_dto.append(edge_obj)
|
||||||
|
|
||||||
|
# Die 3 wichtigsten Kanten als Begründung formulieren
|
||||||
|
top_edges = sorted(edges_dto, key=lambda e: e.confidence, reverse=True)
|
||||||
|
for e in top_edges[:3]:
|
||||||
|
peer = e.source if e.direction == "in" else e.target
|
||||||
|
prov_txt = "Bestätigte" if e.provenance == "explicit" else "KI-basierte"
|
||||||
|
boost_txt = f" [Boost x{applied_boosts.get(e.kind)}]" if applied_boosts and e.kind in applied_boosts else ""
|
||||||
|
|
||||||
def _extract_expand_options(req: QueryRequest) -> Tuple[int, List[str] | None]:
|
reasons.append(Reason(
|
||||||
"""Extrahiert depth und edge_types."""
|
kind="edge",
|
||||||
expand = getattr(req, "expand", None)
|
message=f"{prov_txt} Kante '{e.kind}'{boost_txt} von/zu '{peer}'.",
|
||||||
if not expand:
|
score_impact=edge_w_cfg * e.confidence
|
||||||
return 0, None
|
))
|
||||||
|
|
||||||
depth = 1
|
if scoring_debug["cent_bonus"] > 0.01:
|
||||||
edge_types: List[str] | None = None
|
reasons.append(Reason(kind="centrality", message="Die Notiz ist ein zentraler Informations-Hub.", score_impact=breakdown.centrality_contribution))
|
||||||
|
|
||||||
if hasattr(expand, "depth") or hasattr(expand, "edge_types"):
|
return Explanation(
|
||||||
depth = int(getattr(expand, "depth", 1) or 1)
|
breakdown=breakdown,
|
||||||
types_val = getattr(expand, "edge_types", None)
|
reasons=reasons,
|
||||||
if types_val:
|
related_edges=edges_dto if edges_dto else None,
|
||||||
edge_types = list(types_val)
|
applied_boosts=applied_boosts
|
||||||
return depth, edge_types
|
)
|
||||||
|
|
||||||
if isinstance(expand, dict):
|
|
||||||
if "depth" in expand:
|
|
||||||
depth = int(expand.get("depth") or 1)
|
|
||||||
if "edge_types" in expand and expand["edge_types"] is not None:
|
|
||||||
edge_types = list(expand["edge_types"])
|
|
||||||
return depth, edge_types
|
|
||||||
|
|
||||||
return 0, None
|
|
||||||
|
|
||||||
|
# ==============================================================================
|
||||||
|
# 3. CORE RETRIEVAL PIPELINE
|
||||||
|
# ==============================================================================
|
||||||
|
|
||||||
def _build_hits_from_semantic(
|
def _build_hits_from_semantic(
|
||||||
hits: Iterable[Tuple[str, float, Dict[str, Any]]],
|
hits: Iterable[Tuple[str, float, Dict[str, Any]]],
|
||||||
@@ -224,113 +183,128 @@ def _build_hits_from_semantic(
|
|||||||
used_mode: str,
|
used_mode: str,
|
||||||
subgraph: ga.Subgraph | None = None,
|
subgraph: ga.Subgraph | None = None,
|
||||||
explain: bool = False,
|
explain: bool = False,
|
||||||
|
dynamic_edge_boosts: Dict[str, float] = None
|
||||||
) -> QueryResponse:
|
) -> QueryResponse:
|
||||||
"""Baut strukturierte QueryHits."""
|
"""Wandelt semantische Roh-Treffer in hochgeladene, bewertete QueryHits um."""
|
||||||
t0 = time.time()
|
t0 = time.time()
|
||||||
enriched: List[Tuple[str, float, Dict[str, Any], float, float, float]] = []
|
enriched = []
|
||||||
|
|
||||||
for pid, semantic_score, payload in hits:
|
for pid, semantic_score, payload in hits:
|
||||||
edge_bonus = 0.0
|
edge_bonus, cent_bonus = 0.0, 0.0
|
||||||
cent_bonus = 0.0
|
target_id = payload.get("note_id")
|
||||||
node_key = payload.get("chunk_id") or payload.get("note_id")
|
|
||||||
|
|
||||||
if subgraph is not None and node_key:
|
if subgraph and target_id:
|
||||||
try:
|
try:
|
||||||
edge_bonus = float(subgraph.edge_bonus(node_key))
|
edge_bonus = float(subgraph.edge_bonus(target_id))
|
||||||
|
cent_bonus = float(subgraph.centrality_bonus(target_id))
|
||||||
except Exception:
|
except Exception:
|
||||||
edge_bonus = 0.0
|
pass
|
||||||
try:
|
|
||||||
cent_bonus = float(subgraph.centrality_bonus(node_key))
|
|
||||||
except Exception:
|
|
||||||
cent_bonus = 0.0
|
|
||||||
|
|
||||||
total, edge_bonus, cent_bonus = _compute_total_score(semantic_score, payload, edge_bonus=edge_bonus, cent_bonus=cent_bonus)
|
# Mathematisches Scoring via WP-22 Engine
|
||||||
enriched.append((pid, float(semantic_score), payload, total, edge_bonus, cent_bonus))
|
debug_data = compute_wp22_score(
|
||||||
|
semantic_score, payload, edge_bonus, cent_bonus, dynamic_edge_boosts
|
||||||
|
)
|
||||||
|
enriched.append((pid, semantic_score, payload, debug_data))
|
||||||
|
|
||||||
enriched_sorted = sorted(enriched, key=lambda h: h[3], reverse=True)
|
# Sortierung nach finalem mathematischen Score
|
||||||
limited = enriched_sorted[: max(1, top_k)]
|
enriched_sorted = sorted(enriched, key=lambda h: h[3]["total"], reverse=True)
|
||||||
|
limited_hits = enriched_sorted[: max(1, top_k)]
|
||||||
|
|
||||||
results: List[QueryHit] = []
|
results: List[QueryHit] = []
|
||||||
for pid, semantic_score, payload, total, edge_bonus, cent_bonus in limited:
|
for pid, s_score, pl, dbg in limited_hits:
|
||||||
explanation_obj = None
|
explanation_obj = None
|
||||||
if explain:
|
if explain:
|
||||||
explanation_obj = _build_explanation(
|
explanation_obj = _build_explanation(
|
||||||
semantic_score=float(semantic_score),
|
semantic_score=float(s_score),
|
||||||
payload=payload,
|
payload=pl,
|
||||||
edge_bonus=edge_bonus,
|
scoring_debug=dbg,
|
||||||
cent_bonus=cent_bonus,
|
|
||||||
subgraph=subgraph,
|
subgraph=subgraph,
|
||||||
node_key=payload.get("chunk_id") or payload.get("note_id")
|
target_note_id=pl.get("note_id"),
|
||||||
|
applied_boosts=dynamic_edge_boosts
|
||||||
)
|
)
|
||||||
|
|
||||||
text_content = payload.get("page_content") or payload.get("text") or payload.get("content")
|
# Payload Text-Feld normalisieren
|
||||||
|
text_content = pl.get("page_content") or pl.get("text") or pl.get("content", "[Kein Text]")
|
||||||
|
|
||||||
results.append(QueryHit(
|
results.append(QueryHit(
|
||||||
node_id=str(pid),
|
node_id=str(pid),
|
||||||
note_id=payload.get("note_id"),
|
note_id=str(pl.get("note_id", "unknown")),
|
||||||
semantic_score=float(semantic_score),
|
semantic_score=float(s_score),
|
||||||
edge_bonus=edge_bonus,
|
edge_bonus=dbg["edge_bonus"],
|
||||||
centrality_bonus=cent_bonus,
|
centrality_bonus=dbg["cent_bonus"],
|
||||||
total_score=total,
|
total_score=dbg["total"],
|
||||||
paths=None,
|
|
||||||
source={
|
source={
|
||||||
"path": payload.get("path"),
|
"path": pl.get("path"),
|
||||||
"section": payload.get("section") or payload.get("section_title"),
|
"section": pl.get("section") or pl.get("section_title"),
|
||||||
"text": text_content
|
"text": text_content
|
||||||
},
|
},
|
||||||
# --- FIX: Wir füllen das payload-Feld explizit ---
|
payload=pl,
|
||||||
payload=payload,
|
|
||||||
explanation=explanation_obj
|
explanation=explanation_obj
|
||||||
))
|
))
|
||||||
|
|
||||||
dt = int((time.time() - t0) * 1000)
|
return QueryResponse(results=results, used_mode=used_mode, latency_ms=int((time.time() - t0) * 1000))
|
||||||
return QueryResponse(results=results, used_mode=used_mode, latency_ms=dt)
|
|
||||||
|
|
||||||
|
|
||||||
def semantic_retrieve(req: QueryRequest) -> QueryResponse:
|
|
||||||
"""Reiner semantischer Retriever."""
|
|
||||||
client, prefix = _get_client_and_prefix()
|
|
||||||
vector = _get_query_vector(req)
|
|
||||||
top_k = req.top_k or get_settings().RETRIEVER_TOP_K
|
|
||||||
|
|
||||||
hits = _semantic_hits(client, prefix, vector, top_k=top_k, filters=req.filters)
|
|
||||||
return _build_hits_from_semantic(hits, top_k=top_k, used_mode="semantic", subgraph=None, explain=req.explain)
|
|
||||||
|
|
||||||
|
|
||||||
def hybrid_retrieve(req: QueryRequest) -> QueryResponse:
|
def hybrid_retrieve(req: QueryRequest) -> QueryResponse:
|
||||||
"""Hybrid-Retriever: semantische Suche + optionale Edge-Expansion."""
|
"""
|
||||||
|
Die Haupt-Einstiegsfunktion für die hybride Suche.
|
||||||
|
Kombiniert Vektorsuche mit Graph-Expansion, Provenance-Weighting und Intent-Boosting.
|
||||||
|
"""
|
||||||
client, prefix = _get_client_and_prefix()
|
client, prefix = _get_client_and_prefix()
|
||||||
if req.query_vector:
|
vector = list(req.query_vector) if req.query_vector else _get_query_vector(req)
|
||||||
vector = list(req.query_vector)
|
top_k = req.top_k or 10
|
||||||
else:
|
|
||||||
vector = _get_query_vector(req)
|
|
||||||
|
|
||||||
top_k = req.top_k or get_settings().RETRIEVER_TOP_K
|
# 1. Semantische Seed-Suche
|
||||||
hits = _semantic_hits(client, prefix, vector, top_k=top_k, filters=req.filters)
|
hits = _semantic_hits(client, prefix, vector, top_k=top_k, filters=req.filters)
|
||||||
|
|
||||||
depth, edge_types = _extract_expand_options(req)
|
# 2. Graph Expansion Konfiguration
|
||||||
|
expand_cfg = req.expand if isinstance(req.expand, dict) else {}
|
||||||
|
depth = int(expand_cfg.get("depth", 1))
|
||||||
|
boost_edges = getattr(req, "boost_edges", {}) or {}
|
||||||
|
|
||||||
subgraph: ga.Subgraph | None = None
|
subgraph: ga.Subgraph | None = None
|
||||||
if depth and depth > 0:
|
if depth > 0 and hits:
|
||||||
seed_ids: List[str] = []
|
# Start-IDs für den Graph-Traversal sammeln
|
||||||
for _pid, _score, payload in hits:
|
seed_ids = list({h[2].get("note_id") for h in hits if h[2].get("note_id")})
|
||||||
key = payload.get("chunk_id") or payload.get("note_id")
|
|
||||||
if key and key not in seed_ids:
|
|
||||||
seed_ids.append(key)
|
|
||||||
if seed_ids:
|
if seed_ids:
|
||||||
try:
|
try:
|
||||||
subgraph = ga.expand(client, prefix, seed_ids, depth=depth, edge_types=edge_types)
|
# Subgraph aus RAM/DB laden
|
||||||
except Exception:
|
subgraph = ga.expand(client, prefix, seed_ids, depth=depth, edge_types=expand_cfg.get("edge_types"))
|
||||||
|
|
||||||
|
# --- WP-22: Kanten-Gewichtung im RAM-Graphen vor Bonus-Berechnung ---
|
||||||
|
if subgraph and hasattr(subgraph, "graph"):
|
||||||
|
for _, _, data in subgraph.graph.edges(data=True):
|
||||||
|
# A. Provenance Weighting (WP-22 Bonus für Herkunft)
|
||||||
|
prov = data.get("provenance", "rule")
|
||||||
|
# Belohnung: Explizite Links (1.0) > Smart (0.9) > Rule (0.7)
|
||||||
|
prov_w = 1.0 if prov == "explicit" else (0.9 if prov == "smart" else 0.7)
|
||||||
|
|
||||||
|
# B. Intent Boost Multiplikator (Vom Router dynamisch injiziert)
|
||||||
|
kind = data.get("kind")
|
||||||
|
intent_multiplier = boost_edges.get(kind, 1.0)
|
||||||
|
|
||||||
|
# Finales Gewicht setzen (Basis * Provenance * Intent)
|
||||||
|
data["weight"] = data.get("weight", 1.0) * prov_w * intent_multiplier
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"Graph Expansion failed: {e}")
|
||||||
subgraph = None
|
subgraph = None
|
||||||
|
|
||||||
return _build_hits_from_semantic(hits, top_k=top_k, used_mode="hybrid", subgraph=subgraph, explain=req.explain)
|
# 3. Scoring & Explanation Generierung
|
||||||
|
return _build_hits_from_semantic(hits, top_k, "hybrid", subgraph, req.explain, boost_edges)
|
||||||
|
|
||||||
|
|
||||||
|
def semantic_retrieve(req: QueryRequest) -> QueryResponse:
|
||||||
|
"""Standard Vektorsuche ohne Graph-Einfluss (WP-02 Fallback)."""
|
||||||
|
client, prefix = _get_client_and_prefix()
|
||||||
|
vector = _get_query_vector(req)
|
||||||
|
hits = _semantic_hits(client, prefix, vector, req.top_k or 10, req.filters)
|
||||||
|
return _build_hits_from_semantic(hits, req.top_k or 10, "semantic", explain=req.explain)
|
||||||
|
|
||||||
|
|
||||||
class Retriever:
|
class Retriever:
|
||||||
"""
|
"""Schnittstelle für die asynchrone Suche."""
|
||||||
Wrapper-Klasse für WP-05 (Chat).
|
|
||||||
"""
|
|
||||||
def __init__(self):
|
|
||||||
pass
|
|
||||||
|
|
||||||
async def search(self, request: QueryRequest) -> QueryResponse:
|
async def search(self, request: QueryRequest) -> QueryResponse:
|
||||||
|
"""Führt eine hybride Suche aus."""
|
||||||
return hybrid_retrieve(request)
|
return hybrid_retrieve(request)
|
||||||
@@ -1,116 +0,0 @@
|
|||||||
"""app/core/retriever_config.py
|
|
||||||
---------------------------------
|
|
||||||
Zentrale Konfiguration für den mindnet-Retriever (WP-04).
|
|
||||||
|
|
||||||
Zweck:
|
|
||||||
- Lädt config/retriever.yaml (falls vorhanden) oder nutzt sinnvolle Defaults.
|
|
||||||
- Bietet einen gecachten Zugriff auf die Retriever-Config für
|
|
||||||
andere Module (z. B. graph_adapter, retriever).
|
|
||||||
|
|
||||||
Hinweis zur Weiterentwicklung (Selbstjustierung):
|
|
||||||
- Die hier definierten Parameter sind so gewählt, dass sie später
|
|
||||||
durch ein Feedback-/Learning-to-Rank-Modell überschrieben werden
|
|
||||||
können, ohne die restliche Architektur anzupassen.
|
|
||||||
"""
|
|
||||||
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
import os
|
|
||||||
from dataclasses import dataclass
|
|
||||||
from functools import lru_cache
|
|
||||||
from pathlib import Path
|
|
||||||
from typing import Dict
|
|
||||||
|
|
||||||
try:
|
|
||||||
import yaml # type: ignore
|
|
||||||
except Exception: # pragma: no cover - Fallback, falls PyYAML nicht installiert ist.
|
|
||||||
yaml = None # type: ignore
|
|
||||||
|
|
||||||
@dataclass(frozen=True)
|
|
||||||
class RetrieverConfig:
|
|
||||||
semantic_scale: float
|
|
||||||
edge_scale: float
|
|
||||||
centrality_scale: float
|
|
||||||
edge_weights: Dict[str, float]
|
|
||||||
|
|
||||||
@lru_cache
|
|
||||||
def get_retriever_config() -> RetrieverConfig:
|
|
||||||
"""Lädt die Retriever-Konfiguration (YAML + Defaults).
|
|
||||||
|
|
||||||
Reihenfolge:
|
|
||||||
1. Defaults (sinnvoll gewählte Startwerte).
|
|
||||||
2. Optional: config/retriever.yaml bzw. Pfad aus ENV
|
|
||||||
MINDNET_RETRIEVER_CONFIG überschreibt die Defaults.
|
|
||||||
|
|
||||||
Die Funktion ist bewusst gecached, da sich die Konfiguration zur
|
|
||||||
Laufzeit üblicherweise nicht ändert. Für dynamisches Nachladen
|
|
||||||
könnte der Cache explizit geleert werden.
|
|
||||||
"""
|
|
||||||
|
|
||||||
# 1) Defaults – bewusst konservativ gewählt.
|
|
||||||
semantic_scale = 1.0
|
|
||||||
edge_scale = 1.0
|
|
||||||
centrality_scale = 1.0
|
|
||||||
|
|
||||||
edge_weights: Dict[str, float] = {
|
|
||||||
# Wissens-Kanten
|
|
||||||
"depends_on": 1.0,
|
|
||||||
"related_to": 0.7,
|
|
||||||
"similar_to": 0.7,
|
|
||||||
"references": 0.5,
|
|
||||||
# Struktur-Kanten
|
|
||||||
"belongs_to": 0.2,
|
|
||||||
"next": 0.1,
|
|
||||||
"prev": 0.1,
|
|
||||||
# Sonstige / technische Kanten
|
|
||||||
"backlink": 0.2,
|
|
||||||
"references_at": 0.2,
|
|
||||||
}
|
|
||||||
|
|
||||||
# 2) Optional: YAML-Konfiguration laden
|
|
||||||
cfg_path_env = os.getenv("MINDNET_RETRIEVER_CONFIG")
|
|
||||||
if cfg_path_env:
|
|
||||||
cfg_path = Path(cfg_path_env)
|
|
||||||
else:
|
|
||||||
# Project-Root = zwei Ebenen über app/core/
|
|
||||||
cfg_path = Path(__file__).resolve().parents[2] / "config" / "retriever.yaml"
|
|
||||||
|
|
||||||
if yaml is not None and cfg_path.exists():
|
|
||||||
try:
|
|
||||||
data = yaml.safe_load(cfg_path.read_text(encoding="utf-8")) or {}
|
|
||||||
except Exception:
|
|
||||||
data = {}
|
|
||||||
|
|
||||||
retr = data.get("retriever") or {}
|
|
||||||
|
|
||||||
# Skalenwerte überschreiben, falls angegeben
|
|
||||||
try:
|
|
||||||
semantic_scale = float(retr.get("semantic_scale", semantic_scale))
|
|
||||||
except (TypeError, ValueError):
|
|
||||||
pass
|
|
||||||
|
|
||||||
try:
|
|
||||||
edge_scale = float(retr.get("edge_scale", edge_scale))
|
|
||||||
except (TypeError, ValueError):
|
|
||||||
pass
|
|
||||||
|
|
||||||
try:
|
|
||||||
centrality_scale = float(retr.get("centrality_scale", centrality_scale))
|
|
||||||
except (TypeError, ValueError):
|
|
||||||
pass
|
|
||||||
|
|
||||||
# Edge-Gewichte je Kanten-Typ
|
|
||||||
ew_cfg = retr.get("edge_weights") or {}
|
|
||||||
if isinstance(ew_cfg, dict):
|
|
||||||
for k, v in ew_cfg.items():
|
|
||||||
try:
|
|
||||||
edge_weights[str(k)] = float(v)
|
|
||||||
except (TypeError, ValueError):
|
|
||||||
continue
|
|
||||||
|
|
||||||
return RetrieverConfig(
|
|
||||||
semantic_scale=semantic_scale,
|
|
||||||
edge_scale=edge_scale,
|
|
||||||
centrality_scale=centrality_scale,
|
|
||||||
edge_weights=edge_weights,
|
|
||||||
)
|
|
||||||
@@ -0,0 +1,120 @@
|
|||||||
|
"""
|
||||||
|
FILE: app/core/retriever_scoring.py
|
||||||
|
DESCRIPTION: Mathematische Kern-Logik für das WP-22 Scoring.
|
||||||
|
Berechnet Relevanz-Scores basierend auf Semantik, Graph-Intelligence und Content Lifecycle.
|
||||||
|
VERSION: 1.0.1 (WP-22 Full Math Engine)
|
||||||
|
STATUS: Active
|
||||||
|
DEPENDENCIES: app.config, typing
|
||||||
|
"""
|
||||||
|
import os
|
||||||
|
import logging
|
||||||
|
from functools import lru_cache
|
||||||
|
from typing import Any, Dict, Tuple, Optional
|
||||||
|
|
||||||
|
try:
|
||||||
|
import yaml
|
||||||
|
except ImportError:
|
||||||
|
yaml = None
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
@lru_cache
|
||||||
|
def get_weights() -> Tuple[float, float, float]:
|
||||||
|
"""
|
||||||
|
Liefert die Basis-Gewichtung (semantic, edge, centrality) aus der Konfiguration.
|
||||||
|
Priorität:
|
||||||
|
1. config/retriever.yaml (Scoring-Sektion)
|
||||||
|
2. Umgebungsvariablen (RETRIEVER_W_*)
|
||||||
|
3. System-Defaults (1.0, 0.0, 0.0)
|
||||||
|
"""
|
||||||
|
from app.config import get_settings
|
||||||
|
settings = get_settings()
|
||||||
|
|
||||||
|
# Defaults aus Settings laden
|
||||||
|
sem = float(getattr(settings, "RETRIEVER_W_SEM", 1.0))
|
||||||
|
edge = float(getattr(settings, "RETRIEVER_W_EDGE", 0.0))
|
||||||
|
cent = float(getattr(settings, "RETRIEVER_W_CENT", 0.0))
|
||||||
|
|
||||||
|
# Optionaler Override via YAML
|
||||||
|
config_path = os.getenv("MINDNET_RETRIEVER_CONFIG", "config/retriever.yaml")
|
||||||
|
if yaml and os.path.exists(config_path):
|
||||||
|
try:
|
||||||
|
with open(config_path, "r", encoding="utf-8") as f:
|
||||||
|
data = yaml.safe_load(f) or {}
|
||||||
|
scoring = data.get("scoring", {})
|
||||||
|
sem = float(scoring.get("semantic_weight", sem))
|
||||||
|
edge = float(scoring.get("edge_weight", edge))
|
||||||
|
cent = float(scoring.get("centrality_weight", cent))
|
||||||
|
except Exception as e:
|
||||||
|
logger.warning(f"Retriever Configuration could not be fully loaded from {config_path}: {e}")
|
||||||
|
|
||||||
|
return sem, edge, cent
|
||||||
|
|
||||||
|
def get_status_multiplier(payload: Dict[str, Any]) -> float:
|
||||||
|
"""
|
||||||
|
WP-22 A: Content Lifecycle Multiplier.
|
||||||
|
Steuert das Ranking basierend auf dem Reifegrad der Information.
|
||||||
|
|
||||||
|
- stable: 1.2 (Belohnung für verifiziertes Wissen)
|
||||||
|
- active: 1.0 (Standard-Gewichtung)
|
||||||
|
- draft: 0.5 (Bestrafung für unfertige Fragmente)
|
||||||
|
"""
|
||||||
|
status = str(payload.get("status", "active")).lower().strip()
|
||||||
|
if status == "stable":
|
||||||
|
return 1.2
|
||||||
|
if status == "draft":
|
||||||
|
return 0.5
|
||||||
|
return 1.0
|
||||||
|
|
||||||
|
def compute_wp22_score(
|
||||||
|
semantic_score: float,
|
||||||
|
payload: Dict[str, Any],
|
||||||
|
edge_bonus_raw: float = 0.0,
|
||||||
|
cent_bonus_raw: float = 0.0,
|
||||||
|
dynamic_edge_boosts: Optional[Dict[str, float]] = None
|
||||||
|
) -> Dict[str, Any]:
|
||||||
|
"""
|
||||||
|
Die zentrale mathematische Scoring-Formel der Mindnet Intelligence.
|
||||||
|
Implementiert das WP-22 Hybrid-Scoring (Semantic * Lifecycle * Graph).
|
||||||
|
|
||||||
|
FORMEL:
|
||||||
|
Score = (Similarity * StatusMult) * (1 + (TypeWeight - 1) + ((EdgeW * EB + CentW * CB) * IntentBoost))
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Dict mit dem finalen 'total' Score und allen mathematischen Zwischenwerten für den Explanation Layer.
|
||||||
|
"""
|
||||||
|
sem_w, edge_w_cfg, cent_w_cfg = get_weights()
|
||||||
|
status_mult = get_status_multiplier(payload)
|
||||||
|
|
||||||
|
# Retriever Weight (Type Boost aus types.yaml, z.B. 1.1 für Decisions)
|
||||||
|
node_weight = float(payload.get("retriever_weight", 1.0))
|
||||||
|
|
||||||
|
# 1. Berechnung des Base Scores (Semantik gewichtet durch Lifecycle-Status)
|
||||||
|
base_val = float(semantic_score) * status_mult
|
||||||
|
|
||||||
|
# 2. Graph Boost Factor (Teil C: Intent-spezifische Verstärkung)
|
||||||
|
# Erhöht das Gewicht des gesamten Graphen um 50%, wenn ein spezifischer Intent vorliegt.
|
||||||
|
graph_boost_factor = 1.5 if dynamic_edge_boosts and (edge_bonus_raw > 0 or cent_bonus_raw > 0) else 1.0
|
||||||
|
|
||||||
|
# 3. Einzelne Graph-Komponenten berechnen
|
||||||
|
edge_impact_final = (edge_w_cfg * edge_bonus_raw) * graph_boost_factor
|
||||||
|
cent_impact_final = (cent_w_cfg * cent_bonus_raw) * graph_boost_factor
|
||||||
|
|
||||||
|
# 4. Finales Zusammenführen (Merging)
|
||||||
|
# (node_weight - 1.0) sorgt dafür, dass ein Gewicht von 1.0 keinen Einfluss hat (neutral).
|
||||||
|
total = base_val * (1.0 + (node_weight - 1.0) + edge_impact_final + cent_impact_final)
|
||||||
|
|
||||||
|
# Sicherstellen, dass der Score niemals 0 oder negativ ist (Floor)
|
||||||
|
final_score = max(0.0001, float(total))
|
||||||
|
|
||||||
|
return {
|
||||||
|
"total": final_score,
|
||||||
|
"edge_bonus": float(edge_bonus_raw),
|
||||||
|
"cent_bonus": float(cent_bonus_raw),
|
||||||
|
"status_multiplier": status_mult,
|
||||||
|
"graph_boost_factor": graph_boost_factor,
|
||||||
|
"type_impact": node_weight - 1.0,
|
||||||
|
"base_val": base_val,
|
||||||
|
"edge_impact_final": edge_impact_final,
|
||||||
|
"cent_impact_final": cent_impact_final
|
||||||
|
}
|
||||||
@@ -1,22 +0,0 @@
|
|||||||
from __future__ import annotations
|
|
||||||
import json
|
|
||||||
import os
|
|
||||||
from functools import lru_cache
|
|
||||||
from jsonschema import Draft202012Validator, RefResolver
|
|
||||||
|
|
||||||
SCHEMAS_DIR = os.getenv("SCHEMAS_DIR", os.path.join(os.path.dirname(os.path.dirname(__file__)), "..", "schemas"))
|
|
||||||
|
|
||||||
@lru_cache(maxsize=16)
|
|
||||||
def load_schema(name: str) -> dict:
|
|
||||||
# name: "note.schema.json" | "chunk.schema.json" | "edge.schema.json"
|
|
||||||
path = os.path.join(SCHEMAS_DIR, name)
|
|
||||||
if not os.path.isfile(path):
|
|
||||||
raise FileNotFoundError(f"Schema not found: {path}")
|
|
||||||
with open(path, "r", encoding="utf-8") as f:
|
|
||||||
return json.load(f)
|
|
||||||
|
|
||||||
@lru_cache(maxsize=16)
|
|
||||||
def get_validator(name: str) -> Draft202012Validator:
|
|
||||||
schema = load_schema(name)
|
|
||||||
resolver = RefResolver.from_schema(schema)
|
|
||||||
return Draft202012Validator(schema, resolver=resolver)
|
|
||||||
@@ -1,30 +1,11 @@
|
|||||||
#!/usr/bin/env python3
|
|
||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""
|
"""
|
||||||
Modul: app/core/type_registry.py
|
FILE: app/core/type_registry.py
|
||||||
Version: 1.0.0
|
DESCRIPTION: Loader für types.yaml. Achtung: Wird in der aktuellen Pipeline meist durch lokale Loader in 'ingestion.py' oder 'note_payload.py' umgangen.
|
||||||
Datum: 2025-11-08
|
VERSION: 1.0.0
|
||||||
|
STATUS: Deprecated (Redundant)
|
||||||
Zweck
|
DEPENDENCIES: yaml, os, functools
|
||||||
-----
|
EXTERNAL_CONFIG: config/types.yaml
|
||||||
Lädt eine optionale Typ-Registry (config/types.yaml) und stellt
|
LAST_ANALYSIS: 2025-12-15
|
||||||
komfortable Zugriffsfunktionen bereit. Die Registry ist *optional*:
|
|
||||||
- Fehlt die Datei oder ist das YAML defekt, wird ein konservativer
|
|
||||||
Default (Typ "concept") verwendet und es wird eine Warnung ausgegeben.
|
|
||||||
- Änderungen an der Datei greifen nach einem Neustart des Prozesses.
|
|
||||||
|
|
||||||
Öffentliche API
|
|
||||||
---------------
|
|
||||||
- load_type_registry(path: str = "config/types.yaml") -> dict
|
|
||||||
- get_type_config(note_type: str, reg: dict) -> dict
|
|
||||||
- resolve_note_type(fm_type: str | None, reg: dict) -> str
|
|
||||||
- effective_chunk_profile(note_type: str, reg: dict) -> str | None
|
|
||||||
- profile_overlap(profile: str | None) -> tuple[int,int] # nur Overlap-Empfehlung
|
|
||||||
|
|
||||||
Hinweis
|
|
||||||
-------
|
|
||||||
Die Registry steuert KEINE Breaking Changes. Ohne Datei/Typ bleibt das
|
|
||||||
Verhalten exakt wie im Release-Stand 20251105.
|
|
||||||
"""
|
"""
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
|
|||||||
@@ -1,16 +0,0 @@
|
|||||||
from __future__ import annotations
|
|
||||||
from typing import Dict
|
|
||||||
from jsonschema import ValidationError
|
|
||||||
from .schema_loader import get_validator
|
|
||||||
|
|
||||||
NOTE_SCHEMA_NAME = "note.schema.json"
|
|
||||||
|
|
||||||
def validate_note_payload(payload: Dict) -> None:
|
|
||||||
validator = get_validator(NOTE_SCHEMA_NAME)
|
|
||||||
errors = sorted(validator.iter_errors(payload), key=lambda e: e.path)
|
|
||||||
if errors:
|
|
||||||
msgs = []
|
|
||||||
for e in errors:
|
|
||||||
loc = ".".join([str(x) for x in e.path]) or "<root>"
|
|
||||||
msgs.append(f"{loc}: {e.message}")
|
|
||||||
raise ValidationError(" | ".join(msgs))
|
|
||||||
@@ -1,40 +0,0 @@
|
|||||||
"""
|
|
||||||
Version 1
|
|
||||||
"""
|
|
||||||
from __future__ import annotations
|
|
||||||
from fastapi import FastAPI, HTTPException
|
|
||||||
from pydantic import BaseModel
|
|
||||||
from typing import List, Optional
|
|
||||||
from sentence_transformers import SentenceTransformer
|
|
||||||
|
|
||||||
app = FastAPI(title="mindnet-embed", version="1.0")
|
|
||||||
|
|
||||||
MODEL_NAME = "sentence-transformers/all-MiniLM-L6-v2" # 384-dim
|
|
||||||
_model: SentenceTransformer | None = None
|
|
||||||
|
|
||||||
class EmbedIn(BaseModel):
|
|
||||||
model: Optional[str] = None
|
|
||||||
inputs: List[str]
|
|
||||||
|
|
||||||
class EmbedOut(BaseModel):
|
|
||||||
embeddings: List[List[float]]
|
|
||||||
|
|
||||||
@app.on_event("startup")
|
|
||||||
def _load_model():
|
|
||||||
global _model
|
|
||||||
_model = SentenceTransformer(MODEL_NAME)
|
|
||||||
|
|
||||||
@app.get("/health")
|
|
||||||
def health():
|
|
||||||
return {"ok": True, "model": MODEL_NAME, "dim": 384}
|
|
||||||
|
|
||||||
@app.post("/embed", response_model=EmbedOut)
|
|
||||||
def embed(payload: EmbedIn) -> EmbedOut:
|
|
||||||
if _model is None:
|
|
||||||
raise HTTPException(status_code=503, detail="Model not loaded")
|
|
||||||
if not payload.inputs:
|
|
||||||
return EmbedOut(embeddings=[])
|
|
||||||
vecs = _model.encode(payload.inputs, normalize_embeddings=False).tolist()
|
|
||||||
if any(len(v) != 384 for v in vecs):
|
|
||||||
raise HTTPException(status_code=500, detail="Embedding size mismatch (expected 384)")
|
|
||||||
return EmbedOut(embeddings=vecs)
|
|
||||||
+6
-2
@@ -1,6 +1,10 @@
|
|||||||
"""
|
"""
|
||||||
Version 0.1
|
FILE: app/embeddings.py
|
||||||
|
DESCRIPTION: Lokaler Wrapper für SentenceTransformer Embeddings.
|
||||||
|
VERSION: 0.1.0
|
||||||
|
STATUS: Active (Bestätigung durch Aufrufer erforderlich)
|
||||||
|
DEPENDENCIES: app.config, sentence_transformers
|
||||||
|
LAST_ANALYSIS: 2025-12-15
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|||||||
+42
-475
@@ -1,492 +1,59 @@
|
|||||||
|
"""
|
||||||
|
FILE: app/frontend/ui.py
|
||||||
|
DESCRIPTION: Main Entrypoint für Streamlit. Router, der basierend auf Sidebar-Auswahl die Module (Chat, Editor, Graph) lädt.
|
||||||
|
VERSION: 2.6.0
|
||||||
|
STATUS: Active
|
||||||
|
DEPENDENCIES: streamlit, ui_config, ui_sidebar, ui_chat, ui_editor, ui_graph_service, ui_graph*, ui_graph_cytoscape
|
||||||
|
LAST_ANALYSIS: 2025-12-15
|
||||||
|
"""
|
||||||
|
|
||||||
import streamlit as st
|
import streamlit as st
|
||||||
import requests
|
|
||||||
import uuid
|
import uuid
|
||||||
import os
|
|
||||||
import json
|
|
||||||
import re
|
|
||||||
import yaml
|
|
||||||
from datetime import datetime
|
|
||||||
from pathlib import Path
|
|
||||||
from dotenv import load_dotenv
|
|
||||||
|
|
||||||
# --- CONFIGURATION ---
|
# --- CONFIG & STYLING ---
|
||||||
load_dotenv()
|
st.set_page_config(page_title="mindnet v2.6", page_icon="🧠", layout="wide")
|
||||||
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.3.10", page_icon="🧠", layout="wide")
|
|
||||||
|
|
||||||
# --- CSS STYLING ---
|
|
||||||
st.markdown("""
|
st.markdown("""
|
||||||
<style>
|
<style>
|
||||||
.block-container { padding-top: 2rem; max_width: 1000px; margin: auto; }
|
.block-container { padding-top: 2rem; max_width: 1200px; 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; }
|
||||||
.intent-badge {
|
.draft-box { border: 1px solid #d0d7de; border-radius: 6px; padding: 16px; background-color: #f6f8fa; margin: 10px 0; }
|
||||||
background-color: #e8f0fe; color: #1a73e8;
|
.preview-box { border: 1px solid #e0e0e0; border-radius: 6px; padding: 24px; background-color: white; }
|
||||||
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;
|
|
||||||
}
|
|
||||||
|
|
||||||
.suggestion-card {
|
|
||||||
border-left: 3px solid #1a73e8;
|
|
||||||
background-color: #ffffff;
|
|
||||||
padding: 10px;
|
|
||||||
margin-bottom: 8px;
|
|
||||||
border-radius: 4px;
|
|
||||||
box-shadow: 0 1px 3px rgba(0,0,0,0.1);
|
|
||||||
}
|
|
||||||
</style>
|
</style>
|
||||||
""", unsafe_allow_html=True)
|
""", unsafe_allow_html=True)
|
||||||
|
|
||||||
|
# --- MODULE IMPORTS ---
|
||||||
|
try:
|
||||||
|
from ui_config import QDRANT_URL, QDRANT_KEY, COLLECTION_PREFIX
|
||||||
|
from ui_graph_service import GraphExplorerService
|
||||||
|
|
||||||
|
# Komponenten
|
||||||
|
from ui_sidebar import render_sidebar
|
||||||
|
from ui_chat import render_chat_interface
|
||||||
|
from ui_editor import render_manual_editor
|
||||||
|
|
||||||
|
# Die beiden Graph-Engines
|
||||||
|
from ui_graph import render_graph_explorer as render_graph_agraph
|
||||||
|
from ui_graph_cytoscape import render_graph_explorer_cytoscape # <-- Import
|
||||||
|
|
||||||
|
except ImportError as e:
|
||||||
|
st.error(f"Import Error: {e}. Bitte stelle sicher, dass alle UI-Dateien im Ordner liegen und 'streamlit-cytoscapejs' installiert ist.")
|
||||||
|
st.stop()
|
||||||
|
|
||||||
# --- SESSION STATE ---
|
# --- SESSION STATE ---
|
||||||
if "messages" not in st.session_state: st.session_state.messages = []
|
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())
|
if "user_id" not in st.session_state: st.session_state.user_id = str(uuid.uuid4())
|
||||||
|
|
||||||
# --- HELPER FUNCTIONS ---
|
# --- SERVICE INIT ---
|
||||||
|
graph_service = GraphExplorerService(QDRANT_URL, QDRANT_KEY, COLLECTION_PREFIX)
|
||||||
|
|
||||||
def normalize_meta_and_body(meta, body):
|
# --- MAIN ROUTING ---
|
||||||
"""Sanitizer: Stellt sicher, dass nur erlaubte Felder im Frontmatter bleiben."""
|
|
||||||
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_meta["tags"] = list(set(all_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):
|
|
||||||
"""Robustes Parsing + Sanitization."""
|
|
||||||
clean_text = full_text
|
|
||||||
|
|
||||||
pattern_block = r"```(?:markdown|md)?\s*(.*?)\s*```"
|
|
||||||
match_block = re.search(pattern_block, full_text, re.DOTALL | re.IGNORECASE)
|
|
||||||
if match_block:
|
|
||||||
clean_text = match_block.group(1).strip()
|
|
||||||
|
|
||||||
parts = re.split(r"^---+\s*$", clean_text, maxsplit=2, flags=re.MULTILINE)
|
|
||||||
|
|
||||||
meta = {}
|
|
||||||
body = clean_text
|
|
||||||
|
|
||||||
if len(parts) >= 3:
|
|
||||||
yaml_str = parts[1]
|
|
||||||
body_candidate = parts[2]
|
|
||||||
try:
|
|
||||||
parsed = yaml.safe_load(yaml_str)
|
|
||||||
if isinstance(parsed, dict):
|
|
||||||
meta = parsed
|
|
||||||
body = body_candidate.strip()
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
|
|
||||||
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":
|
|
||||||
safe_title = re.sub(r'[^a-zA-Z0-9]', '-', meta.get('title', 'note')).lower()[:30]
|
|
||||||
meta["id"] = f"{datetime.now().strftime('%Y%m%d')}-{safe_title}-{uuid.uuid4().hex[:4]}"
|
|
||||||
|
|
||||||
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):
|
|
||||||
"""Ruft den neuen Intelligence-Service (WP-11) auf."""
|
|
||||||
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):
|
|
||||||
"""Ruft den neuen Persistence-Service (WP-11) auf."""
|
|
||||||
try:
|
|
||||||
response = requests.post(
|
|
||||||
INGEST_SAVE_ENDPOINT,
|
|
||||||
json={"markdown_content": markdown_content, "filename": filename},
|
|
||||||
timeout=60
|
|
||||||
)
|
|
||||||
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.3.10 | Mode Switch Fix")
|
|
||||||
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):
|
|
||||||
# Ensure ID Stability
|
|
||||||
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 (Nur beim allerersten Laden der Message) ---
|
|
||||||
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 (Source of Truth)
|
|
||||||
st.session_state[data_meta_key] = meta
|
|
||||||
st.session_state[data_sugg_key] = []
|
|
||||||
st.session_state[data_body_key] = body.strip()
|
|
||||||
|
|
||||||
st.session_state[f"{key_base}_init"] = True
|
|
||||||
|
|
||||||
# --- 2. RESURRECTION FIX (WICHTIG!) ---
|
|
||||||
# Wenn wir vom Manuellen Editor zurückkommen, wurde der widget_key von Streamlit gelöscht.
|
|
||||||
# Wir müssen ihn aus dem persistenten data_body_key wiederherstellen.
|
|
||||||
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_body():
|
|
||||||
# Sync Widget -> Data (Source of Truth)
|
|
||||||
st.session_state[data_body_key] = st.session_state[widget_body_key]
|
|
||||||
|
|
||||||
def _insert_text(text_to_insert):
|
|
||||||
# Insert in Widget Key und Sync Data
|
|
||||||
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")
|
|
||||||
|
|
||||||
# Metadata Form
|
|
||||||
meta_ref = st.session_state[data_meta_key]
|
|
||||||
c1, c2 = st.columns([2, 1])
|
|
||||||
with c1:
|
|
||||||
# Auch hier Keys für Widgets nutzen, um Resets zu vermeiden
|
|
||||||
title_key = f"{key_base}_wdg_title"
|
|
||||||
if title_key not in st.session_state: st.session_state[title_key] = meta_ref["title"]
|
|
||||||
meta_ref["title"] = st.text_input("Titel", key=title_key)
|
|
||||||
|
|
||||||
with c2:
|
|
||||||
known_types = ["concept", "project", "decision", "experience", "journal", "value", "goal", "principle"]
|
|
||||||
curr = meta_ref["type"]
|
|
||||||
if curr not in known_types: known_types.append(curr)
|
|
||||||
type_key = f"{key_base}_wdg_type"
|
|
||||||
if type_key not in st.session_state: st.session_state[type_key] = meta_ref["type"]
|
|
||||||
meta_ref["type"] = st.selectbox("Typ", known_types, index=known_types.index(curr) if curr in known_types else 0, key=type_key)
|
|
||||||
|
|
||||||
tags_key = f"{key_base}_wdg_tags"
|
|
||||||
if tags_key not in st.session_state: st.session_state[tags_key] = meta_ref.get("tags_str", "")
|
|
||||||
meta_ref["tags_str"] = st.text_input("Tags", key=tags_key)
|
|
||||||
|
|
||||||
# Tabs
|
|
||||||
tab_edit, tab_intel, tab_view = st.tabs(["✏️ Inhalt", "🧠 Intelligence", "👁️ Vorschau"])
|
|
||||||
|
|
||||||
# --- TAB 1: EDITOR ---
|
|
||||||
with tab_edit:
|
|
||||||
# Hier kein 'value' Argument mehr, da wir den Key oben (Resurrection) initialisiert haben.
|
|
||||||
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] = []
|
|
||||||
|
|
||||||
# Lese vom Widget (aktuell) oder Data (Fallback)
|
|
||||||
text_to_analyze = st.session_state.get(widget_body_key, st.session_state.get(data_body_key, ""))
|
|
||||||
|
|
||||||
with st.spinner("Analysiere..."):
|
|
||||||
analysis = analyze_draft_text(text_to_analyze, meta_ref["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.")
|
|
||||||
|
|
||||||
# Render List
|
|
||||||
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 = [t.strip() for t in meta_ref["tags_str"].split(",") if t.strip()]
|
|
||||||
final_meta = {
|
|
||||||
"id": "generated_on_save",
|
|
||||||
"type": meta_ref["type"],
|
|
||||||
"title": meta_ref["title"],
|
|
||||||
"status": "draft",
|
|
||||||
"tags": final_tags
|
|
||||||
}
|
|
||||||
# Final Doc aus Data
|
|
||||||
final_body = st.session_state.get(widget_body_key, st.session_state[data_body_key])
|
|
||||||
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..."):
|
|
||||||
safe_title = re.sub(r'[^a-zA-Z0-9]', '-', meta_ref["title"]).lower()[:30] 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":
|
|
||||||
# Header
|
|
||||||
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)
|
|
||||||
|
|
||||||
# Logic
|
|
||||||
if intent == "INTERVIEW":
|
|
||||||
render_draft_editor(msg)
|
|
||||||
else:
|
|
||||||
st.markdown(msg["content"])
|
|
||||||
|
|
||||||
# Sources
|
|
||||||
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()
|
mode, top_k, explain = render_sidebar()
|
||||||
|
|
||||||
if mode == "💬 Chat":
|
if mode == "💬 Chat":
|
||||||
render_chat_interface(top_k, explain)
|
render_chat_interface(top_k, explain)
|
||||||
else:
|
elif mode == "📝 Manueller Editor":
|
||||||
render_manual_editor()
|
render_manual_editor()
|
||||||
|
elif mode == "🕸️ Graph (Agraph)":
|
||||||
|
render_graph_agraph(graph_service)
|
||||||
|
elif mode == "🕸️ Graph (Cytoscape)":
|
||||||
|
render_graph_explorer_cytoscape(graph_service)
|
||||||
@@ -0,0 +1,46 @@
|
|||||||
|
"""
|
||||||
|
FILE: app/frontend/ui_api.py
|
||||||
|
DESCRIPTION: Wrapper für Backend-Calls (Chat, Ingest, Feedback). Kapselt requests und Error-Handling.
|
||||||
|
VERSION: 2.6.0
|
||||||
|
STATUS: Active
|
||||||
|
DEPENDENCIES: requests, streamlit, ui_config
|
||||||
|
LAST_ANALYSIS: 2025-12-15
|
||||||
|
"""
|
||||||
|
|
||||||
|
import requests
|
||||||
|
import streamlit as st
|
||||||
|
from ui_config import CHAT_ENDPOINT, INGEST_ANALYZE_ENDPOINT, INGEST_SAVE_ENDPOINT, FEEDBACK_ENDPOINT, API_TIMEOUT
|
||||||
|
|
||||||
|
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
|
||||||
@@ -0,0 +1,70 @@
|
|||||||
|
"""
|
||||||
|
FILE: app/frontend/ui_callbacks.py
|
||||||
|
DESCRIPTION: Event-Handler für UI-Interaktionen. Implementiert den Übergang vom Graphen zum Editor (State Transfer).
|
||||||
|
VERSION: 2.6.0
|
||||||
|
STATUS: Active
|
||||||
|
DEPENDENCIES: streamlit, os, ui_utils
|
||||||
|
LAST_ANALYSIS: 2025-12-15
|
||||||
|
"""
|
||||||
|
|
||||||
|
import streamlit as st
|
||||||
|
import os
|
||||||
|
from ui_utils import build_markdown_doc
|
||||||
|
|
||||||
|
def switch_to_editor_callback(note_payload):
|
||||||
|
"""
|
||||||
|
Callback für den 'Bearbeiten'-Button im Graphen.
|
||||||
|
Versucht, die Datei direkt aus dem Vault (Dateisystem) zu lesen.
|
||||||
|
Das garantiert, dass Frontmatter und Inhalt vollständig sind (Single Source of Truth).
|
||||||
|
"""
|
||||||
|
# 1. Pfad ermitteln (Priorität auf 'path' aus Qdrant)
|
||||||
|
origin_fname = note_payload.get('path')
|
||||||
|
|
||||||
|
# Fallback für Legacy-Datenfelder
|
||||||
|
if not origin_fname:
|
||||||
|
origin_fname = note_payload.get('file_path') or note_payload.get('filename')
|
||||||
|
|
||||||
|
content = ""
|
||||||
|
file_loaded = False
|
||||||
|
|
||||||
|
# 2. Versuch: Direkt von der Festplatte lesen
|
||||||
|
# Wir prüfen, ob der Pfad existiert und lesen den aktuellen Stand der Datei.
|
||||||
|
if origin_fname and os.path.exists(origin_fname):
|
||||||
|
try:
|
||||||
|
with open(origin_fname, "r", encoding="utf-8") as f:
|
||||||
|
content = f.read()
|
||||||
|
file_loaded = True
|
||||||
|
except Exception as e:
|
||||||
|
# Fehler im Terminal loggen, aber UI nicht crashen lassen
|
||||||
|
print(f"Fehler beim Lesen von {origin_fname}: {e}")
|
||||||
|
|
||||||
|
# 3. Fallback: Inhalt aus Qdrant nehmen (wenn Datei nicht zugreifbar)
|
||||||
|
if not file_loaded:
|
||||||
|
# Wir nehmen 'fulltext' aus dem Payload
|
||||||
|
content = note_payload.get('fulltext', '')
|
||||||
|
|
||||||
|
if not content:
|
||||||
|
# Letzter Ausweg: Metadaten nehmen und Dummy-Content bauen
|
||||||
|
content = build_markdown_doc(note_payload, "Inhalt konnte nicht geladen werden (Datei nicht gefunden).")
|
||||||
|
else:
|
||||||
|
# Check: Hat der Text ein Frontmatter? Wenn nein, rekonstruieren wir es.
|
||||||
|
if not content.strip().startswith("---"):
|
||||||
|
content = build_markdown_doc(note_payload, content)
|
||||||
|
|
||||||
|
# Notfall-Pfad Konstruktion (falls gar kein Pfad im System ist)
|
||||||
|
if not origin_fname and 'note_id' in note_payload:
|
||||||
|
origin_fname = f"{note_payload['note_id']}.md"
|
||||||
|
|
||||||
|
# 4. Daten an den Editor übergeben
|
||||||
|
# Wir nutzen den Chat-Verlauf als Transportmittel für den State
|
||||||
|
st.session_state.messages.append({
|
||||||
|
"role": "assistant",
|
||||||
|
"intent": "INTERVIEW",
|
||||||
|
"content": content,
|
||||||
|
"query_id": f"edit_{note_payload.get('note_id', 'unknown')}", # Trigger für den Editor
|
||||||
|
"origin_filename": origin_fname,
|
||||||
|
"origin_note_id": note_payload.get('note_id')
|
||||||
|
})
|
||||||
|
|
||||||
|
# 5. Modus umschalten (wechselt den Tab beim nächsten Rerun)
|
||||||
|
st.session_state["sidebar_mode_selection"] = "📝 Manueller Editor"
|
||||||
@@ -0,0 +1,87 @@
|
|||||||
|
"""
|
||||||
|
FILE: app/frontend/ui_chat.py
|
||||||
|
DESCRIPTION: Chat-UI. Rendert Nachrichtenverlauf, Quellen-Expanders mit Feedback-Buttons und delegiert bei Bedarf an den Editor.
|
||||||
|
VERSION: 2.6.0
|
||||||
|
STATUS: Active
|
||||||
|
DEPENDENCIES: streamlit, ui_api, ui_editor
|
||||||
|
LAST_ANALYSIS: 2025-12-15
|
||||||
|
"""
|
||||||
|
|
||||||
|
import streamlit as st
|
||||||
|
from ui_api import send_chat_message, submit_feedback
|
||||||
|
from ui_editor import render_draft_editor
|
||||||
|
|
||||||
|
def render_chat_interface(top_k, explain):
|
||||||
|
"""
|
||||||
|
Rendert das Chat-Interface.
|
||||||
|
Zeigt Nachrichten an und behandelt User-Input.
|
||||||
|
"""
|
||||||
|
# 1. Verlauf anzeigen
|
||||||
|
for idx, msg in enumerate(st.session_state.messages):
|
||||||
|
with st.chat_message(msg["role"]):
|
||||||
|
if msg["role"] == "assistant":
|
||||||
|
# Intent Badge
|
||||||
|
intent = msg.get("intent", "UNKNOWN")
|
||||||
|
st.markdown(f'<div class="intent-badge">Intent: {intent}</div>', unsafe_allow_html=True)
|
||||||
|
|
||||||
|
# Debugging (optional, gut für Entwicklung)
|
||||||
|
with st.expander("🐞 Payload", expanded=False):
|
||||||
|
st.json(msg)
|
||||||
|
|
||||||
|
# Unterscheidung: Normaler Text oder Editor-Modus (Interview)
|
||||||
|
if intent == "INTERVIEW":
|
||||||
|
render_draft_editor(msg)
|
||||||
|
else:
|
||||||
|
st.markdown(msg["content"])
|
||||||
|
|
||||||
|
# Quellen anzeigen
|
||||||
|
if "sources" in msg and msg["sources"]:
|
||||||
|
for hit in msg["sources"]:
|
||||||
|
score = hit.get('total_score', 0)
|
||||||
|
# Wenn score None ist, 0.0 annehmen
|
||||||
|
if score is None: score = 0.0
|
||||||
|
|
||||||
|
with st.expander(f"📄 {hit.get('note_id', '?')} ({score:.2f})"):
|
||||||
|
st.markdown(f"_{hit.get('source', {}).get('text', '')[:300]}..._")
|
||||||
|
|
||||||
|
# Explanation Layer
|
||||||
|
if hit.get('explanation'):
|
||||||
|
st.caption(f"Grund: {hit['explanation']['reasons'][0]['message']}")
|
||||||
|
|
||||||
|
# Feedback Buttons pro Source
|
||||||
|
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)
|
||||||
|
|
||||||
|
# Globales Feedback für die Antwort
|
||||||
|
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:
|
||||||
|
# User Nachricht
|
||||||
|
st.markdown(msg["content"])
|
||||||
|
|
||||||
|
# 2. Input Feld
|
||||||
|
if prompt := st.chat_input("Frage Mindnet..."):
|
||||||
|
st.session_state.messages.append({"role": "user", "content": prompt})
|
||||||
|
st.rerun()
|
||||||
|
|
||||||
|
# 3. Antwort generieren (wenn letzte Nachricht vom User ist)
|
||||||
|
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"),
|
||||||
|
"sources": resp.get("sources", []),
|
||||||
|
"query_id": resp.get("query_id")
|
||||||
|
})
|
||||||
|
st.rerun()
|
||||||
@@ -0,0 +1,88 @@
|
|||||||
|
"""
|
||||||
|
FILE: app/frontend/ui_config.py
|
||||||
|
DESCRIPTION: Zentrale Konfiguration für das Frontend. Definiert API-Endpoints, Timeouts und Graph-Styles (Farben).
|
||||||
|
VERSION: 2.6.0
|
||||||
|
STATUS: Active
|
||||||
|
DEPENDENCIES: os, hashlib, dotenv, pathlib
|
||||||
|
LAST_ANALYSIS: 2025-12-15
|
||||||
|
"""
|
||||||
|
|
||||||
|
import os
|
||||||
|
import hashlib
|
||||||
|
from dotenv import load_dotenv
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
load_dotenv()
|
||||||
|
|
||||||
|
# --- API & PORTS ---
|
||||||
|
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"
|
||||||
|
|
||||||
|
# --- QDRANT ---
|
||||||
|
QDRANT_URL = os.getenv("QDRANT_URL", "http://localhost:6333")
|
||||||
|
QDRANT_KEY = os.getenv("QDRANT_API_KEY", None)
|
||||||
|
if QDRANT_KEY == "": QDRANT_KEY = None
|
||||||
|
COLLECTION_PREFIX = os.getenv("COLLECTION_PREFIX", "mindnet")
|
||||||
|
|
||||||
|
# --- FILES & TIMEOUTS ---
|
||||||
|
HISTORY_FILE = Path("data/logs/search_history.jsonl")
|
||||||
|
timeout_setting = os.getenv("MINDNET_API_TIMEOUT") or os.getenv("MINDNET_LLM_TIMEOUT")
|
||||||
|
API_TIMEOUT = float(timeout_setting) if timeout_setting else 300.0
|
||||||
|
|
||||||
|
# --- STYLING CONSTANTS ---
|
||||||
|
|
||||||
|
# Basierend auf types.yaml
|
||||||
|
GRAPH_COLORS = {
|
||||||
|
# Kerntypen
|
||||||
|
"experience": "#feca57", # Gelb/Orange
|
||||||
|
"project": "#ff9f43", # Dunkleres Orange
|
||||||
|
"decision": "#5f27cd", # Lila
|
||||||
|
|
||||||
|
# Persönlichkeit
|
||||||
|
"value": "#00d2d3", # Cyan
|
||||||
|
"principle": "#0abde3", # Dunkles Cyan
|
||||||
|
"belief": "#48dbfb", # Helles Blau
|
||||||
|
"profile": "#1dd1a1", # Grün
|
||||||
|
|
||||||
|
# Strategie & Risiko
|
||||||
|
"goal": "#ff9ff3", # Pink
|
||||||
|
"risk": "#ff6b6b", # Rot
|
||||||
|
|
||||||
|
# Basis
|
||||||
|
"concept": "#54a0ff", # Blau
|
||||||
|
"task": "#8395a7", # Grau-Blau
|
||||||
|
"journal": "#c8d6e5", # Hellgrau
|
||||||
|
"source": "#576574", # Dunkelgrau
|
||||||
|
"glossary": "#222f3e", # Sehr dunkel
|
||||||
|
|
||||||
|
"default": "#8395a7" # Fallback
|
||||||
|
}
|
||||||
|
|
||||||
|
# System-Kanten, die wir NICHT im Graphen sehen wollen, um Rauschen zu reduzieren
|
||||||
|
SYSTEM_EDGES = ["prev", "next", "belongs_to"]
|
||||||
|
|
||||||
|
def get_edge_color(kind: str) -> str:
|
||||||
|
"""Generiert eine deterministische Farbe basierend auf dem Edge-Typ."""
|
||||||
|
if not kind: return "#bdc3c7"
|
||||||
|
|
||||||
|
# Einige feste Farben für wichtige semantische Typen
|
||||||
|
fixed_colors = {
|
||||||
|
"depends_on": "#ff6b6b", # Rot (Blocker/Abhängigkeit)
|
||||||
|
"blocks": "#ee5253", # Dunkelrot
|
||||||
|
"caused_by": "#ff9ff3", # Pink
|
||||||
|
"related_to": "#c8d6e5", # Hellgrau (Hintergrund)
|
||||||
|
"references": "#bdc3c7", # Grau
|
||||||
|
"derived_from": "#1dd1a1" # Grün
|
||||||
|
}
|
||||||
|
|
||||||
|
if kind in fixed_colors:
|
||||||
|
return fixed_colors[kind]
|
||||||
|
|
||||||
|
# Fallback: Hash-basierte Farbe für dynamische Typen
|
||||||
|
# Wir nutzen einen Pastell-Generator, damit es nicht zu grell wird
|
||||||
|
hash_obj = hashlib.md5(kind.encode())
|
||||||
|
hue = int(hash_obj.hexdigest(), 16) % 360
|
||||||
|
return f"hsl({hue}, 60%, 50%)"
|
||||||
@@ -0,0 +1,223 @@
|
|||||||
|
"""
|
||||||
|
FILE: app/frontend/ui_editor.py
|
||||||
|
DESCRIPTION: Markdown-Editor mit Live-Vorschau.
|
||||||
|
Refactored für WP-14: Asynchrones Feedback-Handling (Queued State).
|
||||||
|
VERSION: 2.7.0 (Fix: Async Save UI)
|
||||||
|
STATUS: Active
|
||||||
|
DEPENDENCIES: streamlit, uuid, re, datetime, ui_utils, ui_api
|
||||||
|
"""
|
||||||
|
import streamlit as st
|
||||||
|
import uuid
|
||||||
|
import re
|
||||||
|
from datetime import datetime
|
||||||
|
|
||||||
|
from ui_utils import parse_markdown_draft, build_markdown_doc, slugify
|
||||||
|
from ui_api import save_draft_to_vault, analyze_draft_text
|
||||||
|
|
||||||
|
def render_draft_editor(msg):
|
||||||
|
"""
|
||||||
|
Rendert den Markdown-Editor.
|
||||||
|
Nutzt 'origin_filename' aus der Message, um zwischen Update und Neu zu unterscheiden.
|
||||||
|
"""
|
||||||
|
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"
|
||||||
|
|
||||||
|
# --- 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)
|
||||||
|
|
||||||
|
st.session_state[data_meta_key] = meta
|
||||||
|
st.session_state[data_sugg_key] = []
|
||||||
|
st.session_state[data_body_key] = body.strip()
|
||||||
|
|
||||||
|
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"]
|
||||||
|
|
||||||
|
# Pfad übernehmen (Source of Truth)
|
||||||
|
st.session_state[f"{key_base}_origin_filename"] = msg.get("origin_filename")
|
||||||
|
st.session_state[f"{key_base}_init"] = True
|
||||||
|
|
||||||
|
# --- 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]
|
||||||
|
|
||||||
|
# --- SYNC HELPER ---
|
||||||
|
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(t):
|
||||||
|
st.session_state[widget_body_key] = f"{st.session_state.get(widget_body_key, '')}\n\n{t}"
|
||||||
|
st.session_state[data_body_key] = st.session_state[widget_body_key]
|
||||||
|
|
||||||
|
def _remove_text(t):
|
||||||
|
st.session_state[widget_body_key] = st.session_state.get(widget_body_key, '').replace(t, "").strip()
|
||||||
|
st.session_state[data_body_key] = st.session_state[widget_body_key]
|
||||||
|
|
||||||
|
# --- UI LAYOUT ---
|
||||||
|
|
||||||
|
origin_fname = st.session_state.get(f"{key_base}_origin_filename")
|
||||||
|
|
||||||
|
if origin_fname:
|
||||||
|
display_name = str(origin_fname).split("/")[-1]
|
||||||
|
st.success(f"📂 **Update-Modus**: `{display_name}`")
|
||||||
|
with st.expander("Dateipfad Details", expanded=False):
|
||||||
|
st.code(origin_fname)
|
||||||
|
st.markdown(f'<div class="draft-box" style="border-left: 5px solid #ff9f43;">', unsafe_allow_html=True)
|
||||||
|
else:
|
||||||
|
st.info("✨ **Erstell-Modus**: Neue Datei wird angelegt.")
|
||||||
|
st.markdown(f'<div class="draft-box">', unsafe_allow_html=True)
|
||||||
|
|
||||||
|
st.markdown("### Editor")
|
||||||
|
|
||||||
|
# Meta Felder
|
||||||
|
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)
|
||||||
|
|
||||||
|
# Tabs
|
||||||
|
tab_edit, tab_intel, tab_view = st.tabs(["✏️ Inhalt", "🧠 Intelligence", "👁️ Vorschau"])
|
||||||
|
|
||||||
|
with tab_edit:
|
||||||
|
st.text_area("Body", key=widget_body_key, height=600, on_change=_sync_body, label_visibility="collapsed")
|
||||||
|
|
||||||
|
with tab_intel:
|
||||||
|
st.info("Analysiert den Text auf Verknüpfungsmöglichkeiten.")
|
||||||
|
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, ""))
|
||||||
|
with st.spinner("Analysiere..."):
|
||||||
|
analysis = analyze_draft_text(text_to_analyze, st.session_state.get(f"{key_base}_wdg_type", "concept"))
|
||||||
|
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.")
|
||||||
|
else: st.success(f"{len(suggestions)} Vorschläge gefunden.")
|
||||||
|
|
||||||
|
suggestions = st.session_state[data_sugg_key]
|
||||||
|
if suggestions:
|
||||||
|
current_text = 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
|
||||||
|
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;'><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,))
|
||||||
|
|
||||||
|
# Save Logic Preparation
|
||||||
|
final_tags = [t.strip() for t in st.session_state.get(f"{key_base}_wdg_tags", "").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
|
||||||
|
}
|
||||||
|
if "origin_note_id" in msg:
|
||||||
|
final_meta["id"] = msg["origin_note_id"]
|
||||||
|
|
||||||
|
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("---")
|
||||||
|
|
||||||
|
# Save Actions
|
||||||
|
b1, b2 = st.columns([1, 1])
|
||||||
|
with b1:
|
||||||
|
save_label = "💾 Update speichern" if origin_fname else "💾 Neu anlegen & Indizieren"
|
||||||
|
|
||||||
|
if st.button(save_label, type="primary", key=f"{key_base}_save"):
|
||||||
|
with st.spinner("Sende an Backend..."):
|
||||||
|
if origin_fname:
|
||||||
|
target_file = origin_fname
|
||||||
|
else:
|
||||||
|
raw_title = final_meta.get("title", "draft")
|
||||||
|
target_file = f"{datetime.now().strftime('%Y%m%d')}-{slugify(raw_title)[:60]}.md"
|
||||||
|
|
||||||
|
result = save_draft_to_vault(final_doc, filename=target_file)
|
||||||
|
|
||||||
|
# --- WP-14 CHANGE START: Handling Async Response ---
|
||||||
|
if "error" in result:
|
||||||
|
st.error(f"Fehler: {result['error']}")
|
||||||
|
else:
|
||||||
|
status = result.get("status", "success")
|
||||||
|
file_path = result.get("file_path", "unbekannt")
|
||||||
|
|
||||||
|
if status == "queued":
|
||||||
|
# Neuer Status für Async Processing
|
||||||
|
st.info(f"✅ **Eingereiht:** Datei `{file_path}` wurde gespeichert.")
|
||||||
|
st.caption("Die KI-Analyse und Indizierung läuft im Hintergrund. Du kannst weiterarbeiten.")
|
||||||
|
else:
|
||||||
|
# Legacy / Synchroner Fall
|
||||||
|
st.success(f"Gespeichert: {file_path}")
|
||||||
|
|
||||||
|
st.balloons()
|
||||||
|
# --- WP-14 CHANGE END ---
|
||||||
|
|
||||||
|
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_manual_editor():
|
||||||
|
"""
|
||||||
|
Rendert den manuellen Editor.
|
||||||
|
"""
|
||||||
|
target_msg = None
|
||||||
|
if st.session_state.messages:
|
||||||
|
last_msg = st.session_state.messages[-1]
|
||||||
|
qid = str(last_msg.get("query_id", ""))
|
||||||
|
if qid.startswith("edit_"):
|
||||||
|
target_msg = last_msg
|
||||||
|
|
||||||
|
if not target_msg:
|
||||||
|
target_msg = {
|
||||||
|
"content": "---\ntype: concept\ntitle: Neue Notiz\nstatus: draft\ntags: []\n---\n# Titel\n",
|
||||||
|
"query_id": f"manual_{uuid.uuid4()}"
|
||||||
|
}
|
||||||
|
|
||||||
|
render_draft_editor(target_msg)
|
||||||
@@ -0,0 +1,162 @@
|
|||||||
|
"""
|
||||||
|
FILE: app/frontend/ui_graph.py
|
||||||
|
DESCRIPTION: Legacy Graph-Explorer (Streamlit-Agraph). Implementiert Physik-Simulation (BarnesHut) und direkten Editor-Sprung.
|
||||||
|
VERSION: 2.6.0
|
||||||
|
STATUS: Maintenance (Active Fallback)
|
||||||
|
DEPENDENCIES: streamlit, streamlit_agraph, qdrant_client, ui_config, ui_callbacks
|
||||||
|
LAST_ANALYSIS: 2025-12-15
|
||||||
|
"""
|
||||||
|
|
||||||
|
import streamlit as st
|
||||||
|
from streamlit_agraph import agraph, Config
|
||||||
|
from qdrant_client import models
|
||||||
|
from ui_config import COLLECTION_PREFIX, GRAPH_COLORS
|
||||||
|
from ui_callbacks import switch_to_editor_callback
|
||||||
|
|
||||||
|
def render_graph_explorer(graph_service):
|
||||||
|
st.header("🕸️ Graph Explorer")
|
||||||
|
|
||||||
|
# Session State initialisieren
|
||||||
|
if "graph_center_id" not in st.session_state:
|
||||||
|
st.session_state.graph_center_id = None
|
||||||
|
|
||||||
|
# Defaults für View & Physik setzen
|
||||||
|
st.session_state.setdefault("graph_depth", 2)
|
||||||
|
st.session_state.setdefault("graph_show_labels", True)
|
||||||
|
# Höhere Default-Werte für Abstand
|
||||||
|
st.session_state.setdefault("graph_spacing", 250)
|
||||||
|
st.session_state.setdefault("graph_gravity", -4000)
|
||||||
|
|
||||||
|
col_ctrl, col_graph = st.columns([1, 4])
|
||||||
|
|
||||||
|
# --- LINKE SPALTE: CONTROLS ---
|
||||||
|
with col_ctrl:
|
||||||
|
st.subheader("Fokus")
|
||||||
|
|
||||||
|
# Sucheingabe
|
||||||
|
search_term = st.text_input("Suche Notiz", placeholder="Titel eingeben...")
|
||||||
|
|
||||||
|
# Suchlogik Qdrant
|
||||||
|
if search_term:
|
||||||
|
hits, _ = graph_service.client.scroll(
|
||||||
|
collection_name=f"{COLLECTION_PREFIX}_notes",
|
||||||
|
scroll_filter=models.Filter(must=[models.FieldCondition(key="title", match=models.MatchText(text=search_term))]),
|
||||||
|
limit=10
|
||||||
|
)
|
||||||
|
options = {h.payload['title']: h.payload['note_id'] for h in hits}
|
||||||
|
|
||||||
|
if options:
|
||||||
|
selected_title = st.selectbox("Ergebnisse:", list(options.keys()))
|
||||||
|
if st.button("Laden", use_container_width=True):
|
||||||
|
st.session_state.graph_center_id = options[selected_title]
|
||||||
|
st.rerun()
|
||||||
|
|
||||||
|
st.divider()
|
||||||
|
|
||||||
|
# Layout & Physik Einstellungen
|
||||||
|
with st.expander("👁️ Ansicht & Layout", expanded=True):
|
||||||
|
st.session_state.graph_depth = st.slider("Tiefe (Tier)", 1, 3, st.session_state.graph_depth)
|
||||||
|
st.session_state.graph_show_labels = st.checkbox("Kanten-Beschriftung", st.session_state.graph_show_labels)
|
||||||
|
|
||||||
|
st.markdown("**Physik (BarnesHut)**")
|
||||||
|
st.session_state.graph_spacing = st.slider("Federlänge (Abstand)", 50, 800, st.session_state.graph_spacing)
|
||||||
|
st.session_state.graph_gravity = st.slider("Abstoßung (Gravity)", -20000, -500, st.session_state.graph_gravity)
|
||||||
|
|
||||||
|
if st.button("Reset Layout"):
|
||||||
|
st.session_state.graph_spacing = 250
|
||||||
|
st.session_state.graph_gravity = -4000
|
||||||
|
st.rerun()
|
||||||
|
|
||||||
|
st.divider()
|
||||||
|
st.caption("Legende (Top Typen)")
|
||||||
|
for k, v in list(GRAPH_COLORS.items())[:8]:
|
||||||
|
st.markdown(f"<span style='color:{v}'>●</span> {k}", unsafe_allow_html=True)
|
||||||
|
|
||||||
|
# --- RECHTE SPALTE: GRAPH & ACTION BAR ---
|
||||||
|
with col_graph:
|
||||||
|
center_id = st.session_state.graph_center_id
|
||||||
|
|
||||||
|
if center_id:
|
||||||
|
# Action Container oben fixieren (Layout Fix)
|
||||||
|
action_container = st.container()
|
||||||
|
|
||||||
|
# Graph und Daten laden
|
||||||
|
with st.spinner(f"Lade Graph..."):
|
||||||
|
nodes, edges = graph_service.get_ego_graph(
|
||||||
|
center_id,
|
||||||
|
depth=st.session_state.graph_depth,
|
||||||
|
show_labels=st.session_state.graph_show_labels
|
||||||
|
)
|
||||||
|
|
||||||
|
# WICHTIG: Daten für Editor holen (inkl. Pfad)
|
||||||
|
note_data = graph_service.get_note_with_full_content(center_id)
|
||||||
|
|
||||||
|
# Action Bar rendern
|
||||||
|
with action_container:
|
||||||
|
c1, c2 = st.columns([3, 1])
|
||||||
|
with c1:
|
||||||
|
st.caption(f"Aktives Zentrum: **{center_id}**")
|
||||||
|
with c2:
|
||||||
|
if note_data:
|
||||||
|
st.button("📝 Bearbeiten",
|
||||||
|
use_container_width=True,
|
||||||
|
on_click=switch_to_editor_callback,
|
||||||
|
args=(note_data,))
|
||||||
|
else:
|
||||||
|
st.error("Datenfehler: Note nicht gefunden")
|
||||||
|
|
||||||
|
# Debug Inspector
|
||||||
|
with st.expander("🕵️ Data Inspector", expanded=False):
|
||||||
|
if note_data:
|
||||||
|
st.json(note_data)
|
||||||
|
if 'path' in note_data:
|
||||||
|
st.success(f"Pfad OK: {note_data['path']}")
|
||||||
|
else:
|
||||||
|
st.error("Pfad fehlt!")
|
||||||
|
else:
|
||||||
|
st.info("Leer.")
|
||||||
|
|
||||||
|
if not nodes:
|
||||||
|
st.warning("Keine Daten gefunden.")
|
||||||
|
else:
|
||||||
|
# --- CONFIGURATION (BarnesHut) ---
|
||||||
|
# Height-Trick für Re-Render (da key-Parameter manchmal crasht)
|
||||||
|
dyn_height = 800 + (abs(st.session_state.graph_gravity) % 5)
|
||||||
|
|
||||||
|
config = Config(
|
||||||
|
width=1000,
|
||||||
|
height=dyn_height,
|
||||||
|
directed=True,
|
||||||
|
physics={
|
||||||
|
"enabled": True,
|
||||||
|
"solver": "barnesHut",
|
||||||
|
"barnesHut": {
|
||||||
|
"gravitationalConstant": st.session_state.graph_gravity,
|
||||||
|
"centralGravity": 0.005, # Extrem wichtig für die Ausbreitung!
|
||||||
|
"springLength": st.session_state.graph_spacing,
|
||||||
|
"springConstant": 0.04,
|
||||||
|
"damping": 0.09,
|
||||||
|
"avoidOverlap": 0.1
|
||||||
|
},
|
||||||
|
"stabilization": {"enabled": True, "iterations": 600}
|
||||||
|
},
|
||||||
|
hierarchical=False,
|
||||||
|
nodeHighlightBehavior=True,
|
||||||
|
highlightColor="#F7A7A6",
|
||||||
|
collapsible=False
|
||||||
|
)
|
||||||
|
|
||||||
|
return_value = agraph(nodes=nodes, edges=edges, config=config)
|
||||||
|
|
||||||
|
# Interaktions-Logik (Klick auf Node)
|
||||||
|
if return_value:
|
||||||
|
if return_value != center_id:
|
||||||
|
# Navigation: Neues Zentrum setzen
|
||||||
|
st.session_state.graph_center_id = return_value
|
||||||
|
st.rerun()
|
||||||
|
else:
|
||||||
|
# Klick auf das Zentrum selbst
|
||||||
|
st.toast(f"Zentrum: {return_value}")
|
||||||
|
|
||||||
|
else:
|
||||||
|
st.info("👈 Bitte wähle links eine Notiz aus, um den Graphen zu starten.")
|
||||||
@@ -0,0 +1,334 @@
|
|||||||
|
"""
|
||||||
|
FILE: app/frontend/ui_graph_cytoscape.py
|
||||||
|
DESCRIPTION: Moderner Graph-Explorer (Cytoscape.js). Features: COSE-Layout, Deep-Linking (URL Params), Active Inspector Pattern (CSS-Styling ohne Re-Render).
|
||||||
|
VERSION: 2.6.0
|
||||||
|
STATUS: Active
|
||||||
|
DEPENDENCIES: streamlit, st_cytoscape, qdrant_client, ui_config, ui_callbacks
|
||||||
|
LAST_ANALYSIS: 2025-12-15
|
||||||
|
"""
|
||||||
|
|
||||||
|
import streamlit as st
|
||||||
|
from st_cytoscape import cytoscape
|
||||||
|
from qdrant_client import models
|
||||||
|
from ui_config import COLLECTION_PREFIX, GRAPH_COLORS
|
||||||
|
from ui_callbacks import switch_to_editor_callback
|
||||||
|
|
||||||
|
def update_url_params():
|
||||||
|
"""Callback: Schreibt Slider-Werte in die URL und synchronisiert den State."""
|
||||||
|
# Werte aus den Slider-Keys in die Logik-Variablen übertragen
|
||||||
|
if "cy_depth_slider" in st.session_state:
|
||||||
|
st.session_state.cy_depth = st.session_state.cy_depth_slider
|
||||||
|
if "cy_len_slider" in st.session_state:
|
||||||
|
st.session_state.cy_ideal_edge_len = st.session_state.cy_len_slider
|
||||||
|
if "cy_rep_slider" in st.session_state:
|
||||||
|
st.session_state.cy_node_repulsion = st.session_state.cy_rep_slider
|
||||||
|
|
||||||
|
# In URL schreiben
|
||||||
|
st.query_params["depth"] = st.session_state.cy_depth
|
||||||
|
st.query_params["len"] = st.session_state.cy_ideal_edge_len
|
||||||
|
st.query_params["rep"] = st.session_state.cy_node_repulsion
|
||||||
|
|
||||||
|
def render_graph_explorer_cytoscape(graph_service):
|
||||||
|
st.header("🕸️ Graph Explorer (Cytoscape)")
|
||||||
|
|
||||||
|
# ---------------------------------------------------------
|
||||||
|
# 1. STATE & PERSISTENZ
|
||||||
|
# ---------------------------------------------------------
|
||||||
|
if "graph_center_id" not in st.session_state:
|
||||||
|
st.session_state.graph_center_id = None
|
||||||
|
|
||||||
|
if "graph_inspected_id" not in st.session_state:
|
||||||
|
st.session_state.graph_inspected_id = None
|
||||||
|
|
||||||
|
# Lade Einstellungen aus der URL (falls vorhanden), sonst Defaults
|
||||||
|
params = st.query_params
|
||||||
|
|
||||||
|
# Helper um sicher int zu parsen
|
||||||
|
def get_param(key, default):
|
||||||
|
try: return int(params.get(key, default))
|
||||||
|
except: return default
|
||||||
|
|
||||||
|
# Initialisiere Session State Variablen, falls noch nicht vorhanden
|
||||||
|
if "cy_depth" not in st.session_state:
|
||||||
|
st.session_state.cy_depth = get_param("depth", 2)
|
||||||
|
|
||||||
|
if "cy_ideal_edge_len" not in st.session_state:
|
||||||
|
st.session_state.cy_ideal_edge_len = get_param("len", 150)
|
||||||
|
|
||||||
|
if "cy_node_repulsion" not in st.session_state:
|
||||||
|
st.session_state.cy_node_repulsion = get_param("rep", 1000000)
|
||||||
|
|
||||||
|
col_ctrl, col_graph = st.columns([1, 4])
|
||||||
|
|
||||||
|
# ---------------------------------------------------------
|
||||||
|
# 2. LINKES PANEL (Steuerung)
|
||||||
|
# ---------------------------------------------------------
|
||||||
|
with col_ctrl:
|
||||||
|
st.subheader("Fokus")
|
||||||
|
|
||||||
|
search_term = st.text_input("Suche Notiz", placeholder="Titel eingeben...", key="cy_search")
|
||||||
|
|
||||||
|
if search_term:
|
||||||
|
hits, _ = graph_service.client.scroll(
|
||||||
|
collection_name=f"{COLLECTION_PREFIX}_notes",
|
||||||
|
limit=10,
|
||||||
|
scroll_filter=models.Filter(must=[models.FieldCondition(key="title", match=models.MatchText(text=search_term))])
|
||||||
|
)
|
||||||
|
options = {h.payload['title']: h.payload['note_id'] for h in hits}
|
||||||
|
|
||||||
|
if options:
|
||||||
|
selected_title = st.selectbox("Ergebnisse:", list(options.keys()), key="cy_select")
|
||||||
|
if st.button("Laden", use_container_width=True, key="cy_load"):
|
||||||
|
new_id = options[selected_title]
|
||||||
|
st.session_state.graph_center_id = new_id
|
||||||
|
st.session_state.graph_inspected_id = new_id
|
||||||
|
st.rerun()
|
||||||
|
|
||||||
|
st.divider()
|
||||||
|
|
||||||
|
# LAYOUT EINSTELLUNGEN (Mit URL Sync)
|
||||||
|
with st.expander("👁️ Layout Einstellungen", expanded=True):
|
||||||
|
st.slider("Tiefe (Tier)", 1, 3,
|
||||||
|
value=st.session_state.cy_depth,
|
||||||
|
key="cy_depth_slider",
|
||||||
|
on_change=update_url_params)
|
||||||
|
|
||||||
|
st.markdown("**COSE Layout**")
|
||||||
|
st.slider("Kantenlänge", 50, 600,
|
||||||
|
value=st.session_state.cy_ideal_edge_len,
|
||||||
|
key="cy_len_slider",
|
||||||
|
on_change=update_url_params)
|
||||||
|
|
||||||
|
st.slider("Knoten-Abstoßung", 100000, 5000000, step=100000,
|
||||||
|
value=st.session_state.cy_node_repulsion,
|
||||||
|
key="cy_rep_slider",
|
||||||
|
on_change=update_url_params)
|
||||||
|
|
||||||
|
if st.button("Neu berechnen", key="cy_rerun"):
|
||||||
|
st.rerun()
|
||||||
|
|
||||||
|
st.divider()
|
||||||
|
st.caption("Legende")
|
||||||
|
for k, v in list(GRAPH_COLORS.items())[:8]:
|
||||||
|
st.markdown(f"<span style='color:{v}'>●</span> {k}", unsafe_allow_html=True)
|
||||||
|
# ---------------------------------------------------------
|
||||||
|
# 3. RECHTES PANEL (GRAPH & INSPECTOR)
|
||||||
|
# ---------------------------------------------------------
|
||||||
|
with col_graph:
|
||||||
|
center_id = st.session_state.graph_center_id
|
||||||
|
|
||||||
|
# Fallback Init
|
||||||
|
if not center_id and st.session_state.graph_inspected_id:
|
||||||
|
center_id = st.session_state.graph_inspected_id
|
||||||
|
st.session_state.graph_center_id = center_id
|
||||||
|
|
||||||
|
if center_id:
|
||||||
|
# Sync Inspection
|
||||||
|
if not st.session_state.graph_inspected_id:
|
||||||
|
st.session_state.graph_inspected_id = center_id
|
||||||
|
|
||||||
|
inspected_id = st.session_state.graph_inspected_id
|
||||||
|
|
||||||
|
# --- DATEN LADEN ---
|
||||||
|
with st.spinner(f"Lade Graph (Tiefe {st.session_state.cy_depth})..."):
|
||||||
|
# 1. Graph Daten
|
||||||
|
nodes_data, edges_data = graph_service.get_ego_graph(
|
||||||
|
center_id,
|
||||||
|
depth=st.session_state.cy_depth
|
||||||
|
)
|
||||||
|
# 2. Detail Daten (Inspector)
|
||||||
|
inspected_data = graph_service.get_note_with_full_content(inspected_id)
|
||||||
|
|
||||||
|
# --- ACTION BAR ---
|
||||||
|
action_container = st.container()
|
||||||
|
with action_container:
|
||||||
|
c1, c2, c3 = st.columns([2, 1, 1])
|
||||||
|
|
||||||
|
with c1:
|
||||||
|
title_show = inspected_data.get('title', inspected_id) if inspected_data else inspected_id
|
||||||
|
st.info(f"**Ausgewählt:** {title_show}")
|
||||||
|
|
||||||
|
with c2:
|
||||||
|
# NAVIGATION
|
||||||
|
if inspected_id != center_id:
|
||||||
|
if st.button("🎯 Als Zentrum setzen", use_container_width=True, key="cy_nav_btn"):
|
||||||
|
st.session_state.graph_center_id = inspected_id
|
||||||
|
st.rerun()
|
||||||
|
else:
|
||||||
|
st.caption("_(Ist aktuelles Zentrum)_")
|
||||||
|
|
||||||
|
with c3:
|
||||||
|
# EDITIEREN
|
||||||
|
if inspected_data:
|
||||||
|
st.button("📝 Bearbeiten",
|
||||||
|
use_container_width=True,
|
||||||
|
on_click=switch_to_editor_callback,
|
||||||
|
args=(inspected_data,),
|
||||||
|
key="cy_edit_btn")
|
||||||
|
|
||||||
|
# --- DATA INSPECTOR ---
|
||||||
|
with st.expander("🕵️ Data Inspector (Details)", expanded=False):
|
||||||
|
if inspected_data:
|
||||||
|
col_i1, col_i2 = st.columns(2)
|
||||||
|
with col_i1:
|
||||||
|
st.markdown(f"**ID:** `{inspected_data.get('note_id')}`")
|
||||||
|
st.markdown(f"**Typ:** `{inspected_data.get('type')}`")
|
||||||
|
with col_i2:
|
||||||
|
st.markdown(f"**Tags:** {', '.join(inspected_data.get('tags', []))}")
|
||||||
|
path_check = "✅" if inspected_data.get('path') else "❌"
|
||||||
|
st.markdown(f"**Pfad:** {path_check}")
|
||||||
|
|
||||||
|
st.caption("Inhalt (Vorschau):")
|
||||||
|
st.text_area("Content Preview", inspected_data.get('fulltext', '')[:1000], height=200, disabled=True, label_visibility="collapsed")
|
||||||
|
|
||||||
|
with st.expander("📄 Raw JSON anzeigen"):
|
||||||
|
st.json(inspected_data)
|
||||||
|
else:
|
||||||
|
st.warning("Keine Daten geladen.")
|
||||||
|
|
||||||
|
# --- GRAPH ELEMENTS ---
|
||||||
|
cy_elements = []
|
||||||
|
|
||||||
|
for n in nodes_data:
|
||||||
|
is_center = (n.id == center_id)
|
||||||
|
is_inspected = (n.id == inspected_id)
|
||||||
|
|
||||||
|
tooltip_text = n.title if n.title else n.label
|
||||||
|
display_label = n.label
|
||||||
|
if len(display_label) > 15 and " " in display_label:
|
||||||
|
display_label = display_label.replace(" ", "\n", 1)
|
||||||
|
|
||||||
|
cy_node = {
|
||||||
|
"data": {
|
||||||
|
"id": n.id,
|
||||||
|
"label": display_label,
|
||||||
|
"bg_color": n.color,
|
||||||
|
"tooltip": tooltip_text
|
||||||
|
},
|
||||||
|
# Wir steuern das Aussehen rein über Klassen (.inspected / .center)
|
||||||
|
"classes": " ".join([c for c in ["center" if is_center else "", "inspected" if is_inspected else ""] if c]),
|
||||||
|
"selected": False
|
||||||
|
}
|
||||||
|
cy_elements.append(cy_node)
|
||||||
|
|
||||||
|
for e in edges_data:
|
||||||
|
target_id = getattr(e, "to", getattr(e, "target", None))
|
||||||
|
if target_id:
|
||||||
|
cy_edge = {
|
||||||
|
"data": {
|
||||||
|
"source": e.source,
|
||||||
|
"target": target_id,
|
||||||
|
"label": e.label,
|
||||||
|
"line_color": e.color
|
||||||
|
}
|
||||||
|
}
|
||||||
|
cy_elements.append(cy_edge)
|
||||||
|
|
||||||
|
# --- STYLESHEET ---
|
||||||
|
stylesheet = [
|
||||||
|
{
|
||||||
|
"selector": "node",
|
||||||
|
"style": {
|
||||||
|
"label": "data(label)",
|
||||||
|
"width": "30px", "height": "30px",
|
||||||
|
"background-color": "data(bg_color)",
|
||||||
|
"color": "#333", "font-size": "12px",
|
||||||
|
"text-valign": "center", "text-halign": "center",
|
||||||
|
"text-wrap": "wrap", "text-max-width": "90px",
|
||||||
|
"border-width": 2, "border-color": "#fff",
|
||||||
|
"title": "data(tooltip)"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
# Inspiziert (Gelber Rahmen)
|
||||||
|
{
|
||||||
|
"selector": ".inspected",
|
||||||
|
"style": {
|
||||||
|
"border-width": 6,
|
||||||
|
"border-color": "#FFC300",
|
||||||
|
"width": "50px", "height": "50px",
|
||||||
|
"font-weight": "bold",
|
||||||
|
"z-index": 999
|
||||||
|
}
|
||||||
|
},
|
||||||
|
# Zentrum (Roter Rahmen)
|
||||||
|
{
|
||||||
|
"selector": ".center",
|
||||||
|
"style": {
|
||||||
|
"border-width": 4,
|
||||||
|
"border-color": "#FF5733",
|
||||||
|
"width": "40px", "height": "40px"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
# Mix
|
||||||
|
{
|
||||||
|
"selector": ".center.inspected",
|
||||||
|
"style": {
|
||||||
|
"border-width": 6,
|
||||||
|
"border-color": "#FF5733",
|
||||||
|
"width": "55px", "height": "55px"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
# Default Selection unterdrücken
|
||||||
|
{
|
||||||
|
"selector": "node:selected",
|
||||||
|
"style": {
|
||||||
|
"border-width": 0,
|
||||||
|
"overlay-opacity": 0
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"selector": "edge",
|
||||||
|
"style": {
|
||||||
|
"width": 2,
|
||||||
|
"line-color": "data(line_color)",
|
||||||
|
"target-arrow-color": "data(line_color)",
|
||||||
|
"target-arrow-shape": "triangle",
|
||||||
|
"curve-style": "bezier",
|
||||||
|
"label": "data(label)",
|
||||||
|
"font-size": "10px", "color": "#666",
|
||||||
|
"text-background-opacity": 0.8, "text-background-color": "#fff"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
|
||||||
|
# --- RENDER ---
|
||||||
|
graph_key = f"cy_{center_id}_{st.session_state.cy_depth}_{st.session_state.cy_ideal_edge_len}"
|
||||||
|
|
||||||
|
clicked_elements = cytoscape(
|
||||||
|
elements=cy_elements,
|
||||||
|
stylesheet=stylesheet,
|
||||||
|
layout={
|
||||||
|
"name": "cose",
|
||||||
|
"idealEdgeLength": st.session_state.cy_ideal_edge_len,
|
||||||
|
"nodeOverlap": 20,
|
||||||
|
"refresh": 20,
|
||||||
|
"fit": True,
|
||||||
|
"padding": 50,
|
||||||
|
"randomize": False,
|
||||||
|
"componentSpacing": 100,
|
||||||
|
"nodeRepulsion": st.session_state.cy_node_repulsion,
|
||||||
|
"edgeElasticity": 100,
|
||||||
|
"nestingFactor": 5,
|
||||||
|
"gravity": 80,
|
||||||
|
"numIter": 1000,
|
||||||
|
"initialTemp": 200,
|
||||||
|
"coolingFactor": 0.95,
|
||||||
|
"minTemp": 1.0,
|
||||||
|
"animate": False
|
||||||
|
},
|
||||||
|
key=graph_key,
|
||||||
|
height="700px"
|
||||||
|
)
|
||||||
|
|
||||||
|
# --- EVENT HANDLING ---
|
||||||
|
if clicked_elements:
|
||||||
|
clicked_nodes = clicked_elements.get("nodes", [])
|
||||||
|
if clicked_nodes:
|
||||||
|
clicked_id = clicked_nodes[0]
|
||||||
|
|
||||||
|
if clicked_id != st.session_state.graph_inspected_id:
|
||||||
|
st.session_state.graph_inspected_id = clicked_id
|
||||||
|
st.rerun()
|
||||||
|
|
||||||
|
else:
|
||||||
|
st.info("👈 Bitte wähle links eine Notiz aus.")
|
||||||
@@ -0,0 +1,321 @@
|
|||||||
|
"""
|
||||||
|
FILE: app/frontend/ui_graph_service.py
|
||||||
|
DESCRIPTION: Data Layer für den Graphen. Greift direkt auf Qdrant zu (Performance), um Knoten/Kanten zu laden und Texte zu rekonstruieren ("Stitching").
|
||||||
|
VERSION: 2.6.0
|
||||||
|
STATUS: Active
|
||||||
|
DEPENDENCIES: qdrant_client, streamlit_agraph, ui_config, re
|
||||||
|
LAST_ANALYSIS: 2025-12-15
|
||||||
|
"""
|
||||||
|
|
||||||
|
import re
|
||||||
|
from qdrant_client import QdrantClient, models
|
||||||
|
from streamlit_agraph import Node, Edge
|
||||||
|
from ui_config import GRAPH_COLORS, get_edge_color, SYSTEM_EDGES
|
||||||
|
|
||||||
|
class GraphExplorerService:
|
||||||
|
def __init__(self, url, api_key=None, prefix="mindnet"):
|
||||||
|
self.client = QdrantClient(url=url, api_key=api_key)
|
||||||
|
self.prefix = prefix
|
||||||
|
self.notes_col = f"{prefix}_notes"
|
||||||
|
self.chunks_col = f"{prefix}_chunks"
|
||||||
|
self.edges_col = f"{prefix}_edges"
|
||||||
|
self._note_cache = {}
|
||||||
|
|
||||||
|
def get_note_with_full_content(self, note_id):
|
||||||
|
"""
|
||||||
|
Lädt die Metadaten der Note und rekonstruiert den gesamten Text
|
||||||
|
aus den Chunks (Stitching). Wichtig für den Editor-Fallback.
|
||||||
|
"""
|
||||||
|
# 1. Metadaten holen
|
||||||
|
meta = self._fetch_note_cached(note_id)
|
||||||
|
if not meta: return None
|
||||||
|
|
||||||
|
# 2. Volltext aus Chunks bauen
|
||||||
|
full_text = self._fetch_full_text_stitched(note_id)
|
||||||
|
|
||||||
|
# 3. Ergebnis kombinieren (Wir überschreiben das 'fulltext' Feld mit dem frischen Stitching)
|
||||||
|
# Wir geben eine Kopie zurück, um den Cache nicht zu verfälschen
|
||||||
|
complete_note = meta.copy()
|
||||||
|
if full_text:
|
||||||
|
complete_note['fulltext'] = full_text
|
||||||
|
|
||||||
|
return complete_note
|
||||||
|
|
||||||
|
def get_ego_graph(self, center_note_id: str, depth=2, show_labels=True):
|
||||||
|
"""
|
||||||
|
Erstellt den Ego-Graphen um eine zentrale Notiz.
|
||||||
|
Lädt Volltext für das Zentrum und Snippets für Nachbarn.
|
||||||
|
"""
|
||||||
|
nodes_dict = {}
|
||||||
|
unique_edges = {}
|
||||||
|
|
||||||
|
# 1. Center Note laden
|
||||||
|
center_note = self._fetch_note_cached(center_note_id)
|
||||||
|
if not center_note: return [], []
|
||||||
|
self._add_node_to_dict(nodes_dict, center_note, level=0)
|
||||||
|
|
||||||
|
# Initialset für Suche
|
||||||
|
level_1_ids = {center_note_id}
|
||||||
|
|
||||||
|
# Suche Kanten für Center (L1)
|
||||||
|
l1_edges = self._find_connected_edges([center_note_id], center_note.get("title"))
|
||||||
|
|
||||||
|
for edge_data in l1_edges:
|
||||||
|
src_id, tgt_id = self._process_edge(edge_data, nodes_dict, unique_edges, current_depth=1)
|
||||||
|
if src_id: level_1_ids.add(src_id)
|
||||||
|
if tgt_id: level_1_ids.add(tgt_id)
|
||||||
|
|
||||||
|
# Level 2 Suche (begrenzt für Performance)
|
||||||
|
if depth > 1 and len(level_1_ids) > 1 and len(level_1_ids) < 80:
|
||||||
|
l1_subset = list(level_1_ids - {center_note_id})
|
||||||
|
if l1_subset:
|
||||||
|
l2_edges = self._find_connected_edges_batch(l1_subset)
|
||||||
|
for edge_data in l2_edges:
|
||||||
|
self._process_edge(edge_data, nodes_dict, unique_edges, current_depth=2)
|
||||||
|
|
||||||
|
# --- SMART CONTENT LOADING ---
|
||||||
|
|
||||||
|
# A. Fulltext für Center Node holen (Chunks zusammenfügen)
|
||||||
|
center_text = self._fetch_full_text_stitched(center_note_id)
|
||||||
|
if center_note_id in nodes_dict:
|
||||||
|
orig_title = nodes_dict[center_note_id].title
|
||||||
|
clean_full = self._clean_markdown(center_text[:2000])
|
||||||
|
# Wir packen den Text in den Tooltip (title attribute)
|
||||||
|
nodes_dict[center_note_id].title = f"{orig_title}\n\n📄 INHALT:\n{clean_full}..."
|
||||||
|
|
||||||
|
# B. Previews für alle Nachbarn holen (Batch)
|
||||||
|
all_ids = list(nodes_dict.keys())
|
||||||
|
previews = self._fetch_previews_for_nodes(all_ids)
|
||||||
|
|
||||||
|
for nid, node_obj in nodes_dict.items():
|
||||||
|
if nid != center_note_id:
|
||||||
|
prev_raw = previews.get(nid, "Kein Vorschau-Text.")
|
||||||
|
clean_prev = self._clean_markdown(prev_raw[:600])
|
||||||
|
node_obj.title = f"{node_obj.title}\n\n🔍 VORSCHAU:\n{clean_prev}..."
|
||||||
|
|
||||||
|
# Graphen bauen (Nodes & Edges finalisieren)
|
||||||
|
final_edges = []
|
||||||
|
for (src, tgt), data in unique_edges.items():
|
||||||
|
kind = data['kind']
|
||||||
|
prov = data['provenance']
|
||||||
|
color = get_edge_color(kind)
|
||||||
|
is_smart = (prov != "explicit" and prov != "rule")
|
||||||
|
|
||||||
|
# Label Logik
|
||||||
|
label_text = kind if show_labels else " "
|
||||||
|
|
||||||
|
final_edges.append(Edge(
|
||||||
|
source=src, target=tgt, label=label_text, color=color, dashes=is_smart,
|
||||||
|
title=f"Relation: {kind}\nProvenance: {prov}"
|
||||||
|
))
|
||||||
|
|
||||||
|
return list(nodes_dict.values()), final_edges
|
||||||
|
|
||||||
|
def _clean_markdown(self, text):
|
||||||
|
"""Entfernt Markdown-Sonderzeichen für saubere Tooltips im Browser."""
|
||||||
|
if not text: return ""
|
||||||
|
# Entferne Header Marker (## )
|
||||||
|
text = re.sub(r'#+\s', '', text)
|
||||||
|
# Entferne Bold/Italic (** oder *)
|
||||||
|
text = re.sub(r'\*\*|__|\*|_', '', text)
|
||||||
|
# Entferne Links [Text](Url) -> Text
|
||||||
|
text = re.sub(r'\[([^\]]+)\]\([^\)]+\)', r'\1', text)
|
||||||
|
# Entferne Wikilinks [[Link]] -> Link
|
||||||
|
text = re.sub(r'\[\[([^\]]+)\]\]', r'\1', text)
|
||||||
|
return text
|
||||||
|
|
||||||
|
def _fetch_full_text_stitched(self, note_id):
|
||||||
|
"""Lädt alle Chunks einer Note und baut den Text zusammen."""
|
||||||
|
try:
|
||||||
|
scroll_filter = models.Filter(
|
||||||
|
must=[models.FieldCondition(key="note_id", match=models.MatchValue(value=note_id))]
|
||||||
|
)
|
||||||
|
# Limit hoch genug setzen
|
||||||
|
chunks, _ = self.client.scroll(self.chunks_col, scroll_filter=scroll_filter, limit=100, with_payload=True)
|
||||||
|
# Sortieren nach 'ord' (Reihenfolge im Dokument)
|
||||||
|
chunks.sort(key=lambda x: x.payload.get('ord', 999))
|
||||||
|
|
||||||
|
full_text = []
|
||||||
|
for c in chunks:
|
||||||
|
# 'text' ist der reine Inhalt ohne Overlap
|
||||||
|
txt = c.payload.get('text', '')
|
||||||
|
if txt: full_text.append(txt)
|
||||||
|
|
||||||
|
return "\n\n".join(full_text)
|
||||||
|
except:
|
||||||
|
return "Fehler beim Laden des Volltexts."
|
||||||
|
|
||||||
|
def _fetch_previews_for_nodes(self, node_ids):
|
||||||
|
"""Holt Batch-weise den ersten Chunk für eine Liste von Nodes."""
|
||||||
|
if not node_ids: return {}
|
||||||
|
previews = {}
|
||||||
|
try:
|
||||||
|
scroll_filter = models.Filter(must=[models.FieldCondition(key="note_id", match=models.MatchAny(any=node_ids))])
|
||||||
|
# Limit = Anzahl Nodes * 3 (Puffer)
|
||||||
|
chunks, _ = self.client.scroll(self.chunks_col, scroll_filter=scroll_filter, limit=len(node_ids)*3, with_payload=True)
|
||||||
|
|
||||||
|
for c in chunks:
|
||||||
|
nid = c.payload.get("note_id")
|
||||||
|
# Nur den ersten gefundenen Chunk pro Note nehmen
|
||||||
|
if nid and nid not in previews:
|
||||||
|
previews[nid] = c.payload.get("window") or c.payload.get("text") or ""
|
||||||
|
except: pass
|
||||||
|
return previews
|
||||||
|
|
||||||
|
def _find_connected_edges(self, note_ids, note_title=None):
|
||||||
|
"""Findet eingehende und ausgehende Kanten."""
|
||||||
|
|
||||||
|
results = []
|
||||||
|
|
||||||
|
# 1. OUTGOING EDGES (Der "Owner"-Fix)
|
||||||
|
# Wir suchen Kanten, die im Feld 'note_id' (Owner) eine unserer Notizen haben.
|
||||||
|
# Das findet ALLE ausgehenden Kanten, egal ob sie an einem Chunk oder der Note hängen.
|
||||||
|
if note_ids:
|
||||||
|
out_filter = models.Filter(must=[
|
||||||
|
models.FieldCondition(key="note_id", match=models.MatchAny(any=note_ids)),
|
||||||
|
models.FieldCondition(key="kind", match=models.MatchExcept(**{"except": SYSTEM_EDGES}))
|
||||||
|
])
|
||||||
|
# Limit hoch, um alles zu finden
|
||||||
|
res_out, _ = self.client.scroll(self.edges_col, scroll_filter=out_filter, limit=500, with_payload=True)
|
||||||
|
results.extend(res_out)
|
||||||
|
|
||||||
|
# 2. INCOMING EDGES (Ziel = Chunk ID oder Titel oder Note ID)
|
||||||
|
# Hier müssen wir Chunks auflösen, um Treffer auf Chunks zu finden.
|
||||||
|
|
||||||
|
# Chunk IDs der aktuellen Notes holen
|
||||||
|
chunk_ids = []
|
||||||
|
if note_ids:
|
||||||
|
c_filter = models.Filter(must=[models.FieldCondition(key="note_id", match=models.MatchAny(any=note_ids))])
|
||||||
|
chunks, _ = self.client.scroll(self.chunks_col, scroll_filter=c_filter, limit=300)
|
||||||
|
chunk_ids = [c.id for c in chunks]
|
||||||
|
|
||||||
|
shoulds = []
|
||||||
|
# Case A: Edge zeigt auf einen unserer Chunks
|
||||||
|
if chunk_ids:
|
||||||
|
shoulds.append(models.FieldCondition(key="target_id", match=models.MatchAny(any=chunk_ids)))
|
||||||
|
|
||||||
|
# Case B: Edge zeigt direkt auf unsere Note ID
|
||||||
|
if note_ids:
|
||||||
|
shoulds.append(models.FieldCondition(key="target_id", match=models.MatchAny(any=note_ids)))
|
||||||
|
|
||||||
|
# Case C: Edge zeigt auf unseren Titel (Wikilinks)
|
||||||
|
if note_title:
|
||||||
|
shoulds.append(models.FieldCondition(key="target_id", match=models.MatchValue(value=note_title)))
|
||||||
|
|
||||||
|
if shoulds:
|
||||||
|
in_filter = models.Filter(
|
||||||
|
must=[models.FieldCondition(key="kind", match=models.MatchExcept(**{"except": SYSTEM_EDGES}))],
|
||||||
|
should=shoulds
|
||||||
|
)
|
||||||
|
res_in, _ = self.client.scroll(self.edges_col, scroll_filter=in_filter, limit=500, with_payload=True)
|
||||||
|
results.extend(res_in)
|
||||||
|
|
||||||
|
return results
|
||||||
|
|
||||||
|
def _find_connected_edges_batch(self, note_ids):
|
||||||
|
# Wrapper für Level 2 Suche
|
||||||
|
return self._find_connected_edges(note_ids)
|
||||||
|
|
||||||
|
def _process_edge(self, record, nodes_dict, unique_edges, current_depth):
|
||||||
|
"""Verarbeitet eine rohe Edge, löst IDs auf und fügt sie den Dictionaries hinzu."""
|
||||||
|
payload = record.payload
|
||||||
|
src_ref = payload.get("source_id")
|
||||||
|
tgt_ref = payload.get("target_id")
|
||||||
|
kind = payload.get("kind")
|
||||||
|
provenance = payload.get("provenance", "explicit")
|
||||||
|
|
||||||
|
# IDs zu Notes auflösen
|
||||||
|
src_note = self._resolve_note_from_ref(src_ref)
|
||||||
|
tgt_note = self._resolve_note_from_ref(tgt_ref)
|
||||||
|
|
||||||
|
if src_note and tgt_note:
|
||||||
|
src_id = src_note['note_id']
|
||||||
|
tgt_id = tgt_note['note_id']
|
||||||
|
|
||||||
|
if src_id != tgt_id:
|
||||||
|
# Nodes hinzufügen
|
||||||
|
self._add_node_to_dict(nodes_dict, src_note, level=current_depth)
|
||||||
|
self._add_node_to_dict(nodes_dict, tgt_note, level=current_depth)
|
||||||
|
|
||||||
|
# Kante hinzufügen (mit Deduplizierung)
|
||||||
|
key = (src_id, tgt_id)
|
||||||
|
existing = unique_edges.get(key)
|
||||||
|
|
||||||
|
should_update = True
|
||||||
|
# Bevorzuge explizite Kanten vor Smart Kanten
|
||||||
|
is_current_explicit = (provenance in ["explicit", "rule"])
|
||||||
|
if existing:
|
||||||
|
is_existing_explicit = (existing['provenance'] in ["explicit", "rule"])
|
||||||
|
if is_existing_explicit and not is_current_explicit:
|
||||||
|
should_update = False
|
||||||
|
|
||||||
|
if should_update:
|
||||||
|
unique_edges[key] = {"source": src_id, "target": tgt_id, "kind": kind, "provenance": provenance}
|
||||||
|
return src_id, tgt_id
|
||||||
|
return None, None
|
||||||
|
|
||||||
|
def _fetch_note_cached(self, note_id):
|
||||||
|
if note_id in self._note_cache: return self._note_cache[note_id]
|
||||||
|
res, _ = self.client.scroll(
|
||||||
|
collection_name=self.notes_col,
|
||||||
|
scroll_filter=models.Filter(must=[models.FieldCondition(key="note_id", match=models.MatchValue(value=note_id))]),
|
||||||
|
limit=1, with_payload=True
|
||||||
|
)
|
||||||
|
if res:
|
||||||
|
self._note_cache[note_id] = res[0].payload
|
||||||
|
return res[0].payload
|
||||||
|
return None
|
||||||
|
|
||||||
|
def _resolve_note_from_ref(self, ref_str):
|
||||||
|
"""Löst eine ID (Chunk, Note oder Titel) zu einer Note Payload auf."""
|
||||||
|
if not ref_str: return None
|
||||||
|
|
||||||
|
# Fall A: Chunk ID (enthält #)
|
||||||
|
if "#" in ref_str:
|
||||||
|
try:
|
||||||
|
# Versuch 1: Chunk ID direkt
|
||||||
|
res = self.client.retrieve(self.chunks_col, ids=[ref_str], with_payload=True)
|
||||||
|
if res: return self._fetch_note_cached(res[0].payload.get("note_id"))
|
||||||
|
except: pass
|
||||||
|
|
||||||
|
# Versuch 2: NoteID#Section (Hash abtrennen)
|
||||||
|
possible_note_id = ref_str.split("#")[0]
|
||||||
|
if self._fetch_note_cached(possible_note_id): return self._fetch_note_cached(possible_note_id)
|
||||||
|
|
||||||
|
# Fall B: Note ID direkt
|
||||||
|
if self._fetch_note_cached(ref_str): return self._fetch_note_cached(ref_str)
|
||||||
|
|
||||||
|
# Fall C: Titel
|
||||||
|
res, _ = self.client.scroll(
|
||||||
|
collection_name=self.notes_col,
|
||||||
|
scroll_filter=models.Filter(must=[models.FieldCondition(key="title", match=models.MatchValue(value=ref_str))]),
|
||||||
|
limit=1, with_payload=True
|
||||||
|
)
|
||||||
|
if res:
|
||||||
|
self._note_cache[res[0].payload['note_id']] = res[0].payload
|
||||||
|
return res[0].payload
|
||||||
|
return None
|
||||||
|
|
||||||
|
def _add_node_to_dict(self, node_dict, note_payload, level=1):
|
||||||
|
nid = note_payload.get("note_id")
|
||||||
|
if nid in node_dict: return
|
||||||
|
|
||||||
|
ntype = note_payload.get("type", "default")
|
||||||
|
color = GRAPH_COLORS.get(ntype, GRAPH_COLORS["default"])
|
||||||
|
|
||||||
|
# Basis-Tooltip (wird später erweitert)
|
||||||
|
tooltip = f"Titel: {note_payload.get('title')}\nTyp: {ntype}"
|
||||||
|
|
||||||
|
if level == 0: size = 45
|
||||||
|
elif level == 1: size = 25
|
||||||
|
else: size = 15
|
||||||
|
|
||||||
|
node_dict[nid] = Node(
|
||||||
|
id=nid,
|
||||||
|
label=note_payload.get('title', nid),
|
||||||
|
size=size,
|
||||||
|
color=color,
|
||||||
|
shape="dot" if level > 0 else "diamond",
|
||||||
|
title=tooltip,
|
||||||
|
font={'color': 'black', 'face': 'arial', 'size': 14 if level < 2 else 0}
|
||||||
|
)
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
"""
|
||||||
|
FILE: app/frontend/ui_sidebar.py
|
||||||
|
DESCRIPTION: Rendert die Sidebar. Steuert den Modus-Wechsel (Chat/Editor/Graph) und globale Settings (Top-K).
|
||||||
|
VERSION: 2.6.0
|
||||||
|
STATUS: Active
|
||||||
|
DEPENDENCIES: streamlit, ui_utils, ui_config
|
||||||
|
LAST_ANALYSIS: 2025-12-15
|
||||||
|
"""
|
||||||
|
|
||||||
|
import streamlit as st
|
||||||
|
from ui_utils import load_history_from_logs
|
||||||
|
from ui_config import HISTORY_FILE
|
||||||
|
|
||||||
|
def render_sidebar():
|
||||||
|
with st.sidebar:
|
||||||
|
st.title("🧠 mindnet")
|
||||||
|
st.caption("v2.6 | WP-19 Graph View")
|
||||||
|
|
||||||
|
if "sidebar_mode_selection" not in st.session_state:
|
||||||
|
st.session_state["sidebar_mode_selection"] = "💬 Chat"
|
||||||
|
|
||||||
|
mode = st.radio(
|
||||||
|
"Modus",
|
||||||
|
[
|
||||||
|
"💬 Chat",
|
||||||
|
"📝 Manueller Editor",
|
||||||
|
"🕸️ Graph (Agraph)",
|
||||||
|
"🕸️ Graph (Cytoscape)" # <-- Neuer Punkt
|
||||||
|
],
|
||||||
|
key="sidebar_mode_selection"
|
||||||
|
)
|
||||||
|
|
||||||
|
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(HISTORY_FILE, 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
|
||||||
@@ -0,0 +1,146 @@
|
|||||||
|
"""
|
||||||
|
FILE: app/frontend/ui_utils.py
|
||||||
|
DESCRIPTION: String-Utilities. Parser für Markdown/YAML (LLM-Healing) und Helper für History-Loading.
|
||||||
|
VERSION: 2.6.0
|
||||||
|
STATUS: Active
|
||||||
|
DEPENDENCIES: re, yaml, unicodedata, json, datetime
|
||||||
|
LAST_ANALYSIS: 2025-12-15
|
||||||
|
"""
|
||||||
|
|
||||||
|
import re
|
||||||
|
import yaml
|
||||||
|
import unicodedata
|
||||||
|
import json
|
||||||
|
from datetime import datetime
|
||||||
|
|
||||||
|
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):
|
||||||
|
clean_text = full_text.strip()
|
||||||
|
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 = ""
|
||||||
|
|
||||||
|
parts = re.split(r"^---+\s*$", clean_text, maxsplit=2, flags=re.MULTILINE)
|
||||||
|
|
||||||
|
if len(parts) >= 3:
|
||||||
|
yaml_str = parts[1]
|
||||||
|
body = parts[2]
|
||||||
|
elif clean_text.startswith("---"):
|
||||||
|
fallback_match = re.search(r"^---\s*(.*?)(?=\n#)", clean_text, re.DOTALL | re.MULTILINE)
|
||||||
|
if fallback_match:
|
||||||
|
yaml_str = fallback_match.group(1)
|
||||||
|
body = clean_text.replace(f"---{yaml_str}", "", 1).strip()
|
||||||
|
|
||||||
|
if yaml_str:
|
||||||
|
yaml_str_clean = yaml_str.replace("#", "")
|
||||||
|
try:
|
||||||
|
parsed = yaml.safe_load(yaml_str_clean)
|
||||||
|
if isinstance(parsed, dict):
|
||||||
|
meta = parsed
|
||||||
|
except Exception as e:
|
||||||
|
print(f"YAML Parsing Warning: {e}")
|
||||||
|
|
||||||
|
if not meta.get("title"):
|
||||||
|
h1_match = re.search(r"^#\s+(.*)$", body, re.MULTILINE)
|
||||||
|
if h1_match:
|
||||||
|
meta["title"] = h1_match.group(1).strip()
|
||||||
|
|
||||||
|
if meta.get("type") == "draft":
|
||||||
|
meta["status"] = "draft"
|
||||||
|
meta["type"] = "experience"
|
||||||
|
|
||||||
|
return normalize_meta_and_body(meta, body)
|
||||||
|
|
||||||
|
def build_markdown_doc(meta, body):
|
||||||
|
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(filepath, limit=10):
|
||||||
|
queries = []
|
||||||
|
if filepath.exists():
|
||||||
|
try:
|
||||||
|
with open(filepath, "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
|
||||||
@@ -1,172 +0,0 @@
|
|||||||
#!/usr/bin/env python3
|
|
||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""
|
|
||||||
Modul: app/graph/service.py
|
|
||||||
Version: 0.1.0
|
|
||||||
Datum: 2025-09-10
|
|
||||||
|
|
||||||
Zweck
|
|
||||||
-----
|
|
||||||
Leichtgewichtiger Graph-Layer über Qdrant:
|
|
||||||
- get_note(note_id)
|
|
||||||
- get_chunks(note_id)
|
|
||||||
- neighbors(source_id, kinds=[...], scope=['note','chunk'], depth=1)
|
|
||||||
- walk_bfs(source_id, kinds, max_depth)
|
|
||||||
- context_for_note(note_id, max_neighbors): heuristische Kontextsammlung
|
|
||||||
|
|
||||||
Hinweise
|
|
||||||
--------
|
|
||||||
- Nutzt die bestehenden Collections <prefix>_notes/_chunks/_edges.
|
|
||||||
- Edges werden über Payload-Felder (`kind`, `source_id`, `target_id`) abgefragt.
|
|
||||||
"""
|
|
||||||
from __future__ import annotations
|
|
||||||
from typing import List, Dict, Any, Optional, Iterable, Set, Tuple
|
|
||||||
from qdrant_client.http import models as rest
|
|
||||||
from app.core.qdrant import QdrantConfig, get_client
|
|
||||||
|
|
||||||
def _cols(prefix: str):
|
|
||||||
return f"{prefix}_notes", f"{prefix}_chunks", f"{prefix}_edges"
|
|
||||||
|
|
||||||
class GraphService:
|
|
||||||
def __init__(self, cfg: Optional[QdrantConfig] = None, prefix: Optional[str] = None):
|
|
||||||
self.cfg = cfg or QdrantConfig.from_env()
|
|
||||||
if prefix:
|
|
||||||
self.cfg.prefix = prefix
|
|
||||||
self.client = get_client(self.cfg)
|
|
||||||
self.notes_col, self.chunks_col, self.edges_col = _cols(self.cfg.prefix)
|
|
||||||
|
|
||||||
# ------------------------ fetch helpers ------------------------
|
|
||||||
def _scroll(self, col: str, flt: Optional[rest.Filter] = None, limit: int = 256):
|
|
||||||
out = []
|
|
||||||
nextp = None
|
|
||||||
while True:
|
|
||||||
pts, nextp = self.client.scroll(
|
|
||||||
collection_name=col,
|
|
||||||
with_payload=True,
|
|
||||||
with_vectors=False,
|
|
||||||
limit=limit,
|
|
||||||
offset=nextp,
|
|
||||||
scroll_filter=flt,
|
|
||||||
)
|
|
||||||
if not pts:
|
|
||||||
break
|
|
||||||
out.extend(pts)
|
|
||||||
if nextp is None:
|
|
||||||
break
|
|
||||||
return out
|
|
||||||
|
|
||||||
# ------------------------ public API ---------------------------
|
|
||||||
def get_note(self, note_id: str) -> Optional[Dict[str, Any]]:
|
|
||||||
f = rest.Filter(must=[rest.FieldCondition(key="note_id", match=rest.MatchValue(value=note_id))])
|
|
||||||
pts, _ = self.client.scroll(self.notes_col, with_payload=True, with_vectors=False, limit=1, scroll_filter=f)
|
|
||||||
return (pts[0].payload or None) if pts else None
|
|
||||||
|
|
||||||
def get_chunks(self, note_id: str) -> List[Dict[str, Any]]:
|
|
||||||
f = rest.Filter(must=[rest.FieldCondition(key="note_id", match=rest.MatchValue(value=note_id))])
|
|
||||||
pts = self._scroll(self.chunks_col, f)
|
|
||||||
# Sortierung analog Export
|
|
||||||
def key(pl):
|
|
||||||
p = pl.payload or {}
|
|
||||||
s = p.get("seq") or 0
|
|
||||||
ci = p.get("chunk_index") or 0
|
|
||||||
n = 0
|
|
||||||
cid = p.get("chunk_id") or ""
|
|
||||||
if isinstance(cid, str) and "#" in cid:
|
|
||||||
try:
|
|
||||||
n = int(cid.rsplit("#", 1)[-1])
|
|
||||||
except Exception:
|
|
||||||
n = 0
|
|
||||||
return (int(s), int(ci), n)
|
|
||||||
pts_sorted = sorted(pts, key=key)
|
|
||||||
return [p.payload or {} for p in pts_sorted]
|
|
||||||
|
|
||||||
def neighbors(self, source_id: str, kinds: Optional[Iterable[str]] = None,
|
|
||||||
scope: Optional[Iterable[str]] = None, depth: int = 1) -> Dict[str, List[Dict[str, Any]]]:
|
|
||||||
"""
|
|
||||||
Liefert eingehende & ausgehende Nachbarn (nur nach kind gefiltert).
|
|
||||||
depth==1: direkte Kanten.
|
|
||||||
"""
|
|
||||||
kinds = list(kinds) if kinds else None
|
|
||||||
must = [rest.FieldCondition(key="source_id", match=rest.MatchValue(value=source_id))]
|
|
||||||
if kinds:
|
|
||||||
must.append(rest.FieldCondition(key="kind", match=rest.MatchAny(any=kinds)))
|
|
||||||
f = rest.Filter(must=must)
|
|
||||||
edges = self._scroll(self.edges_col, f)
|
|
||||||
out = {"out": [], "in": []}
|
|
||||||
for e in edges:
|
|
||||||
out["out"].append(e.payload or {})
|
|
||||||
# Inverse Richtung (eingehend)
|
|
||||||
must_in = [rest.FieldCondition(key="target_id", match=rest.MatchValue(value=source_id))]
|
|
||||||
if kinds:
|
|
||||||
must_in.append(rest.FieldCondition(key="kind", match=rest.MatchAny(any=kinds)))
|
|
||||||
f_in = rest.Filter(must=must_in)
|
|
||||||
edges_in = self._scroll(self.edges_col, f_in)
|
|
||||||
for e in edges_in:
|
|
||||||
out["in"].append(e.payload or {})
|
|
||||||
return out
|
|
||||||
|
|
||||||
def walk_bfs(self, source_id: str, kinds: Iterable[str], max_depth: int = 2) -> Set[str]:
|
|
||||||
visited: Set[str] = {source_id}
|
|
||||||
frontier: Set[str] = {source_id}
|
|
||||||
kinds = list(kinds)
|
|
||||||
for _ in range(max_depth):
|
|
||||||
nxt: Set[str] = set()
|
|
||||||
for s in frontier:
|
|
||||||
neigh = self.neighbors(s, kinds=kinds)
|
|
||||||
for e in neigh["out"]:
|
|
||||||
t = e.get("target_id")
|
|
||||||
if isinstance(t, str) and t not in visited:
|
|
||||||
visited.add(t)
|
|
||||||
nxt.add(t)
|
|
||||||
frontier = nxt
|
|
||||||
if not frontier:
|
|
||||||
break
|
|
||||||
return visited
|
|
||||||
|
|
||||||
def context_for_note(self, note_id: str, kinds: Iterable[str] = ("references","backlink"), max_neighbors: int = 12) -> Dict[str, Any]:
|
|
||||||
"""
|
|
||||||
Heuristischer Kontext: eigene Chunks + Nachbarn nach Kantenarten, dedupliziert.
|
|
||||||
"""
|
|
||||||
note = self.get_note(note_id) or {}
|
|
||||||
chunks = self.get_chunks(note_id)
|
|
||||||
neigh = self.neighbors(note_id, kinds=list(kinds))
|
|
||||||
targets = []
|
|
||||||
for e in neigh["out"]:
|
|
||||||
t = e.get("target_id")
|
|
||||||
if isinstance(t, str):
|
|
||||||
targets.append(t)
|
|
||||||
for e in neigh["in"]:
|
|
||||||
s = e.get("source_id")
|
|
||||||
if isinstance(s, str):
|
|
||||||
targets.append(s)
|
|
||||||
# de-dupe
|
|
||||||
seen = set()
|
|
||||||
uniq = []
|
|
||||||
for t in targets:
|
|
||||||
if t not in seen:
|
|
||||||
seen.add(t)
|
|
||||||
uniq.append(t)
|
|
||||||
uniq = uniq[:max_neighbors]
|
|
||||||
neighbor_notes = [self.get_note(t) for t in uniq]
|
|
||||||
return {
|
|
||||||
"note": note,
|
|
||||||
"chunks": chunks,
|
|
||||||
"neighbors": [n for n in neighbor_notes if n],
|
|
||||||
"edges_out": neigh["out"],
|
|
||||||
"edges_in": neigh["in"],
|
|
||||||
}
|
|
||||||
|
|
||||||
# Optional: Mini-CLI
|
|
||||||
if __name__ == "__main__": # pragma: no cover
|
|
||||||
import argparse, json
|
|
||||||
ap = argparse.ArgumentParser()
|
|
||||||
ap.add_argument("--prefix", help="Collection-Prefix (überschreibt ENV)")
|
|
||||||
ap.add_argument("--note-id", required=True)
|
|
||||||
ap.add_argument("--neighbors", action="store_true", help="Nur Nachbarn anzeigen")
|
|
||||||
args = ap.parse_args()
|
|
||||||
svc = GraphService(prefix=args.prefix)
|
|
||||||
if args.neighbors:
|
|
||||||
out = svc.neighbors(args.note_id, kinds=["references","backlink","prev","next","belongs_to"])
|
|
||||||
else:
|
|
||||||
out = svc.context_for_note(args.note_id)
|
|
||||||
print(json.dumps(out, ensure_ascii=False, indent=2))
|
|
||||||
+11
-5
@@ -1,11 +1,17 @@
|
|||||||
"""
|
"""
|
||||||
app/main.py — mindnet API bootstrap
|
FILE: app/main.py
|
||||||
|
DESCRIPTION: Bootstrap der FastAPI Anwendung. Inkludiert Router und Middleware.
|
||||||
|
VERSION: 0.6.0
|
||||||
|
STATUS: Active
|
||||||
|
DEPENDENCIES: app.config, app.routers.* (embed, qdrant, query, graph, tools, feedback, chat, ingest, admin)
|
||||||
|
LAST_ANALYSIS: 2025-12-15
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
from fastapi import FastAPI
|
from fastapi import FastAPI
|
||||||
from .config import get_settings
|
from .config import get_settings
|
||||||
from .routers.embed_router import router as embed_router
|
#from .routers.embed_router import router as embed_router
|
||||||
from .routers.qdrant_router import router as qdrant_router
|
#from .routers.qdrant_router import router as qdrant_router
|
||||||
|
|
||||||
from .routers.query import router as query_router
|
from .routers.query import router as query_router
|
||||||
from .routers.graph import router as graph_router
|
from .routers.graph import router as graph_router
|
||||||
@@ -29,8 +35,8 @@ def create_app() -> FastAPI:
|
|||||||
def healthz():
|
def healthz():
|
||||||
return {"status": "ok", "qdrant": s.QDRANT_URL, "prefix": s.COLLECTION_PREFIX}
|
return {"status": "ok", "qdrant": s.QDRANT_URL, "prefix": s.COLLECTION_PREFIX}
|
||||||
|
|
||||||
app.include_router(embed_router)
|
# app.include_router(embed_router)
|
||||||
app.include_router(qdrant_router)
|
# app.include_router(qdrant_router)
|
||||||
|
|
||||||
app.include_router(query_router, prefix="/query", tags=["query"])
|
app.include_router(query_router, prefix="/query", tags=["query"])
|
||||||
app.include_router(graph_router, prefix="/graph", tags=["graph"])
|
app.include_router(graph_router, prefix="/graph", tags=["graph"])
|
||||||
|
|||||||
+30
-28
@@ -1,14 +1,10 @@
|
|||||||
"""
|
"""
|
||||||
app/models/dto.py — Pydantic-Modelle (DTOs) für WP-04/WP-05/WP-06
|
FILE: app/models/dto.py
|
||||||
|
DESCRIPTION: Pydantic-Modelle (DTOs) für Request/Response Bodies. Definiert das API-Schema.
|
||||||
Zweck:
|
VERSION: 0.6.6 (WP-22 Debug & Stability Update)
|
||||||
Laufzeit-Modelle für FastAPI (Requests/Responses).
|
STATUS: Active
|
||||||
WP-06 Update: Intent & Intent-Source in ChatResponse.
|
DEPENDENCIES: pydantic, typing, uuid
|
||||||
|
LAST_ANALYSIS: 2025-12-18
|
||||||
Version:
|
|
||||||
0.6.2 (WP-06: Decision Engine Transparency, Erweiterung des Feeback Request)
|
|
||||||
Stand:
|
|
||||||
2025-12-09
|
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
@@ -16,7 +12,8 @@ from pydantic import BaseModel, Field
|
|||||||
from typing import List, Literal, Optional, Dict, Any
|
from typing import List, Literal, Optional, Dict, Any
|
||||||
import uuid
|
import uuid
|
||||||
|
|
||||||
EdgeKind = Literal["references", "references_at", "backlink", "next", "prev", "belongs_to", "depends_on", "related_to", "similar_to"]
|
# Gültige Kanten-Typen gemäß Manual
|
||||||
|
EdgeKind = Literal["references", "references_at", "backlink", "next", "prev", "belongs_to", "depends_on", "related_to", "similar_to", "caused_by", "derived_from", "based_on", "solves", "blocks", "uses", "guides"]
|
||||||
|
|
||||||
|
|
||||||
# --- Basis-DTOs ---
|
# --- Basis-DTOs ---
|
||||||
@@ -44,6 +41,8 @@ class EdgeDTO(BaseModel):
|
|||||||
target: str
|
target: str
|
||||||
weight: float
|
weight: float
|
||||||
direction: Literal["out", "in", "undirected"] = "out"
|
direction: Literal["out", "in", "undirected"] = "out"
|
||||||
|
provenance: Optional[Literal["explicit", "rule", "smart", "structure"]] = "explicit"
|
||||||
|
confidence: float = 1.0
|
||||||
|
|
||||||
|
|
||||||
# --- Request Models ---
|
# --- Request Models ---
|
||||||
@@ -61,17 +60,17 @@ class QueryRequest(BaseModel):
|
|||||||
ret: Dict = {"with_paths": True, "with_notes": True, "with_chunks": True}
|
ret: Dict = {"with_paths": True, "with_notes": True, "with_chunks": True}
|
||||||
explain: bool = False
|
explain: bool = False
|
||||||
|
|
||||||
|
# WP-22: Semantic Graph Routing
|
||||||
|
boost_edges: Optional[Dict[str, float]] = None
|
||||||
|
|
||||||
|
|
||||||
class FeedbackRequest(BaseModel):
|
class FeedbackRequest(BaseModel):
|
||||||
"""
|
"""
|
||||||
User-Feedback zu einem spezifischen Treffer oder der Gesamtantwort.
|
User-Feedback zu einem spezifischen Treffer oder der Gesamtantwort (WP-08 Basis).
|
||||||
"""
|
"""
|
||||||
query_id: str = Field(..., description="ID der ursprünglichen Suche")
|
query_id: str = Field(..., description="ID der ursprünglichen Suche")
|
||||||
# node_id ist optional: Wenn leer oder "generated_answer", gilt es für die Antwort.
|
|
||||||
# Wenn eine echte Chunk-ID, gilt es für die Quelle.
|
|
||||||
node_id: str = Field(..., description="ID des bewerteten Treffers oder 'generated_answer'")
|
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) bis 5 (Perfekt)")
|
||||||
score: int = Field(..., ge=1, le=5, description="1 (Irrelevant/Falsch) bis 5 (Perfekt)")
|
|
||||||
comment: Optional[str] = None
|
comment: Optional[str] = None
|
||||||
|
|
||||||
|
|
||||||
@@ -80,8 +79,7 @@ class ChatRequest(BaseModel):
|
|||||||
WP-05: Request für /chat.
|
WP-05: Request für /chat.
|
||||||
"""
|
"""
|
||||||
message: str = Field(..., description="Die Nachricht des Users")
|
message: str = Field(..., description="Die Nachricht des Users")
|
||||||
conversation_id: Optional[str] = Field(None, description="Optional: ID für Chat-Verlauf (noch nicht implementiert)")
|
conversation_id: Optional[str] = Field(None, description="ID für Chat-Verlauf")
|
||||||
# RAG Parameter (Override defaults)
|
|
||||||
top_k: int = 5
|
top_k: int = 5
|
||||||
explain: bool = False
|
explain: bool = False
|
||||||
|
|
||||||
@@ -89,7 +87,7 @@ class ChatRequest(BaseModel):
|
|||||||
# --- WP-04b Explanation Models ---
|
# --- WP-04b Explanation Models ---
|
||||||
|
|
||||||
class ScoreBreakdown(BaseModel):
|
class ScoreBreakdown(BaseModel):
|
||||||
"""Aufschlüsselung der Score-Komponenten."""
|
"""Aufschlüsselung der Score-Komponenten nach der WP-22 Formel."""
|
||||||
semantic_contribution: float
|
semantic_contribution: float
|
||||||
edge_contribution: float
|
edge_contribution: float
|
||||||
centrality_contribution: float
|
centrality_contribution: float
|
||||||
@@ -97,11 +95,14 @@ class ScoreBreakdown(BaseModel):
|
|||||||
raw_edge_bonus: float
|
raw_edge_bonus: float
|
||||||
raw_centrality: float
|
raw_centrality: float
|
||||||
node_weight: float
|
node_weight: float
|
||||||
|
# WP-22 Debug Fields für Messbarkeit
|
||||||
|
status_multiplier: float = 1.0
|
||||||
|
graph_boost_factor: float = 1.0
|
||||||
|
|
||||||
|
|
||||||
class Reason(BaseModel):
|
class Reason(BaseModel):
|
||||||
"""Ein semantischer Grund für das Ranking."""
|
"""Ein semantischer Grund für das Ranking."""
|
||||||
kind: Literal["semantic", "edge", "type", "centrality"]
|
kind: Literal["semantic", "edge", "type", "centrality", "lifecycle"]
|
||||||
message: str
|
message: str
|
||||||
score_impact: Optional[float] = None
|
score_impact: Optional[float] = None
|
||||||
details: Optional[Dict[str, Any]] = None
|
details: Optional[Dict[str, Any]] = None
|
||||||
@@ -112,6 +113,9 @@ class Explanation(BaseModel):
|
|||||||
breakdown: ScoreBreakdown
|
breakdown: ScoreBreakdown
|
||||||
reasons: List[Reason]
|
reasons: List[Reason]
|
||||||
related_edges: Optional[List[EdgeDTO]] = None
|
related_edges: Optional[List[EdgeDTO]] = None
|
||||||
|
# WP-22 Debug: Verifizierung des Routings
|
||||||
|
applied_intent: Optional[str] = None
|
||||||
|
applied_boosts: Optional[Dict[str, float]] = None
|
||||||
|
|
||||||
|
|
||||||
# --- Response Models ---
|
# --- Response Models ---
|
||||||
@@ -119,14 +123,14 @@ class Explanation(BaseModel):
|
|||||||
class QueryHit(BaseModel):
|
class QueryHit(BaseModel):
|
||||||
"""Einzelnes Trefferobjekt für /query."""
|
"""Einzelnes Trefferobjekt für /query."""
|
||||||
node_id: str
|
node_id: str
|
||||||
note_id: Optional[str]
|
note_id: str
|
||||||
semantic_score: float
|
semantic_score: float
|
||||||
edge_bonus: float
|
edge_bonus: float
|
||||||
centrality_bonus: float
|
centrality_bonus: float
|
||||||
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
|
payload: Optional[Dict] = None
|
||||||
explanation: Optional[Explanation] = None
|
explanation: Optional[Explanation] = None
|
||||||
|
|
||||||
|
|
||||||
@@ -150,11 +154,9 @@ class ChatResponse(BaseModel):
|
|||||||
"""
|
"""
|
||||||
WP-05/06: Antwortstruktur für /chat.
|
WP-05/06: Antwortstruktur für /chat.
|
||||||
"""
|
"""
|
||||||
query_id: str = Field(..., description="Traceability ID (dieselbe wie für Search)")
|
query_id: str = Field(..., description="Traceability ID")
|
||||||
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 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")
|
||||||
intent_source: Optional[str] = Field("Unknown", description="WP-06: Quelle der Intent-Erkennung (Keyword vs. LLM)")
|
intent_source: Optional[str] = Field("Unknown", description="Quelle der Intent-Erkennung")
|
||||||
|
|
||||||
|
|
||||||
+6
-16
@@ -1,20 +1,10 @@
|
|||||||
"""
|
"""
|
||||||
app/routers/admin.py — Admin-/Monitoring-Endpunkte (optional)
|
FILE: app/routers/admin.py
|
||||||
|
DESCRIPTION: Monitoring-Endpunkt. Zeigt Qdrant-Collection-Counts und geladene Config.
|
||||||
Zweck:
|
VERSION: 0.1.0
|
||||||
Liefert einfache Kennzahlen zu Collections (Counts) und Config.
|
STATUS: Active (Optional)
|
||||||
Kompatibilität:
|
DEPENDENCIES: qdrant_client, app.config
|
||||||
Python 3.12+, FastAPI 0.110+, qdrant-client 1.x
|
LAST_ANALYSIS: 2025-12-15
|
||||||
Version:
|
|
||||||
0.1.0 (Erstanlage)
|
|
||||||
Stand:
|
|
||||||
2025-10-07
|
|
||||||
Bezug:
|
|
||||||
- Qdrant Collections: *_notes, *_chunks, *_edges
|
|
||||||
Nutzung:
|
|
||||||
app.include_router(admin.router, prefix="/admin", tags=["admin"])
|
|
||||||
Änderungsverlauf:
|
|
||||||
0.1.0 (2025-10-07) – Erstanlage.
|
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|||||||
+128
-111
@@ -1,21 +1,20 @@
|
|||||||
"""
|
"""
|
||||||
app/routers/chat.py — RAG Endpunkt (WP-06 Hybrid Router + WP-07 Interview Mode)
|
FILE: app/routers/chat.py
|
||||||
Version: 2.4.0 (Interview Support)
|
DESCRIPTION: Haupt-Chat-Interface (RAG & Interview). Enthält Intent-Router (Keywords/LLM) und Prompt-Construction.
|
||||||
|
VERSION: 2.7.1 (WP-22 Semantic Graph Routing)
|
||||||
Features:
|
STATUS: Active
|
||||||
- Hybrid Intent Router (Keyword + LLM)
|
FIX: Umstellung auf llm.get_prompt() zur Behebung des 500 Server Errors (Dictionary replace crash).
|
||||||
- Strategic Retrieval (Late Binding via Config)
|
DEPENDENCIES: app.config, app.models.dto, app.services.llm_service, app.core.retriever, app.services.feedback_service
|
||||||
- Interview Loop (Schema-driven Data Collection)
|
EXTERNAL_CONFIG: config/decision_engine.yaml, config/types.yaml
|
||||||
- Context Enrichment (Payload/Source Fallback)
|
|
||||||
- Data Flywheel (Feedback Logging Integration)
|
|
||||||
"""
|
"""
|
||||||
|
|
||||||
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
|
||||||
@@ -30,6 +29,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()
|
||||||
@@ -51,12 +51,27 @@ 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", {})
|
||||||
@@ -67,39 +82,39 @@ def get_decision_strategy(intent: str) -> Dict[str, Any]:
|
|||||||
def _detect_target_type(message: str, configured_schemas: Dict[str, Any]) -> str:
|
def _detect_target_type(message: str, configured_schemas: Dict[str, Any]) -> str:
|
||||||
"""
|
"""
|
||||||
Versucht zu erraten, welchen Notiz-Typ der User erstellen will.
|
Versucht zu erraten, welchen Notiz-Typ der User erstellen will.
|
||||||
Nutzt Keywords und Mappings.
|
Nutzt Keywords aus types.yaml UND Mappings.
|
||||||
"""
|
"""
|
||||||
message_lower = message.lower()
|
message_lower = message.lower()
|
||||||
|
|
||||||
# 1. Direkter Match mit Schema-Keys (z.B. "projekt", "entscheidung")
|
# 1. Check types.yaml detection_keywords (Priority!)
|
||||||
# Ignoriere 'default' hier
|
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():
|
for type_key in configured_schemas.keys():
|
||||||
if type_key == "default":
|
if type_key == "default": continue
|
||||||
continue
|
|
||||||
if type_key in message_lower:
|
if type_key in message_lower:
|
||||||
return type_key
|
return type_key
|
||||||
|
|
||||||
# 2. Synonym-Mapping (Deutsch -> Schema Key)
|
# 3. Synonym-Mapping (Legacy Fallback)
|
||||||
# Dies verbessert die UX, falls User deutsche Begriffe nutzen
|
|
||||||
synonyms = {
|
synonyms = {
|
||||||
"projekt": "project",
|
"projekt": "project", "vorhaben": "project",
|
||||||
"vorhaben": "project",
|
"entscheidung": "decision", "beschluss": "decision",
|
||||||
"entscheidung": "decision",
|
|
||||||
"beschluss": "decision",
|
|
||||||
"ziel": "goal",
|
"ziel": "goal",
|
||||||
"erfahrung": "experience",
|
"erfahrung": "experience", "lektion": "experience",
|
||||||
"lektion": "experience",
|
|
||||||
"wert": "value",
|
"wert": "value",
|
||||||
"prinzip": "principle",
|
"prinzip": "principle",
|
||||||
"grundsatz": "principle",
|
"notiz": "default", "idee": "default"
|
||||||
"notiz": "default",
|
|
||||||
"idee": "default"
|
|
||||||
}
|
}
|
||||||
|
|
||||||
for term, schema_key in synonyms.items():
|
for term, schema_key in synonyms.items():
|
||||||
if term in message_lower:
|
if term in message_lower:
|
||||||
# Prüfen, ob der gemappte Key auch konfiguriert ist
|
|
||||||
if schema_key in configured_schemas:
|
|
||||||
return schema_key
|
return schema_key
|
||||||
|
|
||||||
return "default"
|
return "default"
|
||||||
@@ -126,7 +141,6 @@ def _build_enriched_context(hits: List[QueryHit]) -> str:
|
|||||||
)
|
)
|
||||||
title = hit.note_id or "Unbekannt"
|
title = hit.note_id or "Unbekannt"
|
||||||
|
|
||||||
# [FIX] Robustes Auslesen des Typs (Payload > Source > Unknown)
|
|
||||||
payload = hit.payload or {}
|
payload = hit.payload or {}
|
||||||
note_type = payload.get("type") or source.get("type", "unknown")
|
note_type = payload.get("type") or source.get("type", "unknown")
|
||||||
note_type = str(note_type).upper()
|
note_type = str(note_type).upper()
|
||||||
@@ -140,54 +154,72 @@ def _build_enriched_context(hits: List[QueryHit]) -> str:
|
|||||||
|
|
||||||
return "\n\n".join(context_parts)
|
return "\n\n".join(context_parts)
|
||||||
|
|
||||||
|
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]:
|
async def _classify_intent(query: str, llm: LLMService) -> tuple[str, str]:
|
||||||
"""
|
"""
|
||||||
Hybrid Router v3:
|
Hybrid Router v5:
|
||||||
Gibt Tuple zurück: (Intent, Source)
|
1. Decision Keywords (Strategie) -> Prio 1
|
||||||
|
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
|
||||||
return best_intent, "Keyword (Fast Path)"
|
if not _is_question(query_lower):
|
||||||
|
types_cfg = get_types_config()
|
||||||
|
types_def = types_cfg.get("types", {})
|
||||||
|
|
||||||
# 2. SLOW PATH: LLM Router
|
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})"
|
||||||
|
|
||||||
|
# 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", "")
|
# FIX: Nutze get_prompt statt direktem Zugriff auf dict
|
||||||
|
router_prompt_template = llm.get_prompt("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...")
|
||||||
|
|
||||||
raw_response = await llm.generate_raw_response(prompt)
|
try:
|
||||||
|
raw_response = await llm.generate_raw_response(prompt, priority="realtime")
|
||||||
# Parsing logic
|
|
||||||
llm_output_upper = raw_response.upper()
|
llm_output_upper = raw_response.upper()
|
||||||
found_intents = []
|
|
||||||
|
if "INTERVIEW" in llm_output_upper or "CREATE" in llm_output_upper:
|
||||||
|
return "INTERVIEW", "LLM Router"
|
||||||
|
|
||||||
for strat_key in strategies.keys():
|
for strat_key in strategies.keys():
|
||||||
if strat_key in llm_output_upper:
|
if strat_key in llm_output_upper:
|
||||||
found_intents.append(strat_key)
|
return strat_key, "LLM Router"
|
||||||
|
|
||||||
if len(found_intents) == 1:
|
except Exception as e:
|
||||||
return found_intents[0], "LLM Router (Slow Path)"
|
logger.error(f"Router LLM failed: {e}")
|
||||||
elif len(found_intents) > 1:
|
|
||||||
return found_intents[0], f"LLM Ambiguous {found_intents}"
|
|
||||||
else:
|
|
||||||
return "FACT", "LLM Fallback (No Match)"
|
|
||||||
|
|
||||||
return "FACT", "Default (No Match)"
|
return "FACT", "Default (No Match)"
|
||||||
|
|
||||||
@@ -202,7 +234,7 @@ async def chat_endpoint(
|
|||||||
logger.info(f"Chat request [{query_id}]: {request.message[:50]}...")
|
logger.info(f"Chat request [{query_id}]: {request.message[:50]}...")
|
||||||
|
|
||||||
try:
|
try:
|
||||||
# 1. Intent Detection (mit Source)
|
# 1. Intent Detection
|
||||||
intent, intent_source = await _classify_intent(request.message, llm)
|
intent, intent_source = await _classify_intent(request.message, llm)
|
||||||
logger.info(f"[{query_id}] Final Intent: {intent} via {intent_source}")
|
logger.info(f"[{query_id}] Final Intent: {intent} via {intent_source}")
|
||||||
|
|
||||||
@@ -210,91 +242,82 @@ async def chat_endpoint(
|
|||||||
strategy = get_decision_strategy(intent)
|
strategy = get_decision_strategy(intent)
|
||||||
prompt_key = strategy.get("prompt_template", "rag_template")
|
prompt_key = strategy.get("prompt_template", "rag_template")
|
||||||
|
|
||||||
# --- SPLIT LOGIC: INTERVIEW vs. RAG ---
|
|
||||||
|
|
||||||
sources_hits = []
|
sources_hits = []
|
||||||
final_prompt = ""
|
final_prompt = ""
|
||||||
|
|
||||||
if intent == "INTERVIEW":
|
if intent == "INTERVIEW":
|
||||||
# --- WP-07: INTERVIEW MODE ---
|
# --- INTERVIEW MODE ---
|
||||||
# Kein Retrieval. Wir nutzen den Dialog-Kontext.
|
target_type = _detect_target_type(request.message, strategy.get("schemas", {}))
|
||||||
|
|
||||||
# 1. Schema Loading (Late Binding)
|
types_cfg = get_types_config()
|
||||||
schemas = strategy.get("schemas", {})
|
type_def = types_cfg.get("types", {}).get(target_type, {})
|
||||||
target_type = _detect_target_type(request.message, schemas)
|
fields_list = type_def.get("schema", [])
|
||||||
active_schema = schemas.get(target_type, schemas.get("default"))
|
|
||||||
|
|
||||||
logger.info(f"[{query_id}] Starting Interview for Type: {target_type}")
|
if not fields_list:
|
||||||
|
configured_schemas = strategy.get("schemas", {})
|
||||||
# Robustes Schema-Parsing (Dict vs List)
|
fallback_schema = configured_schemas.get(target_type, configured_schemas.get("default"))
|
||||||
if isinstance(active_schema, dict):
|
if isinstance(fallback_schema, dict):
|
||||||
fields_list = active_schema.get("fields", [])
|
fields_list = fallback_schema.get("fields", [])
|
||||||
hint_str = active_schema.get("hint", "")
|
|
||||||
else:
|
else:
|
||||||
fields_list = active_schema # Fallback falls nur Liste definiert
|
fields_list = fallback_schema or []
|
||||||
hint_str = ""
|
|
||||||
|
|
||||||
|
logger.info(f"[{query_id}] Interview Type: {target_type}. Fields: {len(fields_list)}")
|
||||||
fields_str = "\n- " + "\n- ".join(fields_list)
|
fields_str = "\n- " + "\n- ".join(fields_list)
|
||||||
|
|
||||||
# 2. Context Logic
|
# FIX: Nutze get_prompt() zur Auflösung der provider-spezifischen Templates
|
||||||
# Hinweis: In einer Stateless-API ist {context_str} idealerweise die History.
|
template = llm.get_prompt(prompt_key)
|
||||||
# Da ChatRequest (noch) kein History-Feld hat, nutzen wir einen Placeholder
|
final_prompt = template.replace("{context_str}", "Dialogverlauf...") \
|
||||||
# oder verlassen uns darauf, dass der Client die History im Prompt mitschickt
|
|
||||||
# (Streamlit Pattern: Appends history to prompt).
|
|
||||||
# Wir labeln es hier explizit.
|
|
||||||
context_str = "Bisheriger Verlauf (falls vorhanden): Siehe oben/unten."
|
|
||||||
|
|
||||||
# 3. Prompt Assembly
|
|
||||||
template = llm.prompts.get(prompt_key, "")
|
|
||||||
final_prompt = template.replace("{context_str}", context_str) \
|
|
||||||
.replace("{query}", request.message) \
|
.replace("{query}", request.message) \
|
||||||
.replace("{target_type}", target_type) \
|
.replace("{target_type}", target_type) \
|
||||||
.replace("{schema_fields}", fields_str) \
|
.replace("{schema_fields}", fields_str) \
|
||||||
.replace("{schema_hint}", hint_str)
|
.replace("{schema_hint}", "")
|
||||||
|
|
||||||
# Keine Hits im Interview
|
|
||||||
sources_hits = []
|
sources_hits = []
|
||||||
|
|
||||||
else:
|
else:
|
||||||
# --- WP-06: STANDARD RAG MODE ---
|
# --- RAG MODE ---
|
||||||
inject_types = strategy.get("inject_types", [])
|
inject_types = strategy.get("inject_types", [])
|
||||||
prepend_instr = strategy.get("prepend_instruction", "")
|
prepend_instr = strategy.get("prepend_instruction", "")
|
||||||
|
|
||||||
# 2. Primary Retrieval
|
# --- WP-22: Semantic Graph Routing (Teil C) ---
|
||||||
|
edge_boosts = strategy.get("edge_boosts", {})
|
||||||
|
if edge_boosts:
|
||||||
|
logger.info(f"[{query_id}] Applying Edge Boosts: {edge_boosts}")
|
||||||
|
|
||||||
query_req = QueryRequest(
|
query_req = QueryRequest(
|
||||||
query=request.message,
|
query=request.message,
|
||||||
mode="hybrid",
|
mode="hybrid",
|
||||||
top_k=request.top_k,
|
top_k=request.top_k,
|
||||||
explain=request.explain
|
explain=request.explain,
|
||||||
|
boost_edges=edge_boosts
|
||||||
)
|
)
|
||||||
retrieve_result = await retriever.search(query_req)
|
retrieve_result = await retriever.search(query_req)
|
||||||
hits = retrieve_result.results
|
hits = retrieve_result.results
|
||||||
|
|
||||||
# 3. Strategic Retrieval (WP-06 Kernfeature)
|
|
||||||
if inject_types:
|
if inject_types:
|
||||||
logger.info(f"[{query_id}] Executing Strategic Retrieval for types: {inject_types}...")
|
|
||||||
strategy_req = QueryRequest(
|
strategy_req = QueryRequest(
|
||||||
query=request.message,
|
query=request.message,
|
||||||
mode="hybrid",
|
mode="hybrid",
|
||||||
top_k=3,
|
top_k=3,
|
||||||
filters={"type": inject_types},
|
filters={"type": inject_types},
|
||||||
explain=False
|
explain=False,
|
||||||
|
boost_edges=edge_boosts
|
||||||
)
|
)
|
||||||
strategy_result = await retriever.search(strategy_req)
|
strategy_result = await retriever.search(strategy_req)
|
||||||
|
|
||||||
existing_ids = {h.node_id for h in hits}
|
existing_ids = {h.node_id for h in hits}
|
||||||
for strat_hit in strategy_result.results:
|
for strat_hit in strategy_result.results:
|
||||||
if strat_hit.node_id not in existing_ids:
|
if strat_hit.node_id not in existing_ids:
|
||||||
hits.append(strat_hit)
|
hits.append(strat_hit)
|
||||||
|
|
||||||
# 4. Context Building
|
|
||||||
if not hits:
|
if not hits:
|
||||||
context_str = "Keine relevanten Notizen gefunden."
|
context_str = "Keine relevanten Notizen gefunden."
|
||||||
else:
|
else:
|
||||||
context_str = _build_enriched_context(hits)
|
context_str = _build_enriched_context(hits)
|
||||||
|
|
||||||
# 5. Generation Setup
|
# FIX: Nutze get_prompt() zur Auflösung der provider-spezifischen Templates
|
||||||
template = llm.prompts.get(prompt_key, "{context_str}\n\n{query}")
|
template = llm.get_prompt(prompt_key)
|
||||||
|
|
||||||
|
if not template:
|
||||||
|
template = "{context_str}\n\n{query}"
|
||||||
|
|
||||||
if prepend_instr:
|
if prepend_instr:
|
||||||
context_str = f"{prepend_instr}\n\n{context_str}"
|
context_str = f"{prepend_instr}\n\n{context_str}"
|
||||||
@@ -302,35 +325,29 @@ async def chat_endpoint(
|
|||||||
final_prompt = template.replace("{context_str}", context_str).replace("{query}", request.message)
|
final_prompt = template.replace("{context_str}", context_str).replace("{query}", request.message)
|
||||||
sources_hits = hits
|
sources_hits = hits
|
||||||
|
|
||||||
# --- COMMON GENERATION ---
|
# --- GENERATION ---
|
||||||
|
system_prompt = llm.get_prompt("system_prompt")
|
||||||
|
|
||||||
system_prompt = llm.prompts.get("system_prompt", "")
|
# Chat nutzt IMMER realtime priority
|
||||||
|
answer_text = await llm.generate_raw_response(
|
||||||
logger.info(f"[{query_id}] Sending to LLM (Intent: {intent}, Template: {prompt_key})...")
|
prompt=final_prompt,
|
||||||
|
system=system_prompt,
|
||||||
# System-Prompt separat übergeben
|
priority="realtime"
|
||||||
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)
|
||||||
|
|
||||||
# 6. Logging (Fire & Forget)
|
# Logging
|
||||||
try:
|
try:
|
||||||
log_search(
|
log_search(
|
||||||
query_id=query_id,
|
query_id=query_id,
|
||||||
query_text=request.message,
|
query_text=request.message,
|
||||||
results=sources_hits,
|
results=sources_hits,
|
||||||
mode="interview" if intent == "INTERVIEW" else "chat_rag",
|
mode="interview" if intent == "INTERVIEW" else "chat_rag",
|
||||||
metadata={
|
metadata={"intent": intent, "source": intent_source}
|
||||||
"intent": intent,
|
|
||||||
"intent_source": intent_source,
|
|
||||||
"generated_answer": answer_text,
|
|
||||||
"model": llm.settings.LLM_MODEL
|
|
||||||
}
|
|
||||||
)
|
)
|
||||||
except Exception as e:
|
except: pass
|
||||||
logger.error(f"Logging failed: {e}")
|
|
||||||
|
|
||||||
# 7. Response
|
|
||||||
return ChatResponse(
|
return ChatResponse(
|
||||||
query_id=query_id,
|
query_id=query_id,
|
||||||
answer=answer_text,
|
answer=answer_text,
|
||||||
|
|||||||
@@ -1,5 +1,10 @@
|
|||||||
"""
|
"""
|
||||||
Version 0.1
|
FILE: app/routers/embed_router.py
|
||||||
|
DESCRIPTION: Exponiert die lokale Embedding-Funktion als API-Endpunkt.
|
||||||
|
VERSION: 0.1.0
|
||||||
|
STATUS: Active
|
||||||
|
DEPENDENCIES: app.embeddings, pydantic
|
||||||
|
LAST_ANALYSIS: 2025-12-15
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|||||||
@@ -1,6 +1,10 @@
|
|||||||
"""
|
"""
|
||||||
app/routers/feedback.py
|
FILE: app/routers/feedback.py
|
||||||
Endpunkt für User-Feedback (WP-04c).
|
DESCRIPTION: Endpunkt für explizites User-Feedback (WP-04c).
|
||||||
|
VERSION: 0.1.0
|
||||||
|
STATUS: Active
|
||||||
|
DEPENDENCIES: app.models.dto, app.services.feedback_service
|
||||||
|
LAST_ANALYSIS: 2025-12-15
|
||||||
"""
|
"""
|
||||||
from fastapi import APIRouter, HTTPException
|
from fastapi import APIRouter, HTTPException
|
||||||
from app.models.dto import FeedbackRequest
|
from app.models.dto import FeedbackRequest
|
||||||
|
|||||||
+6
-17
@@ -1,21 +1,10 @@
|
|||||||
"""
|
"""
|
||||||
app/routers/graph.py — Graph-Endpunkte (WP-04)
|
FILE: app/routers/graph.py
|
||||||
|
DESCRIPTION: Liefert Graph-Daten (Knoten/Kanten) für UI-Visualisierungen basierend auf einer Seed-ID. (WP4)
|
||||||
Zweck:
|
VERSION: 0.1.0
|
||||||
Liefert die Nachbarschaft einer Note/ID als JSON-Graph (Nodes/Edges/Stats).
|
STATUS: Active
|
||||||
Kompatibilität:
|
DEPENDENCIES: qdrant_client, app.models.dto, app.core.graph_adapter, app.config
|
||||||
Python 3.12+, FastAPI 0.110+, qdrant-client 1.x
|
LAST_ANALYSIS: 2025-12-15
|
||||||
Version:
|
|
||||||
0.1.0 (Erstanlage)
|
|
||||||
Stand:
|
|
||||||
2025-10-07
|
|
||||||
Bezug:
|
|
||||||
- app/core/graph_adapter.py
|
|
||||||
- app/models/dto.py
|
|
||||||
Nutzung:
|
|
||||||
app.include_router(graph.router, prefix="/graph", tags=["graph"])
|
|
||||||
Änderungsverlauf:
|
|
||||||
0.1.0 (2025-10-07) – Erstanlage.
|
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|||||||
+61
-25
@@ -1,12 +1,18 @@
|
|||||||
"""
|
"""
|
||||||
app/routers/ingest.py
|
FILE: app/routers/ingest.py
|
||||||
API-Endpunkte für WP-11 (Discovery & Persistence).
|
DESCRIPTION: Endpunkte für WP-11. Nimmt Markdown entgegen.
|
||||||
Delegiert an Services.
|
Refactored für WP-14: Nutzt BackgroundTasks für non-blocking Save.
|
||||||
|
Update WP-20: Unterstützung für Hybrid-Cloud-Analyse Feedback.
|
||||||
|
VERSION: 0.8.0 (WP-20 Hybrid Ready)
|
||||||
|
STATUS: Active
|
||||||
|
DEPENDENCIES: app.core.ingestion, app.services.discovery, fastapi, pydantic
|
||||||
"""
|
"""
|
||||||
|
|
||||||
import os
|
import os
|
||||||
import time
|
import time
|
||||||
import logging
|
import logging
|
||||||
from fastapi import APIRouter, HTTPException
|
import asyncio
|
||||||
|
from fastapi import APIRouter, HTTPException, BackgroundTasks
|
||||||
from pydantic import BaseModel
|
from pydantic import BaseModel
|
||||||
from typing import Optional, Dict, Any
|
from typing import Optional, Dict, Any
|
||||||
|
|
||||||
@@ -16,7 +22,7 @@ from app.services.discovery import DiscoveryService
|
|||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
router = APIRouter()
|
router = APIRouter()
|
||||||
|
|
||||||
# Services Init (Global oder via Dependency Injection)
|
# Services Init
|
||||||
discovery_service = DiscoveryService()
|
discovery_service = DiscoveryService()
|
||||||
|
|
||||||
class AnalyzeRequest(BaseModel):
|
class AnalyzeRequest(BaseModel):
|
||||||
@@ -32,7 +38,33 @@ class SaveResponse(BaseModel):
|
|||||||
status: str
|
status: str
|
||||||
file_path: str
|
file_path: str
|
||||||
note_id: str
|
note_id: str
|
||||||
stats: Dict[str, Any]
|
message: str # Neu für UX Feedback
|
||||||
|
stats: Dict[str, Any] # Kann leer sein bei async processing
|
||||||
|
|
||||||
|
# --- Background Task Wrapper ---
|
||||||
|
async def run_ingestion_task(markdown_content: str, filename: str, vault_root: str, folder: str):
|
||||||
|
"""
|
||||||
|
Führt die Ingestion im Hintergrund aus, damit der Request nicht blockiert.
|
||||||
|
Integrierter WP-20 Hybrid-Modus über den IngestionService.
|
||||||
|
"""
|
||||||
|
logger.info(f"🔄 Background Task started: Ingesting {filename}...")
|
||||||
|
try:
|
||||||
|
ingest_service = IngestionService()
|
||||||
|
result = await ingest_service.create_from_text(
|
||||||
|
markdown_content=markdown_content,
|
||||||
|
filename=filename,
|
||||||
|
vault_root=vault_root,
|
||||||
|
folder=folder
|
||||||
|
)
|
||||||
|
# Hier könnte man später Notification-Services (Websockets) triggern
|
||||||
|
if result.get("status") == "error":
|
||||||
|
logger.error(f"❌ Background Ingestion Error for {filename}: {result.get('error')}")
|
||||||
|
else:
|
||||||
|
logger.info(f"✅ Background Task finished: {filename} ({result.get('chunks_count')} Chunks)")
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"❌ Critical Background Task Failure: {e}", exc_info=True)
|
||||||
|
|
||||||
|
|
||||||
@router.post("/analyze")
|
@router.post("/analyze")
|
||||||
async def analyze_draft(req: AnalyzeRequest):
|
async def analyze_draft(req: AnalyzeRequest):
|
||||||
@@ -40,7 +72,6 @@ async def analyze_draft(req: AnalyzeRequest):
|
|||||||
WP-11 Intelligence: Liefert Link-Vorschläge via DiscoveryService.
|
WP-11 Intelligence: Liefert Link-Vorschläge via DiscoveryService.
|
||||||
"""
|
"""
|
||||||
try:
|
try:
|
||||||
# Hier rufen wir jetzt den verbesserten Service auf
|
|
||||||
result = await discovery_service.analyze_draft(req.text, req.type)
|
result = await discovery_service.analyze_draft(req.text, req.type)
|
||||||
return result
|
return result
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
@@ -48,42 +79,47 @@ async def analyze_draft(req: AnalyzeRequest):
|
|||||||
return {"suggestions": [], "error": str(e)}
|
return {"suggestions": [], "error": str(e)}
|
||||||
|
|
||||||
@router.post("/save", response_model=SaveResponse)
|
@router.post("/save", response_model=SaveResponse)
|
||||||
async def save_note(req: SaveRequest):
|
async def save_note(req: SaveRequest, background_tasks: BackgroundTasks):
|
||||||
"""
|
"""
|
||||||
WP-11 Persistence: Speichert und indiziert.
|
WP-14 Fix: Startet Ingestion im Hintergrund (Fire & Forget).
|
||||||
|
Verhindert Timeouts bei aktiver Smart-Edge-Allocation (WP-15) und Cloud-Hybrid-Modus (WP-20).
|
||||||
"""
|
"""
|
||||||
try:
|
try:
|
||||||
vault_root = os.getenv("MINDNET_VAULT_ROOT", "./vault")
|
vault_root = os.getenv("MINDNET_VAULT_ROOT", "./vault")
|
||||||
abs_vault_root = os.path.abspath(vault_root)
|
abs_vault_root = os.path.abspath(vault_root)
|
||||||
|
|
||||||
if not os.path.exists(abs_vault_root):
|
if not os.path.exists(abs_vault_root):
|
||||||
try: os.makedirs(abs_vault_root, exist_ok=True)
|
try:
|
||||||
except: pass
|
os.makedirs(abs_vault_root, exist_ok=True)
|
||||||
|
except Exception as e:
|
||||||
|
logger.warning(f"Could not create vault root: {e}")
|
||||||
|
|
||||||
final_filename = req.filename or f"draft_{int(time.time())}.md"
|
final_filename = req.filename or f"draft_{int(time.time())}.md"
|
||||||
ingest_service = IngestionService()
|
|
||||||
|
|
||||||
# Async Call
|
# Wir geben sofort eine ID zurück (optimistisch),
|
||||||
result = await ingest_service.create_from_text(
|
# auch wenn die echte ID erst nach dem Parsing feststeht.
|
||||||
|
# Für UI-Feedback nutzen wir den Filename.
|
||||||
|
|
||||||
|
# Task in die Queue schieben
|
||||||
|
background_tasks.add_task(
|
||||||
|
run_ingestion_task,
|
||||||
markdown_content=req.markdown_content,
|
markdown_content=req.markdown_content,
|
||||||
filename=final_filename,
|
filename=final_filename,
|
||||||
vault_root=abs_vault_root,
|
vault_root=abs_vault_root,
|
||||||
folder=req.folder
|
folder=req.folder
|
||||||
)
|
)
|
||||||
|
|
||||||
if result.get("status") == "error":
|
|
||||||
raise HTTPException(status_code=500, detail=result.get("error"))
|
|
||||||
|
|
||||||
return SaveResponse(
|
return SaveResponse(
|
||||||
status="success",
|
status="queued",
|
||||||
file_path=result.get("path", "unknown"),
|
file_path=os.path.join(req.folder, final_filename),
|
||||||
note_id=result.get("note_id", "unknown"),
|
note_id="pending",
|
||||||
|
message="Speicherung & Hybrid-KI-Analyse (WP-20) im Hintergrund gestartet.",
|
||||||
stats={
|
stats={
|
||||||
"chunks": result.get("chunks_count", 0),
|
"chunks": -1, # Indikator für Async
|
||||||
"edges": result.get("edges_count", 0)
|
"edges": -1
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
except HTTPException as he: raise he
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"Save failed: {e}", exc_info=True)
|
logger.error(f"Save dispatch failed: {e}", exc_info=True)
|
||||||
raise HTTPException(status_code=500, detail=f"Save failed: {str(e)}")
|
raise HTTPException(status_code=500, detail=f"Save dispatch failed: {str(e)}")
|
||||||
@@ -1,160 +0,0 @@
|
|||||||
"""
|
|
||||||
Version 0.1
|
|
||||||
"""
|
|
||||||
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
from typing import Any, Optional, List
|
|
||||||
import uuid
|
|
||||||
|
|
||||||
from fastapi import APIRouter
|
|
||||||
from pydantic import BaseModel, Field
|
|
||||||
from qdrant_client import QdrantClient
|
|
||||||
from qdrant_client.http.models import (
|
|
||||||
Distance,
|
|
||||||
VectorParams,
|
|
||||||
PointStruct,
|
|
||||||
Filter,
|
|
||||||
FieldCondition,
|
|
||||||
MatchValue,
|
|
||||||
)
|
|
||||||
|
|
||||||
from ..config import get_settings
|
|
||||||
from ..embeddings import embed_texts
|
|
||||||
|
|
||||||
router = APIRouter(prefix="/qdrant", tags=["qdrant"])
|
|
||||||
|
|
||||||
def _client() -> QdrantClient:
|
|
||||||
s = get_settings()
|
|
||||||
return QdrantClient(url=s.QDRANT_URL, api_key=s.QDRANT_API_KEY)
|
|
||||||
|
|
||||||
def _col(name: str) -> str:
|
|
||||||
return f"{get_settings().COLLECTION_PREFIX}_{name}"
|
|
||||||
|
|
||||||
def _uuid5(s: str) -> str:
|
|
||||||
"""Deterministic UUIDv5 from arbitrary string (server-side point id)."""
|
|
||||||
return str(uuid.uuid5(uuid.NAMESPACE_URL, s))
|
|
||||||
|
|
||||||
# --- Models ---
|
|
||||||
class BaseMeta(BaseModel):
|
|
||||||
note_id: str = Field(..., description="Stable ID of the note (e.g., hash of vault-relative path)")
|
|
||||||
title: Optional[str] = Field(None, description="Note or chunk title")
|
|
||||||
path: Optional[str] = Field(None, description="Vault-relative path to the .md file")
|
|
||||||
Typ: Optional[str] = None
|
|
||||||
Status: Optional[str] = None
|
|
||||||
tags: Optional[List[str]] = None
|
|
||||||
Rolle: Optional[List[str]] = None # allow list
|
|
||||||
|
|
||||||
class UpsertChunkRequest(BaseMeta):
|
|
||||||
chunk_id: str = Field(..., description="Stable ID of the chunk within the note")
|
|
||||||
text: str = Field(..., description="Chunk text content")
|
|
||||||
links: Optional[List[str]] = Field(default=None, description="Outbound links detected in the chunk")
|
|
||||||
|
|
||||||
class UpsertNoteRequest(BaseMeta):
|
|
||||||
text: Optional[str] = Field(None, description="Full note text (optional)")
|
|
||||||
|
|
||||||
class UpsertEdgeRequest(BaseModel):
|
|
||||||
src_note_id: str
|
|
||||||
dst_note_id: Optional[str] = None
|
|
||||||
src_chunk_id: Optional[str] = None
|
|
||||||
dst_chunk_id: Optional[str] = None
|
|
||||||
relation: str = Field(default="links_to")
|
|
||||||
link_text: Optional[str] = None
|
|
||||||
|
|
||||||
class QueryRequest(BaseModel):
|
|
||||||
query: str
|
|
||||||
limit: int = 5
|
|
||||||
note_id: Optional[str] = None
|
|
||||||
path: Optional[str] = None
|
|
||||||
tags: Optional[List[str]] = None
|
|
||||||
|
|
||||||
# --- Helpers ---
|
|
||||||
def _ensure_collections():
|
|
||||||
s = get_settings()
|
|
||||||
cli = _client()
|
|
||||||
# chunks
|
|
||||||
try:
|
|
||||||
cli.get_collection(_col("chunks"))
|
|
||||||
except Exception:
|
|
||||||
cli.recreate_collection(_col("chunks"), vectors_config=VectorParams(size=s.VECTOR_SIZE, distance=Distance.COSINE))
|
|
||||||
# notes
|
|
||||||
try:
|
|
||||||
cli.get_collection(_col("notes"))
|
|
||||||
except Exception:
|
|
||||||
cli.recreate_collection(_col("notes"), vectors_config=VectorParams(size=s.VECTOR_SIZE, distance=Distance.COSINE))
|
|
||||||
# edges (dummy vector of size 1)
|
|
||||||
try:
|
|
||||||
cli.get_collection(_col("edges"))
|
|
||||||
except Exception:
|
|
||||||
cli.recreate_collection(_col("edges"), vectors_config=VectorParams(size=1, distance=Distance.COSINE))
|
|
||||||
|
|
||||||
@router.post("/upsert_chunk", summary="Upsert a chunk into mindnet_chunks")
|
|
||||||
def upsert_chunk(req: UpsertChunkRequest) -> dict:
|
|
||||||
_ensure_collections()
|
|
||||||
cli = _client()
|
|
||||||
vec = embed_texts([req.text])[0]
|
|
||||||
payload: dict[str, Any] = req.model_dump()
|
|
||||||
payload.pop("text", None)
|
|
||||||
payload["preview"] = (req.text[:240] + "…") if len(req.text) > 240 else req.text
|
|
||||||
qdrant_id = _uuid5(f"chunk:{req.chunk_id}")
|
|
||||||
pt = PointStruct(id=qdrant_id, vector=vec, payload=payload)
|
|
||||||
cli.upsert(collection_name=_col("chunks"), points=[pt])
|
|
||||||
return {"status": "ok", "id": qdrant_id}
|
|
||||||
|
|
||||||
@router.post("/upsert_note", summary="Upsert a note into mindnet_notes")
|
|
||||||
def upsert_note(req: UpsertNoteRequest) -> dict:
|
|
||||||
_ensure_collections()
|
|
||||||
cli = _client()
|
|
||||||
text_for_embedding = req.text if req.text else (req.title or req.note_id)
|
|
||||||
vec = embed_texts([text_for_embedding])[0]
|
|
||||||
payload: dict[str, Any] = req.model_dump()
|
|
||||||
payload.pop("text", None)
|
|
||||||
qdrant_id = _uuid5(f"note:{req.note_id}")
|
|
||||||
pt = PointStruct(id=qdrant_id, vector=vec, payload=payload)
|
|
||||||
cli.upsert(collection_name=_col("notes"), points=[pt])
|
|
||||||
return {"status": "ok", "id": qdrant_id}
|
|
||||||
|
|
||||||
@router.post("/upsert_edge", summary="Upsert a graph edge into mindnet_edges")
|
|
||||||
def upsert_edge(req: UpsertEdgeRequest) -> dict:
|
|
||||||
_ensure_collections()
|
|
||||||
cli = _client()
|
|
||||||
payload = req.model_dump()
|
|
||||||
vec = [0.0]
|
|
||||||
raw_edge_id = f"{req.src_note_id}|{req.src_chunk_id or ''}->{req.dst_note_id or ''}|{req.dst_chunk_id or ''}|{req.relation}"
|
|
||||||
qdrant_id = _uuid5(f"edge:{raw_edge_id}")
|
|
||||||
pt = PointStruct(id=qdrant_id, vector=vec, payload=payload)
|
|
||||||
cli.upsert(collection_name=_col("edges"), points=[pt])
|
|
||||||
return {"status": "ok", "id": qdrant_id}
|
|
||||||
|
|
||||||
@router.post("/query", summary="Vector query over mindnet_chunks with optional filters")
|
|
||||||
def query(req: QueryRequest) -> dict:
|
|
||||||
_ensure_collections()
|
|
||||||
cli = _client()
|
|
||||||
vec = embed_texts([req.query])[0]
|
|
||||||
|
|
||||||
flt: Optional[Filter] = None
|
|
||||||
conds = []
|
|
||||||
if req.note_id:
|
|
||||||
conds.append(FieldCondition(key="note_id", match=MatchValue(value=req.note_id)))
|
|
||||||
if req.path:
|
|
||||||
conds.append(FieldCondition(key="path", match=MatchValue(value=req.path)))
|
|
||||||
if req.tags:
|
|
||||||
for t in req.tags:
|
|
||||||
conds.append(FieldCondition(key="tags", match=MatchValue(value=t)))
|
|
||||||
if conds:
|
|
||||||
flt = Filter(must=conds)
|
|
||||||
|
|
||||||
res = cli.search(collection_name=_col("chunks"), query_vector=vec, limit=req.limit, with_payload=True, with_vectors=False, query_filter=flt)
|
|
||||||
hits = []
|
|
||||||
for p in res:
|
|
||||||
pl = p.payload or {}
|
|
||||||
hits.append({
|
|
||||||
"chunk_id": p.id,
|
|
||||||
"score": p.score,
|
|
||||||
"note_id": pl.get("note_id"),
|
|
||||||
"title": pl.get("title"),
|
|
||||||
"path": pl.get("path"),
|
|
||||||
"preview": pl.get("preview"),
|
|
||||||
"tags": pl.get("tags"),
|
|
||||||
})
|
|
||||||
return {"results": hits}
|
|
||||||
+7
-18
@@ -1,23 +1,12 @@
|
|||||||
"""
|
"""
|
||||||
app/routers/query.py — Query-Endpunkte (WP-04)
|
FILE: app/routers/query.py
|
||||||
|
DESCRIPTION: Klassische Such-Endpunkte (Semantic & Hybrid). Initiiert asynchrones Feedback-Logging und ruft den richtigen Retriever Modus auf
|
||||||
|
VERSION: 0.2.0
|
||||||
|
STATUS: Active
|
||||||
|
DEPENDENCIES: app.models.dto, app.core.retriever, app.services.feedback_service
|
||||||
|
LAST_ANALYSIS: 2025-12-15
|
||||||
|
"""
|
||||||
|
|
||||||
Zweck:
|
|
||||||
Stellt POST /query bereit und ruft den passenden Retriever-Modus auf.
|
|
||||||
Kompatibilität:
|
|
||||||
Python 3.12+, FastAPI 0.110+
|
|
||||||
Version:
|
|
||||||
0.1.0 (Erstanlage)
|
|
||||||
Stand:
|
|
||||||
2025-10-07
|
|
||||||
Bezug:
|
|
||||||
- app/core/retriever.py
|
|
||||||
- app/models/dto.py
|
|
||||||
Nutzung:
|
|
||||||
app.include_router(query.router, prefix="/query", tags=["query"])
|
|
||||||
Änderungsverlauf:
|
|
||||||
0.2.0 (2025-12-07) - Update für WP04c Feedback
|
|
||||||
0.1.0 (2025-10-07) – Erstanlage.
|
|
||||||
"""
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
from fastapi import APIRouter, HTTPException, BackgroundTasks
|
from fastapi import APIRouter, HTTPException, BackgroundTasks
|
||||||
from app.models.dto import QueryRequest, QueryResponse
|
from app.models.dto import QueryRequest, QueryResponse
|
||||||
|
|||||||
+6
-17
@@ -1,21 +1,10 @@
|
|||||||
"""
|
"""
|
||||||
app/routers/tools.py — Tool-Definitionen für Ollama/n8n/MCP (read-only)
|
FILE: app/routers/tools.py
|
||||||
|
DESCRIPTION: Liefert JSON-Schemas für die Integration als 'Tools' in Agents (Ollama/OpenAI). Read-Only.
|
||||||
Zweck:
|
VERSION: 0.1.1
|
||||||
Liefert Funktions-Schemas (OpenAI-/Ollama-kompatibles Tool-JSON) für:
|
STATUS: Active
|
||||||
- mindnet_query -> POST /query
|
DEPENDENCIES: fastapi
|
||||||
- mindnet_subgraph -> GET /graph/{note_id}
|
LAST_ANALYSIS: 2025-12-15
|
||||||
Kompatibilität:
|
|
||||||
Python 3.12+, FastAPI 0.110+
|
|
||||||
Version:
|
|
||||||
0.1.1 (query ODER query_vector möglich)
|
|
||||||
Stand:
|
|
||||||
2025-10-07
|
|
||||||
Nutzung:
|
|
||||||
app.include_router(tools.router, prefix="/tools", tags=["tools"])
|
|
||||||
Änderungsverlauf:
|
|
||||||
0.1.1 (2025-10-07) – mindnet_query: oneOf(query, query_vector).
|
|
||||||
0.1.0 (2025-10-07) – Erstanlage.
|
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|||||||
@@ -1,12 +1,11 @@
|
|||||||
"""
|
"""
|
||||||
app/services/discovery.py
|
FILE: app/services/discovery.py
|
||||||
Service für Link-Vorschläge und Knowledge-Discovery (WP-11).
|
DESCRIPTION: Service für WP-11. Analysiert Texte, findet Entitäten und schlägt typisierte Verbindungen vor ("Matrix-Logic").
|
||||||
|
VERSION: 0.6.0
|
||||||
Features:
|
STATUS: Active
|
||||||
- Sliding Window Analyse für lange Texte.
|
DEPENDENCIES: app.core.qdrant, app.models.dto, app.core.retriever
|
||||||
- Footer-Scan für Projekt-Referenzen.
|
EXTERNAL_CONFIG: config/types.yaml
|
||||||
- 'Matrix-Logic' für intelligente Kanten-Typen (Experience -> Value = based_on).
|
LAST_ANALYSIS: 2025-12-15
|
||||||
- Async & Nomic-Embeddings kompatibel.
|
|
||||||
"""
|
"""
|
||||||
import logging
|
import logging
|
||||||
import asyncio
|
import asyncio
|
||||||
|
|||||||
@@ -0,0 +1,150 @@
|
|||||||
|
"""
|
||||||
|
FILE: app/services/edge_registry.py
|
||||||
|
DESCRIPTION: Single Source of Truth für Kanten-Typen mit dynamischem Reload.
|
||||||
|
WP-22: Fix für absolute Pfade außerhalb des Vaults (Prod-Dictionary).
|
||||||
|
WP-20: Synchronisation mit zentralen Settings (v0.6.2).
|
||||||
|
VERSION: 0.7.5
|
||||||
|
STATUS: Active
|
||||||
|
DEPENDENCIES: re, os, json, logging, time, app.config
|
||||||
|
"""
|
||||||
|
import re
|
||||||
|
import os
|
||||||
|
import json
|
||||||
|
import logging
|
||||||
|
import time
|
||||||
|
from typing import Dict, Optional, Set, Tuple
|
||||||
|
|
||||||
|
from app.config import get_settings
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
class EdgeRegistry:
|
||||||
|
_instance = None
|
||||||
|
FORBIDDEN_SYSTEM_EDGES = {"next", "prev", "belongs_to"}
|
||||||
|
|
||||||
|
def __new__(cls, *args, **kwargs):
|
||||||
|
if cls._instance is None:
|
||||||
|
cls._instance = super(EdgeRegistry, cls).__new__(cls)
|
||||||
|
cls._instance.initialized = False
|
||||||
|
return cls._instance
|
||||||
|
|
||||||
|
def __init__(self):
|
||||||
|
if self.initialized:
|
||||||
|
return
|
||||||
|
|
||||||
|
settings = get_settings()
|
||||||
|
|
||||||
|
# 1. Pfad aus den zentralen Settings laden (WP-20 Synchronisation)
|
||||||
|
# Priorisiert den Pfad aus der .env / config.py (v0.6.2)
|
||||||
|
self.full_vocab_path = os.path.abspath(settings.MINDNET_VOCAB_PATH)
|
||||||
|
|
||||||
|
self.unknown_log_path = "data/logs/unknown_edges.jsonl"
|
||||||
|
self.canonical_map: Dict[str, str] = {}
|
||||||
|
self.valid_types: Set[str] = set()
|
||||||
|
self._last_mtime = 0.0
|
||||||
|
|
||||||
|
# Initialer Ladevorgang
|
||||||
|
logger.info(f">>> [EDGE-REGISTRY] Initializing with Path: {self.full_vocab_path}")
|
||||||
|
self.ensure_latest()
|
||||||
|
self.initialized = True
|
||||||
|
|
||||||
|
def ensure_latest(self):
|
||||||
|
"""
|
||||||
|
Prüft den Zeitstempel der Vokabular-Datei und lädt bei Bedarf neu.
|
||||||
|
Verhindert den AttributeError in der Ingestion-Pipeline.
|
||||||
|
"""
|
||||||
|
if not os.path.exists(self.full_vocab_path):
|
||||||
|
logger.error(f"!!! [EDGE-REGISTRY ERROR] File not found: {self.full_vocab_path} !!!")
|
||||||
|
return
|
||||||
|
|
||||||
|
try:
|
||||||
|
current_mtime = os.path.getmtime(self.full_vocab_path)
|
||||||
|
if current_mtime > self._last_mtime:
|
||||||
|
self._load_vocabulary()
|
||||||
|
self._last_mtime = current_mtime
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"!!! [EDGE-REGISTRY] Error checking file time: {e}")
|
||||||
|
|
||||||
|
def _load_vocabulary(self):
|
||||||
|
"""Parst das Markdown-Wörterbuch und baut die Canonical-Map auf."""
|
||||||
|
self.canonical_map.clear()
|
||||||
|
self.valid_types.clear()
|
||||||
|
|
||||||
|
# Regex für Tabellen-Struktur: | **Typ** | Aliase |
|
||||||
|
pattern = re.compile(r"\|\s*\*\*`?([a-zA-Z0-9_-]+)`?\*\*\s*\|\s*([^|]+)\|")
|
||||||
|
|
||||||
|
try:
|
||||||
|
with open(self.full_vocab_path, "r", encoding="utf-8") as f:
|
||||||
|
c_types, c_aliases = 0, 0
|
||||||
|
for line in f:
|
||||||
|
match = pattern.search(line)
|
||||||
|
if match:
|
||||||
|
canonical = match.group(1).strip().lower()
|
||||||
|
aliases_str = match.group(2).strip()
|
||||||
|
|
||||||
|
self.valid_types.add(canonical)
|
||||||
|
self.canonical_map[canonical] = canonical
|
||||||
|
c_types += 1
|
||||||
|
|
||||||
|
if aliases_str and "Kein Alias" not in aliases_str:
|
||||||
|
aliases = [a.strip() for a in aliases_str.split(",") if a.strip()]
|
||||||
|
for alias in aliases:
|
||||||
|
# Normalisierung: Kleinschreibung, Underscores statt Leerzeichen
|
||||||
|
clean_alias = alias.replace("`", "").lower().strip().replace(" ", "_")
|
||||||
|
self.canonical_map[clean_alias] = canonical
|
||||||
|
c_aliases += 1
|
||||||
|
|
||||||
|
logger.info(f"=== [EDGE-REGISTRY SUCCESS] Loaded {c_types} Canonical Types and {c_aliases} Aliases ===")
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"!!! [EDGE-REGISTRY FATAL] Error reading file: {e} !!!")
|
||||||
|
|
||||||
|
def resolve(self, edge_type: str, provenance: str = "explicit", context: dict = None) -> str:
|
||||||
|
"""
|
||||||
|
Validiert einen Kanten-Typ gegen das Vokabular.
|
||||||
|
Loggt unbekannte Typen für die spätere manuelle Pflege.
|
||||||
|
"""
|
||||||
|
self.ensure_latest()
|
||||||
|
if not edge_type:
|
||||||
|
return "related_to"
|
||||||
|
|
||||||
|
# Normalisierung des Typs
|
||||||
|
clean_type = edge_type.lower().strip().replace(" ", "_").replace("-", "_")
|
||||||
|
ctx = context or {}
|
||||||
|
|
||||||
|
# System-Kanten dürfen nicht manuell vergeben werden
|
||||||
|
if provenance == "explicit" and clean_type in self.FORBIDDEN_SYSTEM_EDGES:
|
||||||
|
self._log_issue(clean_type, "forbidden_system_usage", ctx)
|
||||||
|
return "related_to"
|
||||||
|
|
||||||
|
# System-Kanten sind nur bei struktureller Provenienz erlaubt
|
||||||
|
if provenance == "structure" and clean_type in self.FORBIDDEN_SYSTEM_EDGES:
|
||||||
|
return clean_type
|
||||||
|
|
||||||
|
# Mapping auf kanonischen Namen
|
||||||
|
if clean_type in self.canonical_map:
|
||||||
|
return self.canonical_map[clean_type]
|
||||||
|
|
||||||
|
# Fallback und Logging
|
||||||
|
self._log_issue(clean_type, "unknown_type", ctx)
|
||||||
|
return clean_type
|
||||||
|
|
||||||
|
def _log_issue(self, edge_type: str, error_kind: str, ctx: dict):
|
||||||
|
"""Detailliertes JSONL-Logging für die Vokabular-Optimierung."""
|
||||||
|
try:
|
||||||
|
os.makedirs(os.path.dirname(self.unknown_log_path), exist_ok=True)
|
||||||
|
entry = {
|
||||||
|
"timestamp": time.strftime("%Y-%m-%d %H:%M:%S"),
|
||||||
|
"edge_type": edge_type,
|
||||||
|
"error": error_kind,
|
||||||
|
"file": ctx.get("file", "unknown"),
|
||||||
|
"line": ctx.get("line", "unknown"),
|
||||||
|
"note_id": ctx.get("note_id", "unknown")
|
||||||
|
}
|
||||||
|
with open(self.unknown_log_path, "a", encoding="utf-8") as f:
|
||||||
|
f.write(json.dumps(entry) + "\n")
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
# Singleton Export
|
||||||
|
registry = EdgeRegistry()
|
||||||
@@ -1,12 +1,10 @@
|
|||||||
"""
|
"""
|
||||||
app/services/embeddings_client.py — Text→Embedding Service
|
FILE: app/services/embeddings_client.py
|
||||||
|
DESCRIPTION: Unified Embedding Client. Nutzt Ollama API (HTTP). Ersetzt lokale sentence-transformers.
|
||||||
Zweck:
|
VERSION: 2.5.0
|
||||||
Einheitlicher Client für Embeddings via Ollama (Nomic).
|
STATUS: Active
|
||||||
Stellt sicher, dass sowohl Async (Ingestion) als auch Sync (Retriever)
|
DEPENDENCIES: httpx, requests, app.config
|
||||||
denselben Vektorraum (768 Dim) nutzen.
|
LAST_ANALYSIS: 2025-12-15
|
||||||
|
|
||||||
Version: 2.5.0 (Unified Ollama)
|
|
||||||
"""
|
"""
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
import os
|
import os
|
||||||
|
|||||||
@@ -1,9 +1,10 @@
|
|||||||
"""
|
"""
|
||||||
app/services/feedback_service.py
|
FILE: app/services/feedback_service.py
|
||||||
Service zum Loggen von Suchanfragen und Feedback (WP-04c).
|
DESCRIPTION: Schreibt Search- und Feedback-Logs in JSONL-Dateien.
|
||||||
Speichert Daten als JSONL für späteres Self-Tuning (WP-08).
|
VERSION: 1.1
|
||||||
|
STATUS: Active
|
||||||
Version: 1.1 (Chat-Support)
|
DEPENDENCIES: app.models.dto
|
||||||
|
LAST_ANALYSIS: 2025-12-15
|
||||||
"""
|
"""
|
||||||
import json
|
import json
|
||||||
import os
|
import os
|
||||||
|
|||||||
@@ -1,88 +0,0 @@
|
|||||||
"""
|
|
||||||
app/services/llm_ollama.py — Ollama-Integration & Prompt-Bau (WP-04)
|
|
||||||
|
|
||||||
Zweck:
|
|
||||||
Prompt-Template & (optionaler) lokaler Aufruf von Ollama. Der Aufruf ist
|
|
||||||
bewusst gekapselt und kann gefahrlos deaktiviert bleiben, bis ihr ein
|
|
||||||
konkretes Modell konfigurieren wollt.
|
|
||||||
Kompatibilität:
|
|
||||||
Python 3.12+
|
|
||||||
Version:
|
|
||||||
0.1.0 (Erstanlage)
|
|
||||||
Stand:
|
|
||||||
2025-10-07
|
|
||||||
Bezug:
|
|
||||||
WP-04/05 Kontextbereitstellung für LLM
|
|
||||||
Nutzung:
|
|
||||||
from app.services.llm_ollama import build_prompt, call_ollama
|
|
||||||
Änderungsverlauf:
|
|
||||||
0.1.0 (2025-10-07) – Erstanlage.
|
|
||||||
"""
|
|
||||||
|
|
||||||
from __future__ import annotations
|
|
||||||
from typing import List, Dict, Optional
|
|
||||||
import subprocess
|
|
||||||
import json
|
|
||||||
|
|
||||||
PROMPT_TEMPLATE = """System: You are a helpful expert.
|
|
||||||
User: {question}
|
|
||||||
|
|
||||||
Context (ranked):
|
|
||||||
{contexts}
|
|
||||||
|
|
||||||
Task: Answer precisely. At the end, list sources (note title + section) and important edge paths.
|
|
||||||
"""
|
|
||||||
|
|
||||||
|
|
||||||
def build_context_block(items: List[Dict]) -> str:
|
|
||||||
"""Formatiert Top-K-Kontexte (Chunks) für den Prompt."""
|
|
||||||
lines = []
|
|
||||||
for i, it in enumerate(items, 1):
|
|
||||||
note = it.get("note_title", "") or it.get("note_id", "")
|
|
||||||
sec = it.get("section", "") or it.get("section_title", "")
|
|
||||||
sc = it.get("score", 0)
|
|
||||||
txt = it.get("text", "") or it.get("body", "") or ""
|
|
||||||
lines.append(f"{i}) {note} — {sec} [score={sc:.2f}]\n{txt}\n")
|
|
||||||
return "\n".join(lines)
|
|
||||||
|
|
||||||
|
|
||||||
def build_prompt(question: str, contexts: List[Dict]) -> str:
|
|
||||||
"""Setzt Frage + Kontexte in ein konsistentes Template."""
|
|
||||||
return PROMPT_TEMPLATE.format(question=question, contexts=build_context_block(contexts))
|
|
||||||
|
|
||||||
|
|
||||||
def call_ollama(prompt: str, model: str = "llama3.1:8b", timeout_s: int = 120) -> Optional[str]:
|
|
||||||
"""
|
|
||||||
Optionaler lokaler Aufruf von `ollama run`.
|
|
||||||
Rückgabe: generierter Text oder None bei Fehler/Abbruch.
|
|
||||||
Hinweis: Nur nutzen, wenn Ollama lokal installiert/konfiguriert ist.
|
|
||||||
"""
|
|
||||||
try:
|
|
||||||
proc = subprocess.run(
|
|
||||||
["ollama", "run", model],
|
|
||||||
input=prompt.encode("utf-8"),
|
|
||||||
stdout=subprocess.PIPE,
|
|
||||||
stderr=subprocess.PIPE,
|
|
||||||
timeout=timeout_s,
|
|
||||||
check=False,
|
|
||||||
)
|
|
||||||
out = proc.stdout.decode("utf-8", errors="replace")
|
|
||||||
# viele ollama Builds streamen JSON-Zeilen; robust extrahieren:
|
|
||||||
try:
|
|
||||||
# Falls JSONL, letztes "response" zusammenfassen
|
|
||||||
texts = []
|
|
||||||
for line in out.splitlines():
|
|
||||||
line = line.strip()
|
|
||||||
if not line:
|
|
||||||
continue
|
|
||||||
try:
|
|
||||||
obj = json.loads(line)
|
|
||||||
if "response" in obj:
|
|
||||||
texts.append(obj["response"])
|
|
||||||
except Exception:
|
|
||||||
texts.append(line)
|
|
||||||
return "".join(texts).strip()
|
|
||||||
except Exception:
|
|
||||||
return out.strip()
|
|
||||||
except Exception:
|
|
||||||
return None
|
|
||||||
+265
-33
@@ -1,80 +1,312 @@
|
|||||||
"""
|
"""
|
||||||
app/services/llm_service.py — LLM Client (Ollama)
|
FILE: app/services/llm_service.py
|
||||||
Version: 0.2.1 (Fix: System Prompt Handling for Phi-3)
|
DESCRIPTION: Hybrid-Client für Ollama, Google GenAI (Gemini) und OpenRouter.
|
||||||
|
Verwaltet provider-spezifische Prompts und Background-Last.
|
||||||
|
WP-20: Optimiertes Fallback-Management zum Schutz von Cloud-Quoten.
|
||||||
|
WP-20 Fix: Bulletproof Prompt-Auflösung für format() Aufrufe.
|
||||||
|
WP-22/JSON: Optionales JSON-Schema + strict (für OpenRouter structured outputs).
|
||||||
|
FIX: Intelligente Rate-Limit Erkennung (429 Handling), v1-API Sync & Timeouts.
|
||||||
|
VERSION: 3.3.6
|
||||||
|
STATUS: Active
|
||||||
|
DEPENDENCIES: httpx, yaml, logging, asyncio, json, google-genai, openai, app.config
|
||||||
"""
|
"""
|
||||||
|
|
||||||
import httpx
|
import httpx
|
||||||
import yaml
|
import yaml
|
||||||
import logging
|
import logging
|
||||||
import os
|
import asyncio
|
||||||
|
import json
|
||||||
|
from google import genai
|
||||||
|
from google.genai import types
|
||||||
|
from openai import AsyncOpenAI # Für OpenRouter (OpenAI-kompatibel)
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
from typing import Optional, Dict, Any, Literal
|
||||||
from app.config import get_settings
|
from app.config import get_settings
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
class LLMService:
|
class LLMService:
|
||||||
|
# GLOBALER SEMAPHOR für Hintergrund-Last Steuerung (WP-06)
|
||||||
|
_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()
|
||||||
|
|
||||||
self.client = httpx.AsyncClient(
|
# Initialisiere Semaphore einmalig auf Klassen-Ebene
|
||||||
|
if LLMService._background_semaphore is None:
|
||||||
|
limit = getattr(self.settings, "BACKGROUND_LIMIT", 2)
|
||||||
|
logger.info(f"🚦 LLMService: Initializing Background Semaphore with limit: {limit}")
|
||||||
|
LLMService._background_semaphore = asyncio.Semaphore(limit)
|
||||||
|
|
||||||
|
# 1. Lokaler Ollama Client
|
||||||
|
self.ollama_client = httpx.AsyncClient(
|
||||||
base_url=self.settings.OLLAMA_URL,
|
base_url=self.settings.OLLAMA_URL,
|
||||||
timeout=self.settings.LLM_TIMEOUT
|
timeout=httpx.Timeout(self.settings.LLM_TIMEOUT)
|
||||||
)
|
)
|
||||||
|
|
||||||
|
# 2. Google GenAI Client (Modern SDK)
|
||||||
|
self.google_client = None
|
||||||
|
if self.settings.GOOGLE_API_KEY:
|
||||||
|
# FIX: Wir erzwingen api_version 'v1' für höhere Stabilität bei 2.5er Modellen.
|
||||||
|
self.google_client = genai.Client(
|
||||||
|
api_key=self.settings.GOOGLE_API_KEY,
|
||||||
|
http_options={'api_version': 'v1'}
|
||||||
|
)
|
||||||
|
logger.info("✨ LLMService: Google GenAI (Gemini) active.")
|
||||||
|
|
||||||
|
# 3. OpenRouter Client
|
||||||
|
self.openrouter_client = None
|
||||||
|
if self.settings.OPENROUTER_API_KEY:
|
||||||
|
self.openrouter_client = AsyncOpenAI(
|
||||||
|
base_url="https://openrouter.ai/api/v1",
|
||||||
|
api_key=self.settings.OPENROUTER_API_KEY,
|
||||||
|
# Strikter Timeout für OpenRouter Free-Tier zur Vermeidung von Hangs.
|
||||||
|
timeout=45.0
|
||||||
|
)
|
||||||
|
logger.info("🛰️ LLMService: OpenRouter Integration active.")
|
||||||
|
|
||||||
def _load_prompts(self) -> dict:
|
def _load_prompts(self) -> dict:
|
||||||
|
"""Lädt die Prompt-Konfiguration aus der YAML-Datei."""
|
||||||
path = Path(self.settings.PROMPTS_PATH)
|
path = Path(self.settings.PROMPTS_PATH)
|
||||||
if not path.exists():
|
if not path.exists():
|
||||||
|
logger.error(f"❌ Prompts file not found at {path}")
|
||||||
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) or {}
|
||||||
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:
|
def get_prompt(self, key: str, provider: str = None) -> str:
|
||||||
"""
|
"""
|
||||||
Führt einen LLM Call aus.
|
Hole provider-spezifisches Template mit intelligenter Text-Kaskade.
|
||||||
Unterstützt nun explizite System-Prompts für sauberes Templating.
|
HINWEIS: Dies ist nur ein Text-Lookup und verbraucht kein API-Kontingent.
|
||||||
|
Kaskade: Gewählter Provider -> Gemini (Cloud-Stil) -> Ollama (Basis-Stil).
|
||||||
|
|
||||||
|
WP-20 Fix: Garantiert die Rückgabe eines Strings, um AttributeError zu vermeiden.
|
||||||
"""
|
"""
|
||||||
|
active_provider = provider or self.settings.MINDNET_LLM_PROVIDER
|
||||||
|
data = self.prompts.get(key, "")
|
||||||
|
|
||||||
|
if isinstance(data, dict):
|
||||||
|
# Wir versuchen erst den Provider, dann Gemini, dann Ollama
|
||||||
|
val = data.get(active_provider, data.get("gemini", data.get("ollama", "")))
|
||||||
|
|
||||||
|
# Falls val durch YAML-Fehler immer noch ein Dict ist, extrahiere ersten String
|
||||||
|
if isinstance(val, dict):
|
||||||
|
logger.warning(f"⚠️ [LLMService] Nested dictionary detected for key '{key}'. Using first entry.")
|
||||||
|
val = next(iter(val.values()), "") if val else ""
|
||||||
|
return str(val)
|
||||||
|
|
||||||
|
return str(data)
|
||||||
|
|
||||||
|
async def generate_raw_response(
|
||||||
|
self,
|
||||||
|
prompt: str,
|
||||||
|
system: str = None,
|
||||||
|
force_json: bool = False,
|
||||||
|
max_retries: int = 2,
|
||||||
|
base_delay: float = 2.0,
|
||||||
|
priority: Literal["realtime", "background"] = "realtime",
|
||||||
|
provider: Optional[str] = None,
|
||||||
|
model_override: Optional[str] = None,
|
||||||
|
json_schema: Optional[Dict[str, Any]] = None,
|
||||||
|
json_schema_name: str = "mindnet_json",
|
||||||
|
strict_json_schema: bool = True
|
||||||
|
) -> str:
|
||||||
|
"""
|
||||||
|
Haupteinstiegspunkt für LLM-Anfragen mit Priorisierung.
|
||||||
|
|
||||||
|
force_json:
|
||||||
|
- Ollama: nutzt payload["format"]="json"
|
||||||
|
- Gemini: nutzt response_mime_type="application/json"
|
||||||
|
- OpenRouter: nutzt response_format=json_object (Fallback) oder json_schema
|
||||||
|
"""
|
||||||
|
target_provider = provider or self.settings.MINDNET_LLM_PROVIDER
|
||||||
|
|
||||||
|
if priority == "background":
|
||||||
|
async with LLMService._background_semaphore:
|
||||||
|
return await self._dispatch(
|
||||||
|
target_provider, prompt, system, force_json,
|
||||||
|
max_retries, base_delay, model_override,
|
||||||
|
json_schema, json_schema_name, strict_json_schema
|
||||||
|
)
|
||||||
|
|
||||||
|
return await self._dispatch(
|
||||||
|
target_provider, prompt, system, force_json,
|
||||||
|
max_retries, base_delay, model_override,
|
||||||
|
json_schema, json_schema_name, strict_json_schema
|
||||||
|
)
|
||||||
|
|
||||||
|
async def _dispatch(
|
||||||
|
self,
|
||||||
|
provider: str,
|
||||||
|
prompt: str,
|
||||||
|
system: Optional[str],
|
||||||
|
force_json: bool,
|
||||||
|
max_retries: int,
|
||||||
|
base_delay: float,
|
||||||
|
model_override: Optional[str],
|
||||||
|
json_schema: Optional[Dict[str, Any]],
|
||||||
|
json_schema_name: str,
|
||||||
|
strict_json_schema: bool
|
||||||
|
) -> str:
|
||||||
|
"""
|
||||||
|
Routet die Anfrage mit intelligenter Rate-Limit Erkennung (WP-20 + WP-76).
|
||||||
|
Schleife läuft über MINDNET_LLM_RATE_LIMIT_RETRIES.
|
||||||
|
"""
|
||||||
|
rate_limit_attempts = 0
|
||||||
|
max_rate_retries = getattr(self.settings, "LLM_RATE_LIMIT_RETRIES", 3)
|
||||||
|
wait_time = getattr(self.settings, "LLM_RATE_LIMIT_WAIT", 60.0)
|
||||||
|
|
||||||
|
while rate_limit_attempts <= max_rate_retries:
|
||||||
|
try:
|
||||||
|
if provider == "openrouter" and self.openrouter_client:
|
||||||
|
return await self._execute_openrouter(
|
||||||
|
prompt=prompt,
|
||||||
|
system=system,
|
||||||
|
force_json=force_json,
|
||||||
|
model_override=model_override,
|
||||||
|
json_schema=json_schema,
|
||||||
|
json_schema_name=json_schema_name,
|
||||||
|
strict_json_schema=strict_json_schema
|
||||||
|
)
|
||||||
|
|
||||||
|
if provider == "gemini" and self.google_client:
|
||||||
|
return await self._execute_google(prompt, system, force_json, model_override)
|
||||||
|
|
||||||
|
# Default/Fallback zu Ollama
|
||||||
|
return await self._execute_ollama(prompt, system, force_json, max_retries, base_delay)
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
err_str = str(e)
|
||||||
|
# Intelligente 429 Erkennung für alle Cloud-Provider
|
||||||
|
is_rate_limit = any(x in err_str for x in ["429", "RESOURCE_EXHAUSTED", "rate_limited", "Too Many Requests"])
|
||||||
|
|
||||||
|
if is_rate_limit and rate_limit_attempts < max_rate_retries:
|
||||||
|
rate_limit_attempts += 1
|
||||||
|
logger.warning(
|
||||||
|
f"⏳ [LLMService] Rate Limit (429) detected from {provider}. "
|
||||||
|
f"Attempt {rate_limit_attempts}/{max_rate_retries}. "
|
||||||
|
f"Waiting {wait_time}s before cloud retry..."
|
||||||
|
)
|
||||||
|
await asyncio.sleep(wait_time)
|
||||||
|
continue # Nächster Versuch in der Cloud-Schleife
|
||||||
|
|
||||||
|
# Wenn kein Rate-Limit oder Retries erschöpft -> Fallback zu Ollama (falls aktiviert)
|
||||||
|
if self.settings.LLM_FALLBACK_ENABLED and provider != "ollama":
|
||||||
|
logger.warning(
|
||||||
|
f"🔄 Provider {provider} failed ({err_str}). Falling back to LOCAL OLLAMA."
|
||||||
|
)
|
||||||
|
return await self._execute_ollama(prompt, system, force_json, max_retries, base_delay)
|
||||||
|
raise e
|
||||||
|
|
||||||
|
async def _execute_google(self, prompt, system, force_json, model_override):
|
||||||
|
"""Native Google SDK Integration (Gemini) mit v1 Fix."""
|
||||||
|
model = model_override or self.settings.GEMINI_MODEL
|
||||||
|
# Fix: Bereinige Modellnamen (Entfernung von 'models/' Präfix)
|
||||||
|
clean_model = model.replace("models/", "")
|
||||||
|
|
||||||
|
config = types.GenerateContentConfig(
|
||||||
|
system_instruction=system,
|
||||||
|
response_mime_type="application/json" if force_json else "text/plain"
|
||||||
|
)
|
||||||
|
# Thread-Offloading mit striktem Timeout gegen "Hangs"
|
||||||
|
response = await asyncio.wait_for(
|
||||||
|
asyncio.to_thread(
|
||||||
|
self.google_client.models.generate_content,
|
||||||
|
model=clean_model, contents=prompt, config=config
|
||||||
|
),
|
||||||
|
timeout=45.0
|
||||||
|
)
|
||||||
|
return response.text.strip()
|
||||||
|
|
||||||
|
async def _execute_openrouter(
|
||||||
|
self,
|
||||||
|
prompt: str,
|
||||||
|
system: Optional[str],
|
||||||
|
force_json: bool,
|
||||||
|
model_override: Optional[str],
|
||||||
|
json_schema: Optional[Dict[str, Any]] = None,
|
||||||
|
json_schema_name: str = "mindnet_json",
|
||||||
|
strict_json_schema: bool = True
|
||||||
|
) -> str:
|
||||||
|
"""OpenRouter API Integration (OpenAI-kompatibel) mit Schema-Support."""
|
||||||
|
model = model_override or self.settings.OPENROUTER_MODEL
|
||||||
|
messages = []
|
||||||
|
if system:
|
||||||
|
messages.append({"role": "system", "content": system})
|
||||||
|
messages.append({"role": "user", "content": prompt})
|
||||||
|
|
||||||
|
kwargs: Dict[str, Any] = {}
|
||||||
|
if force_json:
|
||||||
|
if json_schema:
|
||||||
|
kwargs["response_format"] = {
|
||||||
|
"type": "json_schema",
|
||||||
|
"json_schema": {
|
||||||
|
"name": json_schema_name,
|
||||||
|
"strict": strict_json_schema,
|
||||||
|
"schema": json_schema
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else:
|
||||||
|
kwargs["response_format"] = {"type": "json_object"}
|
||||||
|
|
||||||
|
response = await self.openrouter_client.chat.completions.create(
|
||||||
|
model=model,
|
||||||
|
messages=messages,
|
||||||
|
**kwargs
|
||||||
|
)
|
||||||
|
return response.choices[0].message.content.strip()
|
||||||
|
|
||||||
|
async def _execute_ollama(self, prompt, system, force_json, max_retries, base_delay):
|
||||||
|
"""Lokaler Ollama Call mit exponentiellem Backoff."""
|
||||||
payload = {
|
payload = {
|
||||||
"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
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if force_json:
|
||||||
# WICHTIG: System-Prompt separat übergeben, damit Ollama formatiert
|
payload["format"] = "json"
|
||||||
if system:
|
if system:
|
||||||
payload["system"] = system
|
payload["system"] = system
|
||||||
|
|
||||||
|
attempt = 0
|
||||||
|
while True:
|
||||||
try:
|
try:
|
||||||
response = await self.client.post("/api/generate", json=payload)
|
res = await self.ollama_client.post("/api/generate", json=payload)
|
||||||
if response.status_code != 200:
|
res.raise_for_status()
|
||||||
logger.error(f"Ollama Error ({response.status_code}): {response.text}")
|
return res.json().get("response", "").strip()
|
||||||
return "Fehler bei der Generierung."
|
|
||||||
|
|
||||||
data = response.json()
|
|
||||||
return data.get("response", "").strip()
|
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"LLM Raw Gen Error: {e}")
|
attempt += 1
|
||||||
return "Interner LLM Fehler."
|
if attempt > max_retries:
|
||||||
|
logger.error(f"❌ Ollama Error after {attempt} retries: {e}")
|
||||||
|
raise e
|
||||||
|
wait_time = base_delay * (2 ** (attempt - 1))
|
||||||
|
logger.warning(f"⚠️ Ollama attempt {attempt} failed. Retrying in {wait_time}s...")
|
||||||
|
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"""
|
"""Vollständiges RAG Chat-Interface."""
|
||||||
system_prompt = self.prompts.get("system_prompt", "")
|
provider = self.settings.MINDNET_LLM_PROVIDER
|
||||||
rag_template = self.prompts.get("rag_template", "{context_str}\n\n{query}")
|
system_prompt = self.get_prompt("system_prompt", provider)
|
||||||
|
rag_template = self.get_prompt("rag_template", provider)
|
||||||
|
|
||||||
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,
|
||||||
|
priority="realtime"
|
||||||
|
)
|
||||||
|
|
||||||
async def close(self):
|
async def close(self):
|
||||||
await self.client.aclose()
|
"""Schließt die HTTP-Verbindungen."""
|
||||||
|
if self.ollama_client:
|
||||||
|
await self.ollama_client.aclose()
|
||||||
@@ -0,0 +1,199 @@
|
|||||||
|
"""
|
||||||
|
FILE: app/services/semantic_analyzer.py
|
||||||
|
DESCRIPTION: KI-gestützte Kanten-Validierung. Nutzt LLM (Background-Priority), um Kanten präzise einem Chunk zuzuordnen.
|
||||||
|
WP-20 Fix: Volle Kompatibilität mit der provider-basierten Routing-Logik (OpenRouter Primary).
|
||||||
|
WP-22: Integration von valid_types zur Halluzinations-Vermeidung.
|
||||||
|
FIX: Mistral-sicheres JSON-Parsing (<s> & [OUT] Handling) und 100% Logik-Erhalt.
|
||||||
|
VERSION: 2.2.6
|
||||||
|
STATUS: Active
|
||||||
|
DEPENDENCIES: app.services.llm_service, app.services.edge_registry, json, logging, re
|
||||||
|
"""
|
||||||
|
|
||||||
|
import json
|
||||||
|
import logging
|
||||||
|
import re
|
||||||
|
from typing import List, Optional, Any
|
||||||
|
from dataclasses import dataclass
|
||||||
|
|
||||||
|
# Importe
|
||||||
|
from app.services.llm_service import LLMService
|
||||||
|
# WP-22: Registry für Vokabular-Erzwingung
|
||||||
|
from app.services.edge_registry import registry as edge_registry
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
class SemanticAnalyzer:
|
||||||
|
def __init__(self):
|
||||||
|
self.llm = LLMService()
|
||||||
|
|
||||||
|
def _is_valid_edge_string(self, edge_str: str) -> bool:
|
||||||
|
"""
|
||||||
|
Prüft, ob ein String eine valide Kante im Format 'kind:target' ist.
|
||||||
|
Verhindert, dass LLM-Geschwätz als Kante durchrutscht.
|
||||||
|
"""
|
||||||
|
if not isinstance(edge_str, str) or ":" not in edge_str:
|
||||||
|
return False
|
||||||
|
|
||||||
|
parts = edge_str.split(":", 1)
|
||||||
|
kind = parts[0].strip()
|
||||||
|
target = parts[1].strip()
|
||||||
|
|
||||||
|
# Regel 1: Ein 'kind' (Beziehungstyp) darf keine Leerzeichen enthalten.
|
||||||
|
if " " in kind:
|
||||||
|
return False
|
||||||
|
|
||||||
|
# Regel 2: Plausible Länge für den Typ (Vermeidet Sätze als Typ)
|
||||||
|
if len(kind) > 40 or len(kind) < 2:
|
||||||
|
return False
|
||||||
|
|
||||||
|
# Regel 3: Target darf nicht leer sein
|
||||||
|
if not target:
|
||||||
|
return False
|
||||||
|
|
||||||
|
return True
|
||||||
|
|
||||||
|
def _extract_json_safely(self, text: str) -> Any:
|
||||||
|
"""
|
||||||
|
Extrahiert JSON-Daten und bereinigt LLM-Steuerzeichen (Mistral/Llama).
|
||||||
|
Implementiert robuste Recovery-Logik für Cloud-Provider.
|
||||||
|
"""
|
||||||
|
if not text:
|
||||||
|
return []
|
||||||
|
|
||||||
|
# 1. Entferne Mistral/Llama Steuerzeichen und Tags
|
||||||
|
clean = text.replace("<s>", "").replace("</s>", "")
|
||||||
|
clean = clean.replace("[OUT]", "").replace("[/OUT]", "")
|
||||||
|
clean = clean.strip()
|
||||||
|
|
||||||
|
# 2. Suche nach Markdown JSON-Blöcken
|
||||||
|
match = re.search(r"```(?:json)?\s*(.*?)\s*```", clean, re.DOTALL)
|
||||||
|
payload = match.group(1) if match else clean
|
||||||
|
|
||||||
|
try:
|
||||||
|
return json.loads(payload.strip())
|
||||||
|
except json.JSONDecodeError:
|
||||||
|
# 3. Recovery: Suche nach der ersten [ und letzten ]
|
||||||
|
start = payload.find('[')
|
||||||
|
end = payload.rfind(']') + 1
|
||||||
|
if start != -1 and end > start:
|
||||||
|
try:
|
||||||
|
return json.loads(payload[start:end])
|
||||||
|
except: pass
|
||||||
|
|
||||||
|
# 4. Zweite Recovery: Suche nach der ersten { und letzten }
|
||||||
|
start_obj = payload.find('{')
|
||||||
|
end_obj = payload.rfind('}') + 1
|
||||||
|
if start_obj != -1 and end_obj > start_obj:
|
||||||
|
try:
|
||||||
|
return json.loads(payload[start_obj:end_obj])
|
||||||
|
except: pass
|
||||||
|
return []
|
||||||
|
|
||||||
|
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.
|
||||||
|
WP-20: Nutzt primär den konfigurierten Provider (z.B. OpenRouter).
|
||||||
|
"""
|
||||||
|
if not all_edges:
|
||||||
|
return []
|
||||||
|
|
||||||
|
# 1. Bestimmung des Providers und Modells (Dynamisch über Settings)
|
||||||
|
provider = self.llm.settings.MINDNET_LLM_PROVIDER
|
||||||
|
model = self.llm.settings.OPENROUTER_MODEL if provider == "openrouter" else self.llm.settings.GEMINI_MODEL
|
||||||
|
|
||||||
|
# 2. Prompt laden (Provider-spezifisch via get_prompt)
|
||||||
|
prompt_template = self.llm.get_prompt("edge_allocation_template", provider)
|
||||||
|
|
||||||
|
if not prompt_template or not isinstance(prompt_template, str):
|
||||||
|
logger.warning("⚠️ [SemanticAnalyzer] Prompt 'edge_allocation_template' ungültig. Nutze Recovery-Template.")
|
||||||
|
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\"]."
|
||||||
|
)
|
||||||
|
|
||||||
|
# 3. Daten für Template vorbereiten (Vokabular-Check)
|
||||||
|
edge_registry.ensure_latest()
|
||||||
|
valid_types_str = ", ".join(sorted(list(edge_registry.valid_types)))
|
||||||
|
edges_str = "\n".join([f"- {e}" for e in all_edges])
|
||||||
|
|
||||||
|
logger.debug(f"🔍 [SemanticAnalyzer] Request: {len(chunk_text)} chars Text, {len(all_edges)} Candidates.")
|
||||||
|
|
||||||
|
# 4. Prompt füllen mit Format-Check (Kein Shortcut)
|
||||||
|
try:
|
||||||
|
# Wir begrenzen den Text auf eine vernünftige Länge für das Kontextfenster
|
||||||
|
final_prompt = prompt_template.format(
|
||||||
|
chunk_text=chunk_text[:6000],
|
||||||
|
edge_list=edges_str,
|
||||||
|
valid_types=valid_types_str
|
||||||
|
)
|
||||||
|
except Exception as format_err:
|
||||||
|
logger.error(f"❌ [SemanticAnalyzer] Prompt Formatting failed: {format_err}")
|
||||||
|
return []
|
||||||
|
|
||||||
|
try:
|
||||||
|
# 5. LLM Call mit Background Priority & Semaphore Control
|
||||||
|
response_json = await self.llm.generate_raw_response(
|
||||||
|
prompt=final_prompt,
|
||||||
|
force_json=True,
|
||||||
|
max_retries=3,
|
||||||
|
base_delay=2.0,
|
||||||
|
priority="background",
|
||||||
|
provider=provider,
|
||||||
|
model_override=model
|
||||||
|
)
|
||||||
|
|
||||||
|
# 6. Mistral-sicheres JSON Parsing via Helper
|
||||||
|
data = self._extract_json_safely(response_json)
|
||||||
|
|
||||||
|
if not data:
|
||||||
|
return []
|
||||||
|
|
||||||
|
# 7. Robuste Normalisierung (List vs Dict Recovery)
|
||||||
|
raw_candidates = []
|
||||||
|
if isinstance(data, list):
|
||||||
|
raw_candidates = data
|
||||||
|
elif isinstance(data, dict):
|
||||||
|
logger.info(f"ℹ️ [SemanticAnalyzer] LLM returned dict, trying recovery.")
|
||||||
|
for key in ["edges", "results", "kanten", "matches"]:
|
||||||
|
if key in data and isinstance(data[key], list):
|
||||||
|
raw_candidates.extend(data[key])
|
||||||
|
break
|
||||||
|
# Falls immer noch leer, nutze Schlüssel-Wert Paare als Behelf
|
||||||
|
if not raw_candidates:
|
||||||
|
for k, v in data.items():
|
||||||
|
if isinstance(v, str): raw_candidates.append(f"{k}:{v}")
|
||||||
|
elif isinstance(v, list):
|
||||||
|
for target in v:
|
||||||
|
if isinstance(target, str): raw_candidates.append(f"{k}:{target}")
|
||||||
|
|
||||||
|
# 8. Strikte Validierung gegen Kanten-Format
|
||||||
|
valid_edges = []
|
||||||
|
for e in raw_candidates:
|
||||||
|
e_str = str(e).strip()
|
||||||
|
if self._is_valid_edge_string(e_str):
|
||||||
|
valid_edges.append(e_str)
|
||||||
|
else:
|
||||||
|
logger.debug(f" [SemanticAnalyzer] Rejected invalid edge format: '{e_str}'")
|
||||||
|
|
||||||
|
if valid_edges:
|
||||||
|
logger.info(f"✅ [SemanticAnalyzer] Assigned {len(valid_edges)} edges to chunk.")
|
||||||
|
return valid_edges
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"💥 [SemanticAnalyzer] Critical error during analysis: {e}", exc_info=True)
|
||||||
|
return []
|
||||||
|
|
||||||
|
async def close(self):
|
||||||
|
if self.llm:
|
||||||
|
await self.llm.close()
|
||||||
|
|
||||||
|
# Singleton Instanziierung
|
||||||
|
_analyzer_instance = None
|
||||||
|
def get_semantic_analyzer():
|
||||||
|
global _analyzer_instance
|
||||||
|
if _analyzer_instance is None:
|
||||||
|
_analyzer_instance = SemanticAnalyzer()
|
||||||
|
return _analyzer_instance
|
||||||
+69
-67
@@ -1,49 +1,62 @@
|
|||||||
# config/decision_engine.yaml
|
# config/decision_engine.yaml
|
||||||
# Steuerung der Decision Engine (WP-06 + WP-07)
|
# Steuerung der Decision Engine (Intent Recognition & Graph Routing)
|
||||||
# Hybrid-Modus: Keywords (Fast) + LLM Router (Smart Fallback)
|
# VERSION: 2.6.1 (WP-20: Hybrid LLM & WP-22: Semantic Graph Routing)
|
||||||
version: 1.3
|
# STATUS: Active
|
||||||
|
# DoD: Keine Hardcoded Modelle, volle Integration der strategischen Boosts.
|
||||||
|
|
||||||
|
version: 2.6
|
||||||
|
|
||||||
settings:
|
settings:
|
||||||
llm_fallback_enabled: true
|
llm_fallback_enabled: true
|
||||||
|
|
||||||
# Few-Shot Prompting für bessere SLM-Performance
|
# Strategie für den Router selbst (Welches Modell erkennt den Intent?)
|
||||||
# Erweitert um INTERVIEW Beispiele
|
# "auto" nutzt den in MINDNET_LLM_PROVIDER gesetzten Standard (z.B. openrouter).
|
||||||
|
router_provider: "auto"
|
||||||
|
|
||||||
|
# Few-Shot Prompting für den LLM-Router
|
||||||
llm_router_prompt: |
|
llm_router_prompt: |
|
||||||
Du bist ein Klassifikator. Analysiere die Nachricht und wähle die passende Strategie.
|
Du bist der zentrale Intent-Klassifikator für Mindnet, einen digitalen Zwilling.
|
||||||
|
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 strukturieren, Notizen anlegen, Projekte starten ("Neu", "Festhalten").
|
- INTERVIEW: User will Wissen erfassen, Notizen anlegen oder Dinge festhalten.
|
||||||
- DECISION: Rat, Strategie, Vor/Nachteile, "Soll ich".
|
- DECISION: Rat, Strategie, Abwägung von Werten, "Soll ich tun X?".
|
||||||
- EMPATHY: Gefühle, Frust, Freude, Probleme, "Alles ist sinnlos", "Ich bin traurig".
|
- EMPATHY: Gefühle, Reflexion der eigenen Verfassung, Frust, Freude.
|
||||||
- CODING: Code, Syntax, Programmierung, Python.
|
- CODING: Code-Erstellung, Debugging, technische Dokumentation.
|
||||||
- FACT: Wissen, Fakten, Definitionen.
|
- FACT: Reine Wissensabfrage, Definitionen, Suchen von Informationen.
|
||||||
|
|
||||||
BEISPIELE:
|
BEISPIELE:
|
||||||
User: "Wie funktioniert Qdrant?" -> FACT
|
User: "Wie funktioniert die Qdrant-Vektor-DB?" -> FACT
|
||||||
User: "Soll ich Qdrant nutzen?" -> DECISION
|
User: "Soll ich mein Startup jetzt verkaufen?" -> DECISION
|
||||||
User: "Ich möchte ein neues Projekt anlegen" -> INTERVIEW
|
User: "Notiere mir kurz meine Gedanken zum Meeting." -> INTERVIEW
|
||||||
User: "Lass uns eine Entscheidung festhalten" -> INTERVIEW
|
User: "Ich fühle mich heute sehr erschöpft." -> EMPATHY
|
||||||
User: "Schreibe ein Python Script" -> CODING
|
User: "Schreibe eine FastAPI-Route für den Ingest." -> CODING
|
||||||
User: "Alles ist grau und sinnlos" -> EMPATHY
|
|
||||||
User: "Mir geht es heute gut" -> EMPATHY
|
|
||||||
|
|
||||||
NACHRICHT: "{query}"
|
NACHRICHT: "{query}"
|
||||||
|
|
||||||
STRATEGIE:
|
STRATEGIE:
|
||||||
|
|
||||||
strategies:
|
strategies:
|
||||||
# 1. Fakten-Abfrage (Fallback & Default)
|
# 1. Fakten-Abfrage (Turbo-Modus via OpenRouter / Primary)
|
||||||
FACT:
|
FACT:
|
||||||
description: "Reine Wissensabfrage."
|
description: "Reine Wissensabfrage."
|
||||||
|
preferred_provider: "openrouter"
|
||||||
trigger_keywords: []
|
trigger_keywords: []
|
||||||
inject_types: []
|
inject_types: []
|
||||||
|
# WP-22: Definitionen & Hierarchien im Graphen bevorzugen
|
||||||
|
edge_boosts:
|
||||||
|
part_of: 2.0
|
||||||
|
composed_of: 2.0
|
||||||
|
similar_to: 1.5
|
||||||
|
caused_by: 0.5
|
||||||
prompt_template: "rag_template"
|
prompt_template: "rag_template"
|
||||||
prepend_instruction: null
|
prepend_instruction: null
|
||||||
|
|
||||||
# 2. Entscheidungs-Frage
|
# 2. Entscheidungs-Frage (Power-Strategie via Gemini)
|
||||||
DECISION:
|
DECISION:
|
||||||
description: "Der User sucht Rat, Strategie oder Abwägung."
|
description: "Der User sucht Rat, Strategie oder Abwägung."
|
||||||
|
preferred_provider: "gemini"
|
||||||
trigger_keywords:
|
trigger_keywords:
|
||||||
- "soll ich"
|
- "soll ich"
|
||||||
- "meinung"
|
- "meinung"
|
||||||
@@ -51,19 +64,25 @@ 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"]
|
||||||
|
# WP-22: Risiken und Konsequenzen im Graphen priorisieren
|
||||||
|
edge_boosts:
|
||||||
|
blocks: 2.5
|
||||||
|
solves: 2.0
|
||||||
|
depends_on: 1.5
|
||||||
|
risk_of: 2.5
|
||||||
|
impacts: 2.0
|
||||||
prompt_template: "decision_template"
|
prompt_template: "decision_template"
|
||||||
prepend_instruction: |
|
prepend_instruction: |
|
||||||
!!! ENTSCHEIDUNGS-MODUS !!!
|
!!! ENTSCHEIDUNGS-MODUS (HYBRID AI) !!!
|
||||||
BITTE WÄGE FAKTEN GEGEN FOLGENDE WERTE, PRINZIPIEN UND ZIELE AB:
|
BITTE WÄGE FAKTEN GEGEN FOLGENDE WERTE, PRINZIPIEN UND ZIELE AB:
|
||||||
|
|
||||||
# 3. Empathie / "Ich"-Modus
|
# 3. Empathie / "Ich"-Modus (Lokal & Privat via Ollama)
|
||||||
EMPATHY:
|
EMPATHY:
|
||||||
description: "Reaktion auf emotionale Zustände."
|
description: "Reaktion auf emotionale Zustände."
|
||||||
|
preferred_provider: "ollama"
|
||||||
trigger_keywords:
|
trigger_keywords:
|
||||||
- "ich fühle"
|
- "ich fühle"
|
||||||
- "traurig"
|
- "traurig"
|
||||||
@@ -72,13 +91,20 @@ strategies:
|
|||||||
- "angst"
|
- "angst"
|
||||||
- "nervt"
|
- "nervt"
|
||||||
- "überfordert"
|
- "überfordert"
|
||||||
|
- "müde"
|
||||||
inject_types: ["experience", "belief", "profile"]
|
inject_types: ["experience", "belief", "profile"]
|
||||||
|
edge_boosts:
|
||||||
|
based_on: 2.0
|
||||||
|
related_to: 2.0
|
||||||
|
experienced_in: 2.5
|
||||||
|
blocks: 0.1
|
||||||
prompt_template: "empathy_template"
|
prompt_template: "empathy_template"
|
||||||
prepend_instruction: null
|
prepend_instruction: null
|
||||||
|
|
||||||
# 4. Coding / Technical
|
# 4. Coding / Technical (Gemini Power)
|
||||||
CODING:
|
CODING:
|
||||||
description: "Technische Anfragen und Programmierung."
|
description: "Technische Anfragen und Programmierung."
|
||||||
|
preferred_provider: "gemini"
|
||||||
trigger_keywords:
|
trigger_keywords:
|
||||||
- "code"
|
- "code"
|
||||||
- "python"
|
- "python"
|
||||||
@@ -88,56 +114,32 @@ strategies:
|
|||||||
- "syntax"
|
- "syntax"
|
||||||
- "json"
|
- "json"
|
||||||
- "yaml"
|
- "yaml"
|
||||||
|
- "bash"
|
||||||
inject_types: ["snippet", "reference", "source"]
|
inject_types: ["snippet", "reference", "source"]
|
||||||
|
# WP-22: Technische Abhängigkeiten priorisieren
|
||||||
|
edge_boosts:
|
||||||
|
uses: 2.5
|
||||||
|
depends_on: 2.0
|
||||||
|
implemented_in: 3.0
|
||||||
prompt_template: "technical_template"
|
prompt_template: "technical_template"
|
||||||
prepend_instruction: null
|
prepend_instruction: null
|
||||||
|
|
||||||
# 5. Interview / Datenerfassung (WP-07)
|
# 5. Interview / Datenerfassung (Lokal)
|
||||||
INTERVIEW:
|
INTERVIEW:
|
||||||
description: "Der User möchte strukturiertes Wissen erfassen (Projekt, Notiz, Idee)."
|
description: "Der User möchte Wissen erfassen."
|
||||||
|
preferred_provider: "ollama"
|
||||||
trigger_keywords:
|
trigger_keywords:
|
||||||
- "neue notiz"
|
- "neue notiz"
|
||||||
- "neues projekt"
|
- "etwas notieren"
|
||||||
- "neue entscheidung"
|
|
||||||
- "neues ziel"
|
|
||||||
- "festhalten"
|
- "festhalten"
|
||||||
- "entwurf erstellen"
|
- "erstellen"
|
||||||
- "interview"
|
|
||||||
- "dokumentieren"
|
- "dokumentieren"
|
||||||
|
- "anlegen"
|
||||||
|
- "interview"
|
||||||
- "erfassen"
|
- "erfassen"
|
||||||
- "idee speichern"
|
- "idee speichern"
|
||||||
inject_types: [] # Keine RAG-Suche, reiner Kontext-Dialog
|
- "draft"
|
||||||
|
inject_types: []
|
||||||
|
edge_boosts: {}
|
||||||
prompt_template: "interview_template"
|
prompt_template: "interview_template"
|
||||||
prepend_instruction: null
|
prepend_instruction: null
|
||||||
|
|
||||||
# LATE BINDING SCHEMAS:
|
|
||||||
# Definition der Pflichtfelder pro Typ (korrespondiert mit types.yaml)
|
|
||||||
# Wenn ein Typ hier fehlt, wird 'default' genutzt.
|
|
||||||
schemas:
|
|
||||||
default:
|
|
||||||
fields: ["Titel", "Thema/Inhalt", "Tags"]
|
|
||||||
hint: "Halte es einfach und übersichtlich."
|
|
||||||
|
|
||||||
project:
|
|
||||||
fields: ["Titel", "Zielsetzung (Goal)", "Status (draft/active)", "Wichtige Stakeholder", "Nächste Schritte"]
|
|
||||||
hint: "Achte darauf, Abhängigkeiten zu anderen Projekten mit [[rel:depends_on]] zu erfragen."
|
|
||||||
|
|
||||||
decision:
|
|
||||||
fields: ["Titel", "Kontext (Warum entscheiden wir?)", "Getroffene Entscheidung", "Betrachtete Alternativen", "Status (proposed/final)"]
|
|
||||||
hint: "Wichtig: Frage explizit nach den Gründen gegen die Alternativen."
|
|
||||||
|
|
||||||
goal:
|
|
||||||
fields: ["Titel", "Zeitrahmen (Deadline)", "Messkriterien (KPIs)", "Verbundene Werte"]
|
|
||||||
hint: "Ziele sollten SMART formuliert sein."
|
|
||||||
|
|
||||||
experience:
|
|
||||||
fields: ["Titel", "Situation (Kontext)", "Erkenntnis (Learning)", "Emotionale Keywords (für Empathie-Suche)"]
|
|
||||||
hint: "Fokussiere dich auf die persönliche Lektion."
|
|
||||||
|
|
||||||
value:
|
|
||||||
fields: ["Titel (Name des Werts)", "Definition (Was bedeutet das für uns?)", "Anti-Beispiel (Was ist es nicht?)"]
|
|
||||||
hint: "Werte dienen als Entscheidungsgrundlage."
|
|
||||||
|
|
||||||
principle:
|
|
||||||
fields: ["Titel", "Handlungsanweisung", "Begründung"]
|
|
||||||
hint: "Prinzipien sind härter als Werte."
|
|
||||||
@@ -0,0 +1,48 @@
|
|||||||
|
# --- FastAPI Server (Produktion) ---
|
||||||
|
UVICORN_HOST=0.0.0.0
|
||||||
|
UVICORN_PORT=8000
|
||||||
|
DEBUG=false
|
||||||
|
|
||||||
|
# --- Qdrant Vektor-Datenbank ---
|
||||||
|
# Trennung der Daten durch eigenes Prefix
|
||||||
|
QDRANT_URL=http://127.0.0.1:6333
|
||||||
|
QDRANT_API_KEY=
|
||||||
|
COLLECTION_PREFIX=mindnet
|
||||||
|
|
||||||
|
# --- Vektoren-Konfiguration ---
|
||||||
|
# Muss 768 für 'nomic-embed-text' sein
|
||||||
|
VECTOR_DIM=768
|
||||||
|
|
||||||
|
# --- AI Modelle (Lokal/Fallback) ---
|
||||||
|
MINDNET_LLM_MODEL=phi3:mini
|
||||||
|
MINDNET_OLLAMA_URL=http://127.0.0.1:11434
|
||||||
|
MINDNET_LLM_TIMEOUT=300.0
|
||||||
|
MINDNET_LLM_BACKGROUND_LIMIT=2
|
||||||
|
|
||||||
|
# Vektor-Modell für semantische Suche
|
||||||
|
MINDNET_EMBEDDING_MODEL=nomic-embed-text
|
||||||
|
|
||||||
|
# --- WP-20/WP-76: Hybrid-Cloud & Resilienz ---
|
||||||
|
# Primärer Provider für höchste Qualität
|
||||||
|
MINDNET_LLM_PROVIDER=openrouter
|
||||||
|
MINDNET_LLM_FALLBACK=true
|
||||||
|
|
||||||
|
# Intelligente Rate-Limit Steuerung (Sekunden/Versuche)
|
||||||
|
MINDNET_LLM_RATE_LIMIT_WAIT=60.0
|
||||||
|
MINDNET_LLM_RATE_LIMIT_RETRIES=3
|
||||||
|
|
||||||
|
# --- Cloud Provider Keys (Hier Prod-Keys einsetzen) ---
|
||||||
|
GOOGLE_API_KEY=AIzaSy... (Dein Prod-Key)
|
||||||
|
MINDNET_GEMINI_MODEL=gemini-2.5-flash-lite
|
||||||
|
|
||||||
|
OPENROUTER_API_KEY=sk-or-v1-... (Dein Prod-Key)
|
||||||
|
# Stabilstes Free-Modell für strukturierte Extraktion
|
||||||
|
OPENROUTER_MODEL=mistralai/mistral-7b-instruct:free
|
||||||
|
|
||||||
|
# --- Pfade & System (Produktions-Vault) ---
|
||||||
|
MINDNET_TYPES_FILE=./config/types.yaml
|
||||||
|
MINDNET_VAULT_ROOT=./vault_prod
|
||||||
|
MINDNET_VOCAB_PATH=/mindnet/vault/mindnet/_system/dictionary/edge_vocabulary.md
|
||||||
|
|
||||||
|
# Change Detection für effiziente Re-Imports
|
||||||
|
MINDNET_CHANGE_DETECTION_MODE=full
|
||||||
+133
-34
@@ -1,4 +1,7 @@
|
|||||||
# config/prompts.yaml — Final V2.3.1 (Multi-Personality Support)
|
# config/prompts.yaml — Final V2.5.5 (OpenRouter Hardening)
|
||||||
|
# WP-20: Optimierte Cloud-Templates zur Unterdrückung von Modell-Geschwätz.
|
||||||
|
# FIX: Explizite Verbote für Einleitungstexte zur Vermeidung von JSON-Parsing-Fehlern.
|
||||||
|
# OLLAMA: UNVERÄNDERT laut Benutzeranweisung.
|
||||||
|
|
||||||
system_prompt: |
|
system_prompt: |
|
||||||
Du bist 'mindnet', mein digitaler Zwilling und strategischer Partner.
|
Du bist 'mindnet', mein digitaler Zwilling und strategischer Partner.
|
||||||
@@ -15,7 +18,8 @@ system_prompt: |
|
|||||||
# ---------------------------------------------------------
|
# ---------------------------------------------------------
|
||||||
# 1. STANDARD: Fakten & Wissen (Intent: FACT)
|
# 1. STANDARD: Fakten & Wissen (Intent: FACT)
|
||||||
# ---------------------------------------------------------
|
# ---------------------------------------------------------
|
||||||
rag_template: |
|
rag_template:
|
||||||
|
ollama: |
|
||||||
QUELLEN (WISSEN):
|
QUELLEN (WISSEN):
|
||||||
=========================================
|
=========================================
|
||||||
{context_str}
|
{context_str}
|
||||||
@@ -27,11 +31,21 @@ rag_template: |
|
|||||||
ANWEISUNG:
|
ANWEISUNG:
|
||||||
Beantworte die Frage präzise basierend auf den Quellen.
|
Beantworte die Frage präzise basierend auf den Quellen.
|
||||||
Fasse die Informationen zusammen. Sei objektiv und neutral.
|
Fasse die Informationen zusammen. Sei objektiv und neutral.
|
||||||
|
gemini: |
|
||||||
|
Kontext meines digitalen Zwillings: {context_str}
|
||||||
|
Beantworte strukturiert und präzise: {query}
|
||||||
|
openrouter: |
|
||||||
|
Kontext-Analyse für den digitalen Zwilling:
|
||||||
|
{context_str}
|
||||||
|
|
||||||
|
Anfrage: {query}
|
||||||
|
Antworte basierend auf dem Kontext.
|
||||||
|
|
||||||
# ---------------------------------------------------------
|
# ---------------------------------------------------------
|
||||||
# 2. DECISION: Strategie & Abwägung (Intent: DECISION)
|
# 2. DECISION: Strategie & Abwägung (Intent: DECISION)
|
||||||
# ---------------------------------------------------------
|
# ---------------------------------------------------------
|
||||||
decision_template: |
|
decision_template:
|
||||||
|
ollama: |
|
||||||
KONTEXT (FAKTEN & STRATEGIE):
|
KONTEXT (FAKTEN & STRATEGIE):
|
||||||
=========================================
|
=========================================
|
||||||
{context_str}
|
{context_str}
|
||||||
@@ -49,12 +63,18 @@ decision_template: |
|
|||||||
FORMAT:
|
FORMAT:
|
||||||
- **Analyse:** (Kurze Zusammenfassung der Fakten)
|
- **Analyse:** (Kurze Zusammenfassung der Fakten)
|
||||||
- **Abgleich:** (Gibt es Konflikte mit Werten/Zielen? Nenne die Quelle!)
|
- **Abgleich:** (Gibt es Konflikte mit Werten/Zielen? Nenne die Quelle!)
|
||||||
- **Empfehlung:** (Klare Meinung: Ja/Nein/Vielleicht mit Begründung)
|
- **Empfehlung:** (Klare Meinung: Ja/No/Vielleicht mit Begründung)
|
||||||
|
gemini: |
|
||||||
|
Agiere als strategischer Partner. Analysiere die Frage {query} basierend auf meinen Werten im Kontext {context_str}.
|
||||||
|
openrouter: |
|
||||||
|
Strategische Entscheidungsanalyse: {query}
|
||||||
|
Wertebasis aus dem Graphen: {context_str}
|
||||||
|
|
||||||
# ---------------------------------------------------------
|
# ---------------------------------------------------------
|
||||||
# 3. EMPATHY: Der Spiegel / "Ich"-Modus (Intent: EMPATHY)
|
# 3. EMPATHY: Der Spiegel / "Ich"-Modus (Intent: EMPATHY)
|
||||||
# ---------------------------------------------------------
|
# ---------------------------------------------------------
|
||||||
empathy_template: |
|
empathy_template:
|
||||||
|
ollama: |
|
||||||
KONTEXT (ERFAHRUNGEN & GLAUBENSSÄTZE):
|
KONTEXT (ERFAHRUNGEN & GLAUBENSSÄTZE):
|
||||||
=========================================
|
=========================================
|
||||||
{context_str}
|
{context_str}
|
||||||
@@ -71,11 +91,14 @@ empathy_template: |
|
|||||||
|
|
||||||
TONFALL:
|
TONFALL:
|
||||||
Ruhig, verständnisvoll, reflektiert. Keine Aufzählungszeichen, sondern fließender Text.
|
Ruhig, verständnisvoll, reflektiert. Keine Aufzählungszeichen, sondern fließender Text.
|
||||||
|
gemini: "Sei mein digitaler Spiegel für {query}. Kontext: {context_str}"
|
||||||
|
openrouter: "Empathische Reflexion der Situation {query}. Persönlicher Kontext: {context_str}"
|
||||||
|
|
||||||
# ---------------------------------------------------------
|
# ---------------------------------------------------------
|
||||||
# 4. TECHNICAL: Der Coder (Intent: CODING)
|
# 4. TECHNICAL: Der Coder (Intent: CODING)
|
||||||
# ---------------------------------------------------------
|
# ---------------------------------------------------------
|
||||||
technical_template: |
|
technical_template:
|
||||||
|
ollama: |
|
||||||
KONTEXT (DOCS & SNIPPETS):
|
KONTEXT (DOCS & SNIPPETS):
|
||||||
=========================================
|
=========================================
|
||||||
{context_str}
|
{context_str}
|
||||||
@@ -94,47 +117,123 @@ technical_template: |
|
|||||||
- 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.
|
||||||
|
gemini: "Generiere Code für {query} unter Berücksichtigung von {context_str}."
|
||||||
|
openrouter: "Technischer Support für {query}. Code-Referenzen: {context_str}"
|
||||||
|
|
||||||
# ---------------------------------------------------------
|
# ---------------------------------------------------------
|
||||||
# 5. INTERVIEW: Der "One-Shot Extractor" (Performance Mode)
|
# 5. INTERVIEW: Der "One-Shot Extractor" (Performance Mode)
|
||||||
# ---------------------------------------------------------
|
# ---------------------------------------------------------
|
||||||
|
interview_template:
|
||||||
interview_template: |
|
ollama: |
|
||||||
TASK:
|
TASK:
|
||||||
Erstelle einen Markdown-Entwurf für eine Notiz vom Typ '{target_type}'.
|
Du bist ein professioneller Ghostwriter. Verwandle den "USER INPUT" in eine strukturierte Notiz vom Typ '{target_type}'.
|
||||||
|
|
||||||
SCHEMA (Inhaltliche Pflichtfelder für den Body):
|
STRUKTUR (Nutze EXAKT diese Überschriften):
|
||||||
{schema_fields}
|
{schema_fields}
|
||||||
|
|
||||||
USER INPUT:
|
USER INPUT:
|
||||||
"{query}"
|
"{query}"
|
||||||
|
|
||||||
ANWEISUNG:
|
ANWEISUNG ZUM INHALT:
|
||||||
1. Extrahiere Informationen aus dem Input.
|
1. Analysiere den Input genau.
|
||||||
2. Generiere validen Markdown.
|
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 REGELN (STRIKT BEACHTEN):
|
OUTPUT FORMAT (YAML + MARKDOWN):
|
||||||
A. FRONTMATTER (YAML):
|
|
||||||
- Darf NUR folgende Felder enthalten: [type, status, title, tags].
|
|
||||||
- Schreibe KEINE inhaltlichen Sätze (wie 'Situation', 'Ziel') in das YAML!
|
|
||||||
- Setze 'status: draft'.
|
|
||||||
|
|
||||||
B. BODY (Markdown):
|
|
||||||
- Nutze für jedes Schema-Feld eine Markdown-Überschrift (## Feldname).
|
|
||||||
- Schreibe den Inhalt DARUNTER.
|
|
||||||
- Nutze "[TODO: Ergänzen]", wenn Infos fehlen.
|
|
||||||
|
|
||||||
HINWEIS ZUM TYP:
|
|
||||||
{schema_hint}
|
|
||||||
|
|
||||||
OUTPUT FORMAT BEISPIEL:
|
|
||||||
```markdown
|
|
||||||
---
|
---
|
||||||
type: {target_type}
|
type: {target_type}
|
||||||
status: draft
|
status: draft
|
||||||
title: ...
|
title: (Erstelle einen treffenden, kurzen Titel für den Inhalt)
|
||||||
tags: [...]
|
tags: [Tag1, Tag2]
|
||||||
---
|
---
|
||||||
# Titel der Notiz
|
|
||||||
|
|
||||||
## Erstes Schema Feld
|
# (Wiederhole den Titel hier)
|
||||||
Der Inhalt hier...
|
|
||||||
|
## (Erster Begriff aus STRUKTUR)
|
||||||
|
(Text...)
|
||||||
|
|
||||||
|
## (Zweiter Begriff aus STRUKTUR)
|
||||||
|
(Text...)
|
||||||
|
gemini: "Extrahiere Daten für {target_type} aus {query}."
|
||||||
|
openrouter: "Strukturiere den Input {query} nach dem Schema {schema_fields} für Typ {target_type}."
|
||||||
|
|
||||||
|
# ---------------------------------------------------------
|
||||||
|
# 6. EDGE_ALLOCATION: Kantenfilter (Intent: OFFLINE_FILTER)
|
||||||
|
# ---------------------------------------------------------
|
||||||
|
edge_allocation_template:
|
||||||
|
ollama: |
|
||||||
|
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.
|
||||||
|
2. Gib NUR die Strings aus der Kandidaten-Liste zurück, die zum Text passen.
|
||||||
|
3. Erfinde KEINE neuen Kanten.
|
||||||
|
4. Antworte als flache JSON-Liste.
|
||||||
|
|
||||||
|
DEIN OUTPUT (JSON):
|
||||||
|
gemini: |
|
||||||
|
TASK: Ordne Kanten einem Textabschnitt zu.
|
||||||
|
ERLAUBTE TYPEN: {valid_types}
|
||||||
|
TEXT: {chunk_text}
|
||||||
|
KANDIDATEN: {edge_list}
|
||||||
|
OUTPUT: STRIKT eine flache JSON-Liste ["typ:ziel"]. Kein Text davor/danach. Wenn nichts: []. Keine Objekte!
|
||||||
|
openrouter: |
|
||||||
|
TASK: Filtere relevante Kanten aus dem Pool.
|
||||||
|
ERLAUBTE TYPEN: {valid_types}
|
||||||
|
TEXT: {chunk_text}
|
||||||
|
POOL: {edge_list}
|
||||||
|
ANWEISUNG: Gib NUR eine flache JSON-Liste von Strings zurück.
|
||||||
|
BEISPIEL: ["kind:target", "kind:target"]
|
||||||
|
REGEL: Kein Text, keine Analyse, keine Kommentare. Wenn nichts passt, gib [] zurück.
|
||||||
|
OUTPUT:
|
||||||
|
|
||||||
|
# ---------------------------------------------------------
|
||||||
|
# 7. SMART EDGE ALLOCATION: Extraktion (Intent: INGEST)
|
||||||
|
# ---------------------------------------------------------
|
||||||
|
edge_extraction:
|
||||||
|
ollama: |
|
||||||
|
TASK:
|
||||||
|
Du bist ein Wissens-Ingenieur für den digitalen Zwilling 'mindnet'.
|
||||||
|
Deine Aufgabe ist es, semantische Relationen (Kanten) aus dem Text zu extrahieren,
|
||||||
|
die die Hauptnotiz '{note_id}' mit anderen Konzepten verbinden.
|
||||||
|
|
||||||
|
ANWEISUNGEN:
|
||||||
|
1. Identifiziere wichtige Entitäten, Konzepte oder Ereignisse im Text.
|
||||||
|
2. Bestimme die Art der Beziehung (z.B. part_of, uses, related_to, blocks, caused_by).
|
||||||
|
3. Das Ziel (target) muss ein prägnanter Begriff sein.
|
||||||
|
4. Antworte AUSSCHLIESSLICH in validem JSON als Liste von Objekten.
|
||||||
|
|
||||||
|
BEISPIEL:
|
||||||
|
[[ {{"to": "Ziel-Konzept", "kind": "beziehungs_typ"}} ]]
|
||||||
|
|
||||||
|
TEXT:
|
||||||
|
"""
|
||||||
|
{text}
|
||||||
|
"""
|
||||||
|
|
||||||
|
DEIN OUTPUT (JSON):
|
||||||
|
gemini: |
|
||||||
|
Analysiere '{note_id}'. Extrahiere semantische Beziehungen.
|
||||||
|
ERLAUBTE TYPEN: {valid_types}
|
||||||
|
TEXT: {text}
|
||||||
|
OUTPUT: STRIKT JSON-Array von Objekten: [[{{"to":"Ziel","kind":"typ"}}]]. Kein Text davor/danach. Wenn nichts: [].
|
||||||
|
openrouter: |
|
||||||
|
TASK: Extrahiere semantische Relationen für '{note_id}'.
|
||||||
|
ERLAUBTE TYPEN: {valid_types}
|
||||||
|
TEXT: {text}
|
||||||
|
ANWEISUNG: Antworte AUSSCHLIESSLICH mit einem JSON-Array von Objekten.
|
||||||
|
FORMAT: [[{{"to":"Ziel-Begriff","kind":"typ"}}]]
|
||||||
|
STRIKTES VERBOT: Schreibe keine Einleitung, keine Analyse und keine Erklärungen.
|
||||||
|
Wenn keine Relationen existieren, antworte NUR mit: []
|
||||||
|
OUTPUT:
|
||||||
+44
-10
@@ -1,4 +1,4 @@
|
|||||||
version: 1.0
|
version: 1.2
|
||||||
|
|
||||||
scoring:
|
scoring:
|
||||||
# W_sem: skaliert den Term (semantic_score * retriever_weight)
|
# W_sem: skaliert den Term (semantic_score * retriever_weight)
|
||||||
@@ -6,20 +6,54 @@ scoring:
|
|||||||
semantic_weight: 1.0
|
semantic_weight: 1.0
|
||||||
|
|
||||||
# W_edge: skaliert edge_bonus aus dem Subgraph
|
# W_edge: skaliert edge_bonus aus dem Subgraph
|
||||||
# Empfehlung: 0.7 → Graph ist deutlich spürbar, aber überstimmt Semantik nicht komplett
|
# Empfehlung: 0.8 → Graph ist deutlich spürbar, aber überstimmt Semantik nicht komplett
|
||||||
edge_weight: 0.7
|
edge_weight: 0.8
|
||||||
|
|
||||||
# W_cent: skaliert centrality_bonus (Knoten-Zentralität im Subgraph)
|
# W_cent: skaliert centrality_bonus (Knoten-Zentralität im Subgraph)
|
||||||
# Empfehlung: 0.5 → zentrale Knoten werden bevorzugt, aber moderat
|
# Empfehlung: 0.5 → zentrale Knoten werden bevorzugt, aber moderat
|
||||||
centrality_weight: 0.5
|
centrality_weight: 0.5
|
||||||
|
|
||||||
|
# WP-22 Stellschraube: Lifecycle (Status-basiertes Scoring)
|
||||||
|
# Bonus für verifiziertes Wissen, Malus für Entwürfe
|
||||||
|
lifecycle_weights:
|
||||||
|
stable: 1.2 # +20% Bonus
|
||||||
|
active: 1.0 # Standardwert
|
||||||
|
draft: 0.5 # -50% Malus
|
||||||
|
system: 0.0 # Hard Skip via Ingestion
|
||||||
|
|
||||||
# Die nachfolgenden Werte überschreiben die Defaults aus app/core/retriever_config.
|
# Die nachfolgenden Werte überschreiben die Defaults aus app/core/retriever_config.
|
||||||
# Wenn neue Kantentypen, z.B. durch Referenzierung innerhalb einer md-Datei im vault anders gewichtet werden sollen, dann muss hier die Konfiguration erfolgen
|
# Wenn neue Kantentypen, z.B. durch Referenzierung innerhalb einer md-Datei im vault anders gewichtet werden sollen, dann muss hier die Konfiguration erfolgen
|
||||||
edge_types:
|
edge_types:
|
||||||
references: 0.20
|
# --- KATEGORIE 1: LOGIK-BOOSTS (Relevanz-Treiber) ---
|
||||||
depends_on: 0.18
|
# Diese Kanten haben die Kraft, das semantische Ranking aktiv umzugestalten.
|
||||||
related_to: 0.15
|
blocks: 1.6 # Kritisch: Risiken/Blocker müssen sofort sichtbar sein.
|
||||||
similar_to: 0.12
|
solves: 1.5 # Zielführend: Lösungen sind primäre Suchziele.
|
||||||
belongs_to: 0.10
|
depends_on: 1.4 # Logisch: Harte fachliche Abhängigkeit.
|
||||||
next: 0.06
|
resulted_in: 1.4 # Kausal: Ergebnisse und unmittelbare Konsequenzen.
|
||||||
prev: 0.06
|
followed_by: 1.3 # Sequenziell (User): Bewusst gesteuerte Wissenspfade.
|
||||||
|
caused_by: 1.2 # Kausal: Ursachen-Bezug (Basis für Intent-Boost).
|
||||||
|
preceded_by: 1.1 # Sequenziell (User): Rückwärts-Bezug in Logik-Ketten.
|
||||||
|
impacts: 1.2 # Langfristige Auswirkung/Einfluss
|
||||||
|
|
||||||
|
# --- KATEGORIE 2: QUALITATIVER KONTEXT (Stabilitäts-Stützen) ---
|
||||||
|
# Diese Kanten liefern wichtigen Kontext, ohne das Ergebnis zu verfälschen.
|
||||||
|
guides: 1.1 # Qualitativ: Prinzipien oder Werte leiten das Thema.
|
||||||
|
part_of: 1.1 # Strukturell: Zieht übergeordnete Kontexte (Parents) mit hoch.
|
||||||
|
based_on: 0.8 # Fundament: Bezug auf Basis-Werte (kalibriert auf Safe-Retrieval).
|
||||||
|
derived_from: 0.6 # Historisch: Dokumentiert die Herkunft von Wissen.
|
||||||
|
uses: 0.6 # Instrumentell: Genutzte Werkzeuge, Methoden oder Ressourcen.
|
||||||
|
|
||||||
|
# --- KATEGORIE 3: THEMATISCHE NÄHE (Ähnlichkeits-Signal) ---
|
||||||
|
# Diese Werte verhindern den "Drift" in fachfremde Bereiche.
|
||||||
|
similar_to: 0.4 # Analytisch: Thematische Nähe (oft KI-generiert).
|
||||||
|
|
||||||
|
# --- KATEGORIE 4: SYSTEM-NUDGES (Technische Struktur) ---
|
||||||
|
# Reine Orientierungshilfen für das System; fast kein Einfluss auf das Ranking.
|
||||||
|
belongs_to: 0.2 # System: Verknüpft Chunks mit der Note (Metadaten-Träger).
|
||||||
|
next: 0.1 # System: Technische Lesereihenfolge der Absätze.
|
||||||
|
prev: 0.1 # System: Technische Lesereihenfolge der Absätze.
|
||||||
|
|
||||||
|
# --- KATEGORIE 5: WEICHE ASSOZIATIONEN (Rausch-Unterdrückung) ---
|
||||||
|
# Verhindert, dass lose Verknüpfungen das Ergebnis "verwässern".
|
||||||
|
references: 0.1 # Assoziativ: Einfacher Querverweis oder Erwähnung.
|
||||||
|
related_to: 0.05 # Minimal: Schwächste thematische Verbindung.
|
||||||
+304
-55
@@ -1,76 +1,325 @@
|
|||||||
version: 1.0
|
version: 2.6.0 # Final WP-15 Config: Smart Edges & Strict/Soft Chunking
|
||||||
|
|
||||||
|
# ==============================================================================
|
||||||
|
# 1. CHUNKING PROFILES
|
||||||
|
# ==============================================================================
|
||||||
|
|
||||||
|
chunking_profiles:
|
||||||
|
|
||||||
|
# A. SHORT & FAST
|
||||||
|
sliding_short:
|
||||||
|
strategy: sliding_window
|
||||||
|
enable_smart_edge_allocation: false
|
||||||
|
target: 200
|
||||||
|
max: 350
|
||||||
|
overlap: [30, 50]
|
||||||
|
|
||||||
|
# B. STANDARD & FAST
|
||||||
|
sliding_standard:
|
||||||
|
strategy: sliding_window
|
||||||
|
enable_smart_edge_allocation: false
|
||||||
|
target: 450
|
||||||
|
max: 650
|
||||||
|
overlap: [50, 100]
|
||||||
|
|
||||||
|
# C. SMART FLOW (Text-Fluss)
|
||||||
|
# Nutzt Sliding Window, aber mit LLM-Kanten-Analyse.
|
||||||
|
sliding_smart_edges:
|
||||||
|
strategy: sliding_window
|
||||||
|
enable_smart_edge_allocation: true
|
||||||
|
target: 400
|
||||||
|
max: 600
|
||||||
|
overlap: [50, 80]
|
||||||
|
|
||||||
|
# D. SMART STRUCTURE (Soft Split)
|
||||||
|
# Trennt bevorzugt an H2, fasst aber kleine Abschnitte zusammen ("Soft Mode").
|
||||||
|
structured_smart_edges:
|
||||||
|
strategy: by_heading
|
||||||
|
enable_smart_edge_allocation: true
|
||||||
|
split_level: 2
|
||||||
|
strict_heading_split: false
|
||||||
|
max: 600
|
||||||
|
target: 400
|
||||||
|
overlap: [50, 80]
|
||||||
|
|
||||||
|
# E. SMART STRUCTURE STRICT (H2 Hard Split)
|
||||||
|
# Trennt ZWINGEND an jeder H2.
|
||||||
|
# Verhindert, dass "Vater" und "Partner" (Profile) oder Werte verschmelzen.
|
||||||
|
structured_smart_edges_strict:
|
||||||
|
strategy: by_heading
|
||||||
|
enable_smart_edge_allocation: true
|
||||||
|
split_level: 2
|
||||||
|
strict_heading_split: true # Hard Mode
|
||||||
|
max: 600
|
||||||
|
target: 400
|
||||||
|
overlap: [50, 80]
|
||||||
|
|
||||||
|
# F. SMART STRUCTURE DEEP (H3 Hard Split + Merge-Check)
|
||||||
|
# Spezialfall für "Leitbild Prinzipien":
|
||||||
|
# - Trennt H1, H2, H3 hart.
|
||||||
|
# - Aber: Merged "leere" H2 (Tier 2) mit der folgenden H3 (MP1).
|
||||||
|
structured_smart_edges_strict_L3:
|
||||||
|
strategy: by_heading
|
||||||
|
enable_smart_edge_allocation: true
|
||||||
|
split_level: 3
|
||||||
|
strict_heading_split: true
|
||||||
|
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:
|
experience:
|
||||||
chunk_profile: short
|
chunking_profile: sliding_smart_edges
|
||||||
retriever_weight: 0.50
|
retriever_weight: 1.10 # Erhöht für biografische Relevanz
|
||||||
edge_defaults: [] # Quellen sind i. d. R. Ziel von Kanten, erzeugen selbst keine Default-Kanten
|
edge_defaults: ["derived_from", "references"]
|
||||||
|
detection_keywords: ["erleben", "reagieren", "handeln", "prägen", "reflektieren"]
|
||||||
|
schema:
|
||||||
|
- "Situation (Was ist passiert?)"
|
||||||
|
- "Meine Reaktion (Was habe ich getan?)"
|
||||||
|
- "Ergebnis & Auswirkung"
|
||||||
|
- "Reflexion & Learning (Was lerne ich daraus?)"
|
||||||
|
|
||||||
glossary:
|
insight:
|
||||||
chunk_profile: short
|
chunking_profile: sliding_smart_edges
|
||||||
retriever_weight: 0.40
|
retriever_weight: 1.20 # Hoch gewichtet für aktuelle Steuerung
|
||||||
edge_defaults: ["related_to"]
|
edge_defaults: ["references", "based_on"]
|
||||||
|
detection_keywords: ["beobachten", "erkennen", "verstehen", "analysieren", "schlussfolgern"]
|
||||||
|
schema:
|
||||||
|
- "Beobachtung (Was sehe ich?)"
|
||||||
|
- "Interpretation (Was bedeutet das?)"
|
||||||
|
- "Bedürfnis (Was steckt dahinter?)"
|
||||||
|
- "Handlungsempfehlung"
|
||||||
|
|
||||||
# Person & Persönlichkeit
|
project:
|
||||||
profile: # z. B. "Persönliches Leitbild (Kurzprofil)"
|
chunking_profile: sliding_smart_edges
|
||||||
chunk_profile: long
|
retriever_weight: 0.97
|
||||||
retriever_weight: 0.66
|
edge_defaults: ["references", "depends_on"]
|
||||||
edge_defaults: ["references", "related_to"]
|
detection_keywords: ["umsetzen", "planen", "starten", "bauen", "abschließen"]
|
||||||
|
schema:
|
||||||
value: # Werte (z. B. "Mut", "Fairness")
|
- "Mission & Zielsetzung"
|
||||||
chunk_profile: short
|
- "Aktueller Status & Blockaden"
|
||||||
retriever_weight: 0.90
|
- "Nächste konkrete Schritte"
|
||||||
edge_defaults: ["related_to"]
|
|
||||||
|
|
||||||
principle: # Prinzipien/Leitsätze
|
|
||||||
chunk_profile: short
|
|
||||||
retriever_weight: 0.90
|
|
||||||
edge_defaults: ["related_to", "references"]
|
|
||||||
|
|
||||||
experience: # prägende Erlebnisse/Erfahrungen
|
|
||||||
chunk_profile: medium
|
|
||||||
retriever_weight: 0.90
|
|
||||||
edge_defaults: ["related_to", "references"]
|
|
||||||
|
|
||||||
# Ziele, Entscheidungen, Meilensteine
|
|
||||||
goal:
|
|
||||||
chunk_profile: medium
|
|
||||||
retriever_weight: 0.90
|
|
||||||
edge_defaults: ["depends_on", "related_to", "references"]
|
|
||||||
|
|
||||||
decision:
|
decision:
|
||||||
chunk_profile: short
|
chunking_profile: structured_smart_edges_strict
|
||||||
|
retriever_weight: 1.00
|
||||||
|
edge_defaults: ["caused_by", "references"]
|
||||||
|
detection_keywords: ["entscheiden", "wählen", "abwägen", "priorisieren", "festlegen"]
|
||||||
|
schema:
|
||||||
|
- "Kontext & Problemstellung"
|
||||||
|
- "Betrachtete Optionen"
|
||||||
|
- "Die Entscheidung"
|
||||||
|
- "Begründung"
|
||||||
|
|
||||||
|
# --- PERSÖNLICHKEIT & IDENTITÄT ---
|
||||||
|
|
||||||
|
value:
|
||||||
|
chunking_profile: structured_smart_edges_strict
|
||||||
|
retriever_weight: 1.00
|
||||||
|
edge_defaults: ["related_to"]
|
||||||
|
detection_keywords: ["werten", "achten", "verpflichten", "bedeuten"]
|
||||||
|
schema:
|
||||||
|
- "Definition"
|
||||||
|
- "Warum mir das wichtig ist"
|
||||||
|
- "Leitsätze"
|
||||||
|
|
||||||
|
principle:
|
||||||
|
chunking_profile: structured_smart_edges_strict_L3
|
||||||
|
retriever_weight: 0.95
|
||||||
|
edge_defaults: ["derived_from", "references"]
|
||||||
|
detection_keywords: ["leiten", "steuern", "ausrichten", "handhaben"]
|
||||||
|
schema:
|
||||||
|
- "Das Prinzip"
|
||||||
|
- "Anwendung & Beispiele"
|
||||||
|
|
||||||
|
trait:
|
||||||
|
chunking_profile: structured_smart_edges_strict
|
||||||
|
retriever_weight: 1.10
|
||||||
|
edge_defaults: ["related_to"]
|
||||||
|
detection_keywords: ["begeistern", "können", "auszeichnen", "befähigen", "stärken"]
|
||||||
|
schema:
|
||||||
|
- "Eigenschaft / Talent"
|
||||||
|
- "Beispiele aus der Praxis"
|
||||||
|
- "Potenzial für die Zukunft"
|
||||||
|
|
||||||
|
obstacle:
|
||||||
|
chunking_profile: structured_smart_edges_strict
|
||||||
|
retriever_weight: 1.00
|
||||||
|
edge_defaults: ["blocks", "related_to"]
|
||||||
|
detection_keywords: ["blockieren", "fürchten", "vermeiden", "hindern", "zweifeln"]
|
||||||
|
schema:
|
||||||
|
- "Beschreibung der Hürde"
|
||||||
|
- "Ursprung / Auslöser"
|
||||||
|
- "Auswirkung auf Ziele"
|
||||||
|
- "Gegenstrategie"
|
||||||
|
|
||||||
|
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: ["glauben", "meinen", "annehmen", "überzeugen"]
|
||||||
|
schema:
|
||||||
|
- "Der Glaubenssatz"
|
||||||
|
- "Ursprung & Reflexion"
|
||||||
|
|
||||||
milestone:
|
profile:
|
||||||
chunk_profile: short
|
chunking_profile: structured_smart_edges_strict
|
||||||
retriever_weight: 0.70
|
retriever_weight: 0.70
|
||||||
edge_defaults: ["related_to", "references"]
|
edge_defaults: ["references", "related_to"]
|
||||||
|
detection_keywords: ["verkörpern", "verantworten", "agieren", "repräsentieren"]
|
||||||
|
schema:
|
||||||
|
- "Rolle / Identität"
|
||||||
|
- "Fakten & Daten"
|
||||||
|
- "Historie"
|
||||||
|
|
||||||
# Operativ: Projekte, Aufgaben, Journal
|
|
||||||
project:
|
idea:
|
||||||
chunk_profile: long
|
chunking_profile: sliding_short
|
||||||
retriever_weight: 0.97
|
retriever_weight: 0.70
|
||||||
edge_defaults: ["references", "depends_on"] # Projekt stützt sich auf Konzepte/Quellen und hängt von Bausteinen ab
|
edge_defaults: ["leads_to", "references"]
|
||||||
|
detection_keywords: ["einfall", "gedanke", "potenzial", "möglichkeit"]
|
||||||
|
schema:
|
||||||
|
- "Der Kerngedanke"
|
||||||
|
- "Potenzial & Auswirkung"
|
||||||
|
- "Nächste Schritte"
|
||||||
|
|
||||||
|
skill:
|
||||||
|
chunking_profile: sliding_smart_edges
|
||||||
|
retriever_weight: 0.90
|
||||||
|
edge_defaults: ["references", "related_to"]
|
||||||
|
detection_keywords: ["lernen", "beherrschen", "üben", "fertigkeit", "kompetenz"]
|
||||||
|
schema:
|
||||||
|
- "Definition der Fähigkeit"
|
||||||
|
- "Aktueller Stand & Lernpfad"
|
||||||
|
- "Evidenz (Proof of Work)"
|
||||||
|
|
||||||
|
habit:
|
||||||
|
chunking_profile: sliding_short
|
||||||
|
retriever_weight: 0.85
|
||||||
|
edge_defaults: ["related_to", "triggered_by"]
|
||||||
|
detection_keywords: ["gewohnheit", "routine", "automatismus", "immer wenn"]
|
||||||
|
schema:
|
||||||
|
- "Auslöser (Trigger)"
|
||||||
|
- "Routine (Handlung)"
|
||||||
|
- "Belohnung (Reward)"
|
||||||
|
- "Strategie"
|
||||||
|
|
||||||
|
need:
|
||||||
|
chunking_profile: sliding_smart_edges
|
||||||
|
retriever_weight: 1.05
|
||||||
|
edge_defaults: ["related_to", "impacts"]
|
||||||
|
detection_keywords: ["bedürfnis", "brauchen", "mangel", "erfüllung"]
|
||||||
|
schema:
|
||||||
|
- "Das Bedürfnis"
|
||||||
|
- "Zustand (Mangel vs. Erfüllung)"
|
||||||
|
- "Bezug zu Werten"
|
||||||
|
|
||||||
|
motivation:
|
||||||
|
chunking_profile: sliding_smart_edges
|
||||||
|
retriever_weight: 0.95
|
||||||
|
edge_defaults: ["drives", "references"]
|
||||||
|
detection_keywords: ["motivation", "antrieb", "warum", "energie"]
|
||||||
|
schema:
|
||||||
|
- "Der Antrieb"
|
||||||
|
- "Zielbezug"
|
||||||
|
- "Energiequelle"
|
||||||
|
|
||||||
|
bias:
|
||||||
|
chunking_profile: sliding_short
|
||||||
|
retriever_weight: 0.80
|
||||||
|
edge_defaults: ["affects", "related_to"]
|
||||||
|
detection_keywords: ["denkfehler", "verzerrung", "vorurteil", "falle"]
|
||||||
|
schema: ["Beschreibung der Verzerrung", "Typische Situationen", "Gegenstrategie"]
|
||||||
|
|
||||||
|
state:
|
||||||
|
chunking_profile: sliding_short
|
||||||
|
retriever_weight: 0.60
|
||||||
|
edge_defaults: ["impacts"]
|
||||||
|
detection_keywords: ["stimmung", "energie", "gefühl", "verfassung"]
|
||||||
|
schema: ["Aktueller Zustand", "Auslöser", "Auswirkung auf den Tag"]
|
||||||
|
|
||||||
|
boundary:
|
||||||
|
chunking_profile: sliding_smart_edges
|
||||||
|
retriever_weight: 0.90
|
||||||
|
edge_defaults: ["protects", "related_to"]
|
||||||
|
detection_keywords: ["grenze", "nein sagen", "limit", "schutz"]
|
||||||
|
schema: ["Die Grenze", "Warum sie wichtig ist", "Konsequenz bei Verletzung"]
|
||||||
|
# --- STRATEGIE & RISIKO ---
|
||||||
|
|
||||||
|
goal:
|
||||||
|
chunking_profile: sliding_smart_edges
|
||||||
|
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"]
|
||||||
|
schema: ["Beschreibung des Risikos", "Auswirkungen", "Gegenmaßnahmen"]
|
||||||
|
|
||||||
|
# --- BASIS & WISSEN ---
|
||||||
|
|
||||||
|
concept:
|
||||||
|
chunking_profile: sliding_smart_edges
|
||||||
|
retriever_weight: 0.60
|
||||||
|
edge_defaults: ["references", "related_to"]
|
||||||
|
schema: ["Definition", "Kontext", "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"]
|
||||||
|
|
||||||
|
source:
|
||||||
|
chunking_profile: sliding_standard
|
||||||
|
retriever_weight: 0.50
|
||||||
|
edge_defaults: []
|
||||||
|
schema: ["Metadaten", "Zusammenfassung", "Zitate"]
|
||||||
|
|
||||||
|
glossary:
|
||||||
|
chunking_profile: sliding_short
|
||||||
|
retriever_weight: 0.40
|
||||||
|
edge_defaults: ["related_to"]
|
||||||
|
schema: ["Begriff", "Definition"]
|
||||||
|
|
||||||
|
person:
|
||||||
|
chunking_profile: sliding_standard
|
||||||
|
retriever_weight: 0.50
|
||||||
|
edge_defaults: ["related_to"]
|
||||||
|
schema: ["Rolle", "Beziehung", "Kontext"]
|
||||||
|
|
||||||
|
event:
|
||||||
|
chunking_profile: sliding_standard
|
||||||
|
retriever_weight: 0.60
|
||||||
|
edge_defaults: ["related_to"]
|
||||||
|
schema: ["Datum & Ort", "Teilnehmer", "Ergebnisse"]
|
||||||
|
|
||||||
|
# --- FALLBACK ---
|
||||||
|
|
||||||
|
default:
|
||||||
|
chunking_profile: sliding_standard
|
||||||
|
retriever_weight: 1.00
|
||||||
|
edge_defaults: ["references"]
|
||||||
|
schema: ["Inhalt"]
|
||||||
@@ -0,0 +1,113 @@
|
|||||||
|
# Mindnet v2.6 – Documentation Map & Governance
|
||||||
|
**Status:** Active
|
||||||
|
**Context:** Central Navigation & Maintenance Guide
|
||||||
|
|
||||||
|
## 1. Zweck dieses Dokuments
|
||||||
|
|
||||||
|
Diese Karte dient Entwicklern, dem Mindmaster und KI-Agenten als **zentraler Einstiegspunkt**. Sie beantwortet zwei Fragen:
|
||||||
|
1. **Navigation:** In welcher Datei finde ich Informationen zu Thema X?
|
||||||
|
2. **Wartung:** Ich arbeite an Feature Y – welche Dateien muss ich aktualisieren?
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Verzeichnisstruktur & Inhalte
|
||||||
|
|
||||||
|
Das Repository ist in **logische Domänen** unterteilt.
|
||||||
|
|
||||||
|
### 📂 00_General (Grundlagen)
|
||||||
|
*Zielgruppe: Alle*
|
||||||
|
| Datei | Inhalt & Zweck |
|
||||||
|
| :--- | :--- |
|
||||||
|
| `00_vision_and_strategy.md` | **Strategie.** Warum bauen wir das? Prinzipien (Privacy, Local-First), High-Level Architektur. |
|
||||||
|
| `00_glossary.md` | **Definitionen.** Was bedeutet "Smart Edge", "Traffic Control", "Chunk"? Verhindert Begriffsverwirrung. |
|
||||||
|
| `00_documentation_map.md` | **Dieser Index.** Navigationshilfe. |
|
||||||
|
|
||||||
|
### 📂 01_User_Manual (Anwendung)
|
||||||
|
*Zielgruppe: Mindmaster, Autoren, Power-User*
|
||||||
|
| Datei | Inhalt & Zweck |
|
||||||
|
| :--- | :--- |
|
||||||
|
| `01_chat_usage_guide.md` | **Bedienung.** Wie steuere ich die Personas (Berater, Spiegel)? Wie nutze ich das Feedback? |
|
||||||
|
| `01_knowledge_design.md` | **Content-Regeln.** Die "Bibel" für den Vault. Erklärt Note-Typen, Matrix-Logik und Markdown-Syntax. |
|
||||||
|
| `01-authoring-guidelines` | **Content strukturieren-.** primäres Werkzeug, um Wissen so zu strukturieren, so dass Mindnet die Persönlichkeit spiegelt, empathisch reagiert und strategisch berät |
|
||||||
|
|
||||||
|
### 📂 02_Concepts (Fachliche Logik)
|
||||||
|
*Zielgruppe: Architekten, Product Owner*
|
||||||
|
| Datei | Inhalt & Zweck |
|
||||||
|
| :--- | :--- |
|
||||||
|
| `02_concept_graph_logic.md` | **Graph-Theorie.** Abstrakte Erklärung von Knoten, Kanten, Provenance und Idempotenz. |
|
||||||
|
| `02_concept_ai_personality.md`| **KI-Verhalten.** Konzepte hinter dem Hybrid Router, Empathie-Modell und "Teach-the-AI". |
|
||||||
|
|
||||||
|
### 📂 03_Technical_Reference (Technik & Code)
|
||||||
|
*Zielgruppe: Entwickler, DevOps. (Enthält JSON/YAML Beispiele)*
|
||||||
|
| Datei | Inhalt & Zweck |
|
||||||
|
| :--- | :--- |
|
||||||
|
| `03_tech_data_model.md` | **Datenbank.** Exakte Qdrant-Schemas (Payloads) und Index-Anforderungen. |
|
||||||
|
| `03_tech_ingestion_pipeline.md`| **Import.** Ablauflogik (13 Schritte), Chunker-Profile, Smart Edge Allocation. |
|
||||||
|
| `03_tech_retrieval_scoring.md` | **Suche.** Die mathematischen Formeln für Scoring, Hybrid Search und Explanation Layer. |
|
||||||
|
| `03_tech_chat_backend.md` | **API & LLM.** Implementation des Routers, Traffic Control (Semaphore) und Feedback-Traceability. |
|
||||||
|
| `03_tech_frontend.md` | **UI & Graph.** Architektur des Streamlit-Frontends, State-Management, Cytoscape-Integration und Editor-Logik. |
|
||||||
|
| `03_tech_configuration.md` | **Config.** Referenztabellen für `.env`, `types.yaml` und `retriever.yaml`. |
|
||||||
|
|
||||||
|
### 📂 04_Operations (Betrieb)
|
||||||
|
*Zielgruppe: Administratoren*
|
||||||
|
| Datei | Inhalt & Zweck |
|
||||||
|
| :--- | :--- |
|
||||||
|
| `04_admin_operations.md` | **Runbook.** Installation, Docker-Setup, Backup/Restore, Troubleshooting Guide. |
|
||||||
|
|
||||||
|
### 📂 05_Development (Code)
|
||||||
|
*Zielgruppe: Entwickler*
|
||||||
|
| Datei | Inhalt & Zweck |
|
||||||
|
| :--- | :--- |
|
||||||
|
| `05_developer_guide.md` | **Workflow.** Hardware-Setup (Win/Pi/Beelink), Git-Flow, Test-Befehle, Modul-Interna. |
|
||||||
|
| `05_genai_best_practices.md` | **AI Workflow.** Prompt-Library, Templates und Best Practices für die Entwicklung mit LLMs. |
|
||||||
|
|
||||||
|
### 📂 06_Roadmap & 99_Archive
|
||||||
|
*Zielgruppe: Projektleitung*
|
||||||
|
| Datei | Inhalt & Zweck |
|
||||||
|
| :--- | :--- |
|
||||||
|
| `06_active_roadmap.md` | **Zukunft.** Aktive Workpackages (WP16+), Release-Planung und WP-Historie (Tabelle). |
|
||||||
|
| `99_legacy_workpackages.md` | **Vergangenheit.** Detaillierte Archivdaten zu abgeschlossenen WPs (WP01–WP15). |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Maintenance Guide: "Welche Datei muss ich ändern?"
|
||||||
|
|
||||||
|
Nutze diese Matrix, wenn du ein Workpackage bearbeitest, um die Dokumentation konsistent zu halten.
|
||||||
|
|
||||||
|
| Wenn du arbeitest an... | ...aktualisiere diese Dateien: |
|
||||||
|
| :--- | :--- |
|
||||||
|
| **Neuen Note-Typen** | 1. `01_knowledge_design.md` (Für Autoren)<br>2. `03_tech_configuration.md` (Technische Referenz)<br>3. `05_developer_guide.md` (Erweiterungs-How-To) |
|
||||||
|
| **Importer / Parsing** | `03_tech_ingestion_pipeline.md` |
|
||||||
|
| **Datenbank-Schema** | `03_tech_data_model.md` (Payloads anpassen) |
|
||||||
|
| **Retrieval / Scoring** | `03_tech_retrieval_scoring.md` (Formeln anpassen) |
|
||||||
|
| **Frontend / Visualisierung** | 1. `03_tech_frontend.md` (Technische Details)<br>2. `01_chat_usage_guide.md` (Bedienung) |
|
||||||
|
| **Chat-Logik / Prompts**| 1. `02_concept_ai_personality.md` (Konzept)<br>2. `03_tech_chat_backend.md` (Tech)<br>3. `01_chat_usage_guide.md` (User-Sicht) |
|
||||||
|
| **Deployment / Server** | `04_admin_operations.md` |
|
||||||
|
| **Neuen Features (Allg.)**| `06_active_roadmap.md` (Status Update) |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. Prinzipien für die Dokumentation (Governance)
|
||||||
|
|
||||||
|
Damit dieses System wartbar bleibt (auch für KI-Agenten wie NotebookLM), gelten folgende Regeln:
|
||||||
|
|
||||||
|
1. **Single Source of Truth:**
|
||||||
|
Kopiere keine Informationen. Referenziere sie.
|
||||||
|
* *Ausnahme:* Konkrete JSON-Beispiele in `03_Technical_Reference`. Diese müssen dort stehen, damit Entwickler nicht suchen müssen.
|
||||||
|
|
||||||
|
2. **Konkrete Beispiele:**
|
||||||
|
Technische Dokumente (`03_*`) müssen **immer** Code-Snippets (JSON, YAML, Shell) enthalten. Abstrakte Beschreibungen reichen nicht für die Implementierung.
|
||||||
|
|
||||||
|
3. **Human Readable:**
|
||||||
|
User Manuals (`01_*`) müssen Narrative und Szenarien enthalten ("Stell dir vor..."), keine technischen Auflistungen.
|
||||||
|
|
||||||
|
4. **KI-Optimiert (Context Header):**
|
||||||
|
Jede Datei muss mit einem YAML-Frontmatter beginnen, der `context`, `audience` und `scope` definiert. Dies hilft RAG-Systemen, den Inhalt korrekt einzuordnen.
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
---
|
||||||
|
doc_type: technical_reference
|
||||||
|
audience: developer
|
||||||
|
context: "Beschreibung der Scoring-Formel."
|
||||||
|
---
|
||||||
|
```
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
---
|
||||||
|
doc_type: glossary
|
||||||
|
audience: all
|
||||||
|
status: active
|
||||||
|
version: 2.8.0
|
||||||
|
context: "Zentrales Glossar für Mindnet v2.8. Enthält Definitionen zu Hybrid-Cloud Resilienz, WP-76 Quoten-Steuerung und Mistral-safe Parsing."
|
||||||
|
---
|
||||||
|
|
||||||
|
# Mindnet Glossar
|
||||||
|
|
||||||
|
**Quellen:** `01_edge_vocabulary.md`, `llm_service.py`, `ingestion.py`, `edge_registry.py`
|
||||||
|
|
||||||
|
## Kern-Entitäten
|
||||||
|
|
||||||
|
* **Note:** Repräsentiert eine Markdown-Datei. Die fachliche Haupteinheit. Verfügt über einen **Status** (stable, draft, system), der das Scoring beeinflusst.
|
||||||
|
* **Chunk:** Ein Textabschnitt einer Note. Die technische Sucheinheit (Vektor).
|
||||||
|
* **Edge:** Eine gerichtete Verbindung zwischen zwei Knoten. Wird in WP-22 durch die Registry validiert.
|
||||||
|
* **Vault:** Der lokale Ordner mit den Markdown-Dateien (Source of Truth).
|
||||||
|
* **Frontmatter:** Der YAML-Header am Anfang einer Notiz (enthält `id`, `type`, `title`, `status`).
|
||||||
|
|
||||||
|
## Komponenten
|
||||||
|
|
||||||
|
* **Edge Registry:** Der zentrale Dienst (SSOT), der Kanten-Typen validiert und Aliase in kanonische Typen auflöst. Nutzt `01_edge_vocabulary.md` als Basis.
|
||||||
|
* **LLM Service:** Der Hybrid-Client (v3.3.6), der Anfragen zwischen OpenRouter, Google Gemini und lokalem Ollama routet. Verwaltet Cloud-Timeouts und Quoten-Management.
|
||||||
|
* **Retriever:** Besteht in v2.7+ aus der Orchestrierung (`retriever.py`) und der mathematischen Scoring-Engine (`retriever_scoring.py`).
|
||||||
|
* **Decision Engine:** Teil des Routers, der Intents erkennt und entsprechende **Boost-Faktoren** für das Retrieval injiziert.
|
||||||
|
* **Traffic Control:** Verwaltet Prioritäten und drosselt Hintergrund-Tasks (z.B. Smart Edges) mittels Semaphoren und Timeouts (45s) zur Vermeidung von System-Hangs.
|
||||||
|
* **Unknown Edges Log:** Die Datei `unknown_edges.jsonl`, in der das System Kanten-Typen protokolliert, die nicht im Dictionary gefunden wurden.
|
||||||
|
|
||||||
|
## Konzepte & Features
|
||||||
|
|
||||||
|
* **Hybrid Provider Cascade:** Die intelligente Reihenfolge der Modell-Ansprache. Schlägt die Cloud (OpenRouter/Gemini) fehl, erfolgt nach Retries ein Fallback auf den lokalen Ollama (Quoten-Schutz).
|
||||||
|
* **Deep Fallback (v2.11.14, WP20):** Ein inhaltsbasierter Rettungsmechanismus in der Ingestion. Im Gegensatz zum technischen Fallback (bei Verbindungsfehlern) wird der Deep Fallback ausgelöst, wenn ein Cloud-Modell zwar technisch erfolgreich antwortet, aber inhaltlich keine verwertbaren Daten liefert (z. B. bei "Data Policy Violations").
|
||||||
|
* **Silent Refusal (WP20):** Ein Zustand, in dem Cloud-Provider (wie OpenRouter) die Verarbeitung eines Dokuments aufgrund interner Filter ("No data training") verweigern, ohne einen HTTP-Fehler zu senden. Wird durch Deep Fallback abgefangen.
|
||||||
|
* **Rate-Limit Resilience (WP-20):** Automatisierte Erkennung von HTTP 429 Fehlern. Das System pausiert (konfigurierbar via `LLM_RATE_LIMIT_WAIT`) und wiederholt den Cloud-Call, bevor der langsame Fallback ausgelöst wird.
|
||||||
|
* **Mistral-safe Parsing:** Robuste Extraktions-Logik in Ingestion und Analyzer, die technische Steuerzeichen (`<s>`, `[OUT]`) und Framework-Tags erkennt und entfernt, um valides JSON aus Free-Modellen zu gewinnen.
|
||||||
|
* **Lifecycle Scoring (WP-22):** Ein Mechanismus, der die Relevanz einer Notiz basierend auf ihrem Status gewichtet (z.B. Bonus für `stable`, Malus für `draft`).
|
||||||
|
* **Intent Boosting:** Dynamische Erhöhung der Kanten-Gewichte basierend auf der Nutzerfrage (z.B. Fokus auf `caused_by` bei "Warum"-Fragen).
|
||||||
|
* **Provenance Weighting:** Gewichtung einer Kante nach ihrer Herkunft:
|
||||||
|
* `explicit`: Vom Mensch gesetzt (Prio 1).
|
||||||
|
* `semantic_ai`: Von der KI im Turbo-Mode extrahiert und validiert (Prio 2).
|
||||||
|
* `structure`: Durch System-Regeln/Matrix erzeugt (Prio 3).
|
||||||
|
* **Smart Edge Allocation:** KI-Verfahren zur Relevanzprüfung von Links für spezifische Textabschnitte.
|
||||||
|
* **Matrix Logic:** Bestimmung des Kanten-Typs basierend auf Quell- und Ziel-Entität (z.B. Erfahrung -> Wert = `based_on`).
|
||||||
@@ -0,0 +1,67 @@
|
|||||||
|
---
|
||||||
|
doc_type: strategy
|
||||||
|
audience: all
|
||||||
|
status: active
|
||||||
|
version: 2.6
|
||||||
|
context: "Vision, Mission und Architekturprinzipien von Mindnet."
|
||||||
|
---
|
||||||
|
|
||||||
|
# Mindnet Vision & Strategie
|
||||||
|
|
||||||
|
**Quellen:** `Programmplan_V2.2.md`
|
||||||
|
|
||||||
|
## 1. Programmauftrag
|
||||||
|
|
||||||
|
Mindnet v2.6 entwickelt ein persönliches, wachsendes KI-Gedächtnis. Es ist ein **Digitaler Zwilling**, der:
|
||||||
|
- Wissen, Erfahrungen und Werte speichert.
|
||||||
|
- Semantisch verknüpft (Graphen-basiert).
|
||||||
|
- Als Dialogpartner agiert (RAG-Chat).
|
||||||
|
- **Lokal und privat** läuft (Privacy First).
|
||||||
|
|
||||||
|
Es ist **kein statisches Archiv**, sondern ein lebendes System, das durch Interaktion (Feedback, Smart Edges) besser wird.
|
||||||
|
|
||||||
|
## 2. Vision
|
||||||
|
|
||||||
|
> „Ein persönliches semantisches Gedächtnis, das mit mir wächst, meine Persönlichkeit spiegelt und mir als intelligenter, erklärbarer, lernender Begleiter dient.“
|
||||||
|
|
||||||
|
**Kernprinzipien der Vision:**
|
||||||
|
* **Erklärbarkeit:** Jede Antwort muss begründbar sein ("Why-Layer").
|
||||||
|
* **Wachstum:** Das System startet klein und verdichtet sich.
|
||||||
|
* **Autonomie:** Es schlägt fehlende Kanten selbstständig vor (Smart Edges).
|
||||||
|
* **Persönlichkeit:** Es entscheidet basierend auf *deinen* Werten.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Architekturprinzipien
|
||||||
|
|
||||||
|
Die folgenden Prinzipien steuern jede technische Entscheidung:
|
||||||
|
|
||||||
|
1. **Late Binding (Späte Semantik):**
|
||||||
|
Struktur und Interpretation werden in Konfigurationen (`types.yaml`, `prompts.yaml`) definiert, nicht direkt in den Vault-Dateien. Die "Persönlichkeit" ist Config, kein Code.
|
||||||
|
|
||||||
|
2. **Virtual Schema Layer:**
|
||||||
|
Markdown-Dateien benötigen nur minimale, robuste Angaben (Frontmatter). Komplexität (Chunk-Größe, Gewichte) wird zur Laufzeit injiziert.
|
||||||
|
|
||||||
|
3. **Self-Healing Graph:**
|
||||||
|
Der Graph wird regelmäßig auf Konsistenz geprüft. "Dangling Edges" werden bereinigt, fehlende Links durch Smart Edges ergänzt.
|
||||||
|
|
||||||
|
4. **Deterministische IDs:**
|
||||||
|
Notes und Chunks erhalten stabile IDs (UUIDv5). Der Graph ist jederzeit aus dem Markdown wiederaufbaubar.
|
||||||
|
|
||||||
|
5. **Full Explainability:**
|
||||||
|
Keine Blackbox. Jede Antwort liefert Metadaten (`[DECISION]`, `[PROJECT]`) und Begründungen.
|
||||||
|
|
||||||
|
6. **Persistence First:**
|
||||||
|
Obsidian (Markdown) bleibt die **einzige Quelle der Wahrheit**. Die Datenbank ist nur ein abgeleiteter Cache.
|
||||||
|
|
||||||
|
7. **Minimalinvasives Schreiben:**
|
||||||
|
Mindnet schreibt nie ungefragt in deine Notizen. Änderungen erfolgen nur über den Draft Editor oder mit expliziter Zustimmung.
|
||||||
|
|
||||||
|
8. **Incremental Growth:**
|
||||||
|
Das System muss bereits mit wenigen Notizen nützlich sein.
|
||||||
|
|
||||||
|
9. **Observability:**
|
||||||
|
Jeder Importlauf und jede Retriever-Anfrage ist logbar.
|
||||||
|
|
||||||
|
10. **Local First & Privacy:**
|
||||||
|
Nutzung lokaler LLMs (Ollama) für Inference. Keine Daten verlassen den Server.
|
||||||
@@ -0,0 +1,189 @@
|
|||||||
|
---
|
||||||
|
id: 01-authoring-guidelines
|
||||||
|
title: Authoring Guidelines – Handbuch für den Digitalen Zwilling
|
||||||
|
type: principle
|
||||||
|
status: stable
|
||||||
|
version: 1.1.0
|
||||||
|
area: system_documentation
|
||||||
|
tags: [handbuch, authoring, methodik, obsidian, mindnet, best-practice]
|
||||||
|
retriever_weight: 2.0
|
||||||
|
---
|
||||||
|
|
||||||
|
# Authoring Guidelines: Dein Werkzeug für den Digitalen Zwilling
|
||||||
|
|
||||||
|
|
||||||
|
Dieses Handbuch ist dein primäres Werkzeug, um Wissen so zu strukturieren, dass Mindnet deine Persönlichkeit spiegelt, empathisch reagiert und dich strategisch berät.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## ⚡ Die 6 Goldenen Regeln des Knowledge Designs
|
||||||
|
|
||||||
|
1. **Atomare Gedanken:** Eine Notiz = Ein Thema. Trenne z. B. „Meditation“ von „Mobility“, auch wenn beides Ich-Pflege ist.
|
||||||
|
2. **Explizite Typen:** Nutze den `type`, um der KI zu sagen, wie sie den Text verarbeiten soll (z. B. `insight` für Beobachtungen, `experience` für Erlebnisse).
|
||||||
|
3. **Semantische Links:** Verknüpfe aktiv mit `[[rel:depends_on ...]]` oder `[[rel:based_on ...]]`. Sag dem System, *warum* Dinge zusammenhängen.
|
||||||
|
4. **Werte & Ziele definieren:** Erstelle für jeden Nordstern und jeden Kernwert eine eigene Notiz. Ohne Maßstäbe kann der „Berater“ nicht entscheiden.
|
||||||
|
5. **Emotionales Bridging:** Nutze Begriffe wie „Druck“, „Stolz“, „Euphorie“ oder „Hilflosigkeit“, um die Empathie-Ebene der KI zu aktivieren.
|
||||||
|
6. **Narrative Tiefe (Fleisch am Knochen):** Dokumentiere das „Warum“ hinter einer Entscheidung. Fakten informieren, aber Erzählungen prägen den Charakter.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. Strategische Steuerung (Status & Gewicht)
|
||||||
|
|
||||||
|
Du entscheidest über das Frontmatter, wie präsent eine Information im „Gedächtnis“ ist.
|
||||||
|
|
||||||
|
### 1.1 Status-Logik
|
||||||
|
* **`stable`**: Gold-Standard. Für finale Leitbild-Texte und Nordsterne. Erhält +20% Relevanz-Bonus.
|
||||||
|
* **`active`**: Standard für laufende Projekte und aktuelle Beobachtungen.
|
||||||
|
* **`draft`**: Brainstorming oder rohe Tages-Logs. Die KI nutzt diese nur nachrangig (50% Malus), um Rauschen zu vermeiden.
|
||||||
|
* **`system`**: Rein technische Dateien (Templates, Guides). Werden im Chat ignoriert.
|
||||||
|
|
||||||
|
### 1.2 Manuelle Gewichtung (`retriever_weight`)
|
||||||
|
* **Boost (1.20):** Für hochrelevante Erkenntnisse. **Beispiel:** Beobachtungen zum Verhalten von Rohan werden als `insight` mit `1.20` markiert, damit sie bei Erziehungsfragen sofort präsent sind.
|
||||||
|
* **Deboost (0.50 - 0.80):** Für tägliche Routine-Einträge („Heute 10 Min. meditiert“). Sie dienen der Chronik, sollen aber keine tiefen Analysen verfälschen.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Das Kochbuch: Praktische Use-Cases
|
||||||
|
|
||||||
|
### 2.1 Ein Erlebnis aufschreiben (`type: experience`)
|
||||||
|
**Ziel:** Den „Spiegel“ (Empathy) mit deiner Biografie kalibrieren.
|
||||||
|
|
||||||
|
**Struktur & Leitfragen:**
|
||||||
|
- **Kontext:** Was ist passiert? (Sachlich kurz).
|
||||||
|
- **Emotions-Check:** Wie habe ich mich in der Situation gefühlt? (Wichtig für Regel 5).
|
||||||
|
- **Die Lektion:** Was habe ich über mich gelernt? (z. B. „Ich reagiere allergisch auf Ungerechtigkeit“).
|
||||||
|
- **Deep-Edge:** Mit welcher Rolle ist das verknüpft? `[[rel:supports Meine Rollenlandkarte 2025#Vater]]`.
|
||||||
|
|
||||||
|
### 2.2 Eine Beobachtung festhalten (`type: insight`)
|
||||||
|
**Ziel:** Den „Berater“ (Decision) mit Mustern versorgen.
|
||||||
|
|
||||||
|
**Beispiel Rohan-Beobachtung:**
|
||||||
|
- **Beobachtung:** Rohan reagiert positiv auf „leise“ Impulse und 90/10 Coaching.
|
||||||
|
- **Interpretation:** Direkte Konfrontation erzeugt Gegendruck; Fragen erzeugen Ownership.
|
||||||
|
- **Konsequenz:** Prinzip P3a (Familienregeln) muss immer einen Bedürfnischeck vorausschicken.
|
||||||
|
|
||||||
|
### 2.3 Ein Review durchführen (`type: journal` / `insight`)
|
||||||
|
**Ziel:** Den Fortschritt steuern.
|
||||||
|
- **Daily:** Rohes Log (Status `draft`).
|
||||||
|
- **Weekly/Monthly:** Verdichtung der Erkenntnisse in eine `stable` Notiz. Frage: „Was war der größte Hebel diese Woche?“.
|
||||||
|
|
||||||
|
### 2.4 Das Handlungsprinzip (`type: principle`)
|
||||||
|
**Ziel:** Testbare Regeln für schwierige Entscheidungssituationen.
|
||||||
|
|
||||||
|
**Struktur-Vorgabe:**---
|
||||||
|
id: 01-authoring-guidelines
|
||||||
|
title: Authoring Guidelines – Das Handbuch für den Digitalen Zwilling
|
||||||
|
type: principle
|
||||||
|
status: stable
|
||||||
|
version: 1.2.0
|
||||||
|
area: system_documentation
|
||||||
|
tags: [handbuch, authoring, methodik, obsidian, mindnet, best-practice]
|
||||||
|
retriever_weight: 2.0
|
||||||
|
---
|
||||||
|
|
||||||
|
## 🕸️ Teil 3: Netzdesign (Hubs, Edges & Lücken)
|
||||||
|
|
||||||
|
Ein intelligentes Netz wächst durch strategische Verknüpfungen, nicht durch Textmenge.
|
||||||
|
|
||||||
|
### 3.1 Wissens-Hubs (Zentralnotizen)
|
||||||
|
Hubs fungieren als Verteilerzentren im Graphen.
|
||||||
|
* **Struktur:** Nutze Überschriften (H2, H3) und verlinke von dort auf Detailnotizen.
|
||||||
|
* **Deep-Edges:** Verlinke präzise Abschnitte: `[[Rollenlandkarte#Vater]]`. Dies ermöglicht der KI, nur den relevanten Kontext zu laden.
|
||||||
|
|
||||||
|
### 3.2 Forward-Mapping (Strategische Lücken)
|
||||||
|
Setze bewusst Links auf Dateien, die noch nicht existieren (z. B. `[[Die beste Version meiner selbst]]`).
|
||||||
|
* **Zweck:** Du signalisierst dem System: „Hier entsteht ein wichtiges Konzept“.
|
||||||
|
* **Effekt:** Die KI erkennt diese Lücken und kann im Chat proaktiv Fragen stellen, um diese Felder mit dir gemeinsam zu füllen.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. Obsidian Usability & Automatisierung
|
||||||
|
|
||||||
|
### 4.1 Templater-Integration
|
||||||
|
Nutze Vorlagen, die bereits die **Leitfragen** und das richtige **Retriever-Weight** enthalten. Ein Klick auf „Neues Erlebnis“ sollte automatisch das Frontmatter mit `type: experience` und `weight: 1.1` füllen.
|
||||||
|
|
||||||
|
### 4.2 Meta Bind Dashboards
|
||||||
|
Nutze **Meta Bind**, um Felder wie `status` oder `retriever_weight` über Schieberegler direkt in der Notiz zu steuern. Das macht die Gewichtung deines Wissens intuitiv und spielerisch.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. Vernetzung für die Mindnet-Personas
|
||||||
|
|
||||||
|
| Persona | Notiz-Fokus | Effekt im Dialog |
|
||||||
|
| :--- | :--- | :--- |
|
||||||
|
| **🪞 Spiegel (Empathy)** | Gefühle & Biografisches | „Ich verstehe deinen Frust, das war bei Projekt X ähnlich...“. |
|
||||||
|
| **⚖️ Berater (Decision)** | Werte & Wächterfragen | „Option A ist nicht ratsam, da sie gegen dein Prinzip der Integrität verstößt“. |
|
||||||
|
| **📚 Bibliothekar (Facts)** | Struktur & Definitionen | „Deine Mission als Vater ist es, verlässliche Präsenz zu zeigen...“. |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
> [!abstract] Fazit für den Autor
|
||||||
|
> Mindnet ist ein **Persönlichkeitsspiegel**. Dokumentiere weniger „Technik“ und mehr „Mensch“. Jede Notiz sollte die Frage beantworten: „Was sagt das über mich und meine Werte aus?“.
|
||||||
|
- **3 Signale:** Woran merke ich im Alltag, dass ich das Prinzip lebe?.
|
||||||
|
- **Wächterfrage:** Welche Frage stelle ich mir im Moment der Entscheidung?.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. Obsidian Workflow-Hacks
|
||||||
|
|
||||||
|
### 6.1 Templater & Meta Bind
|
||||||
|
- **Automatisierung:** Nutze das **Templater-Plugin**, um beim Erstellen einer Notiz sofort die passenden Leitfragen und das richtige `retriever_weight` einzufügen.
|
||||||
|
- **Interaktive Steuerung:** Nutze **Meta Bind**, um Felder wie `status` oder `retriever_weight` über Buttons oder Slider direkt im Lesemodus zu ändern, ohne im YAML-Code zu tippen.
|
||||||
|
|
||||||
|
### 6.2 Deep-Edges & Verknüpfung
|
||||||
|
- Verknüpfe Erlebnisse immer mit der entsprechenden Rolle: `[[rel:supports Meine Rollenlandkarte 2025#Vater]]`.
|
||||||
|
- Nutze `derived_from`, um Prinzipien an ihre Ursprungs-Session zu binden.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 7. Vernetzung für Mindnet Personas
|
||||||
|
|
||||||
|
| Persona | Notiz-Fokus | Beispiel |
|
||||||
|
| :--- | :--- | :--- |
|
||||||
|
| **🪞 Spiegel (Empathy)** | Emotionen & Prägungen | „Ich fühlte mich hilflos, als...“. |
|
||||||
|
| **⚖️ Berater (Decision)** | Kriterien & Abwägungen | „Option A verletzt Wert X, weil...“. |
|
||||||
|
| **📚 Bibliothekar (Facts)** | Struktur & Definition | „Rollenmission Vater bedeutet...“. |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
> [!tip] Best Practice
|
||||||
|
> Wenn du merkst, dass eine Notiz zu technisch wird: Halte inne und frage dich: „Was macht das mit mir als Mensch?“ Schreibe *das* auf. Das ist die Essenz für deinen KI-Zwilling.
|
||||||
|
|
||||||
|
## 8. Verbindungen von Notiztypen
|
||||||
|
|
||||||
|
```mermaid
|
||||||
|
graph TD
|
||||||
|
%% Identity Stream
|
||||||
|
V[Value] -- definieren --> N[Need]
|
||||||
|
N -- erzeugen --> M[Motivation]
|
||||||
|
B[Belief] -- prägen --> M
|
||||||
|
T[Trait] -- unterstützen --> M
|
||||||
|
|
||||||
|
%% Action Stream
|
||||||
|
M -- treiben --> G[Goal]
|
||||||
|
G -- konkretisiert in --> P[Project]
|
||||||
|
P -- unterteilt in --> TA[Task]
|
||||||
|
D[Decision] -- steuert --> P
|
||||||
|
PR[Principle] -- leitet --> D
|
||||||
|
|
||||||
|
%% History Stream
|
||||||
|
TA -- führt zu --> E[Event]
|
||||||
|
E -- generiert --> EX[Experience]
|
||||||
|
PE[Person] -- beteiligt an --> E
|
||||||
|
|
||||||
|
%% Feedback Loop
|
||||||
|
EX -- liefert --> I[Insight]
|
||||||
|
I -- kalibrieren --> V
|
||||||
|
I -- verfeinern --> PR
|
||||||
|
I -- validieren --> B
|
||||||
|
|
||||||
|
%% Constraints
|
||||||
|
RI[Risk] -- gefährdet --> G
|
||||||
|
O[Obstacle] -- blockiert --> TA
|
||||||
|
BI[Bias] -- verzerrt --> D
|
||||||
|
S[State] -- beeinflusst --> EX
|
||||||
|
|
||||||
|
style V fill:#f9f,stroke:#333,stroke-width:2px
|
||||||
|
style EX fill:#bbf,stroke:#333,stroke-width:2px
|
||||||
|
style P fill:#bfb,stroke:#333,stroke-width:2px
|
||||||
|
|
||||||
@@ -0,0 +1,126 @@
|
|||||||
|
---
|
||||||
|
doc_type: user_manual
|
||||||
|
audience: user, mindmaster
|
||||||
|
scope: chat, ui, feedback, graph
|
||||||
|
status: active
|
||||||
|
version: 2.6
|
||||||
|
context: "Anleitung zur Nutzung der Web-Oberfläche, der Chat-Personas und des Graph Explorers."
|
||||||
|
---
|
||||||
|
|
||||||
|
# Chat & Graph Usage Guide
|
||||||
|
|
||||||
|
**Quellen:** `user_guide.md`
|
||||||
|
|
||||||
|
## 1. Was Mindnet für dich tut
|
||||||
|
|
||||||
|
Mindnet ist ein **assoziatives Gedächtnis** mit Persönlichkeit. Es unterscheidet sich von einer reinen Suche dadurch, dass es **kontextsensitiv** agiert.
|
||||||
|
|
||||||
|
**Das Gedächtnis (Der Graph):**
|
||||||
|
Wenn du nach "Projekt Alpha" suchst, findet Mindnet auch:
|
||||||
|
* **Abhängigkeiten:** "Technologie X wird benötigt".
|
||||||
|
* **Entscheidungen:** "Warum nutzen wir X?".
|
||||||
|
* **Ähnliches:** "Projekt Beta war ähnlich".
|
||||||
|
|
||||||
|
**Der Zwilling (Die Personas):**
|
||||||
|
Mindnet passt seinen Charakter an: Mal ist es der neutrale Bibliothekar, mal der strategische Berater, mal der empathische Spiegel.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Die Oberfläche (Web UI)
|
||||||
|
|
||||||
|
Seit Version 2.3.1 bedienst du Mindnet über eine grafische Oberfläche im Browser.
|
||||||
|
|
||||||
|
### 2.1 Der Chat-Bereich
|
||||||
|
* **Intent-Badge:** Über jeder Antwort siehst du ein Label (z.B. **⚖️ Intent: DECISION**).
|
||||||
|
* **Quellen-Karten:** Unter der Antwort findest du ausklappbare Karten ("Expanders").
|
||||||
|
* **Grüner Punkt:** Hohe Relevanz (Score > 0.8).
|
||||||
|
* **Klick darauf:** Zeigt den Textauszug und die **Begründung** (Explanation Layer).
|
||||||
|
|
||||||
|
### 2.2 Modus: 🕸️ Graph Explorer (Cytoscape)
|
||||||
|
*Neu in v2.6*: Eine interaktive Karte deines Wissens.
|
||||||
|
|
||||||
|
**Die Farb-Logik:**
|
||||||
|
* 🔴 **Roter Rahmen:** Das aktuelle **Zentrum** (Ego). Alle geladenen Knoten sind Nachbarn dieses Knotens.
|
||||||
|
* 🟡 **Gelber Rahmen:** Der **inspizierte** Knoten. Dessen Details siehst du im "Data Inspector" und in der Action-Bar.
|
||||||
|
|
||||||
|
**Bedienung:**
|
||||||
|
1. **Klick auf einen Knoten:** Wählt ihn aus (Gelb). Der Graph bleibt stabil, aber die Info-Leiste oben aktualisiert sich.
|
||||||
|
2. **Button "🎯 Als Zentrum setzen":** Lädt den Graphen neu und macht den ausgewählten Knoten zum roten Zentrum.
|
||||||
|
3. **Button "📝 Bearbeiten":** Springt mit dem Inhalt dieses Knotens direkt in den Editor.
|
||||||
|
|
||||||
|
**Layout & Persistenz:**
|
||||||
|
Du kannst in der linken Spalte die Physik (Abstoßung, Kantenlänge) einstellen. Diese Einstellungen werden in der **URL gespeichert**. Du kannst den Link als Lesezeichen speichern, um genau diese Ansicht wiederzufinden.
|
||||||
|
|
||||||
|
### 2.3 Modus: 📝 Manueller Editor
|
||||||
|
Ein Editor mit **"File System First"** Garantie.
|
||||||
|
* Wenn du eine Datei bearbeitest, liest Mindnet sie direkt von der Festplatte.
|
||||||
|
* **Resurrection:** Wenn du zwischendurch in den Graph wechselst und zurückkommst, ist dein getippter Text noch da.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Den Chat steuern (Intents)
|
||||||
|
|
||||||
|
Du steuerst die Persönlichkeit von Mindnet durch deine Wortwahl. Der **Hybrid Router v5** unterscheidet intelligent:
|
||||||
|
|
||||||
|
### 3.1 Frage-Modus (Wissen abrufen)
|
||||||
|
Ausgelöst durch `?` oder W-Wörter.
|
||||||
|
|
||||||
|
* **Entscheidung ("Soll ich?"):** Der **Berater**.
|
||||||
|
* Mindnet lädt deine Werte (`type: value`) und Ziele (`type: goal`).
|
||||||
|
* *Beispiel:* "Soll ich Tool X nutzen?" -> "Nein, Tool X speichert Daten in den USA. Das verstößt gegen dein Prinzip 'Privacy First'."
|
||||||
|
* **Empathie ("Ich fühle..."):** Der **Spiegel**.
|
||||||
|
* Mindnet lädt deine Erfahrungen (`type: experience`).
|
||||||
|
* *Beispiel:* "Ich bin frustriert." -> "Das erinnert mich an Projekt Y, da ging es uns ähnlich..."
|
||||||
|
* **Fakten ("Was ist?"):** Der **Bibliothekar**.
|
||||||
|
* Liefert präzise Definitionen.
|
||||||
|
|
||||||
|
### 3.2 Befehls-Modus (Interview)
|
||||||
|
Ausgelöst durch Aussagen wie "Neues Projekt", "Ich will festhalten".
|
||||||
|
|
||||||
|
* **Was passiert:** Mindnet sucht nicht, 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 eine **Begründung** ("Reasons"), warum es etwas gefunden hat.
|
||||||
|
Öffne eine Quellen-Karte, um zu sehen:
|
||||||
|
* *"Hohe textuelle Übereinstimmung."* (Semantik)
|
||||||
|
* *"Bevorzugt aufgrund des Typs 'decision'."* (Wichtigkeit)
|
||||||
|
* *"Verweist auf 'Projekt X' via 'depends_on'."* (Graph-Kontext)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. Feedback & Lernen
|
||||||
|
|
||||||
|
Mindnet wird schlauer, wenn du es pflegst.
|
||||||
|
|
||||||
|
* **Globales Feedback (Sterne):** Bewertet die generierte Antwort (Prompting, Tonfall).
|
||||||
|
* **Granulares Feedback (Smileys):** Bewertet die einzelne Quelle.
|
||||||
|
* 😞 (Sad): Irrelevant. (Senkt das Gewicht dieser Verbindung).
|
||||||
|
* 😀 (Grin): Perfekter Treffer! (Stärkt diesen Typ/Kante).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. Neues Wissen beisteuern (Authoring & Intelligence)
|
||||||
|
|
||||||
|
Mindnet lebt von deinem Input. Du hast drei Wege, Wissen einzugeben:
|
||||||
|
|
||||||
|
### 6.1 Weg A: Der Interview-Assistent (Auto-Drafting)
|
||||||
|
1. **Start:** Schreibe im Chat: *"Ich möchte ein neues Projekt 'Apollo' starten."*
|
||||||
|
2. **Generierung:** Mindnet erkennt `INTERVIEW`, wählt das Schema und erstellt einen Entwurf.
|
||||||
|
3. **Editor:** Die UI zeigt den Entwurf (`status: draft`).
|
||||||
|
* *Healing UI:* Falls das LLM Syntax-Fehler gemacht hat, hat der Editor sie bereits repariert.
|
||||||
|
4. **Speichern:** Klicke auf "💾 Speichern".
|
||||||
|
|
||||||
|
### 6.2 Weg B: Der Intelligence-Workflow
|
||||||
|
Wenn du 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" als Alias für "Mindnet".
|
||||||
|
* **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 ein.
|
||||||
|
4. **Speichern:** Der Text wird sofort in den Vault geschrieben und indiziert.
|
||||||
@@ -0,0 +1,340 @@
|
|||||||
|
---
|
||||||
|
doc_type: user_manual
|
||||||
|
audience: user, author
|
||||||
|
scope: vault, markdown, schema
|
||||||
|
status: active
|
||||||
|
version: 2.8.0
|
||||||
|
context: "Regelwerk für das Erstellen von Notizen im Vault. Die 'Source of Truth' für Autoren."
|
||||||
|
---
|
||||||
|
|
||||||
|
# Knowledge Design Manual
|
||||||
|
|
||||||
|
**Quellen:** `knowledge_design.md`, `types.yaml`
|
||||||
|
|
||||||
|
## ⚡ Die 6 Goldenen Regeln (TL;DR)
|
||||||
|
|
||||||
|
1. **Atomare Gedanken:** Eine Notiz = Ein Thema. Vermischung führt zu "Context-Pollution", wodurch die KI unpräzise berät.
|
||||||
|
2. **Explizite Typen:** Der `type` im Frontmatter ist der wichtigste Hebel. Er entscheidet über die mathematische Gewichtung im System.
|
||||||
|
3. **Semantische Links:** Nutze das Vokabular aus der `01_edge_vocabulary.md`. Ersetze einfache Verweise durch funktionale Beziehungen wie `caused_by` oder `based_on`.
|
||||||
|
4. **Werte & Ziele definieren:** Ohne explizite Kriterien (`type: value`) fehlt dem System der Maßstab für eine Bewertung.
|
||||||
|
5. **Emotionales Bridging:** Dokumentiere deine Gefühle. Begriffe wie „Druck“ oder „Euphorie“ sind die Schnittstelle für die Empathie-Logik.
|
||||||
|
6. **Narrative Tiefe (Fleisch am Knochen):** Ein „Was“ ohne „Warum“ ist für die KI nur ein Fakt, für dich als Mensch aber bedeutungslos. Dokumentiere die Intention hinter deinen Taten.
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. Zweck & Scope
|
||||||
|
|
||||||
|
Mindnet ist mehr als eine Dokumentablage. Es ist ein vernetztes System, das deine Persönlichkeit abbildet. Die Markdown-Dateien in deinem Vault sind die **einzige Quelle der Wahrheit** ("Source of Truth"). Was nicht im Markdown steht, existiert für das System nicht.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Note-Struktur & Frontmatter
|
||||||
|
|
||||||
|
Jede Notiz benötigt einen YAML-Header (Frontmatter).
|
||||||
|
|
||||||
|
**Pflichtfelder:**
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
---
|
||||||
|
id: 20251212-projekt-alpha # Eindeutige Kennung (YYYYMMDD-slug empfohlen)
|
||||||
|
title: Projekt Alpha # Sprechender Titel
|
||||||
|
type: project # Steuert Chunking & Wichtigkeit
|
||||||
|
status: active # active, archived, draft
|
||||||
|
created: 2025-12-12 # ISO 8601
|
||||||
|
tags: [ki, entwicklung] # Taxonomie
|
||||||
|
aliases: [KI Projekt, Codename Quickhack]
|
||||||
|
---
|
||||||
|
```
|
||||||
|
|
||||||
|
### **2.1 [NEU] Naming Convention: Intuitiv vs. Technisch**
|
||||||
|
Für die Benutzerfreundlichkeit und die intuitive Navigation in Obsidian wird die Nutzung von **menschenlesbaren Titeln** bevorzugt (z. B. `Mein Persönliches Leitbild 2025` statt `leitbild_identity`).
|
||||||
|
- Die technische Eindeutigkeit wird primär über die `id` im Frontmatter sichergestellt.
|
||||||
|
- Die KI nutzt die Semantik des Dateinamens als zusätzlichen Kontext-Vektor.
|
||||||
|
|
||||||
|
### 2.2 Advanced Overrides: Die KI-Steuerung übernehmen
|
||||||
|
|
||||||
|
|
||||||
|
In 95% der Fälle setzt der `type` (z.B. "concept") automatisch die richtigen Einstellungen. In Spezialfällen kannst du diese manuell im Frontmatter überschreiben, um das Verhalten der KI zu erzwingen.
|
||||||
|
|
||||||
|
#### A. `retriever_weight`: Die Sichtbarkeit steuern
|
||||||
|
Dieser Faktor (Default: 1.0) ist ein Multiplikator für das Ranking in der Vektorsuche. Er entscheidet, welche Notiz "gewinnt", wenn zwei Texte inhaltlich ähnlich sind.
|
||||||
|
|
||||||
|
* **Standard (1.0):** Normale Wichtigkeit.
|
||||||
|
* **Boost (1.2 - 2.0):** "Das hier ist die Wahrheit."
|
||||||
|
* *Einsatz:* Finale Entscheidungen, Kernprinzipien, die "Single Source of Truth".
|
||||||
|
* *Effekt:* Verdrängt weniger wichtige Notizen (z.B. Meeting-Protokolle) aus dem Kontext-Fenster der KI.
|
||||||
|
* **Deboost (0.5 - 0.8):** "Nur Kontext, keine Fakten."
|
||||||
|
* *Einsatz:* Glossare, externe Quellen (`source`), reine Datensammlungen.
|
||||||
|
* *Effekt:* Die Notiz wird nur gefunden, wenn man sehr spezifisch danach sucht.
|
||||||
|
|
||||||
|
#### B. `chunking_profile`: Die Zerstückelung steuern
|
||||||
|
Das Profil bestimmt, wie der Text für die Datenbank zerschnitten wird. Falsches Chunking zerreißt den Kontext. Wähle das Profil basierend auf der **Struktur** deines Textes.
|
||||||
|
|
||||||
|
| Profil-Name | Strategie | Einsatzzweck & Wirkung |
|
||||||
|
| :--- | :--- | :--- |
|
||||||
|
| **`sliding_standard`** | Sliding Window | **Der Allrounder.** Für Fließtexte (Tagebuch, Artikel). Der Text wird in überlappende Fenster geschnitten. Gut, wenn der Inhalt von oben nach unten fließt. |
|
||||||
|
| **`sliding_short`** | Sliding Window (Klein) | **Für Dichte.** Für Texte mit sehr hoher Informationsdichte (Glossare, Task-Listen), wo jeder Satz wichtig ist. Erzeugt viele kleine Chunks. |
|
||||||
|
| **`sliding_smart_edges`** | Sliding + AI | **Der Intelligente.** Wie Standard, aber das LLM analysiert jeden Chunk zusätzlich auf implizite Querverweise. Standard für `concept` und `project`. |
|
||||||
|
| **`structured_smart_edges`** | Heading Split (Soft) | **Für Strukturierte Texte.** Trennt an Überschriften (H2). *Besonderheit:* Wenn ein Abschnitt sehr kurz ist, wird er mit dem nächsten verschmolzen ("Soft Mode"), um den Kontext zu wahren. |
|
||||||
|
| **`structured_smart_edges_strict`** | Heading Split (Hard) | **Für Listen & Kataloge.** Trennt *zwingend* an jeder H2-Überschrift. Verhindert das Verschmelzen. <br>**Wichtig für:** `decision` (Option A darf nicht mit Option B verschmelzen), `value`, `profile`. |
|
||||||
|
|
||||||
|
**Beispiel für ein Override:**
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
---
|
||||||
|
title: Sammlung meiner Passwörter-Regeln
|
||||||
|
type: list
|
||||||
|
# Wir erzwingen eine strikte Trennung, damit Regel 1 nicht mit Regel 2 vermischt wird.
|
||||||
|
chunking_profile: structured_smart_edges_strict
|
||||||
|
# Extrem wichtig, soll immer beachtet werden.
|
||||||
|
retriever_weight: 1.5
|
||||||
|
---
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
## 3. Frontmatter Felder und ihre Bedeutung
|
||||||
|
### 3.1 Typ-Referenz & Stream-Logik
|
||||||
|
|
||||||
|
Das System euriert Informationen in funktionalen Streams. Wähle den Typ danach aus, in welchem "Gedächtnis-Bereich" die Information landen soll.
|
||||||
|
|
||||||
|
### 3.1 Identity Stream (Der Kern / Das „Warum“)
|
||||||
|
Dieser Stream definiert deine stabilen Merkmale und inneren Kompasse.
|
||||||
|
|
||||||
|
| Typ | Gewicht | Chunking Profil | Zweck & Inhalt |
|
||||||
|
| :--- | :--- | :--- | :--- |
|
||||||
|
| **`value`** | 1.00 | `structured_strict` | Fundamentale Werte und moralische Maßstäbe. |
|
||||||
|
| **`principle`** | 0.95 | `structured_strict_L3` | Handlungsleitlinien mit tiefer Hierarchie (H3-Split). |
|
||||||
|
| **`trait`** | 1.10 | `structured_strict` | Charakterliche Stärken und Talente. |
|
||||||
|
| **`belief`** | 0.90 | `sliding_short` | Tiefe Überzeugungen über dich und die Gesellschaft. |
|
||||||
|
| **`profile`** | 0.70 | `structured_strict` | Rollenidentitäten (z. B. Vater, Mentor, Unternehmer). |
|
||||||
|
| **`need`** | 1.05 | `sliding_smart_edges` | Psychologische Grundbedürfnisse (z. B. Autonomie, Bindung). |
|
||||||
|
| **`motivation`**| 0.95 | `sliding_smart_edges` | Innere Antreiber und Quellen deiner Energie. |
|
||||||
|
| **`boundary`** | 0.90 | `sliding_smart_edges` | Deine persönlichen Grenzen und Integritäts-Leitplanken. |
|
||||||
|
| **`bias`** | 0.80 | `sliding_short` | Bekannte kognitive Verzerrungen und Denkfallen. |
|
||||||
|
|
||||||
|
### 3.1.2 Action Stream (Die Dynamik / Das „Was“)
|
||||||
|
Dieser Stream umfasst alles, was auf Umsetzung, Planung und aktuelle Zustände zielt.
|
||||||
|
|
||||||
|
| Typ | Gewicht | Chunking Profil | Zweck & Inhalt |
|
||||||
|
| :--- | :--- | :--- | :--- |
|
||||||
|
| **`project`** | 0.97 | `sliding_smart_edges` | Aktive Vorhaben mit Mission und Zielsetzung. |
|
||||||
|
| **`goal`** | 0.95 | `sliding_smart_edges` | Strategische Nordsterne und Zielzustände. |
|
||||||
|
| **`decision`** | 1.00 | `structured_strict` | Getroffene Entscheidungen (ADR-Logik). |
|
||||||
|
| **`risk`** | 0.85 | `sliding_short` | Potenzielle Gefahren und Bedrohungsszenarien. |
|
||||||
|
| **`obstacle`** | 1.00 | `structured_strict` | Aktuelle Hürden, Ängste und Blockaden. |
|
||||||
|
| **`task`** | 0.80 | `sliding_short` | Operative Aufgaben und Definition of Done. |
|
||||||
|
| **`skill`** | 0.90 | `sliding_smart_edges` | Fertigkeiten, Lernpfade und Meisterschaft. |
|
||||||
|
| **`habit`** | 0.85 | `sliding_short` | Routinen, Automatismen und Verhaltensmuster. |
|
||||||
|
| **`idea`** | 0.70 | `sliding_short` | Flüchtige Einfälle und Rohmaterial für Projekte. |
|
||||||
|
| **`state`** | 0.60 | `sliding_short` | Momentane Verfassung, Stimmung und Energielevel. |
|
||||||
|
|
||||||
|
### 3.1.3 History & Basis Stream (Die Evidenz / Das „Wann“)
|
||||||
|
Dieser Stream speichert deine Erlebnisse, Fakten und externes Wissen als Belege.
|
||||||
|
|
||||||
|
| Typ | Gewicht | Chunking Profil | Zweck & Inhalt |
|
||||||
|
| :--- | :--- | :--- | :--- |
|
||||||
|
| **`insight`** | 1.20 | `sliding_smart_edges` | Hochrelevante Erkenntnisse und Verhaltensmuster. |
|
||||||
|
| **`experience`**| 1.10 | `sliding_smart_edges` | Biografische Lektionen und prägende Erlebnisse. |
|
||||||
|
| **`event`** | 0.60 | `sliding_standard` | Chronologische Protokolle und Ereignisse. |
|
||||||
|
| **`journal`** | 0.80 | `sliding_standard` | Tägliche Logs und ungefilterte Gedanken. |
|
||||||
|
| **`person`** | 0.50 | `sliding_standard` | Kontaktprofile und soziale Vernetzung. |
|
||||||
|
| **`source`** | 0.50 | `sliding_standard` | Externe Quellen wie Bücher, Videos oder Artikel. |
|
||||||
|
| **`concept`** | 0.60 | `sliding_smart_edges` | Fachbegriffe, Theorien und zeitloses Wissen. |
|
||||||
|
| **`glossary`** | 0.40 | `sliding_short` | Kurze Begriffsdefinitionen. |
|
||||||
|
| **`default`** | 1.00 | `sliding_standard` | Fallback für alle nicht klassifizierten Notizen. |
|
||||||
|
|
||||||
|
### 3.2 Status und Bedeutung
|
||||||
|
|
||||||
|
| Status | Bedeutung | Auswirkung auf die KI |
|
||||||
|
| :--- | :--- | :--- |
|
||||||
|
| **`stable`** | **Geprüftes Wissen.** Die Notiz ist inhaltlich korrekt, finalisiert und verlässlich (Gold-Standard). | **🚀 Bevorzugt (Bonus):** Die KI vertraut diesen Inhalten mehr (+20% Relevanz-Score). Bei widersprüchlichen Infos gewinnt `stable`. |
|
||||||
|
| **`active`** | **Standard.** Aktuelle Arbeitsnotizen, Projekte oder Dokumentationen (Default, wenn leer). | **🔵 Neutral:** Standard-Gewichtung (Faktor 1.0). |
|
||||||
|
| **`draft`** | **Entwurf.** Brainstorming, unstrukturierte Mitschriften oder rohe Ideen. | **🔻 Gedämpft (Malus):** Die KI nutzt diese Infos nur, wenn es keine besseren Treffer gibt (Relevanz auf 50% reduziert). Reduziert "Rauschen" in den Antworten. |
|
||||||
|
| **`system`** | **Intern.** Konfigurationsdateien, technische Logs oder Admin-Skripte. | **❌ Ignoriert (Hard Skip):** Die Datei wird **nicht** in den Suchindex aufgenommen und ist für den Chat unsichtbar. |
|
||||||
|
| **`template`**| **Vorlage.** Leere Gerüste für neue Notizen (z.B. für Obsidian). | **❌ Ignoriert (Hard Skip):** Verhindert, dass leere Vorlagen als Suchergebnisse auftauchen. |
|
||||||
|
|
||||||
|
### Wann nutze ich welchen Status?
|
||||||
|
|
||||||
|
1. **Ideenfindung:** Setzen Sie neue Ideen immer auf **`draft`**. So können Sie frei schreiben, ohne dass die KI sofort "Halbwissen" als Fakten verkauft.
|
||||||
|
2. **Finalisierung:** Sobald eine Entscheidung getroffen oder ein Konzept fertig ist, ändern Sie den Status auf **`stable`**.
|
||||||
|
3. **Konfiguration:** Nutzen Sie **`system`** für Dateien wie die `01_edge_vocabulary.md`, damit die KI nicht die Definition der Kanten zitiert, wenn Sie eigentlich nach Inhalten suchen.
|
||||||
|
|
||||||
|
### 3.3 Aliases (Synonyme & Verlinkung)
|
||||||
|
|
||||||
|
Nutze `aliases: [Synonym]` für:
|
||||||
|
1. **Flüssiges Schreiben:** `[[RAG]]` statt `[[Retrieval Augmented Generation]]`.
|
||||||
|
2. **Semantische Anker:** Der Chat findet die Notiz auch über den Alias-Begriff.
|
||||||
|
|
||||||
|
|
||||||
|
Das optionale Feld `aliases` erlaubt es dir, einer Notiz alternative Titel oder Synonyme zu geben. Dies ist ein mächtiges Werkzeug für die Usability und die Suche.
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
---
|
||||||
|
title: Leitbild – Handlungsprinzipien
|
||||||
|
aliases: [Prinzipien, Handlungsleitlinien, Entscheidungsprinzipien]
|
||||||
|
---
|
||||||
|
|
||||||
|
**Best Practices für Aliases**
|
||||||
|
|
||||||
|
Damit dein System sauber bleibt, beachte diese Regeln:
|
||||||
|
|
||||||
|
* ✅ **Akronyme & Abkürzungen:**
|
||||||
|
Nutze Aliases für technische Kürzel.
|
||||||
|
* *Note:* `Retrieval Augmented Generation`
|
||||||
|
* *Alias:* `[RAG, RAG-Architektur]`
|
||||||
|
* *Vorteil:* Du tippst im Fließtext nur `[[RAG]]` und bist fertig.
|
||||||
|
|
||||||
|
* ✅ **Projekt-Codenamen:**
|
||||||
|
Verbinde den offiziellen Titel mit dem Flur-Namen.
|
||||||
|
* *Note:* `Projekt Phoenix – Cloud Migration`
|
||||||
|
* *Alias:* `[Phoenix, Cloud-Projekt]`
|
||||||
|
|
||||||
|
* ❌ **Vermeide generische Begriffe (Namespace Pollution):**
|
||||||
|
Gib einer spezifischen Notiz niemals einen Alias, der ein allgemeines Wort ist.
|
||||||
|
* *Schlecht:* Alias `[Meeting]` für `2025-10-JourFixe`.
|
||||||
|
* *Folge:* Jedes Mal, wenn du das Wort "Meeting" tippst, schlägt Obsidian dir diesen einen alten Jour Fixe vor. Das zerstört den Schreibfluss.
|
||||||
|
|
||||||
|
* ❌ **Keine Plural-Wahn:**
|
||||||
|
Mindnet und Obsidian finden meist auch den Plural (Fuzzy Search). Du musst nicht `[Prinzip, Prinzipien, Prinzips]` anlegen. Ein Stammbegriff reicht oft.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. Edges & Verlinkung
|
||||||
|
|
||||||
|
Mindnet versteht Zusammenhänge durch Kanten.
|
||||||
|
|
||||||
|
### 4.1 Inline-Relationen (Semantische Verknüpfung)
|
||||||
|
Dies ist die **mächtigste** Methode. Du sagst dem System explizit, **wie** Dinge zusammenhängen.
|
||||||
|
|
||||||
|
> "Daher [[rel:depends_on Qdrant]]."
|
||||||
|
> "Dieses Konzept ist [[rel:similar_to Pinecone]]."
|
||||||
|
|
||||||
|
**Gültige Relationen:**
|
||||||
|
* `depends_on`: Hängt ab von / Benötigt.
|
||||||
|
* `blocks`: Blockiert oder gefährdet (z.B. Risiko -> Projekt).
|
||||||
|
* `caused_by`: Wurde verursacht durch (Kausalität).
|
||||||
|
* `similar_to`: Ähnelt / Ist vergleichbar mit.
|
||||||
|
* `solves`: Löst (Problem).
|
||||||
|
* `based_on`: Basiert auf (Fundament).
|
||||||
|
* **`prev` / `next` [NEU]**: Markiert chronologische oder evolutionäre Abfolgen (z.B. Leitbild-Evolution).
|
||||||
|
|
||||||
|
### 4.2 Callout-Edges (empfohlen)
|
||||||
|
Für Zusammenfassungen am Ende einer Notiz, oder eines Absatzes:
|
||||||
|
|
||||||
|
```markdown
|
||||||
|
> [!edge] related_to
|
||||||
|
> [[Vector Embeddings]]
|
||||||
|
> [[AI Agents]]
|
||||||
|
```
|
||||||
|
|
||||||
|
### 4.3 Implizite Bidirektionalität (Edger-Logik) [NEU] [PRÜFEN!]
|
||||||
|
In Mindnet musst du Kanten **nicht** manuell in beide Richtungen pflegen. Der **Edger** übernimmt die Paarbildung automatisch im Hintergrund.
|
||||||
|
|
||||||
|
**Deine Aufgabe:** Setze die Kante in der Datei, die du gerade bearbeitest, so wie es der **logische Fluss** vorgibt.
|
||||||
|
|
||||||
|
* **Blick zurück (Rückwärtslink):** Wenn du ein Ergebnis dokumentierst, nutze `derived_from`, `based_on` oder `prev`.
|
||||||
|
* **Blick nach vorn (Vorwärtslink):** Wenn du einen Plan oder ein Protokoll schreibst, nutze `resulted_in`, `supports` oder `next`.
|
||||||
|
|
||||||
|
**System-Logik (Beispiele):**
|
||||||
|
- Schreibst du in Note A: `next: [[B]]`, weiß das System automatisch: `B prev A`.
|
||||||
|
- Schreibst du in Note B: `derived_from: [[A]]`, weiß das System automatisch: `A resulted_in B`.
|
||||||
|
|
||||||
|
**Vorteil:** Keine redundante Datenpflege, kein "Link-Nightmare", volle Konsistenz im Graphen.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. Schreiben für den KI-Zwilling (Szenarien)
|
||||||
|
|
||||||
|
Damit der **RAG-Chat** dich berät, musst du "Futter" für die Decision Engine liefern.
|
||||||
|
|
||||||
|
### 5.1 Szenario A: Decision Engine (`DECISION`)
|
||||||
|
* **Ziel:** Das System soll abwägen: "Passt Tool X zu mir?"
|
||||||
|
* **Vorgehen:** Erstelle Notizen mit `type: value` oder `type: goal`.
|
||||||
|
|
||||||
|
* **Effekt:** Wenn du fragst "Soll ich Notion nutzen?", lädt die Engine diese Notiz und antwortet: *"Nein, Notion ist SaaS ohne E2E. Das verletzt dein Prinzip der Datensparsamkeit."*
|
||||||
|
|
||||||
|
### Szenario B: Empathie (`EMPATHY`)
|
||||||
|
* **Ziel:** Das System soll dich verstehen.
|
||||||
|
* **Vorgehen:** Erstelle `type: experience` mit **emotionalen Brückenwörtern**.
|
||||||
|
|
||||||
|
**Beispiel Notiz:**
|
||||||
|
```yaml
|
||||||
|
---
|
||||||
|
type: experience
|
||||||
|
title: Erfahrung: Der Durchbruch nach der Krise
|
||||||
|
tags: [krise, hoffnung, grau, angst]
|
||||||
|
---
|
||||||
|
Es gibt Projektphasen, da wirkt alles **sinnlos** und **grau**.
|
||||||
|
Ich habe gelernt: Das ist oft das Zeichen kurz vor dem Durchbruch.
|
||||||
|
```
|
||||||
|
* **Effekt:** Bei "Alles ist grau" findet das System diese Notiz und spiegelt die Lektion zurück.
|
||||||
|
|
||||||
|
### 5.2 **Szenario C: Forward-Mapping (Lücken-Analyse) [NEU]**
|
||||||
|
* **Ziel:** Strategische Wissenslücken füllen.
|
||||||
|
* **Vorgehen:** Erstelle Hub-Notizen mit Forward-Links auf noch nicht existierende Dateien (z. B. `[[Besten Version meiner Selbst]]`).
|
||||||
|
* **Effekt:** Das System erkennt die semantische Bedeutung des geplanten Wissens und kann proaktiv Fragen stellen, um diese Lücken zu schließen.
|
||||||
|
|
||||||
|
### 5.3 **Szenario D: Narratives Gedächtnis (Intention) [NEU]**
|
||||||
|
* **Ziel:** Das System soll verstehen, *warum* eine Entscheidung getroffen wurde, um in ähnlichen künftigen Situationen konsistent zu beraten.
|
||||||
|
* **Vorgehen:** Nutze in `journal`- oder `experience`-Notizen Abschnitte für "Hintergrund" und "Interpretation".
|
||||||
|
* **Beispiel:** Statt "Wert: Disziplin" schreibe "Ich wähle Disziplin, weil ich in meiner Kindheit erlebt habe, wie Willkür schadet."
|
||||||
|
* **Effekt:** Die KI spiegelt nicht nur die Regel, sondern die Überzeugung dahinter.
|
||||||
|
|
||||||
|
### 5.4 Szenario C: Forward-Mapping (Lücken-Analyse)
|
||||||
|
Setze bewusst Links auf Dateien, die noch nicht existieren (z.B. `[[Die beste Version meiner selbst]]`). Die KI erkennt diese semantischen Lücken und stellt im Chat proaktive Fragen, um diese Felder mit dir zu füllen.
|
||||||
|
|
||||||
|
### 5.5 Szenario D: Narratives Gedächtnis
|
||||||
|
Dokumentiere das "Warum" (Fleisch am Knochen). Wenn du schreibst: *"Ich wähle Disziplin, weil ich Willkür als Kind schmerzhaft erlebt habe"*, versteht die KI die emotionale Kausalität und kann dich in Krisen an diesen Ursprung erinnern.
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. Best Practices & Beispiele
|
||||||
|
|
||||||
|
### 6.1 Beispiel: Projekt-Notiz (Standard)
|
||||||
|
Projekte profitieren von `depends_on`, um Abhängigkeiten zu klären.
|
||||||
|
|
||||||
|
```markdown
|
||||||
|
---
|
||||||
|
id: 20251115-proj-mindnet
|
||||||
|
title: Mindnet Implementierung
|
||||||
|
type: project
|
||||||
|
status: active
|
||||||
|
---
|
||||||
|
|
||||||
|
# Mindnet Implementierung
|
||||||
|
|
||||||
|
Wir bauen ein persönliches Wissensnetz.
|
||||||
|
|
||||||
|
## Tech Stack
|
||||||
|
Wir nutzen [[rel:depends_on Qdrant]] für die Vektorsuche und [[rel:depends_on FastAPI]] für das Backend.
|
||||||
|
|
||||||
|
## Architektur
|
||||||
|
Das Konzept basiert auf [[RAG Architecture]].
|
||||||
|
```
|
||||||
|
|
||||||
|
### 6.2 Beispiel: Advanced Tuning (Manuelles Override)
|
||||||
|
Hier zwingen wir das System, eine Entscheidung extrem kleinteilig (`strict`) zu zerlegen und in der Suche maximal zu priorisieren.
|
||||||
|
|
||||||
|
```markdown
|
||||||
|
---
|
||||||
|
id: 20251120-adr-vektordb
|
||||||
|
title: ADR: Wahl von Qdrant
|
||||||
|
type: decision
|
||||||
|
status: final
|
||||||
|
tags: [architektur, db]
|
||||||
|
chunking_profile: structured_smart_edges_strict
|
||||||
|
retriever_weight: 1.5
|
||||||
|
---
|
||||||
|
|
||||||
|
# Entscheidung: Qdrant
|
||||||
|
|
||||||
|
Wir haben uns für Qdrant entschieden.
|
||||||
|
|
||||||
|
## Alternativen
|
||||||
|
Wir haben auch [[rel:similar_to Pinecone]] und [[rel:similar_to Weaviate]] betrachtet.
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 7. Virtual Schema Layer
|
||||||
|
|
||||||
|
Grundsätzlich gilt das Prinzip des **Virtual Schema Layers**. Die Logik (wie `chunk_size`) wird zentral in der `types.yaml` verwaltet.
|
||||||
|
**Aber:** Als Power-User hast du über die Overrides jederzeit die Möglichkeit, aus diesem Standard auszubrechen.
|
||||||
@@ -0,0 +1,72 @@
|
|||||||
|
---
|
||||||
|
doc_type: technical_reference
|
||||||
|
audience: developer, power_user
|
||||||
|
scope: obsidian, scripts, workflow
|
||||||
|
status: active
|
||||||
|
version: 1.0.0
|
||||||
|
context: "Setup und Dokumentation der Obsidian-Integration für Mindnet v2.9."
|
||||||
|
---
|
||||||
|
|
||||||
|
# Obsidian Integration Guide
|
||||||
|
|
||||||
|
Dieses Dokument beschreibt die technische Implementierung der Mindnet-Logik innerhalb von Obsidian mittels Templater-Skripten.
|
||||||
|
|
||||||
|
## 1. Voraussetzungen
|
||||||
|
|
||||||
|
Um die volle Funktionalität des Mindnet-Workflows zu nutzen, sind folgende Obsidian-Plugins zwingend erforderlich:
|
||||||
|
* **Templater:** Für die Ausführung der JavaScript-Logik beim Erstellen von Notizen und Kanten.
|
||||||
|
* **Meta Bind (Optional):** Zur intuitiven Steuerung von Frontmatter-Feldern wie `retriever_weight`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Kern-Komponenten
|
||||||
|
|
||||||
|
### 2.1 Mindnet Universal Creator (`mindnetCreate.js`)
|
||||||
|
Das zentrale Skript zur Erstellung neuer Notizen. Es stellt sicher, dass jede Datei im korrekten Ordner landet und das notwendige Frontmatter für das Mindnet-Backend erhält.
|
||||||
|
|
||||||
|
**Kern-Funktionen:**
|
||||||
|
* Automatische Typ-Auswahl basierend auf den Vorlagen in `_system/templates/creation`.
|
||||||
|
* Validierung und Erzwingung der ID-Syntax (`YYYYMMDDHHmm-slug`).
|
||||||
|
* Pfad-Erzwingung bei Verlinkungen, um die Konsistenz des Graphen zu wahren.
|
||||||
|
|
||||||
|
### 2.2 Edge Callout Selector Skript
|
||||||
|
Dieses Skript ermöglicht das Einfügen von semantischen Kanten (`[!edge]`) durch Auswahl aus dem zentralen Wörterbuch.
|
||||||
|
|
||||||
|
**Features:**
|
||||||
|
* **Kategorisierte Auswahl:** Gruppierung der Kanten nach Themenbereichen (H3-Ebene der Vokabel-Datei).
|
||||||
|
* **Alias-Support:** Ermöglicht die Wahl zwischen technischem System-Namen (Canonical) und benutzerfreundlichen Aliasen.
|
||||||
|
* **Automatisches Callout-Formatting:** Transformiert markierte Wikilinks direkt in einen validen Edge-Block.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Konfiguration & Speicherorte
|
||||||
|
|
||||||
|
Damit die Skripte funktionieren, müssen folgende Pfade im Vault existieren:
|
||||||
|
|
||||||
|
| Pfad | Inhalt / Zweck |
|
||||||
|
| :--- | :--- |
|
||||||
|
| `_system/scripts/` | Speicherort für die `.js` Module (z.B. `mindnetCreate.js`). |
|
||||||
|
| `_system/templates/` | Ablage für die Templater-Trigger-Dateien. |
|
||||||
|
| `_system/templates/creation/` | Enthält die Typ-spezifischen Vorlagen (z.B. `template-insight.md`). |
|
||||||
|
| `_system/dictionary/edge_vocabulary.md` | Single Source of Truth für alle erlaubten Kanten-Typen. |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. Workflow-Integration
|
||||||
|
|
||||||
|
### 4.1 Notiz-Erstellung
|
||||||
|
1. Verwenden des Hotkeys für den `Mindnet Creator`.
|
||||||
|
2. Auswahl des gewünschten Typs (z. B. `EXPERIENCE`).
|
||||||
|
3. Das Skript erstellt die Datei im Zielordner und öffnet sie mit den passenden Leitfragen.
|
||||||
|
|
||||||
|
### 4.2 Kanten-Management
|
||||||
|
1. Markieren eines oder mehrerer Wikilinks im Text.
|
||||||
|
2. Starten des `Insert Edge Callout` Skripts.
|
||||||
|
3. Auswahl des Kanten-Typs (z. B. `caused_by`) und der gewünschten Bezeichnung.
|
||||||
|
4. Das Skript fügt den Block automatisch unter der Markierung ein.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. Wartung & Updates
|
||||||
|
|
||||||
|
Bei Änderungen an den Notiz-Typen in der `types.yaml` müssen die entsprechenden Markdown-Vorlagen im Ordner `creation` manuell synchronisiert werden, um die Konsistenz zwischen Obsidian und dem Backend zu wahren.
|
||||||
@@ -0,0 +1,102 @@
|
|||||||
|
---
|
||||||
|
doc_type: concept
|
||||||
|
audience: architect, product_owner
|
||||||
|
scope: ai, router, personas, resilience
|
||||||
|
status: active
|
||||||
|
version: 2.8.1
|
||||||
|
context: "Fachkonzept der hybriden KI-Persönlichkeit, der Provider-Kaskade und der kognitiven Resilienz (Deep Fallback)."
|
||||||
|
---
|
||||||
|
|
||||||
|
# Konzept: KI-Persönlichkeit & Router
|
||||||
|
|
||||||
|
**Quellen:** `mindnet_functional_architecture.md`, `llm_service.py`, `config.py`, `ingestion.py`
|
||||||
|
|
||||||
|
Mindnet soll nicht wie eine Suchmaschine wirken, sondern wie ein **Digitaler Zwilling**. Dazu muss das System erkennen, **was** der Nutzer will, und seine „Persönlichkeit“ sowie seine technische Infrastruktur dynamisch anpassen.
|
||||||
|
|
||||||
|
## 1. Der Hybrid Router (Das Gehirn)
|
||||||
|
|
||||||
|
Jede Eingabe durchläuft den **Hybrid Router**. Er entscheidet über die fachliche Strategie und die technische Ausführung.
|
||||||
|
|
||||||
|
### Modus A: RAG (Retrieval Augmented Generation)
|
||||||
|
* **Intent:** Der Nutzer hat eine Frage oder ein Problem (`FACT`, `DECISION`, `EMPATHY`).
|
||||||
|
* **Aktion:** Das System sucht im Gedächtnis und generiert eine Antwort.
|
||||||
|
|
||||||
|
### Modus B: Interview (Knowledge Capture)
|
||||||
|
* **Intent:** Der Nutzer will Wissen speichern (`INTERVIEW`).
|
||||||
|
* **Aktion:** Das System sucht **nicht**, sondern fragt ab und erstellt einen Draft.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Die hybride LLM-Landschaft (Resilienz-Kaskade)
|
||||||
|
|
||||||
|
Ein intelligenter Zwilling muss jederzeit verfügbar sein. Mindnet v2.8.1 nutzt eine **dreistufige Kaskade**, um Intelligenz, Kosten und Verfügbarkeit zu optimieren:
|
||||||
|
|
||||||
|
1. **Stufe 1: Cloud-Speed (Turbo-Mode):** Primäre Wahl für komplexe Extraktionsaufgaben und schnelle RAG-Antworten mittels OpenRouter (Mistral-7B) oder Google Gemini (2.5-flash-lite).
|
||||||
|
2. **Stufe 2: Quoten-Resilienz:** Erkennt das System eine Drosselung durch Cloud-Provider (HTTP 429), pausiert es kontrolliert (`LLM_RATE_LIMIT_WAIT`), führt automatisierte Retries durch und schützt so den laufenden Prozess.
|
||||||
|
3. **Stufe 3: Deep Fallback & lokale Souveränität (Ollama):** * **Technischer Fallback:** Schlagen alle Cloud-Versuche fehl, übernimmt das lokale Modell (Phi-3).
|
||||||
|
* **Kognitiver Fallback (v2.11.14):** Liefert die Cloud zwar technisch eine Antwort, verweigert aber inhaltlich die Verarbeitung (Silent Refusal/Policy Violation), wird ein **Deep Fallback** erzwungen, um die Datenintegrität lokal zu retten.
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Die Personas (Strategien)
|
||||||
|
|
||||||
|
Mindnet wechselt den Hut, je nach Situation.
|
||||||
|
|
||||||
|
### 3.1 Der Berater (Strategy: DECISION)
|
||||||
|
* **Auslöser:** Fragen wie „Soll ich...?“, „Was ist besser?“.
|
||||||
|
* **Strategic Retrieval:** Lädt aktiv Notizen der Typen `value` (Werte), `goal` (Ziele) und `risk` (Risiken), auch wenn sie im Text nicht direkt vorkommen.
|
||||||
|
* **Reasoning:** *„Wäge die Fakten gegen meine Werte ab. Sei strikt bei Risiken.“*
|
||||||
|
|
||||||
|
### 3.2 Der Spiegel (Strategy: EMPATHY)
|
||||||
|
* **Auslöser:** Emotionale Aussagen („Ich bin frustriert“).
|
||||||
|
* **Strategic Retrieval:** Lädt `experience` (Erfahrungen) und `belief` (Glaubenssätze).
|
||||||
|
* **Reasoning:** *„Nutze meine eigenen Erfahrungen, um die Situation einzuordnen.“*
|
||||||
|
|
||||||
|
### 3.3 Der Bibliothekar (Strategy: FACT)
|
||||||
|
* **Auslöser:** Sachfragen („Was ist Qdrant?“).
|
||||||
|
* **Behavior:** Präzise, neutral, kurz.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. Future Concepts: The Empathic Digital Twin
|
||||||
|
|
||||||
|
### 4.1 Antizipation durch Erfahrung
|
||||||
|
* **Konzept:** Das System soll Konsequenzen vorhersagen („Was passiert, wenn...?“).
|
||||||
|
* **Logik:** *„In einer ähnlichen Situation (Projekt A) hat Entscheidung X zu Ergebnis Y geführt.“* (Analogie-Schluss).
|
||||||
|
|
||||||
|
### 4.2 Empathie & „Ich“-Modus
|
||||||
|
* **Konzept:** Das System antwortet im Tonfall des Nutzers.
|
||||||
|
* **Umsetzung:** Few-Shot Prompting mit eigenen E-Mails/Texten als Stilvorlage.
|
||||||
|
|
||||||
|
### 4.3 Resilienz als Charakterzug
|
||||||
|
Durch die **WP-20 Implementierung** zeigt das System „Geduld“: Bei Quoten-Engpässen bricht es nicht ab, sondern wartet auf freie Kapazitäten. Durch das **Deep Fallback (v2.11.14)** besitzt Mindnet eine kognitive Ausdauer, die inhaltliche Zensur oder Blockaden der Cloud erkennt und durch lokale Rechenpower auflöst.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. Erweiterbarkeit: Das „Teach-the-AI“ Paradigma
|
||||||
|
|
||||||
|
Mindnet lernt durch **Konfiguration** und **Vernetzung**.
|
||||||
|
|
||||||
|
**Beispiel: Du willst den Typ `risk` einführen.**
|
||||||
|
|
||||||
|
**1. Daten-Ebene (Physik)**
|
||||||
|
In `types.yaml`: Definiere Gewicht und Verhalten.
|
||||||
|
```yaml
|
||||||
|
risk:
|
||||||
|
retriever_weight: 0.90 # Hohe Priorität
|
||||||
|
edge_defaults: ["blocks"] # Automatische Kante zu Projekten
|
||||||
|
```
|
||||||
|
|
||||||
|
**2. Strategie-Ebene (Router)**
|
||||||
|
In `decision_engine.yaml`: Wann soll das geladen werden?
|
||||||
|
```yaml
|
||||||
|
DECISION:
|
||||||
|
inject_types: ["value", "risk"] # Füge 'risk' hinzu
|
||||||
|
```
|
||||||
|
|
||||||
|
**3. Kognitive Ebene (Verständnis)**
|
||||||
|
In `prompts.yaml`: Erkläre dem LLM (provider-spezifisch mittels der Prompt-Kaskade), was ein Risiko ist.
|
||||||
|
|
||||||
|
**Fazit:** Nur wenn **Daten** (Vault), **Infrastruktur** (Resiliente Kaskade) und **Semantik** (Prompt) zusammenspielen, entsteht ein intelligenter Zwilling.
|
||||||
@@ -0,0 +1,125 @@
|
|||||||
|
---
|
||||||
|
doc_type: concept
|
||||||
|
audience: architect, product_owner
|
||||||
|
scope: graph, logic, provenance
|
||||||
|
status: active
|
||||||
|
version: 2.7.0
|
||||||
|
context: "Fachliche Beschreibung des Wissensgraphen: Knoten, Kanten, Provenance, Matrix-Logik und WP-22 Scoring-Prinzipien."
|
||||||
|
---
|
||||||
|
|
||||||
|
# Konzept: Die Graph-Logik
|
||||||
|
|
||||||
|
**Quellen:** `mindnet_functional_architecture.md`, `chunking_strategy.md`, `01_edge_vocabulary.md`, `retriever_scoring.py`, `03_tech_retrieval_scoring.md`
|
||||||
|
|
||||||
|
Mindnet ist keine reine Dokumentablage, sondern ein **semantischer Graph**. Dieses Dokument beschreibt, wie aus statischen Textdateien ein vernetztes Wissensobjekt wird.
|
||||||
|
|
||||||
|
## 1. Die Knoten (Nodes)
|
||||||
|
|
||||||
|
Der Graph besteht aus zwei Ebenen von Knoten.
|
||||||
|
|
||||||
|
### 1.1 Die Note (Das Fachobjekt)
|
||||||
|
Eine Note repräsentiert ein atomares Konzept (z.B. "Projekt Alpha").
|
||||||
|
* **Eigenschaften:** Titel, Typ, Tags, Erstellungsdatum sowie der **Status** (Lifecycle).
|
||||||
|
* **Rolle:** Sie ist der Container für Metadaten und steuert via `type`, wie der Inhalt verarbeitet wird (siehe `types.yaml`).
|
||||||
|
* **Identität:** Definiert durch eine deterministische UUIDv5.
|
||||||
|
|
||||||
|
### 1.2 Der Chunk (Das Suchobjekt)
|
||||||
|
Da LLMs (Large Language Models) nicht unendlich viel Text auf einmal lesen können, werden Notes in kleinere Segmente (**Chunks**) zerlegt.
|
||||||
|
* **Eigenschaften:** Vektor (Embedding 768d), Textfenster, Link zum Vorgänger/Nachfolger.
|
||||||
|
* **Rolle:** Dies sind die eigentlichen Treffer bei einer Suche.
|
||||||
|
* **Hierarchie:** Jeder Chunk gehört streng zu einer Note (`belongs_to`).
|
||||||
|
|
||||||
|
### 1.3 Content Lifecycle & Status (WP-22)
|
||||||
|
Seit v2.7 beeinflusst der `status` einer Note direkt deren Gewichtung im Retrieval (Lifecycle Scoring).
|
||||||
|
* **Stable:** Notizen mit `status: stable` erhalten einen positiven Modifier (Standard: 1.0), da sie geprüftes Wissen repräsentieren.
|
||||||
|
* **Draft:** Notizen mit `status: draft` werden durch einen Malus (Standard: 0.5 - 0.8) herabgestuft, um "Rauschen" durch unfertige Gedanken zu reduzieren.
|
||||||
|
* **System/Template:** Diese Status-Typen führen zu einem vollständigen Ausschluss aus dem Index.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Die Kanten (Edges)
|
||||||
|
|
||||||
|
Kanten machen aus isolierten Informationen Wissen. Mindnet nutzt gerichtete Kanten mit semantischer Bedeutung, die durch die **Edge Registry** validiert werden.
|
||||||
|
|
||||||
|
### 2.1 Kanonische Typen & Aliase
|
||||||
|
Um eine konsistente mathematische Gewichtung zu garantieren, werden alle Kanten auf **kanonische Typen** normalisiert.
|
||||||
|
|
||||||
|
| Kanonischer Typ | Aliase (Beispiele) | Bedeutung |
|
||||||
|
| :--- | :--- | :--- |
|
||||||
|
| `caused_by` | `ausgelöst_durch`, `wegen` | Kausalität: A löst B aus. |
|
||||||
|
| `derived_from` | `abgeleitet_von`, `quelle` | Herkunft: A stammt von B. |
|
||||||
|
| `based_on` | `basiert_auf`, `fundament` | Fundament: B baut auf A auf. |
|
||||||
|
| `solves` | `löst`, `fix_für` | Lösung: A ist Lösung für Problem B. |
|
||||||
|
| `part_of` | `teil_von`, `cluster` | Hierarchie: Kind -> Eltern. |
|
||||||
|
| `depends_on` | `braucht`, `requires` | Abhängigkeit: A braucht B. |
|
||||||
|
| `blocks` | `blockiert`, `risiko_für` | Blocker: A verhindert B. |
|
||||||
|
| `related_to` | `siehe_auch`, `kontext` | Lose Assoziation. |
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
### 2.2 Provenance (Herkunft & Vertrauen)
|
||||||
|
|
||||||
|
Nicht alle Kanten sind gleich viel wert. Mindnet unterscheidet drei Qualitätsstufen (**Provenance**), um bei der Berechnung des Edge-Bonus Prioritäten zu setzen.
|
||||||
|
|
||||||
|
**1. Explicit (Der Mensch hat es gesagt)**
|
||||||
|
* *Quelle:* Inline-Links (`[[rel:...]]`) oder Wikilinks im Text.
|
||||||
|
* *Vertrauen:* **Hoch (1.0)**.
|
||||||
|
* *Bedeutung:* Hartes Faktenwissen. Die explizite menschliche Intention wird im Scoring am stärksten gewichtet.
|
||||||
|
|
||||||
|
**2. Smart (Die KI hat es bestätigt)**
|
||||||
|
* *Quelle:* Smart Edge Allocation (WP15).
|
||||||
|
* *Vertrauen:* **Mittel (0.9)**.
|
||||||
|
* *Bedeutung:* Ein LLM hat die Relevanz des Links im Kontext geprüft. Dies filtert irrelevante Links (z.B. aus Navigationsleisten) heraus.
|
||||||
|
|
||||||
|
**3. Rule (Die Regel hat es vermutet)**
|
||||||
|
* *Quelle:* `types.yaml` Defaults oder Matrix-Logik.
|
||||||
|
* *Vertrauen:* **Niedrig (0.7)**.
|
||||||
|
* *Bedeutung:* Systemseitige Heuristik. Diese Verbindungen dienen der Entdeckung neuer Pfade, haben aber weniger Gewicht als explizite Links.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Matrix-Logik (Kontext-Sensitivität)
|
||||||
|
|
||||||
|
Die Matrix-Logik bestimmt Kanten-Typen dynamisch anhand der Quell- und Ziel-Typen der verknüpften Notizen.
|
||||||
|
|
||||||
|
**Logik-Beispiele:**
|
||||||
|
* **Quelle `experience` → Ziel `value`**: Wird zu `based_on` (Erfahrungen fußen auf Werten).
|
||||||
|
* **Quelle `principle` → Ziel `source`**: Wird zu `derived_from` (Prinzipien stammen aus Quellen).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. Semantisch bezogene Booster & Scoring-Logik
|
||||||
|
|
||||||
|
Das Scoring in Mindnet v2.7 folgt einer hybriden Logik, bei der semantische Ähnlichkeit durch kontextuelle Faktoren modifiziert wird.
|
||||||
|
|
||||||
|
### 4.1 Semantische Modifikatoren (Type & Status)
|
||||||
|
Bevor der Graph-Bonus berechnet wird, durchläuft die semantische Ähnlichkeit (Cosine Similarity) zwei Filter:
|
||||||
|
1. **Type-Weight ($W_{type}$):** Bestimmt die "Wichtigkeit" einer Notizklasse. Ein Wert von 1.0 (z. B. für `decision`) lässt die volle semantische Stärke durch. Ein Wert von 0.4 (z. B. für `glossary`) dämpft den Treffer massiv ab, es sei denn, die Frage passt exakt auf den Text.
|
||||||
|
2. **Status-Modifier:** Agiert als Qualitätsfilter. `draft` markierte Inhalte werden herabgestuft, damit `stable` Inhalte bei gleicher semantischer Passung immer oben stehen.
|
||||||
|
|
||||||
|
### 4.2 Graph-Boosting (Additive Boni)
|
||||||
|
Der Graph-Bonus wird auf den modifizierten semantischen Score addiert. Dies ermöglicht es Inhalten, im Ranking nach oben zu steigen, wenn sie stark mit anderen relevanten Treffern vernetzt sind.
|
||||||
|
|
||||||
|
| Parameter-Gruppe | Wertebereich | Logik |
|
||||||
|
| :--- | :--- | :--- |
|
||||||
|
| **Notiz-Gewichte** | 0.1 - 1.0 | Multiplikativ. Dient als Relevanz-Filter für Informationstypen. |
|
||||||
|
| **Kanten-Boosts** | 0.1 - 3.0+ | Additiv. Hebt vernetztes Wissen über isolierte Texttreffer. |
|
||||||
|
| **Status-Malus** | 0.5 - 0.9 | Multiplikativ. Bestraft unfertiges Wissen (Drafts). |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. Dynamic Intent Boosting (WP-22)
|
||||||
|
|
||||||
|
In v2.7 ist die Graph-Gewichtung nicht mehr statisch, sondern hängt vom **Intent** der Nutzerfrage ab (Query-Time Boosting).
|
||||||
|
|
||||||
|
Der Intent-Router injiziert spezifische Multiplikatoren für kanonische Typen:
|
||||||
|
* **Intent `EMPATHY`**: Boostet `based_on` (Fokus auf Werte).
|
||||||
|
* **Intent `WHY`**: Boostet `caused_by` (Fokus auf Ursachenforschung).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. Idempotenz & Konsistenz
|
||||||
|
|
||||||
|
Das System garantiert fachliche Konsistenz auch bei mehrfachen Importen.
|
||||||
|
* **Stabile IDs:** Deterministische IDs verhindern Duplikate bei Re-Imports.
|
||||||
|
* **Deduplizierung:** Kanten werden anhand ihrer Identität erkannt. Die "stärkere" Provenance gewinnt.
|
||||||
@@ -0,0 +1,102 @@
|
|||||||
|
---
|
||||||
|
doc_type: technical_reference
|
||||||
|
audience: developer, architect
|
||||||
|
scope: backend, chat, llm_service, traffic_control, resilience
|
||||||
|
status: active
|
||||||
|
version: 2.8.1
|
||||||
|
context: "Technische Implementierung des FastAPI-Routers, des hybriden LLMService (v3.3.6) und der WP-20 Resilienz-Logik."
|
||||||
|
---
|
||||||
|
|
||||||
|
# Chat Backend & Traffic Control
|
||||||
|
|
||||||
|
## 1. Hybrid Router (Decision Engine)
|
||||||
|
|
||||||
|
Der zentrale Einstiegspunkt für jede Chatanfrage ist der **Hybrid Router** (`app/routers/chat.py`). Er entscheidet dynamisch über die Strategie und nutzt den `LLMService` zur provider-agnostischen Generierung.
|
||||||
|
|
||||||
|
### 1.1 Intent-Erkennung (Logik)
|
||||||
|
|
||||||
|
Der Router prüft den Input in drei Stufen (Wasserfall-Prinzip):
|
||||||
|
|
||||||
|
1. **Question Detection (Regelbasiert):**
|
||||||
|
* Prüfung auf Vorhandensein von `?` oder W-Wörtern (Wer, Wie, Was, Soll ich).
|
||||||
|
* Wenn positiv: **RAG Modus** (Interview wird blockiert).
|
||||||
|
2. **Keyword Scan (Fast Path):**
|
||||||
|
* Lädt `types.yaml` (Objekte) und `decision_engine.yaml` (Handlungen).
|
||||||
|
* Wenn Match (z.B. "Projekt" + "neu"): **INTERVIEW Modus**.
|
||||||
|
3. **LLM Fallback (Slow Path):**
|
||||||
|
* Wenn unklar: Anfrage an LLM zur Klassifizierung mittels `router_prompt`.
|
||||||
|
|
||||||
|
### 1.2 Prompt-Auflösung (Bulletproof Resolution)
|
||||||
|
|
||||||
|
Um Kompatibilitätsprobleme mit verschachtelten YAML-Prompts zu vermeiden, nutzt der Router die Methode `llm.get_prompt()`. Diese implementiert eine **Provider-Kaskade**:
|
||||||
|
* **Spezifischer Provider:** Das System sucht zuerst nach einem Prompt für den aktiv konfigurierten Provider (z.B. `openrouter`).
|
||||||
|
* **Cloud-Stil Fallback:** Existiert dieser nicht, erfolgt ein Fallback auf das `gemini`-Template.
|
||||||
|
* **Basis-Fallback:** Als letzte Instanz wird das `ollama`-Template geladen.
|
||||||
|
* **String-Garantie:** Die Methode garantiert die Rückgabe eines Strings (selbst bei verschachtelten YAML-Dicts), was 500-Fehler bei String-Operationen wie `.replace()` oder `.format()` verhindert.
|
||||||
|
|
||||||
|
### 1.3 RAG Flow (Technisch)
|
||||||
|
|
||||||
|
Wenn der Intent `FACT` oder `DECISION` ist, wird folgender Flow ausgeführt:
|
||||||
|
|
||||||
|
1. **Pre-Processing:** Query Rewriting (optional).
|
||||||
|
2. **Context Enrichment:**
|
||||||
|
* Abruf via `retriever.py` (Hybrid Search).
|
||||||
|
* Integration von **Edge Boosts** aus der `decision_engine.yaml` zur Beeinflussung der Graph-Gewichtung.
|
||||||
|
* Injection von Metadaten (`[TYPE]`, `[SCORE]`) in den Prompt.
|
||||||
|
3. **Prompt Construction:** Assembly aus System-Prompt (Persona) + Context + Query.
|
||||||
|
4. **Streaming:** LLM-Antwort wird via **SSE (Server-Sent Events)** an den Client gestreamt.
|
||||||
|
5. **Post-Processing:** Anhängen des `Explanation` Layers (JSON-Breakdown) an das Ende des Streams.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. LLM Service & Traffic Control (WP-20)
|
||||||
|
|
||||||
|
Der `LLMService` (`app/services/llm_service.py`) fungiert als zentraler Hybrid-Client für OpenRouter, Google Gemini und Ollama. Er schützt das System vor Überlastung und verwaltet Quoten.
|
||||||
|
|
||||||
|
### 2.1 Prioritäts-Semaphor
|
||||||
|
|
||||||
|
Jeder LLM-Request steuert über ein `priority`-Flag den Zugriff auf Hardware- und API-Ressourcen:
|
||||||
|
|
||||||
|
| Priority | Verwendung | Limitierung |
|
||||||
|
| :--- | :--- | :--- |
|
||||||
|
| **realtime** | Chat-Anfragen, Intent-Routing | Keine (Hardware-Limit) |
|
||||||
|
| **background** | Smart Edge Allocation, Import-Tasks | `MINDNET_LLM_BACKGROUND_LIMIT` |
|
||||||
|
|
||||||
|
**Funktionsweise:**
|
||||||
|
* Hintergrund-Tasks nutzen ein globales `asyncio.Semaphore`.
|
||||||
|
* Das Limit (Standard: 2) verhindert, dass parallele Import-Vorgänge die API-Quoten oder die lokale CPU erschöpfen.
|
||||||
|
* Chat-Tasks umgehen die Semaphore für minimale Latenz.
|
||||||
|
|
||||||
|
### 2.2 Task-Mapping & Model Selection
|
||||||
|
|
||||||
|
Die Konfiguration ermöglicht eine spezialisierte Modell-Auswahl je nach Anwendungsfall:
|
||||||
|
* **Semantische Extraktion (Turbo):** Nutzt bevorzugt `OPENROUTER_MODEL` (Mistral-7B) für schnelles und präzises JSON-Parsing.
|
||||||
|
* **RAG-Chat:** Nutzt bevorzugt `GEMINI_MODEL` (2.5 flash-lite) für hohe Kapazität und Stabilität mittels erzwungener **v1-API Version**.
|
||||||
|
|
||||||
|
### 2.3 Timeout-Konfiguration
|
||||||
|
|
||||||
|
Deadlocks und "hängende" Importe werden durch differenzierte Timeouts verhindert:
|
||||||
|
* **Cloud-Calls (OpenRouter/Gemini):** Strikte **45 Sekunden** zur Vermeidung von Blockaden bei Provider-Latenz.
|
||||||
|
* **Lokales LLM (Ollama):** Konfigurierbar via `MINDNET_LLM_TIMEOUT` (Default: 300s).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Resilience & Quota Management (WP-20)
|
||||||
|
|
||||||
|
In v2.8 wurde ein intelligentes Fehler-Handling für Cloud-Provider implementiert:
|
||||||
|
|
||||||
|
1. **Rate-Limit Erkennung:** Der Service erkennt HTTP 429 Fehler sowie provider-spezifische Meldungen wie `RESOURCE_EXHAUSTED`.
|
||||||
|
2. **Intelligenter Backoff:** Statt sofort auf das langsame lokale Modell zu wechseln, pausiert das System für die Dauer von `LLM_RATE_LIMIT_WAIT` (Standard: 60s).
|
||||||
|
3. **Cloud-Retry:** Nach der Pause erfolgt ein erneuter Versuch (bis zu `LLM_RATE_LIMIT_RETRIES` Mal).
|
||||||
|
4. **Ollama Fallback:** Erst nach Erschöpfung der Retries schaltet das System auf den lokalen Ollama um, um die Betriebssicherheit zu gewährleisten ("Quoten-Schutz").
|
||||||
|
5. **Deep Fallback Support:** Der Service stellt die Infrastruktur für den inhaltsbasierten Fallback (v2.11.14) bereit, falls die Cloud zwar technisch antwortet, aber inhaltlich (z.B. wegen Policy-Filtern oder Silent Refusal) keine validen Daten liefert.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. Feedback Traceability
|
||||||
|
|
||||||
|
Unterstützt das geplante Self-Tuning (WP08).
|
||||||
|
|
||||||
|
1. **Query ID:** Generiert bei jedem `/query` Call eine `UUIDv4`.
|
||||||
|
2. **Logging:** Speichert einen Snapshot in `data/logs/query_snapshot.jsonl` (Input + Retrieved Context).
|
||||||
|
3. **Feedback:** Der `/feedback` Endpoint verknüpft das User-Rating (1-5) mit der `query_id`.
|
||||||
@@ -0,0 +1,328 @@
|
|||||||
|
---
|
||||||
|
doc_type: technical_reference
|
||||||
|
audience: developer, admin
|
||||||
|
scope: configuration, env, registry, scoring, resilience
|
||||||
|
status: active
|
||||||
|
version: 2.8.0
|
||||||
|
context: "Umfassende Referenztabellen für Umgebungsvariablen (inkl. Hybrid-Cloud & WP-76), YAML-Konfigurationen und die Edge Registry Struktur."
|
||||||
|
---
|
||||||
|
|
||||||
|
# Konfigurations-Referenz
|
||||||
|
|
||||||
|
Dieses Dokument beschreibt alle Steuerungsdateien von Mindnet. In der Version 2.8 wurde die Konfiguration professionalisiert, um die Edge Registry, dynamische Scoring-Parameter (Lifecycle & Intent) sowie die neue Hybrid-Cloud-Resilienz zu unterstützen.
|
||||||
|
|
||||||
|
## 1. Environment Variablen (`.env`)
|
||||||
|
|
||||||
|
Diese Variablen steuern die Infrastruktur, Pfade und globale Timeouts.
|
||||||
|
|
||||||
|
| Variable | Default | Beschreibung |
|
||||||
|
| :--- | :--- | :--- |
|
||||||
|
| `QDRANT_URL` | `http://localhost:6333` | URL zur Vektor-DB API. |
|
||||||
|
| `QDRANT_API_KEY` | *(leer)* | Optionaler Key für Absicherung. |
|
||||||
|
| `COLLECTION_PREFIX` | `mindnet` | Namensraum für Collections (erzeugt `{prefix}_notes` etc). |
|
||||||
|
| `VECTOR_DIM` | `768` | **Muss 768 sein** (für Nomic Embeddings). |
|
||||||
|
| `MINDNET_VOCAB_PATH` | *(Pfad)* | **Neu (WP-22):** Absoluter Pfad zur `01_edge_vocabulary.md`. Definiert den Ort des Dictionarys. |
|
||||||
|
| `MINDNET_VAULT_ROOT` | `./vault` | Basis-Pfad für Datei-Operationen. |
|
||||||
|
| `MINDNET_TYPES_FILE` | `config/types.yaml` | Pfad zur Typ-Registry. |
|
||||||
|
| `MINDNET_RETRIEVER_CONFIG`| `config/retriever.yaml`| Pfad zur Scoring-Konfiguration. |
|
||||||
|
| `MINDNET_DECISION_CONFIG` | `config/decision_engine.yaml` | Pfad zur Router & Intent Config. |
|
||||||
|
| `MINDNET_PROMPTS_PATH` | `config/prompts.yaml` | Pfad zu LLM Prompts. |
|
||||||
|
| `MINDNET_LLM_PROVIDER` | `openrouter` | **Neu (WP-20):** Aktiver Provider (`openrouter`, `gemini`, `ollama`). |
|
||||||
|
| `MINDNET_LLM_FALLBACK` | `true` | **Neu (WP-20):** Aktiviert automatischen Ollama-Fallback bei Cloud-Fehlern. |
|
||||||
|
| `MINDNET_LLM_RATE_LIMIT_WAIT`| `60.0` | **Neu (WP-76):** Wartezeit in Sekunden bei HTTP 429 (Rate Limit). |
|
||||||
|
| `MINDNET_LLM_RATE_LIMIT_RETRIES`| `3` | **Neu (WP-76):** Anzahl Cloud-Retries vor lokalem Fallback. |
|
||||||
|
| `GOOGLE_API_KEY` | *(Key)* | API Key für Google AI Studio. |
|
||||||
|
| `MINDNET_GEMINI_MODEL` | `gemini-2.5-flash-lite` | **Update 2025:** Optimiertes Lite-Modell für hohe Quoten. |
|
||||||
|
| `OPENROUTER_API_KEY` | *(Key)* | API Key für OpenRouter Integration. |
|
||||||
|
| `OPENROUTER_MODEL` | `mistralai/mistral-7b-instruct:free` | **Update 2025:** Verifiziertes Free-Modell für strukturierte Extraktion. |
|
||||||
|
| `MINDNET_LLM_MODEL` | `phi3:mini` | Name des lokalen Chat-Modells (Ollama). |
|
||||||
|
| `MINDNET_EMBEDDING_MODEL` | `nomic-embed-text` | Name des Embedding-Modells (Ollama). |
|
||||||
|
| `MINDNET_OLLAMA_URL` | `http://127.0.0.1:11434`| URL zum lokalen LLM-Server. |
|
||||||
|
| `MINDNET_LLM_TIMEOUT` | `300.0` | Timeout in Sekunden für LLM-Anfragen. |
|
||||||
|
| `MINDNET_API_TIMEOUT` | `300.0` | Globales API-Timeout für das Frontend. |
|
||||||
|
| `MINDNET_LL_BACKGROUND_LIMIT`| `2` | **Traffic Control:** Max. parallele Hintergrund-Tasks (Semaphore). |
|
||||||
|
| `MINDNET_CHANGE_DETECTION_MODE` | `full` | `full` (Text + Meta) oder `body` (nur Text). |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Typ-Registry (`types.yaml`)
|
||||||
|
|
||||||
|
Steuert das Import-Verhalten, Chunking und die Kanten-Logik pro Typ.
|
||||||
|
|
||||||
|
### 2.1 Konfigurations-Hierarchie (Override-Logik)
|
||||||
|
Seit Version 2.7.0 gilt für `chunking_profile` und `retriever_weight` folgende Priorität:
|
||||||
|
1. **Frontmatter (Höchste Prio):** Ein Wert direkt in der Markdown-Datei überschreibt alles.
|
||||||
|
2. **Type Config:** Der Standardwert für den `type` aus `types.yaml`.
|
||||||
|
3. **Global Default:** Fallback aus `defaults` in `types.yaml`.
|
||||||
|
|
||||||
|
|
||||||
|
## 2.2 Typ-Referenz & Stream-Logik (Vollständige Liste: 28 Typen)
|
||||||
|
|
||||||
|
Das System euriert Informationen in drei funktionalen Streams. Wähle den Typ danach aus, in welchem Bereich deines „Digitalen Zwillings“ die Information wirken soll.
|
||||||
|
|
||||||
|
### 2.2.1 Identity Stream (Der Kern / Das „Warum“)
|
||||||
|
Dieser Stream definiert deine stabilen Merkmale und inneren Kompasse.
|
||||||
|
|
||||||
|
| Typ | Gewicht | Chunking Profil | Zweck & Inhalt |
|
||||||
|
| :--- | :--- | :--- | :--- |
|
||||||
|
| **`value`** | 1.00 | `structured_strict` | Fundamentale Werte und moralische Maßstäbe. |
|
||||||
|
| **`principle`** | 0.95 | `structured_strict_L3` | Handlungsleitlinien mit tiefer Hierarchie (H3-Split). |
|
||||||
|
| **`trait`** | 1.10 | `structured_strict` | Charakterliche Stärken und Talente. |
|
||||||
|
| **`belief`** | 0.90 | `sliding_short` | Tiefe Überzeugungen über dich und die Gesellschaft. |
|
||||||
|
| **`profile`** | 0.70 | `structured_strict` | Rollenidentitäten (z. B. Vater, Mentor, Unternehmer). |
|
||||||
|
| **`need`** | 1.05 | `sliding_smart_edges` | Psychologische Grundbedürfnisse (z. B. Autonomie, Bindung). |
|
||||||
|
| **`motivation`**| 0.95 | `sliding_smart_edges` | Innere Antreiber und Quellen deiner Energie. |
|
||||||
|
| **`boundary`** | 0.90 | `sliding_smart_edges` | Deine persönlichen Grenzen und Integritäts-Leitplanken. |
|
||||||
|
| **`bias`** | 0.80 | `sliding_short` | Bekannte kognitive Verzerrungen und Denkfallen. |
|
||||||
|
|
||||||
|
### 2.2.2 Action Stream (Die Dynamik / Das „Was“)
|
||||||
|
Dieser Stream umfasst alles, was auf Umsetzung, Planung und aktuelle Zustände zielt.
|
||||||
|
|
||||||
|
| Typ | Gewicht | Chunking Profil | Zweck & Inhalt |
|
||||||
|
| :--- | :--- | :--- | :--- |
|
||||||
|
| **`project`** | 0.97 | `sliding_smart_edges` | Aktive Vorhaben mit Mission und Zielsetzung. |
|
||||||
|
| **`goal`** | 0.95 | `sliding_smart_edges` | Strategische Nordsterne und Zielzustände. |
|
||||||
|
| **`decision`** | 1.00 | `structured_strict` | Getroffene Entscheidungen (ADR-Logik). |
|
||||||
|
| **`risk`** | 0.85 | `sliding_short` | Potenzielle Gefahren und Bedrohungsszenarien. |
|
||||||
|
| **`obstacle`** | 1.00 | `structured_strict` | Aktuelle Hürden, Ängste und Blockaden. |
|
||||||
|
| **`task`** | 0.80 | `sliding_short` | Operative Aufgaben und Definition of Done. |
|
||||||
|
| **`skill`** | 0.90 | `sliding_smart_edges` | Fertigkeiten, Lernpfade und Meisterschaft. |
|
||||||
|
| **`habit`** | 0.85 | `sliding_short` | Routinen, Automatismen und Verhaltensmuster. |
|
||||||
|
| **`idea`** | 0.70 | `sliding_short` | Flüchtige Einfälle und Rohmaterial für Projekte. |
|
||||||
|
| **`state`** | 0.60 | `sliding_short` | Momentane Verfassung, Stimmung und Energielevel. |
|
||||||
|
|
||||||
|
### 2.2.3 History & Basis Stream (Die Evidenz / Das „Wann“)
|
||||||
|
Dieser Stream speichert deine Erlebnisse, Fakten und externes Wissen als Belege.
|
||||||
|
|
||||||
|
| Typ | Gewicht | Chunking Profil | Zweck & Inhalt |
|
||||||
|
| :--- | :--- | :--- | :--- |
|
||||||
|
| **`insight`** | 1.20 | `sliding_smart_edges` | Hochrelevante Erkenntnisse und Verhaltensmuster. |
|
||||||
|
| **`experience`**| 1.10 | `sliding_smart_edges` | Biografische Lektionen und prägende Erlebnisse. |
|
||||||
|
| **`event`** | 0.60 | `sliding_standard` | Chronologische Protokolle und Ereignisse. |
|
||||||
|
| **`journal`** | 0.80 | `sliding_standard` | Tägliche Logs und ungefilterte Gedanken. |
|
||||||
|
| **`person`** | 0.50 | `sliding_standard` | Kontaktprofile und soziale Vernetzung. |
|
||||||
|
| **`source`** | 0.50 | `sliding_standard` | Externe Quellen wie Bücher, Videos oder Artikel. |
|
||||||
|
| **`concept`** | 0.60 | `sliding_smart_edges` | Fachbegriffe, Theorien und zeitloses Wissen. |
|
||||||
|
| **`glossary`** | 0.40 | `sliding_short` | Kurze Begriffsdefinitionen. |
|
||||||
|
| **`default`** | 1.00 | `sliding_standard` | Fallback für alle nicht klassifizierten Notizen. |
|
||||||
|
|
||||||
|
*Richtwert für $W_{type}$: 0.1 (minimale Relevanz/Filter) bis 1.0 (maximale Relevanz).*
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Retriever Config (`retriever.yaml`)
|
||||||
|
|
||||||
|
Steuert die Gewichtung der Scoring-Formel und die neuen Lifecycle-Modifier.
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
version: 1.2
|
||||||
|
|
||||||
|
scoring:
|
||||||
|
# W_sem: skaliert den Term (semantic_score * retriever_weight)
|
||||||
|
# Empfehlung Startwert: 1.0 → Semantik bleibt Hauptsignal
|
||||||
|
semantic_weight: 1.0
|
||||||
|
|
||||||
|
# W_edge: skaliert edge_bonus aus dem Subgraph
|
||||||
|
# Empfehlung: 0.8 → Graph ist deutlich spürbar, aber überstimmt Semantik nicht komplett
|
||||||
|
edge_weight: 0.8
|
||||||
|
|
||||||
|
# W_cent: skaliert centrality_bonus (Knoten-Zentralität im Subgraph)
|
||||||
|
# Empfehlung: 0.5 → zentrale Knoten werden bevorzugt, aber moderat
|
||||||
|
centrality_weight: 0.5
|
||||||
|
|
||||||
|
# WP-22 Stellschraube: Lifecycle (Status-basiertes Scoring)
|
||||||
|
# Bonus für verifiziertes Wissen, Malus für Entwürfe
|
||||||
|
lifecycle_weights:
|
||||||
|
stable: 1.2 # +20% Bonus
|
||||||
|
active: 1.0 # Standardwert
|
||||||
|
draft: 0.5 # -50% Malus
|
||||||
|
system: 0.0 # Hard Skip via Ingestion
|
||||||
|
|
||||||
|
# Die nachfolgenden Werte überschreiben die Defaults aus app/core/retriever_config.
|
||||||
|
# Wenn neue Kantentypen, z.B. durch Referenzierung innerhalb einer md-Datei im vault anders gewichtet werden sollen, dann muss hier die Konfiguration erfolgen
|
||||||
|
edge_types:
|
||||||
|
# --- KATEGORIE 1: LOGIK-BOOSTS (Relevanz-Treiber) ---
|
||||||
|
# Diese Kanten haben die Kraft, das semantische Ranking aktiv umzugestalten.
|
||||||
|
blocks: 1.6 # Kritisch: Risiken/Blocker müssen sofort sichtbar sein.
|
||||||
|
solves: 1.5 # Zielführend: Lösungen sind primäre Suchziele.
|
||||||
|
depends_on: 1.4 # Logisch: Harte fachliche Abhängigkeit.
|
||||||
|
resulted_in: 1.4 # Kausal: Ergebnisse und unmittelbare Konsequenzen.
|
||||||
|
followed_by: 1.3 # Sequenziell (User): Bewusst gesteuerte Wissenspfade.
|
||||||
|
caused_by: 1.2 # Kausal: Ursachen-Bezug (Basis für Intent-Boost).
|
||||||
|
preceded_by: 1.1 # Sequenziell (User): Rückwärts-Bezug in Logik-Ketten.
|
||||||
|
|
||||||
|
# --- KATEGORIE 2: QUALITATIVER KONTEXT (Stabilitäts-Stützen) ---
|
||||||
|
# Diese Kanten liefern wichtigen Kontext, ohne das Ergebnis zu verfälschen.
|
||||||
|
guides: 1.1 # Qualitativ: Prinzipien oder Werte leiten das Thema.
|
||||||
|
part_of: 1.1 # Strukturell: Zieht übergeordnete Kontexte (Parents) mit hoch.
|
||||||
|
based_on: 0.8 # Fundament: Bezug auf Basis-Werte (kalibriert auf Safe-Retrieval).
|
||||||
|
derived_from: 0.6 # Historisch: Dokumentiert die Herkunft von Wissen.
|
||||||
|
uses: 0.6 # Instrumentell: Genutzte Werkzeuge, Methoden oder Ressourcen.
|
||||||
|
|
||||||
|
# --- KATEGORIE 3: THEMATISCHE NÄHE (Ähnlichkeits-Signal) ---
|
||||||
|
# Diese Werte verhindern den "Drift" in fachfremde Bereiche.
|
||||||
|
similar_to: 0.4 # Analytisch: Thematische Nähe (oft KI-generiert).
|
||||||
|
|
||||||
|
# --- KATEGORIE 4: SYSTEM-NUDGES (Technische Struktur) ---
|
||||||
|
# Reine Orientierungshilfen für das System; fast kein Einfluss auf das Ranking.
|
||||||
|
belongs_to: 0.2 # System: Verknüpft Chunks mit der Note (Metadaten-Träger).
|
||||||
|
next: 0.1 # System: Technische Lesereihenfolge der Absätze.
|
||||||
|
prev: 0.1 # System: Technische Lesereihenfolge der Absätze.
|
||||||
|
|
||||||
|
# --- KATEGORIE 5: WEICHE ASSOZIATIONEN (Rausch-Unterdrückung) ---
|
||||||
|
# Verhindert, dass lose Verknüpfungen das Ergebnis "verwässern".
|
||||||
|
references: 0.1 # Assoziativ: Einfacher Querverweis oder Erwähnung.
|
||||||
|
related_to: 0.05 # Minimal: Schwächste thematische Verbindung.
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. Edge Typen & Registry Referenz
|
||||||
|
|
||||||
|
Die `EdgeRegistry` ist die **Single Source of Truth** für das Vokabular.
|
||||||
|
|
||||||
|
### 4.1 Dateistruktur & Speicherort
|
||||||
|
Die Registry erwartet eine Markdown-Datei an folgendem Ort:
|
||||||
|
* **Standard-Pfad:** `<MINDNET_VAULT_ROOT>/01_User_Manual/01_edge_vocabulary.md`.
|
||||||
|
* **Custom-Pfad:** Kann via `.env` Variable `MINDNET_VOCAB_PATH` überschrieben werden.
|
||||||
|
|
||||||
|
### 4.2 Aufbau des Dictionaries (Markdown-Schema)
|
||||||
|
Die Datei muss eine Markdown-Tabelle enthalten, die vom Regex-Parser gelesen wird.
|
||||||
|
|
||||||
|
**Erwartetes Format:**
|
||||||
|
```markdown
|
||||||
|
| System-Typ (Canonical) | Erlaubte Aliasse (User) | Beschreibung |
|
||||||
|
| :--- | :--- | :--- |
|
||||||
|
| **`based_on`** | `basiert_auf`, `fundament` | Fundament: B baut auf A auf. |
|
||||||
|
| **`caused_by`** | `ausgelöst_durch`, `wegen` | Kausalität: A löst B aus. |
|
||||||
|
```
|
||||||
|
|
||||||
|
**Regeln für die Spalten:**
|
||||||
|
1. **Canonical:** Muss fett gedruckt sein (`**type**` oder `**`type`**`). Dies ist der Wert, der in der DB landet.
|
||||||
|
2. **Aliasse:** Kommagetrennte Liste von Synonymen. Diese werden beim Import automatisch zum Canonical aufgelöst.
|
||||||
|
3. **Beschreibung:** Rein informativ für den Nutzer.
|
||||||
|
|
||||||
|
### 4.3 Verfügbare Kanten-Typen (System-Standard)
|
||||||
|
|
||||||
|
| System-Typ (Canonical) | Erlaubte Aliasse (User) | Beschreibung |
|
||||||
|
| :--------------------- | :--------------------------------------------------- | :-------------------------------------- |
|
||||||
|
| **`caused_by`** | `ausgelöst_durch`, `wegen`, `ursache_ist` | Kausalität: A löst B aus. |
|
||||||
|
| **`derived_from`** | `abgeleitet_von`, `quelle`, `inspiriert_durch` | Herkunft: A stammt von B. |
|
||||||
|
| **`based_on`** | `basiert_auf`, `fundament`, `grundlage` | Fundament: B baut auf A auf. |
|
||||||
|
| **`solves`** | `löst`, `beantwortet`, `fix_für` | Lösung: A ist Lösung für Problem B. |
|
||||||
|
| **`part_of`** | `teil_von`, `gehört_zu`, `cluster` | Hierarchie: Kind -> Eltern. |
|
||||||
|
| **`depends_on`** | `hängt_ab_von`, `braucht`, `requires`, `enforced_by` | Abhängigkeit: A braucht B. |
|
||||||
|
| **`blocks`** | `blockiert`, `verhindert`, `risiko_für` | Blocker: A verhindert B. |
|
||||||
|
| **`uses`** | `nutzt`, `verwendet`, `tool` | Werkzeug: A nutzt B. |
|
||||||
|
| **`guides`** | `steuert`, `leitet`, `orientierung` | Soft-Dependency: A gibt Richtung für B. |
|
||||||
|
| **`followed_by`** | `danach`, `folgt`, `nachfolger`, `followed_by` | Prozess: A -> B. |
|
||||||
|
| **`preceeded_by`** | `davor`, `vorgänger`, `preceded_by` | Prozess: B <- A. |
|
||||||
|
| **`related_to`** | `siehe_auch`, `kontext`, `thematisch` | Lose Assoziation. |
|
||||||
|
| **`similar_to`** | `ähnlich_wie`, `vergleichbar` | Synonym / Ähnlichkeit. |
|
||||||
|
| **`references`** | *(Kein Alias)* | Standard-Verweis (Fallback). |
|
||||||
|
| **`resulted_in`** | `ergebnis`, `resultat`, `erzeugt` | Herkunft: A erzeugt Ergebnis B |
|
||||||
|
|
||||||
|
**ACHTUNG!** Die Kantentypen
|
||||||
|
**belongs_to**, **next** und **prev** dürfen nicht vom Nutzer gesetzt werden
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
|
||||||
|
## 5. Decision Engine (`decision_engine.yaml`)
|
||||||
|
|
||||||
|
Die Decision Engine fungiert als zentraler Orchestrator für die Intent-Erkennung und das dynamische Retrieval-Routing. Sie bestimmt, wie das System auf eine Nutzeranfrage reagiert, welche Informationstypen bevorzugt werden und wie der Wissensgraph für die spezifische Situation verformt wird.
|
||||||
|
|
||||||
|
### 5.1 Intent Recognition: Dual-Path Routing
|
||||||
|
Das System nutzt ein zweistufiges Verfahren, um die Absicht des Nutzers zu identifizieren:
|
||||||
|
|
||||||
|
1. **Fast Path (Keyword Trigger):** Das System scannt die Anfrage nach definierten `trigger_keywords`. Wird ein Treffer gefunden, wird die entsprechende Strategie sofort ohne LLM-Einsatz gewählt.
|
||||||
|
2. **Slow Path (LLM Router):** Wenn kein Keyword matcht und `llm_fallback_enabled: true` gesetzt ist, analysiert ein LLM die Nachricht mittels Few-Shot Prompting.
|
||||||
|
|
||||||
|
#### LLM Router Konfiguration
|
||||||
|
Der Router nutzt den `llm_router_prompt`, um Anfragen in eine der fünf Kern-Strategien (`FACT`, `DECISION`, `EMPATHY`, `CODING`, `INTERVIEW`) zu klassifizieren.
|
||||||
|
|
||||||
|
| Einstellung | Wert | Beschreibung |
|
||||||
|
| :--- | :--- | :--- |
|
||||||
|
| `llm_fallback_enabled` | `true` | Aktiviert die KI-basierte Klassifizierung, falls Keywords fehlen. |
|
||||||
|
| `llm_router_prompt` | *(Template)* | Enthält die Strategie-Definitionen und Few-Shot Beispiele für den LLM-Entscheidungsweg. |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 5.2 Strategie-Mechaniken (Graph Shaping)
|
||||||
|
Jede Strategie definiert drei Hebel, um das Ergebnis des Retrievers zu beeinflussen:
|
||||||
|
|
||||||
|
* **`inject_types`:** Erzwingt die Einbindung bestimmter Notiz-Typen (z. B. `value` bei Entscheidungen), auch wenn diese semantisch eine geringere Ähnlichkeit aufweisen.
|
||||||
|
* **`edge_boosts`:** Erhöht die Gewichtung spezifischer Kanten-Typen in der Scoring-Formel. Dies ermöglicht es dem Graphen, die Textsuche situativ zu "überstimmen".
|
||||||
|
* **`prepend_instruction`:** Injiziert eine spezifische Systemanweisung in das LLM-Prompt, um den Antwortstil anzupassen (z. B. "Wäge Fakten gegen Werte ab").
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 5.3 Übersicht der Strategien
|
||||||
|
|
||||||
|
| Strategie | Fokus | Bevorzugte Kanten (`edge_boosts`) | Injektionstypen |
|
||||||
|
| :--- | :--- | :--- | :--- |
|
||||||
|
| **FACT** | Wissensabfrage & Definitionen | `part_of` (2.0), `composed_of` (2.0), `similar_to` (1.5) | *(Keine)* |
|
||||||
|
| **DECISION** | Rat, Strategie & Abwägung | `blocks` (2.5), `solves` (2.0), `risk_of` (2.5) | `value`, `principle`, `goal`, `risk` |
|
||||||
|
| **EMPATHY** | Emotionale Resonanz | `based_on` (2.0), `experienced_in` (2.5), `related_to` (2.0) | `experience`, `belief`, `profile` |
|
||||||
|
| **CODING** | Programmierung & Syntax | `implemented_in` (3.0), `uses` (2.5), `depends_on` (2.0) | `snippet`, `reference`, `source` |
|
||||||
|
| **INTERVIEW** | Erfassung neuer Daten | *(Keine)* | *(Keine)* |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 5.4 Der Interview-Modus & Schemas
|
||||||
|
Die Strategie `INTERVIEW` dient der strukturierten Datenerfassung.
|
||||||
|
|
||||||
|
* **Trigger:** Aktiviert durch Phrasen wie "neue notiz", "festhalten" oder "dokumentieren".
|
||||||
|
* **Schema-Logik:** Nutzt das `default`-Schema mit den Feldern `Titel`, `Thema/Inhalt` und `Tags`, sofern kein spezifisches Typ-Schema aus der `types.yaml` greift.
|
||||||
|
* **Dynamik:** In diesem Modus wird der Fokus vom Retrieval (Wissen finden) auf die Extraktion (Wissen speichern) verschoben.
|
||||||
|
|
||||||
|
> **Hinweis:** Da spezifische Schemas für Projekte oder Erfahrungen direkt in der `types.yaml` definiert werden, dient die `decision_engine.yaml` hier primär als Fallback für generische Datenaufnahmen.
|
||||||
|
|
||||||
|
|
||||||
|
Auszug aus der decision_engine.yaml
|
||||||
|
```yaml
|
||||||
|
strategies:
|
||||||
|
# 1. Fakten-Abfrage (Fallback & Default)
|
||||||
|
FACT:
|
||||||
|
description: "Reine Wissensabfrage."
|
||||||
|
trigger_keywords: []
|
||||||
|
inject_types: []
|
||||||
|
# WP-22: Definitionen & Hierarchien bevorzugen
|
||||||
|
edge_boosts:
|
||||||
|
part_of: 2.0
|
||||||
|
composed_of: 2.0
|
||||||
|
similar_to: 1.5
|
||||||
|
caused_by: 0.5
|
||||||
|
prompt_template: "rag_template"
|
||||||
|
prepend_instruction: null
|
||||||
|
|
||||||
|
# 2. Entscheidungs-Frage
|
||||||
|
DECISION:
|
||||||
|
description: "Der User sucht Rat, Strategie oder Abwägung."
|
||||||
|
trigger_keywords:
|
||||||
|
- "soll ich"
|
||||||
|
- "meinung"
|
||||||
|
- "besser"
|
||||||
|
- "empfehlung"
|
||||||
|
- "strategie"
|
||||||
|
- "entscheidung"
|
||||||
|
- "abwägung"
|
||||||
|
- "vergleich"
|
||||||
|
inject_types: ["value", "principle", "goal", "risk"]
|
||||||
|
# WP-22: Risiken und Konsequenzen hervorheben
|
||||||
|
edge_boosts:
|
||||||
|
blocks: 2.5
|
||||||
|
solves: 2.0
|
||||||
|
depends_on: 1.5
|
||||||
|
risk_of: 2.5
|
||||||
|
prompt_template: "decision_template"
|
||||||
|
prepend_instruction: |
|
||||||
|
!!! ENTSCHEIDUNGS-MODUS !!!
|
||||||
|
BITTE WÄGE FAKTEN GEGEN FOLGENDE WERTE, PRINZIPIEN UND ZIELE AB:
|
||||||
|
|
||||||
|
# 3. Empathie / "Ich"-Modus
|
||||||
|
|
||||||
|
```
|
||||||
|
|
||||||
|
*Richtwert für Kanten-Boosts: 0.1 (Abwertung) bis 3.0+ (Dominanz gegenüber Text-Match).*
|
||||||
@@ -0,0 +1,123 @@
|
|||||||
|
---
|
||||||
|
doc_type: technical_reference
|
||||||
|
audience: developer, architect
|
||||||
|
scope: database, qdrant, schema
|
||||||
|
status: active
|
||||||
|
version: 2.7.0
|
||||||
|
context: "Exakte Definition der Datenmodelle (Payloads) in Qdrant und Index-Anforderungen."
|
||||||
|
---
|
||||||
|
|
||||||
|
# Technisches Datenmodell (Qdrant Schema)
|
||||||
|
|
||||||
|
## 1. Collections & Namenskonvention
|
||||||
|
|
||||||
|
Mindnet speichert Daten in drei getrennten Qdrant-Collections. Der Prefix ist via ENV `COLLECTION_PREFIX` konfigurierbar (Default: `mindnet`).
|
||||||
|
|
||||||
|
Das System nutzt folgende drei Collections:
|
||||||
|
* `{prefix}_notes`: Metadaten der Dateien.
|
||||||
|
* `{prefix}_chunks`: Vektorisierte Textsegmente.
|
||||||
|
* `{prefix}_edges`: Gerichtete Graph-Kanten.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Note Payload (`mindnet_notes`)
|
||||||
|
|
||||||
|
Repräsentiert die Metadaten einer Markdown-Datei (1:1 Beziehung).
|
||||||
|
|
||||||
|
**JSON-Schema:**
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"note_id": "string (keyword)", // UUIDv5 (deterministisch) oder Slug
|
||||||
|
"title": "string (text)", // Titel aus Frontmatter
|
||||||
|
"type": "string (keyword)", // Logischer Typ (z.B. 'project', 'concept')
|
||||||
|
"retriever_weight": "float", // Effektive Wichtigkeit (Frontmatter > Type > Default)
|
||||||
|
"chunk_profile": "string", // Effektives Profil (Frontmatter > Type > Default)
|
||||||
|
"edge_defaults": ["string"], // Liste der aktiven Default-Kanten
|
||||||
|
"tags": ["string"], // Liste von Tags aus Frontmatter
|
||||||
|
"aliases": ["string"], // Synonyme für Discovery (WP-11)
|
||||||
|
"created": "string (iso-date)", // Erstellungsdatum
|
||||||
|
"updated": "integer", // Timestamp (File Modification Time)
|
||||||
|
"fulltext": "string (no-index)", // Gesamter Text (nur für Recovery/Export)
|
||||||
|
|
||||||
|
// NEU in v2.7: Multi-Hash für flexible Change Detection
|
||||||
|
"hashes": {
|
||||||
|
"body:parsed:canonical": "string", // Hash nur über den Text-Body
|
||||||
|
"full:parsed:canonical": "string" // Hash über Text + Metadaten (Tags, Title, Config)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Erforderliche Indizes:**
|
||||||
|
Es müssen Payload-Indizes für folgende Felder existieren:
|
||||||
|
* `note_id`
|
||||||
|
* `type`
|
||||||
|
* `tags`
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Chunk Payload (`mindnet_chunks`)
|
||||||
|
|
||||||
|
Die atomare Sucheinheit. Enthält den Vektor.
|
||||||
|
|
||||||
|
**Vektor-Konfiguration:**
|
||||||
|
* Modell: `nomic-embed-text`
|
||||||
|
* Dimension: **768**
|
||||||
|
* Metrik: Cosine Similarity
|
||||||
|
|
||||||
|
**JSON-Schema:**
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"chunk_id": "string (keyword)", // Format: {note_id}#c{index} (z.B. 'abc-123#c01')
|
||||||
|
"note_id": "string (keyword)", // Foreign Key zur Note
|
||||||
|
"type": "string (keyword)", // Kopie aus Note (Denormalisiert für Filterung)
|
||||||
|
"text": "string (text)", // Reintext für Anzeige (ohne Overlap)
|
||||||
|
"window": "string (text)", // Text + Overlap (Basis für Embedding)
|
||||||
|
"ord": "integer", // Laufende Nummer (1..N) für Sortierung
|
||||||
|
"retriever_weight": "float", // Geerbt von Note (für schnelles Re-Ranking)
|
||||||
|
"chunk_profile": "string", // Geerbt von Note (für Debugging/Filtering)
|
||||||
|
"neighbors_prev": ["string"], // ID des Vorgängers (Linked List)
|
||||||
|
"neighbors_next": ["string"], // ID des Nachfolgers
|
||||||
|
"section": "string", // Pfad/Überschrift, zu der der Chunk gehört
|
||||||
|
"source_path": "string" // Relativer Pfad zur Datei
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Erforderliche Indizes:**
|
||||||
|
Es müssen Payload-Indizes für folgende Felder existieren:
|
||||||
|
* `note_id`
|
||||||
|
* `chunk_id`
|
||||||
|
* `type`
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. Edge Payload (`mindnet_edges`)
|
||||||
|
|
||||||
|
Gerichtete Kanten zwischen Knoten. Stark erweitert in v2.6 für Provenienz-Tracking.
|
||||||
|
|
||||||
|
**JSON-Schema:**
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"edge_id": "string (keyword)", // Deterministischer Hash aus (src, dst, kind)
|
||||||
|
"source_id": "string (keyword)", // Chunk-ID (Start)
|
||||||
|
"target_id": "string (keyword)", // Chunk-ID oder Note-Titel (bei Unresolved)
|
||||||
|
"kind": "string (keyword)", // Beziehungsart (z.B. 'depends_on')
|
||||||
|
"scope": "string (keyword)", // Immer 'chunk' (Legacy-Support: 'note')
|
||||||
|
"note_id": "string (keyword)", // Owner Note ID (Ursprung der Kante)
|
||||||
|
|
||||||
|
// Provenance & Quality (WP03/WP15)
|
||||||
|
"provenance": "keyword", // 'explicit', 'rule', 'smart', 'structure'
|
||||||
|
"rule_id": "string (keyword)", // Traceability: 'inline:rel', 'explicit:wikilink', 'smart:llm'
|
||||||
|
"confidence": "float" // Vertrauenswürdigkeit (0.0 - 1.0)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Erforderliche Indizes:**
|
||||||
|
Es müssen Payload-Indizes für folgende Felder existieren:
|
||||||
|
* `source_id`
|
||||||
|
* `target_id`
|
||||||
|
* `kind`
|
||||||
|
* `scope`
|
||||||
|
* `note_id`
|
||||||
@@ -0,0 +1,172 @@
|
|||||||
|
---
|
||||||
|
doc_type: technical_reference
|
||||||
|
audience: developer, frontend_architect
|
||||||
|
scope: architecture, graph_viz, state_management
|
||||||
|
status: active
|
||||||
|
version: 2.7.0
|
||||||
|
context: "Technische Dokumentation des modularen Streamlit-Frontends, der Graph-Engines und des Editors."
|
||||||
|
---
|
||||||
|
|
||||||
|
# Technical Reference: Frontend & Visualization
|
||||||
|
|
||||||
|
**Kontext:** Mindnet nutzt Streamlit nicht nur als einfaches UI, sondern als komplexe Applikation mit eigenem State-Management, Routing und Persistenz.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. Architektur & Modularisierung (WP19)
|
||||||
|
|
||||||
|
Seit Version 2.6 ist das Frontend (`app/frontend/`) kein Monolith mehr, sondern in funktionale Module unterteilt.
|
||||||
|
|
||||||
|
### 1.1 Dateistruktur & Aufgaben
|
||||||
|
|
||||||
|
| Modul | Funktion |
|
||||||
|
| :--- | :--- |
|
||||||
|
| `ui.py` | **Router.** Der Entrypoint. Initialisiert Session-State und entscheidet anhand der Sidebar-Auswahl, welche View gerendert wird. |
|
||||||
|
| `ui_config.py` | **Konstanten.** Zentraler Ort für Farben (`GRAPH_COLORS`), API-Endpunkte und Timeouts. |
|
||||||
|
| `ui_api.py` | **Backend-Bridge.** Kapselt alle `requests`-Aufrufe an die FastAPI. |
|
||||||
|
| `ui_callbacks.py` | **State Transitions.** Logik für View-Wechsel (z.B. Sprung vom Graph in den Editor). |
|
||||||
|
| `ui_utils.py` | **Helper.** Markdown-Parsing (`parse_markdown_draft`) und String-Normalisierung. |
|
||||||
|
| `ui_graph_service.py`| **Data Logic.** Holt Daten aus Qdrant und bereitet Nodes/Edges auf (unabhängig von der Vis-Library). |
|
||||||
|
| `ui_graph_cytoscape.py`| **View: Graph.** Implementierung mit `st-cytoscape` (COSE Layout). |
|
||||||
|
| `ui_editor.py` | **View: Editor.** Logik für Drafts, manuelles Editieren und **Async Feedback**. |
|
||||||
|
|
||||||
|
### 1.2 Konfiguration (`ui_config.py`)
|
||||||
|
|
||||||
|
Zentrale Steuerung der visuellen Semantik.
|
||||||
|
|
||||||
|
# Mapping von Node-Typen zu Farben (Hex)
|
||||||
|
GRAPH_COLORS = {
|
||||||
|
"project": "#ff9f43", # Orange
|
||||||
|
"decision": "#5f27cd", # Lila
|
||||||
|
"experience": "#feca57", # Gelb (Empathie)
|
||||||
|
"concept": "#54a0ff", # Blau
|
||||||
|
"risk": "#ff6b6b" # Rot
|
||||||
|
}
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Graph Visualisierung
|
||||||
|
|
||||||
|
Mindnet nutzt primär **Cytoscape** für Stabilität bei großen Graphen.
|
||||||
|
|
||||||
|
### 2.1 Engine: Cytoscape (`st-cytoscape`)
|
||||||
|
* **Algorithmus:** `COSE` (Compound Spring Embedder).
|
||||||
|
* **Vorteil:** Verhindert Überlappungen aktiv (`nodeRepulsion`).
|
||||||
|
|
||||||
|
### 2.2 Architektur-Pattern: "Active Inspector, Passive Graph"
|
||||||
|
Ein häufiges Problem bei Streamlit-Graphen ist das "Flackern" (Re-Render) bei Klicks. Wir lösen das durch Entkopplung:
|
||||||
|
|
||||||
|
1. **Stable Key:** Der React-Key der Komponente hängt *nicht* von der Selektion ab, sondern nur vom Zentrum (`center_id`) und Layout-Settings.
|
||||||
|
2. **CSS-Selektion:** Wir nutzen **nicht** den nativen `:selected` State (buggy bei Single-Select), sondern injizieren eine CSS-Klasse `.inspected`.
|
||||||
|
|
||||||
|
**Stylesheet Implementierung (`ui_graph_cytoscape.py`):**
|
||||||
|
|
||||||
|
stylesheet = [
|
||||||
|
{
|
||||||
|
"selector": "node",
|
||||||
|
"style": { "background-color": "data(bg_color)" }
|
||||||
|
},
|
||||||
|
# Wir steuern das Highlight manuell über eine Klasse
|
||||||
|
{
|
||||||
|
"selector": ".inspected",
|
||||||
|
"style": {
|
||||||
|
"border-width": 6,
|
||||||
|
"border-color": "#FFC300", # Gelb/Gold
|
||||||
|
"z-index": 999
|
||||||
|
}
|
||||||
|
},
|
||||||
|
# Native Selektion wird unterdrückt/unsichtbar gemacht
|
||||||
|
{
|
||||||
|
"selector": "node:selected",
|
||||||
|
"style": { "overlay-opacity": 0, "border-width": 0 }
|
||||||
|
}
|
||||||
|
]
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Editor & Single Source of Truth
|
||||||
|
|
||||||
|
Ein kritisches Design-Pattern ist der Umgang mit Datenkonsistenz beim Editieren ("File System First").
|
||||||
|
|
||||||
|
### 3.1 Das Problem
|
||||||
|
Qdrant speichert Metadaten und Chunks, aber das Feld `fulltext` im Payload kann veraltet sein oder Formatierungen verlieren.
|
||||||
|
|
||||||
|
### 3.2 Die Lösung (Logic Flow)
|
||||||
|
Der `switch_to_editor_callback` in `ui_callbacks.py` implementiert folgende Kaskade:
|
||||||
|
|
||||||
|
def switch_to_editor_callback(note_payload):
|
||||||
|
# 1. Pfad aus Qdrant Payload lesen
|
||||||
|
origin_fname = note_payload.get('path')
|
||||||
|
|
||||||
|
content = ""
|
||||||
|
# 2. Versuch: Hard Read von der Festplatte (Source of Truth)
|
||||||
|
if origin_fname and os.path.exists(origin_fname):
|
||||||
|
with open(origin_fname, "r", encoding="utf-8") as f:
|
||||||
|
content = f.read()
|
||||||
|
else:
|
||||||
|
# 3. Fallback: Rekonstruktion aus der DB ("Stitching")
|
||||||
|
# Nur Notfall, falls Docker-Volume fehlt
|
||||||
|
content = note_payload.get('fulltext', '')
|
||||||
|
|
||||||
|
# State setzen (Transport via Message-Bus)
|
||||||
|
st.session_state.messages.append({
|
||||||
|
"role": "assistant",
|
||||||
|
"intent": "INTERVIEW",
|
||||||
|
"content": content,
|
||||||
|
"origin_filename": origin_fname
|
||||||
|
})
|
||||||
|
st.session_state["sidebar_mode_selection"] = "📝 Manueller Editor"
|
||||||
|
|
||||||
|
### 3.3 Async Save Pattern (Neu in v2.7 / WP-14)
|
||||||
|
Um Timeouts bei der Smart-Edge-Berechnung zu vermeiden, nutzt der Editor ein **"Fire & Forget"** Muster.
|
||||||
|
|
||||||
|
1. **Request:** UI sendet Markdown an `/ingest/save`.
|
||||||
|
2. **Backend:**
|
||||||
|
* Validiert Request.
|
||||||
|
* Speichert Datei auf Disk (Persistenz garantiert).
|
||||||
|
* Startet `BackgroundTasks` für LLM-Analyse und Embedding.
|
||||||
|
* Returniert sofort `status: queued`.
|
||||||
|
3. **UI Feedback:**
|
||||||
|
* Editor zeigt "Erfolgreich eingereiht".
|
||||||
|
* User muss nicht warten.
|
||||||
|
* (ToDo: WebSocket Notification bei Abschluss).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. State Management Patterns
|
||||||
|
|
||||||
|
### 4.1 URL Persistenz (Deep Linking)
|
||||||
|
Layout-Einstellungen werden in der URL gespeichert, damit sie einen Page-Refresh (F5) überleben.
|
||||||
|
|
||||||
|
# ui_graph_cytoscape.py
|
||||||
|
def update_url_params():
|
||||||
|
st.query_params["depth"] = st.session_state.cy_depth
|
||||||
|
st.query_params["rep"] = st.session_state.cy_node_repulsion
|
||||||
|
|
||||||
|
# Init
|
||||||
|
if "cy_depth" not in st.session_state:
|
||||||
|
st.session_state.cy_depth = int(st.query_params.get("depth", 2))
|
||||||
|
|
||||||
|
### 4.2 Resurrection Pattern
|
||||||
|
Verhindert Datenverlust, wenn der Nutzer während des Tippens den Tab wechselt. Der Editor-Inhalt wird bei jedem Keystroke (`on_change`) in `st.session_state` gespiegelt und beim Neuladen der Komponente von dort wiederhergestellt.
|
||||||
|
|
||||||
|
### 4.3 Healing Parser (`ui_utils.py`)
|
||||||
|
Das LLM liefert oft invalides YAML oder Markdown. Der Parser (`parse_markdown_draft`):
|
||||||
|
* Repariert fehlende Frontmatter-Trenner (`---`).
|
||||||
|
* Extrahiert JSON/YAML aus Code-Blöcken.
|
||||||
|
* Normalisiert Tags (entfernt `#`).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. Constraints & Security (Known Limitations)
|
||||||
|
|
||||||
|
### 5.1 File System Security
|
||||||
|
Der Editor ("File System First") vertraut dem Pfad im Qdrant-Feld `path`.
|
||||||
|
* **Risiko:** Path Traversal (z.B. `../../etc/passwd`).
|
||||||
|
* **Mitigation:** Aktuell findet keine strikte Prüfung statt, ob der Pfad innerhalb des `./vault` Ordners liegt. Das System setzt voraus, dass die Vektor-Datenbank eine **Trusted Source** ist und nur vom internen Importer befüllt wird.
|
||||||
|
* **ToDo:** Bei Öffnung der API für Dritte muss hier eine `Path.resolve().is_relative_to(VAULT_ROOT)` Prüfung implementiert werden.
|
||||||
|
|
||||||
|
### 5.2 Browser Performance
|
||||||
|
Die Graph-Visualisierung (`st-cytoscape`) rendert Client-seitig im Browser.
|
||||||
|
* **Limit:** Ab ca. **500 Knoten/Kanten** kann das Rendering träge werden.
|
||||||
|
* **Design-Entscheidung:** Das UI ist auf **Ego-Graphen** (Nachbarn eines Knotens) und gefilterte Ansichten ausgelegt, nicht auf die Darstellung des gesamten Knowledge-Graphs ("Whole Brain Visualization").
|
||||||
@@ -0,0 +1,168 @@
|
|||||||
|
---
|
||||||
|
doc_type: technical_reference
|
||||||
|
audience: developer, devops
|
||||||
|
scope: backend, ingestion, smart_edges, edge_registry
|
||||||
|
status: active
|
||||||
|
version: 2.8.1
|
||||||
|
context: "Detaillierte technische Beschreibung der Import-Pipeline, Mistral-safe Parsing und Deep Fallback Resilienz."
|
||||||
|
---
|
||||||
|
|
||||||
|
# Ingestion Pipeline & Smart Processing
|
||||||
|
|
||||||
|
**Quellen:** `pipeline_playbook.md`, `ingestion.py`, `edge_registry.py`, `01_edge_vocabulary.md`, `llm_service.py`
|
||||||
|
|
||||||
|
Die Ingestion transformiert Markdown in den Graphen. Entrypoint: `scripts/import_markdown.py` (CLI) oder `routers/ingest.py` (API). Seit v2.8 integriert dieser Prozess eine **intelligente Quoten-Steuerung** (WP-20) und ein **robustes JSON-Parsing** für Cloud-Modelle (Mistral/Gemini).
|
||||||
|
|
||||||
|
## 1. Der Import-Prozess (16-Schritte-Workflow)
|
||||||
|
|
||||||
|
Der Prozess ist **asynchron** und **idempotent**.
|
||||||
|
|
||||||
|
1. **Trigger & Async Dispatch:**
|
||||||
|
* **API (`/save`):** Nimmt Request entgegen, validiert und startet Background-Task ("Fire & Forget"). Antwortet sofort mit `202/Queued`.
|
||||||
|
* **CLI:** Iteriert über Dateien und nutzt `asyncio.Semaphore` zur Drosselung.
|
||||||
|
2. **Markdown lesen:** Rekursives Scannen des Vaults.
|
||||||
|
3. **Frontmatter Check & Hard Skip (WP-22):**
|
||||||
|
* Extraktion von `status` und `type`.
|
||||||
|
* **Hard Skip Rule:** Wenn `status` in `['system', 'template', 'archive', 'hidden']` ist, wird die Datei **sofort übersprungen**. Sie wird weder vektorisiert noch in den Graphen aufgenommen.
|
||||||
|
* Validierung der Pflichtfelder (`id`, `title`) für alle anderen Dateien.
|
||||||
|
4. **Edge Registry Initialisierung (WP-22):**
|
||||||
|
* Laden der Singleton-Instanz der `EdgeRegistry`.
|
||||||
|
* Validierung der Vokabular-Datei unter `MINDNET_VOCAB_PATH`.
|
||||||
|
5. **Config Resolution:**
|
||||||
|
* Bestimmung von `chunking_profile` und `retriever_weight`.
|
||||||
|
* **Priorität:** 1. Frontmatter (Override) -> 2. `types.yaml` (Type) -> 3. Global Default.
|
||||||
|
6. **Note-Payload generieren:**
|
||||||
|
* Erstellen des JSON-Objekts inklusive `status` (für Scoring).
|
||||||
|
* **Multi-Hash Calculation:** Berechnet Hashtabellen für `body` (nur Text) und `full` (Text + Metadaten).
|
||||||
|
7. **Change Detection:**
|
||||||
|
* Vergleich des Hashes mit Qdrant.
|
||||||
|
* Strategie wählbar via ENV `MINDNET_CHANGE_DETECTION_MODE` (`full` oder `body`).
|
||||||
|
8. **Chunking anwenden:** Zerlegung des Textes basierend auf dem ermittelten Profil (siehe Kap. 3).
|
||||||
|
9. **Smart Edge Allocation (WP-20):**
|
||||||
|
* Wenn `enable_smart_edge_allocation: true`: Der `SemanticAnalyzer` sendet Chunks an das LLM.
|
||||||
|
* **Traffic Control:** Request nutzt `priority="background"`. Semaphore drosselt die Last.
|
||||||
|
* **Resilienz (Quota Handling):** Erkennt HTTP 429 (Rate-Limit) und pausiert kontrolliert (via `LLM_RATE_LIMIT_WAIT`), bevor ein Cloud-Retry erfolgt.
|
||||||
|
* **Mistral-safe Parsing:** Automatisierte Bereinigung von BOS-Tokens (`<s>`) und Framework-Tags (`[OUT]`) sowie Recovery-Logik für Dictionaries (Suche nach `edges`, `links`, `results`, `kanten`).
|
||||||
|
* **Deep Fallback (v2.11.14):** Erkennt "Silent Refusals" (Data Policy Violations). Liefert die Cloud trotz erfolgreicher Verbindung keine verwertbaren Kanten, wird ein lokaler Fallback via Ollama erzwungen, um Kantenverlust zu vermeiden.
|
||||||
|
10. **Inline-Kanten finden:** Parsing von `[[rel:...]]`.
|
||||||
|
11. **Alias-Auflösung & Kanonisierung (WP-22):**
|
||||||
|
* Jede Kante wird via `edge_registry.resolve()` normalisiert.
|
||||||
|
* Aliase (z.B. `basiert_auf`) werden zu kanonischen Typen (z.B. `based_on`) aufgelöst.
|
||||||
|
* Unbekannte Typen werden in `unknown_edges.jsonl` protokolliert.
|
||||||
|
12. **Callout-Kanten finden:** Parsing von `> [!edge]`.
|
||||||
|
13. **Default- & Matrix-Edges erzeugen:** Anwendung der `edge_defaults` aus Registry und Matrix-Logik.
|
||||||
|
14. **Strukturkanten erzeugen:** `belongs_to`, `next`, `prev`.
|
||||||
|
15. **Embedding (Async):** Generierung via `nomic-embed-text` (768 Dim).
|
||||||
|
16. **Diagnose:** Integritäts-Check nach dem Lauf.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Betrieb & CLI Befehle
|
||||||
|
|
||||||
|
### 2.1 Standard-Betrieb (Inkrementell)
|
||||||
|
Für regelmäßige Updates (Cronjob). Erkennt Änderungen via Hash.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
export QDRANT_URL="http://localhost:6333"
|
||||||
|
export COLLECTION_PREFIX="mindnet"
|
||||||
|
# Steuert, wann eine Datei als "geändert" gilt
|
||||||
|
export MINDNET_CHANGE_DETECTION_MODE="full"
|
||||||
|
|
||||||
|
# Nutzt das Venv der Produktionsumgebung
|
||||||
|
/home/llmadmin/mindnet/.venv/bin/python3 -m scripts.import_markdown \
|
||||||
|
--vault ./vault \
|
||||||
|
--prefix "$COLLECTION_PREFIX" \
|
||||||
|
--apply \
|
||||||
|
--purge-before-upsert \
|
||||||
|
--sync-deletes
|
||||||
|
```
|
||||||
|
|
||||||
|
> **[!WARNING] Purge-Before-Upsert**
|
||||||
|
> Das Flag `--purge-before-upsert` ist kritisch. Es löscht vor dem Schreiben einer Note ihre alten Chunks/Edges. Ohne dieses Flag entstehen **"Geister-Chunks"** (alte Textabschnitte, die im Markdown gelöscht wurden, aber im Index verbleiben).
|
||||||
|
|
||||||
|
### 2.2 Full Rebuild (Clean Slate)
|
||||||
|
Notwendig bei Änderungen an `types.yaml` (z.B. neue Chunking-Profile), der Registry oder Modell-Wechsel.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 0. Modell sicherstellen
|
||||||
|
ollama pull nomic-embed-text
|
||||||
|
|
||||||
|
# 1. Qdrant Collections löschen (Wipe)
|
||||||
|
python3 -m scripts.reset_qdrant --mode wipe --prefix "mindnet" --yes
|
||||||
|
|
||||||
|
# 2. Vollständiger Import (Force)
|
||||||
|
# --force ignoriert alle Hashes und schreibt alles neu
|
||||||
|
python3 -m scripts.import_markdown --vault ./vault --prefix "mindnet" --apply --force
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Chunking & Payload
|
||||||
|
|
||||||
|
Das Chunking ist profilbasiert und in `types.yaml` konfiguriert.
|
||||||
|
|
||||||
|
### 3.1 Profile und Strategien (Vollständige Referenz)
|
||||||
|
|
||||||
|
| Profil | Strategie | Parameter | Einsatzgebiet |
|
||||||
|
| :--- | :--- | :--- | :--- |
|
||||||
|
| `sliding_short` | `sliding_window` | Max: 350, Target: 200 | Kurze Logs, Chats, Risiken. |
|
||||||
|
| `sliding_standard` | `sliding_window` | Max: 650, Target: 450 | Massendaten (Journal, Quellen). |
|
||||||
|
| `sliding_smart_edges`| `sliding_window` | Max: 600, Target: 400 | Fließtexte mit hohem Wert (Projekte). |
|
||||||
|
| `structured_smart_edges` | `by_heading` | `strict: false` (Soft) | Strukturierte Texte, Merging erlaubt. |
|
||||||
|
| `structured_smart_edges_strict` | `by_heading` | `strict: true` (Hard) | **Atomare Einheiten**: Entscheidungen, Werte. |
|
||||||
|
| `structured_smart_edges_strict_L3`| `by_heading` | `strict: true`, `level: 3` | Tief geschachtelte Prinzipien (Tier 2/MP1). |
|
||||||
|
|
||||||
|
### 3.2 Die `by_heading` Logik (v2.9 Hybrid)
|
||||||
|
|
||||||
|
Die Strategie `by_heading` zerlegt Texte anhand ihrer Struktur (Überschriften). Sie unterstützt seit v2.9 ein "Safety Net" gegen zu große Chunks.
|
||||||
|
|
||||||
|
* **Split Level:** Definiert die Tiefe (z.B. `2` = H1 & H2 triggern Split).
|
||||||
|
* **Modus "Strict" (`strict_heading_split: true`):**
|
||||||
|
* Jede Überschrift (`<= split_level`) erzwingt einen neuen Chunk.
|
||||||
|
* *Merge-Check:* Wenn der vorherige Chunk leer war (nur Überschriften), wird gemergt.
|
||||||
|
* *Safety Net:* Wird ein Abschnitt zu lang (> `max` Token), wird auch ohne Überschrift getrennt.
|
||||||
|
* **Modus "Soft" (`strict_heading_split: false`):**
|
||||||
|
* **Hierarchie-Check:** Überschriften *oberhalb* des Split-Levels erzwingen **immer** einen Split.
|
||||||
|
* **Füll-Logik:** Überschriften *auf* dem Split-Level lösen nur dann einen neuen Chunk aus, wenn der aktuelle Chunk die `target`-Größe erreicht hat.
|
||||||
|
* *Safety Net:* Auch hier greift das `max` Token Limit.
|
||||||
|
|
||||||
|
### 3.3 Payload-Felder (Qdrant)
|
||||||
|
|
||||||
|
* `text`: Der reine Inhalt (Anzeige im UI).
|
||||||
|
* `window`: Inhalt plus Overlap (für Embedding).
|
||||||
|
* `chunk_profile`: Das effektiv genutzte Profil (zur Nachverfolgung).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. Edge-Erzeugung & Prioritäten (Provenance)
|
||||||
|
|
||||||
|
Kanten werden nach Vertrauenswürdigkeit (`provenance`) priorisiert. Die höhere Prio gewinnt.
|
||||||
|
|
||||||
|
| Prio | Quelle | Rule ID / Provenance | Confidence | Erläuterung |
|
||||||
|
| :--- | :--- | :--- | :--- | :--- |
|
||||||
|
| **1** | Wikilink | `explicit:wikilink` | **1.00** | Harte menschliche Setzung. |
|
||||||
|
| **2** | Inline | `inline:rel` | **0.95** | Typisierte menschliche Kante. |
|
||||||
|
| **3** | Callout | `callout:edge` | **0.90** | Explizite Meta-Information. |
|
||||||
|
| **4** | Semantic AI | `semantic_ai` | **0.90** | KI-extrahierte Verbindung (Mistral-safe). |
|
||||||
|
| **5** | Type Default | `edge_defaults` | **0.70** | Heuristik aus der Registry. |
|
||||||
|
| **6** | Struktur | `structure` | **1.00** | System-interne Verkettung (`belongs_to`). |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. Quality Gates & Monitoring
|
||||||
|
|
||||||
|
In v2.7+ wurden Tools zur Überwachung der Datenqualität integriert:
|
||||||
|
|
||||||
|
**1. Registry Review:** Prüfung der `data/logs/unknown_edges.jsonl`. Administratoren sollten hier gelistete Begriffe als Aliase in die `01_edge_vocabulary.md` aufnehmen.
|
||||||
|
|
||||||
|
**2. Payload Dryrun (Schema-Check):**
|
||||||
|
Simuliert Import, prüft JSON-Schema Konformität.
|
||||||
|
```bash
|
||||||
|
python3 -m scripts.payload_dryrun --vault ./test_vault
|
||||||
|
```
|
||||||
|
|
||||||
|
**3. Full Edge Check (Graph-Integrität):**
|
||||||
|
Prüft Invarianten (z.B. `next` muss reziprok zu `prev` sein).
|
||||||
|
```bash
|
||||||
|
python3 -m scripts.edges_full_check
|
||||||
|
```
|
||||||
@@ -0,0 +1,129 @@
|
|||||||
|
---
|
||||||
|
doc_type: technical_reference
|
||||||
|
audience: developer, data_scientist
|
||||||
|
scope: backend, retrieval, scoring, modularization
|
||||||
|
status: active
|
||||||
|
version: 2.7.1
|
||||||
|
context: "Detaillierte Dokumentation der Scoring-Algorithmen, inklusive WP-22 Lifecycle-Modifier, Intent-Boosting und Modularisierung."
|
||||||
|
---
|
||||||
|
|
||||||
|
# Retrieval & Scoring Algorithmen
|
||||||
|
|
||||||
|
Der Retriever unterstützt **Semantic Search** und **Hybrid Search**. Seit v2.4 nutzt Mindnet ein gewichtetes Scoring-Modell, das Semantik, Graphentheorie und Metadaten kombiniert. Mit Version 2.7 (WP-22) wurde dieses Modell um **Lifecycle-Faktoren** und **Intent-Boosting** erweitert sowie die Architektur modularisiert.
|
||||||
|
|
||||||
|
## 1. Scoring Formel (v2.7.0)
|
||||||
|
|
||||||
|
Der Gesamtscore eines Treffers berechnet sich als gewichtete Summe. Alle Gewichte ($W$) und Modifier ($M$) sind in `retriever.yaml` und `decision_engine.yaml` konfigurierbar.
|
||||||
|
|
||||||
|
$$
|
||||||
|
TotalScore = (W_{sem} \cdot S_{sem} \cdot W_{type} \cdot M_{status}) + (W_{edge} \cdot B_{edge}) + (W_{cent} \cdot B_{cent}) + B_{intent}
|
||||||
|
$$
|
||||||
|
|
||||||
|
### Die Komponenten (Klassisch v2.4)
|
||||||
|
|
||||||
|
**1. Semantic Score ($S_{sem}$):**
|
||||||
|
* **Basis:** Cosine Similarity des Vektors.
|
||||||
|
* **Modell:** `nomic-embed-text` (768d).
|
||||||
|
* **Wertebereich:** 0.0 bis 1.0.
|
||||||
|
|
||||||
|
**2. Type Weight ($W_{type}$):**
|
||||||
|
* **Herkunft:** Feld `retriever_weight` aus der Note/Chunk Payload oder `types.yaml`.
|
||||||
|
* **Zweck:** Priorisierung bestimmter Dokumententypen unabhängig vom Inhalt.
|
||||||
|
* **Beispiel:** Eine `decision` (1.0) schlägt ein `concept` (0.6) bei gleicher Ähnlichkeit.
|
||||||
|
|
||||||
|
**3. Edge Bonus ($B_{edge}$):**
|
||||||
|
* **Kontext:** Berechnet im lokalen Subgraphen (Expansion Tiefe 1).
|
||||||
|
* **Logik:** Summe der `confidence` aller eingehenden Kanten von Knoten im aktuellen Result-Set.
|
||||||
|
* **Zweck:** Belohnt Chunks, die "im Thema" vernetzt sind.
|
||||||
|
|
||||||
|
**4. Centrality Bonus ($B_{cent}$):**
|
||||||
|
* **Kontext:** Berechnet im lokalen Subgraphen.
|
||||||
|
* **Logik:** Vereinfachte PageRank-Metrik (Degree Centrality).
|
||||||
|
* **Zweck:** Belohnt "Hubs" mit vielen Verbindungen zu anderen Treffern.
|
||||||
|
|
||||||
|
### Die WP-22 Erweiterungen (v2.7.0)
|
||||||
|
|
||||||
|
**5. Status Modifier ($M_{status}$):**
|
||||||
|
* **Herkunft:** Feld `status` aus dem Frontmatter.
|
||||||
|
* **Zweck:** Bestraft unfertiges Wissen (Drafts) oder bevorzugt stabiles Wissen.
|
||||||
|
* **Werte (Auftrag WP-22):** * `stable`: **1.2** (Bonus für Qualität).
|
||||||
|
* `draft`: **0.5** (Malus für Entwürfe).
|
||||||
|
* `system`: Exkludiert (siehe Ingestion).
|
||||||
|
|
||||||
|
**6. Intent Boost ($B_{intent}$):**
|
||||||
|
* **Herkunft:** Dynamische Injektion durch die Decision Engine basierend auf der Nutzerfrage.
|
||||||
|
* **Zweck:** Erhöhung des Scores für Knoten, die über spezifische Kanten-Typen (z.B. `caused_by` bei "Warum"-Fragen) verbunden sind.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Hybrid Retrieval Flow & Modularisierung
|
||||||
|
|
||||||
|
In v2.7 wurde die Engine in einen Orchestrator (`retriever.py`) und eine Scoring-Engine (`retriever_scoring.py`) aufgeteilt.
|
||||||
|
|
||||||
|
**Phase 1: Vector Search (Seed Generation)**
|
||||||
|
* Der Orchestrator sucht Top-K (Standard: 20) Kandidaten via Embeddings in Qdrant.
|
||||||
|
* Diese bilden die "Seeds" für den Graphen.
|
||||||
|
|
||||||
|
**Phase 2: Graph Expansion**
|
||||||
|
* Nutze `graph_adapter.expand(seeds, depth=1)`.
|
||||||
|
* Lade direkte Nachbarn aus der `_edges` Collection.
|
||||||
|
* Konstruiere einen `NetworkX`-Graphen im Speicher.
|
||||||
|
|
||||||
|
**Phase 3: Re-Ranking (Modular)**
|
||||||
|
* Der Orchestrator übergibt den Graphen und die Seeds an die `ScoringEngine`.
|
||||||
|
* Berechne Boni ($B_{edge}$, $B_{cent}$) sowie die neuen Lifecycle- und Intent-Modifier.
|
||||||
|
* Sortierung absteigend nach `TotalScore` und Limitierung auf Top-Resultate (z.B. 5).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Explanation Layer (WP-22 Update)
|
||||||
|
|
||||||
|
Bei `explain=True` generiert das System eine detaillierte Begründung.
|
||||||
|
|
||||||
|
**Erweiterte JSON-Struktur:**
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"score_breakdown": {
|
||||||
|
"semantic": 0.85,
|
||||||
|
"type_boost": 1.0,
|
||||||
|
"lifecycle_modifier": 0.5,
|
||||||
|
"edge_bonus": 0.4,
|
||||||
|
"intent_boost": 0.5,
|
||||||
|
"centrality": 0.1
|
||||||
|
},
|
||||||
|
"reasons": [
|
||||||
|
"Hohe textuelle Übereinstimmung (>0.85).",
|
||||||
|
"Status 'draft' reduziert Relevanz (Modifier 0.5).",
|
||||||
|
"Wird referenziert via 'caused_by' (Intent-Bonus 0.5).",
|
||||||
|
"Bevorzugt, da Typ 'decision' (Gewicht 1.0)."
|
||||||
|
]
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. Konfiguration (`retriever.yaml`)
|
||||||
|
|
||||||
|
Steuert die Gewichtung der mathematischen Komponenten.
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
scoring:
|
||||||
|
semantic_weight: 1.0 # Basis-Relevanz
|
||||||
|
edge_weight: 0.7 # Graphen-Einfluss
|
||||||
|
centrality_weight: 0.5 # Hub-Einfluss
|
||||||
|
|
||||||
|
# WP-22 Lifecycle Konfiguration (Abgleich mit Auftrag)
|
||||||
|
lifecycle_weights:
|
||||||
|
stable: 1.2 # Bonus für Qualität
|
||||||
|
draft: 0.5 # Malus für Entwürfe
|
||||||
|
|
||||||
|
# Kanten-Gewichtung für den Edge-Bonus (Basis)
|
||||||
|
edge_weights:
|
||||||
|
depends_on: 1.5 # Harte Abhängigkeiten
|
||||||
|
blocks: 1.5 # Risiken/Blocker
|
||||||
|
caused_by: 1.2 # Kausalitäten
|
||||||
|
based_on: 1.3 # Werte-Bezug
|
||||||
|
related_to: 0.5 # Weiche Themen
|
||||||
|
references: 0.8 # Standard-Referenzen
|
||||||
|
```
|
||||||
@@ -0,0 +1,164 @@
|
|||||||
|
---
|
||||||
|
doc_type: operations_manual
|
||||||
|
audience: admin, devops
|
||||||
|
scope: deployment, maintenance, backup, edge_registry
|
||||||
|
status: active
|
||||||
|
version: 2.7.0
|
||||||
|
context: "Installationsanleitung, Systemd-Units und Wartungsprozesse für Mindnet v2.7."
|
||||||
|
---
|
||||||
|
|
||||||
|
# Admin Operations Guide
|
||||||
|
|
||||||
|
## 1. Installation & Setup
|
||||||
|
|
||||||
|
### 1.1 Voraussetzungen
|
||||||
|
* **OS:** Ubuntu 22.04+ (empfohlen).
|
||||||
|
* **Tools:** Python 3.10+, Docker, Ollama.
|
||||||
|
* **Hardware:** Min. 8GB RAM, 4 CPU Cores (für Async Import).
|
||||||
|
|
||||||
|
### 1.2 Qdrant (Docker)
|
||||||
|
Startet die Vektor-DB mit persistentem Storage auf Port 6333.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker run -d \
|
||||||
|
--name mindnet_qdrant \
|
||||||
|
--restart always \
|
||||||
|
-p 6333:6333 \
|
||||||
|
-v $(pwd)/qdrant_storage:/qdrant/storage \
|
||||||
|
qdrant/qdrant
|
||||||
|
```
|
||||||
|
|
||||||
|
### 1.3 Ollama (Modelle)
|
||||||
|
**Wichtig:** Seit v2.4 ist `nomic-embed-text` Pflicht für Embeddings.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Modelle laden
|
||||||
|
ollama pull phi3:mini
|
||||||
|
ollama pull nomic-embed-text
|
||||||
|
|
||||||
|
# Testen
|
||||||
|
curl http://localhost:11434/api/generate -d '{"model": "phi3:mini", "prompt":"Hi"}'
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Deployment (Systemd Services)
|
||||||
|
|
||||||
|
Wir unterscheiden strikt zwischen **Prod** (Port 8001/8501) und **Dev** (Port 8002/8502).
|
||||||
|
|
||||||
|
### 2.1 Backend Service (`/etc/systemd/system/mindnet-prod.service`)
|
||||||
|
|
||||||
|
```ini
|
||||||
|
[Unit]
|
||||||
|
Description=Mindnet API Prod (8001)
|
||||||
|
After=network.target
|
||||||
|
|
||||||
|
[Service]
|
||||||
|
User=llmadmin
|
||||||
|
Group=llmadmin
|
||||||
|
WorkingDirectory=/home/llmadmin/mindnet
|
||||||
|
# Startet Uvicorn (Async Server)
|
||||||
|
# Hinweis: Die .env muss MINDNET_VOCAB_PATH für die Edge Registry enthalten.
|
||||||
|
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
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2.2 UI Service (`/etc/systemd/system/mindnet-ui-prod.service`)
|
||||||
|
|
||||||
|
```ini
|
||||||
|
[Unit]
|
||||||
|
Description=Mindnet UI Prod (8501)
|
||||||
|
After=mindnet-prod.service
|
||||||
|
|
||||||
|
[Service]
|
||||||
|
User=llmadmin
|
||||||
|
Group=llmadmin
|
||||||
|
WorkingDirectory=/home/llmadmin/mindnet
|
||||||
|
|
||||||
|
# Environment für Streamlit Port & API-Ziel
|
||||||
|
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"
|
||||||
|
|
||||||
|
# WICHTIG: Pfad zur neuen Router-Datei (ui.py)
|
||||||
|
ExecStart=/home/llmadmin/mindnet/.venv/bin/streamlit run app/frontend/ui.py
|
||||||
|
Restart=always
|
||||||
|
RestartSec=5
|
||||||
|
|
||||||
|
[Install]
|
||||||
|
WantedBy=multi-user.target
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Wartung & Monitoring
|
||||||
|
|
||||||
|
### 3.1 Regelmäßiger Import (Cron)
|
||||||
|
Führt den Sync stündlich durch. Nutzt `--purge-before-upsert` für Sauberkeit.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Crontab Eintrag (user: llmadmin)
|
||||||
|
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
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3.2 Monitoring der Edge Registry (WP-22)
|
||||||
|
Administratoren sollten regelmäßig das Log für unbekannte Kanten-Typen prüfen.
|
||||||
|
* **Pfad:** `data/logs/unknown_edges.jsonl`.
|
||||||
|
* **Aktion:** Wenn neue Typen häufig auftreten, sollten diese als Alias in die `01_edge_vocabulary.md` aufgenommen werden.
|
||||||
|
|
||||||
|
### 3.3 Troubleshooting Guide
|
||||||
|
|
||||||
|
**Fehler: "Registry Initialization Failure" (Neu in v2.7)**
|
||||||
|
* **Symptom:** API startet, aber Kanten werden nicht gewichtet oder Fehlermeldung im Log.
|
||||||
|
* **Lösung:** Prüfen Sie `MINDNET_VOCAB_PATH` in der `.env`. Der Pfad muss absolut sein und auf eine existierende Markdown-Tabelle zeigen.
|
||||||
|
|
||||||
|
**Fehler: "ModuleNotFoundError: No module named 'st_cytoscape'"**
|
||||||
|
* Ursache: Alte Dependencies oder falsches Paket installiert.
|
||||||
|
* Lösung: Environment aktualisieren.
|
||||||
|
```bash
|
||||||
|
source .venv/bin/activate
|
||||||
|
pip uninstall streamlit-cytoscapejs
|
||||||
|
pip install st-cytoscape
|
||||||
|
```
|
||||||
|
|
||||||
|
**Fehler: "Vector dimension error: expected 768, got 384"**
|
||||||
|
* Ursache: Alte DB (v2.2), neues Modell (v2.4).
|
||||||
|
* Lösung: **Full Reset** (siehe Kap. 4.2).
|
||||||
|
|
||||||
|
**Fehler: Import sehr langsam**
|
||||||
|
* Ursache: Smart Edges sind aktiv und analysieren jeden Chunk.
|
||||||
|
* Lösung: `MINDNET_LLM_BACKGROUND_LIMIT` prüfen oder Feature in `types.yaml` deaktivieren.
|
||||||
|
|
||||||
|
**Fehler: UI "Read timed out"**
|
||||||
|
* Ursache: Backend braucht für Smart Edges länger als 60s.
|
||||||
|
* Lösung: `MINDNET_API_TIMEOUT=300.0` in `.env` setzen (oder im Systemd Service).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. Backup & Restore
|
||||||
|
|
||||||
|
### 4.1 Qdrant Snapshot
|
||||||
|
Sichert den Vektor-Index.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker stop mindnet_qdrant
|
||||||
|
tar -czf qdrant_backup_$(date +%F).tar.gz ./qdrant_storage
|
||||||
|
docker start mindnet_qdrant
|
||||||
|
```
|
||||||
|
|
||||||
|
### 4.2 Notfall-Rebuild (Clean Slate)
|
||||||
|
Wenn alles inkonsistent ist oder Dimensionen sich ändern:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 1. DB löschen
|
||||||
|
python3 -m scripts.reset_qdrant --mode wipe --prefix "mindnet" --yes
|
||||||
|
|
||||||
|
# 2. Neu importieren (Force Hash recalculation)
|
||||||
|
python3 -m scripts.import_markdown --vault ./vault --prefix "mindnet" --apply --force
|
||||||
|
```
|
||||||
@@ -0,0 +1,281 @@
|
|||||||
|
---
|
||||||
|
doc_type: operations_manual
|
||||||
|
audience: system_admin, devops
|
||||||
|
scope: server_lifecycle, disaster_recovery, maintenance, backup, monitoring
|
||||||
|
status: active
|
||||||
|
version: 1.9
|
||||||
|
hostname: llm-node
|
||||||
|
ip_address: 192.168.2.144
|
||||||
|
context: "Zentrale Dokumentation für Host-Konfiguration, Mindnet-Applikation, Gitea und Backup-Strategie. Aktualisiert um die Two-Stage Disaster Recovery und Backup-Monitoring."
|
||||||
|
created_date: 2025-12-14
|
||||||
|
last_updated: 2025-12-15
|
||||||
|
---
|
||||||
|
|
||||||
|
# Server Operations Manual: llm-node (192.168.2.144)
|
||||||
|
|
||||||
|
Dieses Dokument beschreibt den Betrieb, die Wartung und die Wiederherstellung (Disaster Recovery) des Servers "llm-node".
|
||||||
|
|
||||||
|
## 1. Systemübersicht & Netzwerk
|
||||||
|
|
||||||
|
### 1.1 Host Details
|
||||||
|
* **Hostname:** `llm-node`
|
||||||
|
* **IP-Adresse:** `192.168.2.144`
|
||||||
|
* **OS:** Ubuntu Server
|
||||||
|
* **Qdrant Host-Volume Pfad:** `/home/llmadmin/docker/qdrant/qdrant_data` (Bind-Mount)
|
||||||
|
|
||||||
|
### 1.2 Storage & NAS Mount
|
||||||
|
Das System sichert auf ein Synology NAS via NFSv3.
|
||||||
|
|
||||||
|
* **Mount Point:** `/mnt/nas_backup`
|
||||||
|
* **Quelle:** `192.168.2.63:/volume1/Backup_LLM`
|
||||||
|
* **Fstab-Eintrag (Referenz für Restore):**
|
||||||
|
```text
|
||||||
|
192.168.2.63:/volume1/Backup_LLM /mnt/nas_backup nfs vers=3,_netdev,x-systemd.automount,nofail 0 0
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Dienste & Port-Matrix
|
||||||
|
|
||||||
|
### 2.1 Native Dienste (Systemd)
|
||||||
|
|
||||||
|
| Service | Port | User | Beschreibung |
|
||||||
|
| :--- | :--- | :--- | :--- |
|
||||||
|
| **SSH** | 22 | root | Remote Zugriff |
|
||||||
|
| **Gitea** | 3000 | `git` | Git Version Control (User: git) |
|
||||||
|
| **Ollama** | 11434 | `ollama` | AI Model Server |
|
||||||
|
| **Mindnet Prod API** | 8001 | `llmadmin` | Backend Applikation |
|
||||||
|
| **Mindnet Dev API** | 8002 | `llmadmin` | Backend Applikation (Entwicklung) |
|
||||||
|
| **Mindnet Prod UI** | 8501 | `llmadmin` | Frontend Applikation |
|
||||||
|
| **Mindnet Dev UI** | 8502 | `llmadmin` | Frontend Applikation (Entwicklung) |
|
||||||
|
| **Act Runner** | 38703 | `root` | Gitea CI/CD Runner |
|
||||||
|
|
||||||
|
### 2.2 Docker Container
|
||||||
|
Übersicht der Container (`docker ps`).
|
||||||
|
|
||||||
|
| Container Name | Port | Beschreibung | Backup Strategie |
|
||||||
|
| :--- | :--- | :--- | :--- |
|
||||||
|
| **qdrant** | 6333 | Vektor Datenbank (Container Name: `qdrant`) | **Stop -> Tar -> Start** (Konsistenter Snapshot) |
|
||||||
|
| **mindnet-embed** | 8990 | Embeddings Service | Volume Backup |
|
||||||
|
| **code-server** | 8443 | VS Code (Web) | Volume Backup |
|
||||||
|
| **silverbullet** | 13000 | Knowledge Base | Volume Backup |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Applikations-Management
|
||||||
|
|
||||||
|
### 3.1 Gitea (Git Server)
|
||||||
|
* **User:** `git`
|
||||||
|
* **Datenpfad:** `/var/lib/gitea`
|
||||||
|
* **Backup:** Konsistenter Dump (`gitea-dump.zip`) im `before_backup` Hook integriert.
|
||||||
|
|
||||||
|
### 3.2 Ollama (AI Models)
|
||||||
|
* **User:** `ollama`
|
||||||
|
* **Modell-Speicher:** `/usr/share/ollama/.ollama/models`
|
||||||
|
* **Backup:** Nur Metadaten. Blobs werden exkludiert.
|
||||||
|
|
||||||
|
### 3.3 Mindnet (AI App)
|
||||||
|
* **User:** `llmadmin`
|
||||||
|
* **Qdrant Storage:** `/home/llmadmin/docker/qdrant/qdrant_data`
|
||||||
|
* **Cronjob:** Regelmäßiger Import (stündlich) unter User `llmadmin`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. Backup Strategie (Borgmatic)
|
||||||
|
|
||||||
|
**Status:** Automatisiert via `systemctl start borgmatic.timer`.
|
||||||
|
**Ziel:** `/mnt/nas_backup/borg_repo`
|
||||||
|
|
||||||
|
### 4.1 Konsistenz-Strategie
|
||||||
|
Alle schreibenden Dienste werden durch Hooks für das Backup vorbereitet:
|
||||||
|
|
||||||
|
### 4.2 Konfiguration (`/etc/borgmatic/config.yaml`)
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
source_directories:
|
||||||
|
- /etc
|
||||||
|
- /home
|
||||||
|
- /var
|
||||||
|
- /opt
|
||||||
|
- /root
|
||||||
|
|
||||||
|
repositories:
|
||||||
|
- path: /mnt/nas_backup/borg_repo
|
||||||
|
label: nas
|
||||||
|
|
||||||
|
exclude_patterns:
|
||||||
|
- /mnt/*
|
||||||
|
- /var/lib/gitea/data/tmp/*
|
||||||
|
# Ollama Blobs (Speicher sparen)
|
||||||
|
- /usr/share/ollama/.ollama/models/blobs/*
|
||||||
|
- /home/*/.ollama/models/blobs/*
|
||||||
|
# Qdrant Live-Daten exkludieren
|
||||||
|
- /home/llmadmin/docker/qdrant/qdrant_data/*
|
||||||
|
|
||||||
|
keep_daily: 7
|
||||||
|
keep_weekly: 4
|
||||||
|
keep_monthly: 6
|
||||||
|
|
||||||
|
before_backup:
|
||||||
|
- echo "--- Start Pre-Backup Hooks ---"
|
||||||
|
|
||||||
|
# 1. Ollama Liste sichern
|
||||||
|
- ollama list > /root/ollama_models_backup.txt
|
||||||
|
|
||||||
|
# 2. Gitea Dump
|
||||||
|
- echo "Erstelle Gitea Dump..."
|
||||||
|
- rm -f /var/lib/gitea/gitea-dump.zip
|
||||||
|
- runuser -u git -- gitea dump -c /etc/gitea/app.ini -f /var/lib/gitea/gitea-dump.zip
|
||||||
|
|
||||||
|
# 3. Qdrant Snapshot
|
||||||
|
- echo "Erstelle Qdrant Snapshot..."
|
||||||
|
- docker stop qdrant
|
||||||
|
- rm -f /home/llmadmin/qdrant_backup_latest.tar.gz
|
||||||
|
# Tar Archiv im Home-Verzeichnis erstellen (wird von Borg gesichert)
|
||||||
|
- tar -czf /home/llmadmin/qdrant_backup_latest.tar.gz -C /home/llmadmin/docker/qdrant qdrant_data
|
||||||
|
- docker start qdrant
|
||||||
|
|
||||||
|
after_backup:
|
||||||
|
- echo "Backup erfolgreich beendet."
|
||||||
|
# Nach erfolgreichem Backup wird das temporäre Tar-Archiv gelöscht
|
||||||
|
- rm -f /home/llmadmin/qdrant_backup_latest.tar.gz
|
||||||
|
|
||||||
|
on_error:
|
||||||
|
- echo "FEHLER aufgetreten! Versuche Container zu retten..."
|
||||||
|
- docker start qdrant
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. Disaster Recovery (Wiederherstellung) - Two-Stage DR
|
||||||
|
|
||||||
|
Das Wiederherstellungsverfahren basiert auf einer **"Two-Stage DR"**-Strategie, die die Geschwindigkeit eines Basis-Images mit der Datenkonsistenz des Borgmatic-Archives kombiniert.
|
||||||
|
|
||||||
|
### 5.0 Vorbereitung: Erstellung des Basis-Images (Monatlich/Quartalsweise)
|
||||||
|
|
||||||
|
Dieses Image sichert das bootfähige System (OS, Pakete, Konfiguration) und dient als schneller Startpunkt bei einem Festplattenausfall.
|
||||||
|
|
||||||
|
1. **System Bereinigen:** Führen Sie eine Systembereinigung durch, um die Image-Größe zu minimieren.
|
||||||
|
```bash
|
||||||
|
sudo apt clean
|
||||||
|
sudo journalctl --vacuum-time=7d
|
||||||
|
```
|
||||||
|
2. **Booten vom Live-Medium:** Starten Sie den Server von einem **Ubuntu Live USB-Stick** (Größe min. 8 GB).
|
||||||
|
3. **Mount NAS:** Stellen Sie die Verbindung zum NAS her, um das Image direkt dorthin zu schreiben.
|
||||||
|
```bash
|
||||||
|
sudo mkdir /mnt/nas_backup
|
||||||
|
sudo mount -t nfs 192.168.2.63:/volume1/Backup_LLM /mnt/nas_backup
|
||||||
|
```
|
||||||
|
4. **Image erstellen und streamen:** Ermitteln Sie die Root-Partition des Servers (z.B. `/dev/sda1`) und erstellen Sie das komprimierte Image direkt auf dem NAS.
|
||||||
|
```bash
|
||||||
|
# Das Image wird direkt zum NAS gestreamt (USB-Stick benötigt nur 8GB für Live OS)
|
||||||
|
sudo dd if=/dev/sda1 bs=1M status=progress | gzip > /mnt/nas_backup/base_image_$(date +%Y%m%d).img.gz
|
||||||
|
```
|
||||||
|
|
||||||
|
### 5.1 Stage 1: Basis-Image Restore (Bare Metal Recovery)
|
||||||
|
|
||||||
|
Dieses Verfahren setzt das System auf den Stand des letzten Basis-Images zurück.
|
||||||
|
|
||||||
|
**Prozedur (Von Live-Medium booten):**
|
||||||
|
|
||||||
|
1. **Voraussetzungen:** Booten Sie den neuen/reparierten PC von einem **Live-Medium** (z.B. Ubuntu Live USB).
|
||||||
|
2. **Mount NAS (auf Live-System):** Stellen Sie die Verbindung zum Backup-Speicher her, um auf das Image zuzugreifen.
|
||||||
|
```bash
|
||||||
|
sudo mkdir /mnt/nas_backup
|
||||||
|
sudo mount -t nfs 192.168.2.63:/volume1/Backup_LLM /mnt/nas_backup
|
||||||
|
```
|
||||||
|
3. **Zielpartition identifizieren:** Ermitteln Sie den Gerätenamen der Root-Partition der **neuen** Festplatte (z.B. `/dev/sda1`). **ACHTUNG: Falsches Gerät löscht alle Daten!**
|
||||||
|
```bash
|
||||||
|
sudo fdisk -l
|
||||||
|
```
|
||||||
|
4. **Image Restore:** Schreiben Sie das komprimierte Basis-Image auf die neue Partition zurück. Ersetzen Sie `YYYYMMDD` durch das tatsächliche Datum und `/dev/sda1` durch Ihre Zielpartition.
|
||||||
|
```bash
|
||||||
|
sudo gunzip -c /mnt/nas_backup/base_image_YYYYMMDD.img.gz | sudo dd of=/dev/sda1 status=progress bs=1M
|
||||||
|
```
|
||||||
|
5. **Neustart:** Entfernen Sie den Live-USB und starten Sie das System neu. Es sollte nun in das wiederhergestellte Basis-OS booten.
|
||||||
|
|
||||||
|
### 5.2 Stage 2: Daten-Update (Borgmatic)
|
||||||
|
|
||||||
|
Nach dem Booten des Basis-Systems (Stage 1) werden die aktuellen Daten und die kritischen Applikations-Snapshots wiederhergestellt.
|
||||||
|
|
||||||
|
#### Schritt 1: Aktueller Daten Restore (Borg)
|
||||||
|
Das Borg-Repository ist dank des Basis-Images bereits in `/etc/borgmatic/config.yaml` und `/etc/fstab` bekannt.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Alle Daten aus dem letzten Archiv (latest) auf das laufende System wiederherstellen
|
||||||
|
sudo borgmatic extract --archive latest --path / --destination /
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Schritt 2: Dienste spezifisch wiederherstellen (Gitea/Qdrant/Ollama)
|
||||||
|
|
||||||
|
**A. Gitea (Aus Dump):**
|
||||||
|
1. Dump entpacken: `unzip /var/lib/gitea/gitea-dump.zip -d /tmp/gitea_restore`
|
||||||
|
2. Service starten: `systemctl enable --now gitea`
|
||||||
|
|
||||||
|
**B. Qdrant (Aus Snapshot):**
|
||||||
|
Das Tar-Archiv liegt im Home-Verzeichnis (`/home/llmadmin/`) und muss in das Volume-Verzeichnis entpackt werden.
|
||||||
|
|
||||||
|
1. Wechsle in das Host-Verzeichnis des Volumes:
|
||||||
|
```bash
|
||||||
|
cd /home/llmadmin/docker/qdrant
|
||||||
|
```
|
||||||
|
2. Entpacke das gesicherte Tar (stellt den Ordner `qdrant_data` wieder her):
|
||||||
|
```bash
|
||||||
|
sudo tar -xzf /home/llmadmin/qdrant_backup_latest.tar.gz
|
||||||
|
```
|
||||||
|
3. Container starten (Volume-Mount ist korrekt):
|
||||||
|
```bash
|
||||||
|
docker start qdrant
|
||||||
|
```
|
||||||
|
|
||||||
|
**C. Ollama (Smart Restore):**
|
||||||
|
1. Ollama installieren (falls im Basis-Image nicht enthalten).
|
||||||
|
2. Modelle mit dem Script aus `/root/ollama_models_backup.txt` neu ziehen:
|
||||||
|
```bash
|
||||||
|
sudo tail -n +2 /root/ollama_models_backup.txt | awk '{print $1}' | while read model; do ollama pull "$model"; done
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. Log- und Fehleranalyse & Wartung
|
||||||
|
|
||||||
|
### 6.1 Backup-Überwachung (Monitoring)
|
||||||
|
|
||||||
|
Die Überprüfung der Backup-Korrektheit erfolgt über das Systemd Journal und die Borgmatic-Befehle.
|
||||||
|
|
||||||
|
| Aktion | Befehl | Zweck |
|
||||||
|
| :--- | :--- | :--- |
|
||||||
|
| **Prüfung letzter Lauf** | `sudo journalctl -u borgmatic --since "yesterday"` | Zeigt das Journal der letzten 24 Stunden, inklusive der Hooks und Fehler. |
|
||||||
|
| **Liste Archive** | `sudo borgmatic list` | Zeigt alle existierenden Archive, sortiert nach Datum/Uhrzeit. Dient zur Bestätigung, dass das Backup erstellt wurde. |
|
||||||
|
| **Repo-Integrität** | `sudo borgmatic check` | Führt eine Konsistenzprüfung des gesamten Repositorys durch (kann lange dauern). |
|
||||||
|
|
||||||
|
### 6.2 Granulare Wiederherstellung (Einzelne Dateien)
|
||||||
|
|
||||||
|
Um auf einzelne Dateien oder Verzeichnisse in einem Archiv zuzugreifen, wird das Archiv als virtuelles Dateisystem gemountet.
|
||||||
|
|
||||||
|
1. **Mount-Punkt erstellen:**
|
||||||
|
```bash
|
||||||
|
mkdir /tmp/borg_mount
|
||||||
|
```
|
||||||
|
2. **Archiv einhängen:** Hängen Sie das gewünschte Archiv (hier: `latest`) in den Mount-Punkt ein. Geben Sie bei Bedarf den vollständigen ARCHIVNAMEN an.
|
||||||
|
```bash
|
||||||
|
sudo borgmatic mount --destination /tmp/borg_mount --archive latest
|
||||||
|
```
|
||||||
|
3. **Dateizugriff:** Das gesamte Backup-Dateisystem ist nun unter `/tmp/borg_mount` verfügbar. Dateien können mit `cp` kopiert werden.
|
||||||
|
```bash
|
||||||
|
# Beispiel: Eine Datei aus dem Home-Verzeichnis wiederherstellen
|
||||||
|
sudo cp /tmp/borg_mount/home/llmadmin/wichtige_datei.txt /home/llmadmin/
|
||||||
|
```
|
||||||
|
4. **Archiv aushängen:** Nach dem Kopieren muss das virtuelle Dateisystem immer ausgehängt werden.
|
||||||
|
```bash
|
||||||
|
sudo umount /tmp/borg_mount
|
||||||
|
# Oder:
|
||||||
|
# sudo borgmatic umount /tmp/borg_mount
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 7. Anhang
|
||||||
|
|
||||||
|
* **Qdrant Container Logs:** `docker logs qdrant`
|
||||||
|
* **Applikations-Logs:** `journalctl -u mindnet-prod`
|
||||||
@@ -0,0 +1,457 @@
|
|||||||
|
---
|
||||||
|
doc_type: developer_guide
|
||||||
|
audience: developer
|
||||||
|
scope: workflow, testing, architecture, modules
|
||||||
|
status: active
|
||||||
|
version: 2.6.1
|
||||||
|
context: "Umfassender Guide für Entwickler: Architektur, Modul-Interna (Deep Dive), Setup, Git-Workflow und Erweiterungs-Anleitungen."
|
||||||
|
---
|
||||||
|
|
||||||
|
# Mindnet Developer Guide & Workflow
|
||||||
|
|
||||||
|
**Quellen:** `developer_guide.md`, `dev_workflow.md`, `Architecture_Audit_v2.6`
|
||||||
|
|
||||||
|
Dieser Guide ist die zentrale technische Referenz für Mindnet v2.6. Er vereint das technische Verständnis der Module mit dem operativen Workflow zwischen Windows (Dev) und Linux (Runtime).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
# Inhaltsverzeichnis
|
||||||
|
- [Mindnet Developer Guide \& Workflow](#mindnet-developer-guide--workflow)
|
||||||
|
- [Inhaltsverzeichnis](#inhaltsverzeichnis)
|
||||||
|
- [1. Einführung \& Systemüberblick](#1-einführung--systemüberblick)
|
||||||
|
- [Was ist Mindnet?](#was-ist-mindnet)
|
||||||
|
- [Kern-Philosophie](#kern-philosophie)
|
||||||
|
- [2. Architektur](#2-architektur)
|
||||||
|
- [2.1 High-Level Übersicht](#21-high-level-übersicht)
|
||||||
|
- [2.2 Datenfluss-Muster](#22-datenfluss-muster)
|
||||||
|
- [A. Ingestion (Write)](#a-ingestion-write)
|
||||||
|
- [B. Retrieval (Read)](#b-retrieval-read)
|
||||||
|
- [C. Visualisierung (Graph)](#c-visualisierung-graph)
|
||||||
|
- [3. Physische Architektur](#3-physische-architektur)
|
||||||
|
- [4. Projektstruktur \& Modul-Referenz (Deep Dive)](#4-projektstruktur--modul-referenz-deep-dive)
|
||||||
|
- [4.1 Verzeichnisbaum](#41-verzeichnisbaum)
|
||||||
|
- [4.2 Frontend Architecture (`app/frontend/`)](#42-frontend-architecture-appfrontend)
|
||||||
|
- [Frontend Design Patterns (Wichtig!)](#frontend-design-patterns-wichtig)
|
||||||
|
- [4.3 Backend Architecture (`app/`)](#43-backend-architecture-app)
|
||||||
|
- [4.4 Scripts \& Tooling (Die Admin-Toolbox)](#44-scripts--tooling-die-admin-toolbox)
|
||||||
|
- [1. Script-Übersicht](#1-script-übersicht)
|
||||||
|
- [2. Einsatzszenarien \& Bewertung](#2-einsatzszenarien--bewertung)
|
||||||
|
- [5. Maintenance \& "Kill List"](#5-maintenance--kill-list)
|
||||||
|
- [6. Lokales Setup (Development)](#6-lokales-setup-development)
|
||||||
|
- [7. Der Entwicklungs-Zyklus (Workflow)](#7-der-entwicklungs-zyklus-workflow)
|
||||||
|
- [Phase 1: Windows (Code)](#phase-1-windows-code)
|
||||||
|
- [Phase 2: Beelink (Test / Dev)](#phase-2-beelink-test--dev)
|
||||||
|
- [Phase 3: Release \& Deployment (Prod)](#phase-3-release--deployment-prod)
|
||||||
|
- [8. Erweiterungs-Guide: "Teach-the-AI"](#8-erweiterungs-guide-teach-the-ai)
|
||||||
|
- [Workflow A: Neuen Typ implementieren (z. B. `type: risk`)](#workflow-a-neuen-typ-implementieren-z-b-type-risk)
|
||||||
|
- [Workflow B: Graph-Farben ändern](#workflow-b-graph-farben-ändern)
|
||||||
|
- [9. Tests \& Debugging](#9-tests--debugging)
|
||||||
|
- [10. Troubleshooting \& One-Liners](#10-troubleshooting--one-liners)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. Einführung & Systemüberblick
|
||||||
|
|
||||||
|
### Was ist Mindnet?
|
||||||
|
Mindnet ist ein **Hybrides Knowledge Management System**, das klassische Notizen (Markdown) mit KI-gestützter Analyse verbindet. Es kombiniert **RAG** (Retrieval Augmented Generation) mit einer **Graphen-Datenbank** (Qdrant), um Wissen nicht nur semantisch zu finden, sondern auch strukturell zu vernetzen.
|
||||||
|
|
||||||
|
### Kern-Philosophie
|
||||||
|
1. **Filesystem First:** Die Wahrheit liegt immer auf der Festplatte (Markdown-Dateien). Die Datenbank ist ein abgeleiteter Index.
|
||||||
|
2. **Hybrid Retrieval:** Relevanz entsteht aus Textähnlichkeit (Semantik) + Graphen-Verbindungen (Edges) + Wichtigkeit (Centrality).
|
||||||
|
3. **Active Intelligence:** Das System wartet nicht nur auf Anfragen, sondern schlägt beim Schreiben proaktiv Verbindungen vor ("Matrix Logic").
|
||||||
|
4. **Local Privacy:** Alle KI-Berechnungen (Ollama) laufen lokal. Keine Cloud-Abhängigkeit für Inference.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Architektur
|
||||||
|
|
||||||
|
### 2.1 High-Level Übersicht
|
||||||
|
Das System folgt einer strikten Trennung zwischen Frontend (Streamlit) und Backend (FastAPI), wobei bestimmte Performance-Pfade (Graph-Visualisierung) optimiert wurden.
|
||||||
|
|
||||||
|
```mermaid
|
||||||
|
graph TD
|
||||||
|
User((User))
|
||||||
|
|
||||||
|
subgraph "Frontend Layer (Streamlit)"
|
||||||
|
UI["ui.py Router"]
|
||||||
|
ViewChat["Chat View"]
|
||||||
|
ViewGraph["Graph View"]
|
||||||
|
ViewEditor["Editor View"]
|
||||||
|
Logic["Callbacks & State"]
|
||||||
|
end
|
||||||
|
|
||||||
|
subgraph "Backend Layer (FastAPI)"
|
||||||
|
API["main.py"]
|
||||||
|
RouterChat["Chat / RAG"]
|
||||||
|
RouterIngest["Ingest / Write"]
|
||||||
|
CoreRet["Retriever Engine"]
|
||||||
|
CoreIngest["Ingestion Pipeline"]
|
||||||
|
end
|
||||||
|
|
||||||
|
subgraph "Infrastructure & Services"
|
||||||
|
LLM["Ollama (Phi3/Nomic)"]
|
||||||
|
DB[("Qdrant Vector DB")]
|
||||||
|
FS["File System (.md)"]
|
||||||
|
end
|
||||||
|
|
||||||
|
User <--> UI
|
||||||
|
UI -- "REST (Chat, Save, Feedback)" --> API
|
||||||
|
UI -. "Direct Read (Graph Viz Performance)" .-> DB
|
||||||
|
API -- "Embeddings & Completion" --> LLM
|
||||||
|
API -- "Read/Write" --> DB
|
||||||
|
API -- "Read/Write (Source of Truth)" --> FS
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2.2 Datenfluss-Muster
|
||||||
|
|
||||||
|
#### A. Ingestion (Write)
|
||||||
|
Vom Markdown zur Vektor-Datenbank.
|
||||||
|
```mermaid
|
||||||
|
graph LR
|
||||||
|
MD["Markdown File"] --> Parser("Parser")
|
||||||
|
Parser --> Chunker("Chunker")
|
||||||
|
Chunker -- "Text Chunks" --> SemAn{"SemanticAnalyzer<br/>(LLM)"}
|
||||||
|
SemAn -- "Smart Edges" --> Embedder("Embedder")
|
||||||
|
Embedder --> DB[("Qdrant<br/>Points")]
|
||||||
|
|
||||||
|
style DB fill:#f9f,stroke:#333,stroke-width:2px
|
||||||
|
style SemAn fill:#ff9,stroke:#333,stroke-width:2px
|
||||||
|
```
|
||||||
|
|
||||||
|
#### B. Retrieval (Read)
|
||||||
|
Die hybride Suche für Chat & RAG.
|
||||||
|
```mermaid
|
||||||
|
graph LR
|
||||||
|
Query(["Query"]) --> Embed("Embedding")
|
||||||
|
Embed --> Hybrid{"Hybrid Search"}
|
||||||
|
|
||||||
|
subgraph Search Components
|
||||||
|
Vec["Vector Score"]
|
||||||
|
Graph["Graph/Edge Bonus"]
|
||||||
|
end
|
||||||
|
|
||||||
|
Vec --> Hybrid
|
||||||
|
Graph --> Hybrid
|
||||||
|
|
||||||
|
Hybrid --> Rank("Re-Ranking")
|
||||||
|
Rank --> Ctx["LLM Context"]
|
||||||
|
```
|
||||||
|
|
||||||
|
#### C. Visualisierung (Graph)
|
||||||
|
Der optimierte Pfad für das Frontend.
|
||||||
|
```mermaid
|
||||||
|
graph LR
|
||||||
|
UI["Frontend UI"] --> Service("GraphService")
|
||||||
|
Service -- "Direct Read" --> DB[("Qdrant<br/>Edges Collection")]
|
||||||
|
DB --> Cyto["Cytoscape<br/>Rendering"]
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Physische Architektur
|
||||||
|
|
||||||
|
Mindnet läuft in einer verteilten Umgebung (Post-WP15 Setup).
|
||||||
|
|
||||||
|
* **Windows 11 (VS Code):** Entwicklungsumgebung. **Nie** direkt auf `main` arbeiten!
|
||||||
|
* **Beelink (Runtime):** Der Server hostet zwei Instanzen via Systemd:
|
||||||
|
* **PROD:** API (Port 8001) + UI (Port 8501). Home: `~/mindnet`.
|
||||||
|
* **DEV:** API (Port 8002) + UI (Port 8502). Home: `~/mindnet_dev`.
|
||||||
|
* **Gitea (Raspberry Pi):** Versionskontrolle ("Safe"). Speichert den Code.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. Projektstruktur & Modul-Referenz (Deep Dive)
|
||||||
|
|
||||||
|
Das System ist modular aufgebaut. Hier ist die detaillierte Analyse aller Komponenten.
|
||||||
|
|
||||||
|
### 4.1 Verzeichnisbaum
|
||||||
|
|
||||||
|
```text
|
||||||
|
mindnet/
|
||||||
|
├── app/
|
||||||
|
│ ├── core/ # Business Logic & Algorithms
|
||||||
|
│ ├── routers/ # API Interface (FastAPI)
|
||||||
|
│ ├── services/ # External Integrations (LLM, DB)
|
||||||
|
│ ├── models/ # Pydantic DTOs
|
||||||
|
│ └── frontend/ # UI Logic (Streamlit)
|
||||||
|
├── config/ # Configuration Files (YAML)
|
||||||
|
├── scripts/ # CLI Tools (Ops & Maintenance)
|
||||||
|
└── vault/ # Local Content Storage
|
||||||
|
```
|
||||||
|
|
||||||
|
### 4.2 Frontend Architecture (`app/frontend/`)
|
||||||
|
|
||||||
|
Das Frontend ist eine Streamlit-App, die sich wie eine Single-Page-Application (SPA) verhält.
|
||||||
|
|
||||||
|
| Modul | Status | Verantwortung |
|
||||||
|
| :--- | :--- | :--- |
|
||||||
|
| **`ui.py`** | 🟢 **Core** | **Main Router.** Initialisiert Session-State und entscheidet anhand der Sidebar-Auswahl, welche View gerendert wird. |
|
||||||
|
| **`ui_config.py`** | 🟢 **Config** | **Constants.** Zentraler Ort für Farben (`GRAPH_COLORS`), API-URLs und Timeouts. Änderungen am Look & Feel passieren hier. |
|
||||||
|
| **`ui_chat.py`** | 🟢 **View** | **Chat UI.** Rendert Nachrichtenverlauf, Intent-Badges, Quellen-Expanders und Feedback-Buttons. |
|
||||||
|
| **`ui_editor.py`** | 🟢 **View** | **Editor UI.** Markdown-Editor mit Live-Vorschau. Integriert "Intelligence" (KI-Link-Vorschläge). |
|
||||||
|
| **`ui_graph_cytoscape.py`**| 🟢 **View** | **Modern Graph.** Interaktiver Graph basierend auf Cytoscape.js (COSE Layout). |
|
||||||
|
| **`ui_graph.py`** | 🟡 **Legacy** | **Graph UI (Fallback).** Alte Implementierung mittels `streamlit-agraph`. |
|
||||||
|
| **`ui_callbacks.py`** | 🟢 **Logic** | **State Controller.** Handhabt komplexe State-Übergänge (z.B. Graph -> Editor). |
|
||||||
|
| **`ui_utils.py`** | 🟢 **Logic** | **Helper.** Enthält den **Healing Parser** (`parse_markdown_draft`), der defektes JSON/YAML von LLMs repariert. |
|
||||||
|
| **`ui_api.py`** | 🟢 **Data** | **API Client.** Wrapper für Backend REST-Calls. |
|
||||||
|
| **`ui_graph_service.py`** | 🟢 **Data** | **Performance Hack.** Greift direkt auf Qdrant zu (bypass API), um Graphen schnell zu laden. |
|
||||||
|
|
||||||
|
#### Frontend Design Patterns (Wichtig!)
|
||||||
|
|
||||||
|
1. **Active Inspector Pattern (`ui_graph_cytoscape.py`)**
|
||||||
|
Um Re-Renders im Graphen zu vermeiden, nutzen wir CSS-Klassen. Wird ein Knoten angeklickt, ändert sich nur die CSS-Klasse (`.inspected`), aber die Physik-Simulation startet nicht neu. Das sorgt für ein stabiles UI-Gefühl.
|
||||||
|
|
||||||
|
2. **Resurrection Pattern (`ui_editor.py`)**
|
||||||
|
Streamlit neigt dazu, Eingaben bei Re-Runs zu "vergessen". Der Editor synchronisiert seinen Inhalt aggressiv in den `session_state`.
|
||||||
|
* Logik: `if widget_key not in session_state: restore_from_data_key()`.
|
||||||
|
* Ergebnis: Texteingaben überleben Tab-Wechsel.
|
||||||
|
|
||||||
|
3. **Filesystem First (`ui_callbacks.py`)**
|
||||||
|
Wenn man im Graphen auf "Bearbeiten" klickt:
|
||||||
|
1. Versucht das System, die **echte Datei** von der Festplatte zu lesen.
|
||||||
|
2. Nur wenn das fehlschlägt, wird der Text aus den Datenbank-Chunks rekonstruiert ("Stitching").
|
||||||
|
Dies verhindert, dass veraltete Datenbank-Stände die echten Dateien überschreiben.
|
||||||
|
|
||||||
|
### 4.3 Backend Architecture (`app/`)
|
||||||
|
|
||||||
|
Das Backend ist das Herzstück. Es stellt die Logik via REST-API bereit.
|
||||||
|
|
||||||
|
| Layer | Datei | Status | Verantwortung |
|
||||||
|
| :--- | :--- | :--- | :--- |
|
||||||
|
| **Entry** | `app/main.py` | 🟢 **Core** | **Entrypoint.** Initialisiert FastAPI, CORS, und bindet alle Router ein. |
|
||||||
|
| **Config** | `app/config.py` | 🟢 **Core** | **Settings.** Zentrale Konfiguration (Pydantic). Lädt Env-Vars für Qdrant, LLM und Pfade. |
|
||||||
|
| **Router** | `app/routers/chat.py` | 🟢 **API** | **Conversation API.** Haupt-Endpunkt für Chat. Entscheidet zwischen Interview- und RAG-Modus. |
|
||||||
|
| | `app/routers/ingest.py` | 🟢 **API** | **Write API.** Nimmt Markdown entgegen, steuert Ingestion und Discovery-Analyse. |
|
||||||
|
| | `app/routers/query.py` | 🟢 **API** | **Search API.** Klassischer Hybrid-Retriever Endpunkt. |
|
||||||
|
| | `app/routers/graph.py` | 🟢 **API** | **Viz API.** Liefert Knoten/Kanten für Frontend-Graphen (Cytoscape). |
|
||||||
|
| | `app/routers/tools.py` | 🟢 **API** | **Agent Specs.** Liefert JSON-Schemas für die Integration in externe Agenten (Ollama/MCP). |
|
||||||
|
| **Engine** | `app/core/ingestion.py` | ⚙️ **Core** | **Pipeline Controller.** Koordiniert Parsing, Hashing (Change-Detection) und DB-Upserts. |
|
||||||
|
| | `app/core/retriever.py` | ⚙️ **Core** | **Search Engine.** Berechnet Scores (Vektor + Graph + Centrality) und baut Erklärungen. |
|
||||||
|
| | `app/core/chunker.py` | ⚙️ **Core** | **Segmentation.** Zerlegt Text intelligent. Orchestriert `SemanticAnalyzer` für Smart Edges. |
|
||||||
|
| | `app/core/parser.py` | ⚙️ **Core** | **I/O.** Liest Markdown robust (Encoding-Fallback), trennt Frontmatter/Body. |
|
||||||
|
| | `app/core/derive_edges.py`| ⚙️ **Core** | **Link Extractor.** Findet Wikilinks, Callouts und Typed Relations im Text. |
|
||||||
|
| | `app/core/note_payload.py`| ⚙️ **Core** | **Builder.** Erzeugt JSON für `mindnet_notes`. Vererbt Configs (Frontmatter > Type > Default). |
|
||||||
|
| | `app/core/qdrant_points.py`| ⚙️ **Core** | **Object Mapper.** Wandelt Payloads in Qdrant `PointStruct`s um. Handhabt UUIDs. |
|
||||||
|
| **Services** | `app/services/llm_service.py`| 🧠 **AI** | **AI Client.** Async Client für Ollama. Verwaltet Concurrency (Semaphore). |
|
||||||
|
| | `app/services/embeddings_client.py`| 🧠 **AI** | **Vector Client.** Unified Client für Embeddings (Ollama/Nomic). Ersetzt lokale Modelle. |
|
||||||
|
| | `app/services/discovery.py`| 🧠 **AI** | **Intelligence.** "Matrix Logic" für Link-Vorschläge (WP-11). |
|
||||||
|
| | `app/services/semantic_analyzer.py`| 🧠 **AI** | **Filter.** KI-Validierung von Kanten im Hintergrund (Background Priority). |
|
||||||
|
|
||||||
|
### 4.4 Scripts & Tooling (Die Admin-Toolbox)
|
||||||
|
|
||||||
|
Der Ordner `scripts/` enthält verifizierte Werkzeuge für den Betrieb.
|
||||||
|
|
||||||
|
#### 1. Script-Übersicht
|
||||||
|
|
||||||
|
| Skript | Status | Zweck | Argumente & Parameter | Beispielaufruf |
|
||||||
|
| :--- | :--- | :--- | :--- | :--- |
|
||||||
|
| **`import_markdown.py`** | 🟢 **Core** | **Ingestion.** Scannt den Vault und importiert Dateien asynchron in Qdrant. Beachtet Hashes. | `--vault PATH` (Quellordner)<br>`--prefix TEXT` (Collection Prefix)<br>`--force` (Erzwingt Re-Index)<br>`--apply` (Schreibt in DB; sonst Dry-Run) | `python3 scripts/import_markdown.py --vault ./vault --apply` |
|
||||||
|
| **`reset_qdrant.py`** | 🟢 **Core** | **DB-Reset.** Löscht Collections (`wipe`) oder leert sie (`truncate`). Legt Indizes neu an. | `--mode {wipe,truncate}`<br>`--prefix TEXT`<br>`--yes` (Keine Rückfrage)<br>`--no-indexes` (Skip Index-Erstellung) | `python3 -m scripts.reset_qdrant --mode wipe --yes` |
|
||||||
|
| **`health_check_mindnet.py`** | 🟢 **Ops** | **Monitoring.** Prüft API-Verfügbarkeit (`/query`) und Antwortqualität. Standalone (keine Imports). | `--url URL`<br>`--query TEXT`<br>`--top-k INT`<br>`--strict` (Exit-Code 1 bei Warnings) | `python3 scripts/health_check_mindnet.py --strict` |
|
||||||
|
| **`payload_dryrun.py`** | 🟡 **Dev** | **Debugger.** Simuliert die JSON-Erstellung (Payloads) ohne DB-Schreibzugriff. Prüft `types.yaml`. | `--vault PATH`<br>`--note-id ID` (Filter)<br>`--with-edges` (Zeigt Kanten) | `python3 -m scripts.payload_dryrun --vault ./vault --note-id "projekt-alpha"` |
|
||||||
|
| **`edges_full_check.py`** | 🟡 **Audit** | **Integritäts-Check.** Zählt Kanten in der DB und prüft logische Konsistenz (z.B. Chunk-Reihenfolge). | Keine (Liest Konfiguration nur aus Umgebungsvariablen `.env`) | `python3 -m scripts.edges_full_check` |
|
||||||
|
| **`resolve_unresolved_references.py`** | 🔵 **Maint** | **Link-Healer.** Repariert "tote" Links in der DB nachträglich und erzeugt Backlinks. | `--prefix TEXT`<br>`--limit INT`<br>`--apply` (Schreibt Änderungen) | `python3 -m scripts.resolve_unresolved_references --apply` |
|
||||||
|
| **`export_markdown.py`** | ⚪ **Utility** | **Reverse ETL.** Exportiert den Datenbank-Inhalt zurück in Markdown-Dateien (Backup/Recovery). | `--out PATH` (Ziel)<br>`--note-id ID`<br>`--include-edges {yaml,footer}`<br>`--flatten-paths` | `python3 -m scripts.export_markdown --out ./backup` |
|
||||||
|
|
||||||
|
#### 2. Einsatzszenarien & Bewertung
|
||||||
|
|
||||||
|
* **🟢 Essentiell für den Betrieb (Must-Have):**
|
||||||
|
* **`import_markdown.py`**: Das Arbeitspferd. Ohne dieses Skript kommen keine Daten ins System.
|
||||||
|
* **`reset_qdrant.py`**: Zwingend notwendig für CI/CD-Pipelines.
|
||||||
|
* **`health_check_mindnet.py`**: Ideal für Docker-Healthchecks.
|
||||||
|
|
||||||
|
* **🟡 Hilfreich für Entwicklung & Debugging (Should-Have):**
|
||||||
|
* **`payload_dryrun.py`**: Wertvoll, wenn man an der `config/types.yaml` arbeitet.
|
||||||
|
* **`edges_full_check.py`**: Wichtiges Diagnose-Tool für den Graphen.
|
||||||
|
|
||||||
|
* **🔵 Wartung & Spezialfälle (Nice-to-Have):**
|
||||||
|
* **`resolve_unresolved_references.py`**: Sinnvoll in einem "Knowledge Garden", wo oft Links auf noch nicht existierende Notizen gesetzt werden ("Red Links"). Dieses Skript "heilt" den Graphen nachträglich.
|
||||||
|
* **`export_markdown.py`**: Ein Notfall-Tool. Da Mindnet nach dem Prinzip "Filesystem First" arbeitet, ist ein Export aus der DB selten nötig, kann aber bei versehentlichem Löschen von Dateien lebensrettend sein.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. Maintenance & "Kill List"
|
||||||
|
|
||||||
|
Folgende Dateien wurden im Audit v2.6 als veraltet, redundant oder "Zombie-Code" identifiziert und sollten entfernt werden.
|
||||||
|
|
||||||
|
| Datei | Diagnose | Empfohlene Aktion |
|
||||||
|
| :--- | :--- | :--- |
|
||||||
|
| `app/embed_server.py` | **Zombie.** Alter Standalone-Server. | 🗑️ Löschen |
|
||||||
|
| `app/embeddings.py` | **Zombie.** Veraltete lokale Lib. **(Achtung: Erst Importe in `main.py` entfernen!)** | 🗑️ Löschen |
|
||||||
|
| `app/routers/embed_router.py` | **Zombie.** Nutzt `embeddings.py`. | 🗑️ Löschen |
|
||||||
|
| `app/routers/qdrant_router.py`| **Deprecated.** Keine Logik, nur CRUD. | 🗑️ Löschen |
|
||||||
|
| `app/core/edges.py` | **Redundant.** Ersetzt durch `derive_edges.py`. | 🗑️ Löschen |
|
||||||
|
| `app/core/ranking.py` | **Redundant.** Logik in `retriever.py` integriert. | 🗑️ Löschen |
|
||||||
|
| `app/core/type_registry.py` | **Redundant.** Logik in `ingestion.py` integriert. | 🗑️ Löschen |
|
||||||
|
| `app/core/env_vars.py` | **Veraltet.** Ersetzt durch `config.py`. | 🗑️ Löschen |
|
||||||
|
| `app/services/llm_ollama.py` | **Veraltet.** Ersetzt durch `llm_service.py`. | 🗑️ Löschen |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. Lokales Setup (Development)
|
||||||
|
|
||||||
|
**Voraussetzungen:** Python 3.10+, Docker, Ollama.
|
||||||
|
|
||||||
|
**Installation:**
|
||||||
|
```bash
|
||||||
|
# 1. Repo & Venv
|
||||||
|
git clone <repo> mindnet
|
||||||
|
cd mindnet
|
||||||
|
python3 -m venv .venv
|
||||||
|
source .venv/bin/activate
|
||||||
|
|
||||||
|
# 2. Dependencies
|
||||||
|
pip install -r requirements.txt
|
||||||
|
|
||||||
|
# 3. Ollama (Nomic ist Pflicht!)
|
||||||
|
ollama pull phi3:mini
|
||||||
|
ollama pull nomic-embed-text
|
||||||
|
```
|
||||||
|
|
||||||
|
**Konfiguration (`.env`):**
|
||||||
|
```ini
|
||||||
|
QDRANT_URL="http://localhost:6333"
|
||||||
|
MINDNET_OLLAMA_URL="http://localhost:11434"
|
||||||
|
MINDNET_LLM_MODEL="phi3:mini"
|
||||||
|
MINDNET_EMBEDDING_MODEL="nomic-embed-text"
|
||||||
|
COLLECTION_PREFIX="mindnet_dev"
|
||||||
|
VECTOR_DIM=768
|
||||||
|
MINDNET_LLM_BACKGROUND_LIMIT=2
|
||||||
|
MINDNET_API_URL="http://localhost:8002"
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 7. Der Entwicklungs-Zyklus (Workflow)
|
||||||
|
|
||||||
|
### Phase 1: Windows (Code)
|
||||||
|
1. **Basis aktualisieren:** `git checkout main && git pull`.
|
||||||
|
2. **Branch erstellen:** `git checkout -b feature/mein-feature`.
|
||||||
|
3. **Coden & Committen.**
|
||||||
|
4. **Push:** `git push origin feature/mein-feature`.
|
||||||
|
|
||||||
|
### Phase 2: Beelink (Test / Dev)
|
||||||
|
Hier prüfst du, ob dein Code auf Linux läuft.
|
||||||
|
1. **Einloggen:** `ssh user@beelink`.
|
||||||
|
2. **Ordner:** `cd ~/mindnet_dev`.
|
||||||
|
3. **Code holen:** `git fetch && git checkout feature/mein-feature && git pull`.
|
||||||
|
4. **Dependencies:** `pip install -r requirements.txt`.
|
||||||
|
5. **Restart:** `sudo systemctl restart mindnet-dev`.
|
||||||
|
6. **Validierung (Smoke Tests):**
|
||||||
|
* **Last-Test:** Starte `python3 -m scripts.import_markdown ...` im Terminal und chatte gleichzeitig im UI (Port 8502).
|
||||||
|
* **API Check:** `curl -X POST "http://localhost:8002/ingest/analyze" ...`
|
||||||
|
|
||||||
|
### Phase 3: Release & Deployment (Prod)
|
||||||
|
Wenn alles getestet ist:
|
||||||
|
1. **Gitea:** Pull Request erstellen und mergen.
|
||||||
|
2. **Deploy auf Prod (Beelink):**
|
||||||
|
```bash
|
||||||
|
cd ~/mindnet
|
||||||
|
git pull origin main
|
||||||
|
|
||||||
|
# Sicherstellen, dass Prod-Dependencies aktuell sind
|
||||||
|
source .venv/bin/activate
|
||||||
|
pip install -r requirements.txt
|
||||||
|
ollama pull nomic-embed-text # Falls neue Modelle nötig sind
|
||||||
|
|
||||||
|
# Restart
|
||||||
|
sudo systemctl restart mindnet-prod
|
||||||
|
sudo systemctl restart mindnet-ui-prod
|
||||||
|
```
|
||||||
|
3. **Cleanup:** Branch löschen (lokal und remote).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 8. Erweiterungs-Guide: "Teach-the-AI"
|
||||||
|
|
||||||
|
Mindnet lernt nicht durch Training (Fine-Tuning), sondern durch **Konfiguration** und **Vernetzung**.
|
||||||
|
|
||||||
|
### Workflow A: Neuen Typ implementieren (z. B. `type: risk`)
|
||||||
|
1. **Physik (`config/types.yaml`):**
|
||||||
|
```yaml
|
||||||
|
risk:
|
||||||
|
chunk_profile: sliding_short
|
||||||
|
retriever_weight: 0.90 # Sehr wichtig
|
||||||
|
edge_defaults: ["blocks"] # Automatische Kante
|
||||||
|
detection_keywords: ["gefahr", "risiko"]
|
||||||
|
```
|
||||||
|
2. **Strategie (`config/decision_engine.yaml`):**
|
||||||
|
```yaml
|
||||||
|
DECISION:
|
||||||
|
inject_types: ["value", "risk"] # <--- "risk" hinzufügen
|
||||||
|
```
|
||||||
|
*Ergebnis:* Wenn der Intent `DECISION` erkannt wird, sucht das System nun auch aktiv nach Risiken.
|
||||||
|
|
||||||
|
### Workflow B: Graph-Farben ändern
|
||||||
|
1. Öffne `app/frontend/ui_config.py`.
|
||||||
|
2. Bearbeite das Dictionary `GRAPH_COLORS`.
|
||||||
|
|
||||||
|
```python
|
||||||
|
GRAPH_COLORS = {
|
||||||
|
"project": "#FF4B4B",
|
||||||
|
"risk": "#8B0000" # Neu
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 9. Tests & Debugging
|
||||||
|
|
||||||
|
**Unit Tests (Pytest):**
|
||||||
|
```bash
|
||||||
|
pytest tests/test_retriever_basic.py
|
||||||
|
pytest tests/test_chunking.py
|
||||||
|
```
|
||||||
|
|
||||||
|
**Pipeline Tests (Integration):**
|
||||||
|
```bash
|
||||||
|
# JSON-Schema prüfen
|
||||||
|
python3 -m scripts.payload_dryrun --vault ./test_vault
|
||||||
|
|
||||||
|
# Graph-Integrität prüfen
|
||||||
|
python3 -m scripts.edges_full_check
|
||||||
|
```
|
||||||
|
|
||||||
|
**E2E Smoke Tests:**
|
||||||
|
```bash
|
||||||
|
# Decision Engine
|
||||||
|
python tests/test_wp06_decision.py -p 8002 -e DECISION -q "Soll ich X tun?"
|
||||||
|
|
||||||
|
# Feedback
|
||||||
|
python tests/test_feedback_smoke.py --url http://localhost:8002/query
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 10. Troubleshooting & One-Liners
|
||||||
|
|
||||||
|
**DB komplett zurücksetzen (Vorsicht!):**
|
||||||
|
```bash
|
||||||
|
# --yes überspringt die Bestätigung
|
||||||
|
python3 -m scripts.reset_qdrant --mode wipe --prefix "mindnet_dev" --yes
|
||||||
|
```
|
||||||
|
|
||||||
|
**Graphen reparieren (Red Links auflösen):**
|
||||||
|
Nutze dies, wenn Kanten im Graphen ins Leere zeigen (weil die Notiz beim Import noch nicht da war).
|
||||||
|
```bash
|
||||||
|
python3 -m scripts.resolve_unresolved_references --apply
|
||||||
|
```
|
||||||
|
|
||||||
|
**Einen einzelnen File inspizieren (Parser-Sicht):**
|
||||||
|
```bash
|
||||||
|
python3 tests/inspect_one_note.py --file ./vault/MeinFile.md
|
||||||
|
```
|
||||||
|
|
||||||
|
**Live-Logs sehen:**
|
||||||
|
```bash
|
||||||
|
journalctl -u mindnet-dev -f
|
||||||
|
journalctl -u mindnet-ui-dev -f
|
||||||
|
```
|
||||||
|
|
||||||
|
**"UnicodeDecodeError in .env":**
|
||||||
|
* **Ursache:** Umlaute oder Sonderzeichen in der `.env`.
|
||||||
|
* **Lösung:** Datei bereinigen (nur ASCII) und sicherstellen, dass UTF-8 ohne BOM genutzt wird.
|
||||||
|
|
||||||
|
**"Read timed out" im Frontend:**
|
||||||
|
* **Ursache:** Smart Edges brauchen länger als 60s.
|
||||||
|
* **Lösung:** `MINDNET_API_TIMEOUT=300.0` in `.env`.
|
||||||
@@ -0,0 +1,152 @@
|
|||||||
|
---
|
||||||
|
doc_type: developer_guide
|
||||||
|
audience: developer, architect
|
||||||
|
scope: genai, prompting, workflow
|
||||||
|
status: active
|
||||||
|
version: 1.0
|
||||||
|
context: "Leitfaden für die effiziente Softwareentwicklung mit LLMs im Mindnet-Projekt."
|
||||||
|
---
|
||||||
|
|
||||||
|
# GenAI Development Best Practices & Prompt Library
|
||||||
|
|
||||||
|
Dieser Leitfaden definiert Standards für die Zusammenarbeit mit KI-Modellen (ChatGPT, Claude, Gemini) im Rahmen der Mindnet-Entwicklung. Ziel ist es, Halluzinationen zu minimieren, den Kontext effizient zu nutzen und die Dokumentation synchron zum Code zu halten.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. Grundprinzipien
|
||||||
|
|
||||||
|
### 1.1 Context is King (aber teuer)
|
||||||
|
LLMs haben ein begrenztes Kontext-Fenster.
|
||||||
|
* **Don't:** "Hier ist mein ganzer Code, fix den Bug." (Führt zu Vergessen von Details).
|
||||||
|
* **Do:** Nutze die **"Map & Fetch" Strategie**:
|
||||||
|
1. Gib der KI eine Inhaltsübersicht (z.B. `project_scan_report.json` oder `tree`).
|
||||||
|
2. Lass die KI entscheiden, welche Dateien sie für die Aufgabe benötigt.
|
||||||
|
3. Lade nur diese Dateien hoch.
|
||||||
|
|
||||||
|
### 1.2 Trust but Verify (Validierung)
|
||||||
|
* **Code:** Führe generierten Code **immer** lokal aus (Unit Tests oder Smoke Tests), bevor du ihn committest.
|
||||||
|
* **Pfade:** KIs erfinden gerne Pfade (z.B. `app/utils.py`, obwohl es `app/core/utils.py` ist). Prüfe Importe immer gegen die Projektstruktur.
|
||||||
|
* **Security:** Achte darauf, dass keine Secrets (API-Keys) in den Prompts landen und keine Secrets vom LLM halluziniert und hardcodiert werden.
|
||||||
|
|
||||||
|
### 1.3 Atomic Chats
|
||||||
|
Nutze für verschiedene Aufgaben frische Chat-Kontexte.
|
||||||
|
* Ein Chat für "Frontend Refactoring".
|
||||||
|
* Ein neuer Chat für "Documentation Update".
|
||||||
|
* *Grund:* Alte Chats akkumulieren "Rauschen" und führen zu Fehlern.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Prompt Library (Standard-Vorlagen)
|
||||||
|
|
||||||
|
Nutze diese Prompts, um konsistente Ergebnisse zu erzielen.
|
||||||
|
|
||||||
|
### 2.1 Der "Render-Safe" Prompt (System Instruction)
|
||||||
|
**Wann nutzen?** Immer am Anfang eines Chats, wenn die KI Markdown-Dateien oder Code generieren soll.
|
||||||
|
**Zweck:** Verhindert, dass die Antwort im Chat-Fenster abbricht, weil die KI Code-Blöcke falsch verschachtelt.
|
||||||
|
|
||||||
|
```text
|
||||||
|
# SYSTEM-ANWEISUNG: SICHERES MARKDOWN-RENDERING
|
||||||
|
|
||||||
|
Du agierst als technischer Assistent. Deine Aufgabe ist das Erstellen von Markdown-Dateien, die oft selbst Code-Blöcke enthalten.
|
||||||
|
|
||||||
|
**DAS PROBLEM:**
|
||||||
|
Wenn du eine Markdown-Datei generierst, die Code-Blöcke (```) enthält, und diese Ausgabe selbst in einen Code-Block packst, interpretiert das Chat-Interface das erste innere ``` oft fälschlicherweise als das Ende der Ausgabe.
|
||||||
|
|
||||||
|
**DIE REGEL (STRIKT BEFOLGEN):**
|
||||||
|
Um eine ununterbrochene Darstellung zu garantieren, musst du zwingend eine der folgenden Kapselungs-Methoden anwenden:
|
||||||
|
|
||||||
|
### Methode A: Die 4-Backtick-Methode (Bevorzugt)
|
||||||
|
Umschließe den **gesamten** Datei-Inhalt mit **4 Backticks** (````).
|
||||||
|
Dies erlaubt dir, innerhalb der Datei normale 3 Backticks zu verwenden.
|
||||||
|
|
||||||
|
### Methode B: Die 4-Space-Einrückung (Alternative)
|
||||||
|
Wenn du außen 3 Backticks verwendest, darfst du im Inneren **KEINE** Backticks verwenden.
|
||||||
|
Stattdessen müssen alle inneren Code-Beispiele mit **4 Leerzeichen (Spaces)** eingerückt werden.
|
||||||
|
|
||||||
|
**ZUSAMMENFASSUNG:**
|
||||||
|
Generiere niemals verschachtelte 3-Backtick-Blöcke innerhalb von 3-Backtick-Blöcken.
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 2.2 Der "Doku-Update" Prompt (Nach WP-Abschluss)
|
||||||
|
**Wann nutzen?** Wenn ein Feature fertig codiert ist und die Doku (`docs/`) nachgezogen werden muss.
|
||||||
|
**Zweck:** Automatische Identifikation der betroffenen Doku-Dateien ohne manuelles Suchen.
|
||||||
|
|
||||||
|
**Vorbedingung:** Lade `docs/00_General/00_documentation_map.md` und `docs/06_Roadmap/06_active_roadmap.md` hoch.
|
||||||
|
|
||||||
|
```text
|
||||||
|
Du agierst als **Technical Documentation Lead**.
|
||||||
|
|
||||||
|
**Kontext:**
|
||||||
|
Wir haben soeben ein Workpackage (WP) abgeschlossen. Der Code ist implementiert.
|
||||||
|
Jetzt müssen wir die Systemdokumentation (Mindnet v2.6 Modular Docs) aktualisieren.
|
||||||
|
|
||||||
|
**Deine Aufgabe - Phase 1: Identifikation**
|
||||||
|
Analysiere die durchgeführten Änderungen dieses Workpackages (aus dem Chat-Verlauf).
|
||||||
|
Nutze die beiliegende `00_documentation_map.md`, um zu identifizieren, welche Dokumentations-Module betroffen sind.
|
||||||
|
|
||||||
|
**Mapping-Logik:**
|
||||||
|
* Neue Features? -> `00_glossary.md`, `02_Concepts/*`
|
||||||
|
* DB/Payloads geändert? -> `03_tech_data_model.md`
|
||||||
|
* Import/Algorithmus geändert? -> `03_tech_ingestion_pipeline.md`, `03_tech_retrieval_scoring.md`
|
||||||
|
* Neue Configs? -> `03_tech_configuration.md`, `04_admin_operations.md`
|
||||||
|
* UI/UX geändert? -> `01_User_Manual/*`, `03_tech_frontend.md`
|
||||||
|
|
||||||
|
**Output für Phase 1:**
|
||||||
|
Erstelle eine **Liste der betroffenen Dateien** mit Begründung.
|
||||||
|
Fordere mich explizit auf, dir diese Dateien hochzuladen.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
**Deine Aufgabe - Phase 2: Sequenzielle Bearbeitung**
|
||||||
|
Sobald ich die Dateien hochgeladen habe:
|
||||||
|
1. Nimm dir **eine** Datei aus der Liste vor.
|
||||||
|
2. Schreibe den kompletten, aktualisierten Inhalt (Markdown).
|
||||||
|
* *Wichtig:* Halte dich an den bestehenden Stil und die "Render-Safe"-Regel (4 Backticks).
|
||||||
|
3. **Warte** nach der Ausgabe auf mein "OK", bevor du die nächste Datei bearbeitest.
|
||||||
|
|
||||||
|
**Bist du bereit für die Analyse?**
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 2.3 Der "Code Architect" Prompt (Refactoring & Analyse)
|
||||||
|
**Wann nutzen?** Wenn du dich in den Code einarbeiten willst oder Aufräumen musst.
|
||||||
|
**Vorbedingung:** Führe lokal `deep_scan.py` aus und lade `project_scan_report.json` hoch.
|
||||||
|
|
||||||
|
```text
|
||||||
|
Du agierst als **Senior Software Architect**.
|
||||||
|
|
||||||
|
**INPUT:**
|
||||||
|
Ich habe dir die Datei `project_scan_report.json` hochgeladen. Sie enthält eine Liste aller Dateien und ihrer Import-Beziehungen.
|
||||||
|
|
||||||
|
**DIE SOLL-STRUKTUR (4 SÄULEN):**
|
||||||
|
Jede Datei muss einem dieser Zweige zugeordnet werden können:
|
||||||
|
1. **Backend:** via `app/main.py`
|
||||||
|
2. **Frontend:** via `app/frontend/ui.py`
|
||||||
|
3. **Batch/Ops:** via `scripts/` (Produktions-Tools)
|
||||||
|
4. **Tests:** via `tests/`
|
||||||
|
|
||||||
|
**DEINE AUFGABE:**
|
||||||
|
Analysiere das JSON. Identifiziere "Zombies" (Dateien, die nirgends importiert werden und keinen klaren Entrypoint haben).
|
||||||
|
Erstelle eine:
|
||||||
|
1. **Modul-Tabelle** (Wer ruft wen auf?).
|
||||||
|
2. **Lösch-Vorschlagsliste** (Dead Code).
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Workflow für ein Workpackage (WP)
|
||||||
|
|
||||||
|
Ein typisches Mindnet-Feature wird so entwickelt:
|
||||||
|
|
||||||
|
1. **Start:** Neuer Chat. Prompt **2.1 (Render-Safe)** eingeben.
|
||||||
|
2. **Kontext:** `project_scan_report.json` oder relevante Core-Dateien hochladen.
|
||||||
|
3. **Code:** Feature implementieren (Iterativ).
|
||||||
|
4. **Test:** Code lokal validieren.
|
||||||
|
5. **Doku:**
|
||||||
|
* Neuer Chat (optional, für sauberen Kontext).
|
||||||
|
* Prompt **2.1** + Prompt **2.2 (Doku-Update)** eingeben.
|
||||||
|
* Doku aktualisieren lassen.
|
||||||
|
6. **Commit:** Code + Doku zusammen pushen.
|
||||||
@@ -0,0 +1,256 @@
|
|||||||
|
---
|
||||||
|
doc_type: roadmap
|
||||||
|
audience: product_owner, developer
|
||||||
|
status: active
|
||||||
|
version: 2.8.0
|
||||||
|
context: "Aktuelle Planung für kommende Features (ab WP16), Release-Strategie und Historie der abgeschlossenen WPs."
|
||||||
|
---
|
||||||
|
|
||||||
|
# Mindnet Active Roadmap
|
||||||
|
|
||||||
|
**Aktueller Stand:** v2.8.0 (Post-WP20/WP76)
|
||||||
|
**Fokus:** Visualisierung, Exploration & Cloud-Resilienz.
|
||||||
|
|
||||||
|
## 1. Programmstatus
|
||||||
|
|
||||||
|
Wir haben mit der Implementierung des Graph Explorers (WP19), der Smart Edge Allocation (WP15) und der hybriden Cloud-Resilienz (WP20) die Basis für ein intelligentes, robustes System gelegt. Der nächste Schritt (WP19a) vertieft die Analyse, während WP16 die "Eingangs-Intelligenz" erhöht.
|
||||||
|
|
||||||
|
| Phase | Fokus | Status |
|
||||||
|
| :--- | :--- | :--- |
|
||||||
|
| **Phase A** | Fundament & Import | ✅ Fertig |
|
||||||
|
| **Phase B** | Semantik & Graph | ✅ Fertig |
|
||||||
|
| **Phase C** | Persönlichkeit | ✅ Fertig |
|
||||||
|
| **Phase D** | Interaktion & Tools | ✅ Fertig |
|
||||||
|
| **Phase E** | Maintenance & Visualisierung | 🚀 Aktiv |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Historie: Abgeschlossene Workpackages
|
||||||
|
|
||||||
|
Eine Übersicht der implementierten Features zum schnellen Auffinden von Funktionen. Details siehe `99_legacy_workpackages.md`.
|
||||||
|
|
||||||
|
| WP | Titel | Ergebnis / Kern-Feature |
|
||||||
|
| :--- | :--- | :--- |
|
||||||
|
| **WP-01** | Knowledge Design | Definition von `types.yaml` und Note-Typen (Project, Concept, etc.). |
|
||||||
|
| **WP-02** | Chunking Strategy | Implementierung von Sliding-Window und Hash-basierter Änderungserkennung. |
|
||||||
|
| **WP-03** | Import-Pipeline | Asynchroner Importer, der Markdown in Qdrant (Notes/Edges) schreibt. |
|
||||||
|
| **WP-04a**| Retriever Scoring | Hybride Suche: `Score = Semantik + GraphBonus + TypGewicht`. |
|
||||||
|
| **WP-04b**| Explanation Layer | Transparenz: API liefert "Reasons" (Warum wurde das gefunden?). |
|
||||||
|
| **WP-04c**| Feedback Loop | Logging von User-Feedback (JSONL) als Basis für Learning. |
|
||||||
|
| **WP-05** | RAG-Chat | Integration von Ollama (`phi3`) und Context-Enrichment im Prompt. |
|
||||||
|
| **WP-06** | Decision Engine | Hybrid Router unterscheidet Frage (`RAG`) vs. Handlung (`Interview`). |
|
||||||
|
| **WP-07** | Interview-Assistent | One-Shot Extraction: Erzeugt Markdown-Drafts aus User-Input. |
|
||||||
|
| **WP-08** | Interview-Assistent | One-Shot Extraction: Erzeugt Markdown-Drafts aus User-Input. |
|
||||||
|
| **WP-09** | Interview-Assistent | One-Shot Extraction: Erzeugt Markdown-Drafts aus User-Input. |
|
||||||
|
| **WP-10** | Web UI | Streamlit-Frontend als Ersatz für das Terminal. |
|
||||||
|
| **WP-10a**| Draft Editor | GUI-Komponente zum Bearbeiten und Speichern generierter Notizen. |
|
||||||
|
| **WP-11** | Backend Intelligence | `nomic-embed-text` (768d) und Matrix-Logik für Kanten-Typisierung. |
|
||||||
|
| **WP-15** | Smart Edge Allocation | LLM-Filter für Kanten in Chunks + Traffic Control (Semaphore) + Strict Chunking. |
|
||||||
|
| **WP-19** | Graph Visualisierung | **Frontend Modularisierung:** Umbau auf `ui_*.py`.<br>**Graph Engines:** Parallelbetrieb von Cytoscape (COSE) und Agraph.<br>**Tools:** "Single Source of Truth" Editor, Persistenz via URL. |
|
||||||
|
| **WP-20** | **Cloud Hybrid Mode & Resilienz** | **Ergebnis:** Integration von OpenRouter (Mistral 7B) & Gemini 2.5 Lite. Implementierung von WP-76 (Rate-Limit Wait) & Mistral-safe JSON Parsing. |
|
||||||
|
| **WP-21** | Semantic Graph Routing & Canonical Edges | Transformation des Graphen von statischen Verbindungen zu dynamischen, kontextsensitiven Pfaden. Das System soll verstehen, *welche* Art von Verbindung für die aktuelle Frage relevant ist ("Warum?" vs. "Was kommt danach?"). |
|
||||||
|
| **WP-22** | **Content Lifecycle & Registry** | **Ergebnis:** SSOT via `01_edge_vocabulary.md`, Alias-Mapping, Status-Scoring (`stable`/`draft`) und Modularisierung der Scoring-Engine. |
|
||||||
|
|
||||||
|
### 2.1 WP-22 Lessons Learned
|
||||||
|
* **Architektur:** Die Trennung von `retriever.py` und `retriever_scoring.py` war notwendig, um LLM-Context-Limits zu wahren und die Testbarkeit der mathematischen Formeln zu erhöhen.
|
||||||
|
* **Kanten-Validierung:** Die Edge Registry muss beim Start explizit initialisiert werden (Singleton), um "Lazy Loading" Probleme in der API zu vermeiden.
|
||||||
|
|
||||||
|
### 2.2 WP-20 Lessons Learned (Resilienz)
|
||||||
|
* **Quoten-Management:** Die Nutzung von Free-Tier Modellen (Mistral/OpenRouter) erfordert zwingend eine intelligente Rate-Limit-Erkennung (HTTP 429) mit automatisierten Wartezyklen, um Batch-Prozesse stabil zu halten.
|
||||||
|
* **Parser-Robustheit:** Cloud-Modelle betten JSON oft in technische Steuerzeichen (`<s>`, `[OUT]`) ein. Ein robuster Extraktor mit Recovery-Logik ist essentiell zur Vermeidung von Datenverlust.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Offene Workpackages (Planung)
|
||||||
|
|
||||||
|
### WP-08 – Self-Tuning v1/v2 (geplant)
|
||||||
|
Diese Features stehen als nächstes an oder befinden sich in der Umsetzung.
|
||||||
|
**Phase:** B/C
|
||||||
|
**Status:** 🟡 geplant (Nächster Fokus)
|
||||||
|
|
||||||
|
**Ziel:** Aufbau eines Self-Tuning-Mechanismus, der auf Basis von Feedback-Daten (WP-04c) Vorschläge für Retriever- und Policy-Anpassungen macht.
|
||||||
|
|
||||||
|
**Umfang:**
|
||||||
|
- Auswertung der JSONL-Feedback-Daten.
|
||||||
|
- Regel-basierte Anpassungs-Vorschläge für `retriever.yaml` und Typ-Prioritäten.
|
||||||
|
|
||||||
|
**Aufwand / Komplexität:**
|
||||||
|
- Aufwand: Hoch
|
||||||
|
- Komplexität: Hoch
|
||||||
|
|
||||||
|
### WP-09 – Vault-Onboarding & Migration (geplant)
|
||||||
|
|
||||||
|
**Phase:** B
|
||||||
|
**Status:** 🟡 geplant
|
||||||
|
|
||||||
|
**Ziel:** Sicherstellen, dass bestehende und neue Obsidian-Vaults schrittweise in mindnet installiert werden können – ohne Massenumbau.
|
||||||
|
|
||||||
|
**Umfang:**
|
||||||
|
- Tools zur Analyse des Vault-Status.
|
||||||
|
- Empfehlungen für minimale Anpassungen.
|
||||||
|
|
||||||
|
**Aufwand / Komplexität:**
|
||||||
|
- Aufwand: Mittel
|
||||||
|
- Komplexität: Niedrig/Mittel
|
||||||
|
|
||||||
|
### WP-15b – Candidate-Based Edge Validation & Inheritance
|
||||||
|
**Phase:** B/E (Refactoring & Semantic)
|
||||||
|
**Status:** 🚀 Startklar (Ersatz für WP-15 Logik)
|
||||||
|
**Ziel:** Ablösung der fehleranfälligen "Open-End-Extraktion" durch eine KI-gestützte Validierung menschlicher Vorarbeit zur Steigerung von Speed, Integrität und semantischer Tiefe.
|
||||||
|
|
||||||
|
**Herausforderung:**
|
||||||
|
Der bisherige WP-15 Ansatz litt unter Halluzinationen (erfundene Kantentypen), hohem Token-Verbrauch und dem Verlust physikalisch gesetzter Kanten bei der Chunk-Verteilung.
|
||||||
|
|
||||||
|
**Anforderungen & Strategie:**
|
||||||
|
1. **Hard-Link Integrity:** Kanten, die im Markdown-Text eines Chunks stehen, werden zwingend und ohne LLM-Prüfung gesetzt (`provenance: explicit`).
|
||||||
|
2. **Edge Inheritance:** Kanten, die auf Dokument-Ebene (Frontmatter) oder Sektions-Ebene (Heading) definiert sind, werden automatisch an alle zugehörigen Sub-Chunks vererbt, wenn ein semantischer Block aufgrund von Größengrenzen geteilt wurde.
|
||||||
|
3. **Candidate Pool Extraction:** Definition eines "Edge-Pools" pro Dokument. Dieser speist sich aus dem Frontmatter und einer speziellen Sektion (z. B. `### Unzugeordnete Kanten`).
|
||||||
|
4. **Semantic Validation Gate:** Das LLM fungiert als binärer Validator. Es prüft ausschließlich Kanten aus dem Kandidaten-Pool gegen den konkreten Chunk-Inhalt UND eine Zusammenfassung der Ziel-Note (Inhalt, Typ, Kanten-Typ).
|
||||||
|
5. **Registry Enforcement:** Strikte Blockade von Halluzinationen. Nur Kanten, die im Pool definiert UND im `edge_vocabulary.md` vorhanden sind, werden zugelassen.
|
||||||
|
|
||||||
|
**Lösungsskizze:**
|
||||||
|
* **Parser-Update:** `extract_candidate_pool` zur Identifikation aller im Dokument beabsichtigten Links.
|
||||||
|
* **Chunker-Update:** Implementierung einer `propagate_edges`-Logik für "by_heading" und "sliding_window" Strategien.
|
||||||
|
* **Ingestion-Update:** Umstellung von `_perform_smart_edge_allocation` auf einen binären Validierungs-Prompt (VALID/INVALID).
|
||||||
|
|
||||||
|
### WP-19a – Graph Intelligence & Discovery (Sprint-Fokus)
|
||||||
|
**Status:** 🚀 Startklar
|
||||||
|
**Ziel:** Vom "Anschauen" zum "Verstehen". Deep-Dive Werkzeuge für den Graphen.
|
||||||
|
* **Discovery Screen:** Neuer Tab für semantische Suche ("Finde Notizen über Vaterschaft") und Wildcard-Filter.
|
||||||
|
* **Filter-Logik:** "Zeige nur Wege, die zu `type:decision` führen".
|
||||||
|
* **Chunk Inspection:** Umschaltbare Granularität (Notiz vs. Chunk) zur Validierung des Smart Chunkers.
|
||||||
|
|
||||||
|
### WP-14 – Review / Refactoring / Dokumentation
|
||||||
|
**Status:** 🟡 Laufend (Phase E)
|
||||||
|
**Ziel:** Technische Schulden abbauen, die durch schnelle Feature-Entwicklung (WP15/WP19) entstanden sind.
|
||||||
|
* **Refactoring `chunker.py`:** Die Datei ist monolithisch geworden (Parsing, Strategien, LLM-Orchestrierung).
|
||||||
|
* *Lösung:* Aufteilung in ein Package `app/core/chunking/` mit Modulen (`strategies.py`, `orchestration.py`, `utils.py`).
|
||||||
|
* **Dokumentation:** Kontinuierliche Synchronisation von Code und Docs (v2.8 Stand).
|
||||||
|
|
||||||
|
### WP-16 – Auto-Discovery & Intelligent Ingestion
|
||||||
|
**Status:** 🟡 Geplant
|
||||||
|
**Ziel:** Das System soll "dumme" Textdateien beim Import automatisch analysieren, strukturieren und anreichern, bevor sie gespeichert werden.
|
||||||
|
**Kern-Features:**
|
||||||
|
1. **Smart Link Enricher:** Automatisches Erkennen von fehlenden Kanten in Texten ohne explizite Wikilinks. Ein "Enricher" scannt Text vor dem Import, findet Keywords (z.B. "Mindnet") und schlägt Links vor (`[[Mindnet]]`).
|
||||||
|
2. **Structure Analyzer (Auto-Strategy):**
|
||||||
|
* *Problem:* Manuelle Zuweisung von `chunking_profile` in `types.yaml` ist starr.
|
||||||
|
* *Lösung:* Vorschalten einer Analysestufe im Importer (`chunker.py`), die die Text-Topologie prüft und die Strategie wählt.
|
||||||
|
* *Metrik 1 (Heading Density):* Verhältnis `Anzahl Überschriften / Wortanzahl`. Hohe Dichte (> 1/200) -> Indikator für `structured_smart_edges`. Niedrige Dichte -> `sliding_smart_edges`.
|
||||||
|
* *Metrik 2 (Variance):* Regelmäßigkeit der Abstände zwischen Headings.
|
||||||
|
3. **Context-Aware Hierarchy Merging:**
|
||||||
|
* *Problem:* Leere Zwischenüberschriften (z.B. "Tier 2") gingen früher als bedeutungslose Chunks verloren oder wurden isoliert.
|
||||||
|
* *Lösung:* Generalisierung der Logik aus WP-15, die leere Eltern-Elemente automatisch mit dem ersten Kind-Element verschmilzt ("Tier 2 + MP1"), um den Kontext für das Embedding zu wahren.
|
||||||
|
|
||||||
|
### WP-17 – Conversational Memory (Gedächtnis)
|
||||||
|
**Status:** 🟡 Geplant
|
||||||
|
**Ziel:** Echte Dialoge statt Request-Response.
|
||||||
|
* **Tech:** Erweiterung des `ChatRequest` DTO um `history`.
|
||||||
|
* **Logik:** Token-Management (Context Window Balancing zwischen RAG-Doks und Chat-Verlauf).
|
||||||
|
|
||||||
|
### WP-18 – Graph Health & Maintenance
|
||||||
|
**Status:** 🟡 Geplant (Prio 2)
|
||||||
|
**Ziel:** Konsistenzprüfung ("Garbage Collection").
|
||||||
|
* **Feature:** Cronjob `check_graph_integrity.py`.
|
||||||
|
* **Funktion:** Findet "Dangling Edges" (Links auf gelöschte Notizen) und repariert/löscht sie.
|
||||||
|
|
||||||
|
### WP-13 – MCP-Integration & Agenten-Layer
|
||||||
|
**Status:** 🟡 Geplant
|
||||||
|
**Ziel:** mindnet als MCP-Server bereitstellen, damit Agenten (Claude Desktop, OpenAI) standardisierte Tools nutzen können.
|
||||||
|
* **Umfang:** MCP-Server mit Tools (`mindnet_query`, `mindnet_explain`, etc.).
|
||||||
|
|
||||||
|
### WP-21 – Semantic Graph Routing & Canonical Edges
|
||||||
|
**Status:** 🟡 Geplant
|
||||||
|
**Ziel:** Transformation des Graphen von statischen Verbindungen zu dynamischen, kontextsensitiven Pfaden. Das System soll verstehen, *welche* Art von Verbindung für die aktuelle Frage relevant ist ("Warum?" vs. "Was kommt danach?").
|
||||||
|
**Problem:**
|
||||||
|
1. **Statische Gewichte:** Aktuell ist `caused_by` immer gleich wichtig (z.B. 1.2), egal ob der User nach Ursachen oder Definitionen fragt.
|
||||||
|
2. **Vokabular-Zwang:** Der Nutzer muss exakte System-Begriffe (`caused_by`) verwenden. Natürliche Synonyme (`führt_zu`, `ausgelöst_durch`) werden als unbekannte Kanten ignoriert oder nicht speziell gewichtet.
|
||||||
|
|
||||||
|
**Lösungsansätze & Kern-Features:**
|
||||||
|
1. **Canonical Edge Mapping (Middleware):**
|
||||||
|
* Einführung einer Mapping-Schicht (z.B. in `edges.yaml`).
|
||||||
|
* *Funktion:* Normalisiert User-Vokabular (`leads_to`, `triggers`, `starts`) automatisch auf System-Typen (`caused_by`).
|
||||||
|
* *Benefit:* Maximale Schreibfreiheit für den Nutzer bei gleichzeitiger System-Konsistenz.
|
||||||
|
2. **Dynamic Intent Boosting (Query-Time):**
|
||||||
|
* Erweiterung der `Decision Engine`.
|
||||||
|
* *Funktion:* Der Router erkennt den Intent der Frage (z.B. `EXPLANATION` für "Warum-Fragen") und injiziert temporäre `edge_weights` in den Retriever.
|
||||||
|
* *Beispiel:* Bei "Warum ist das passiert?" wird `caused_by` von 1.2 auf 2.5 geboostet, während `related_to` auf 0.1 sinkt.
|
||||||
|
3. **Graph Reasoning:**
|
||||||
|
* Der Retriever priorisiert Pfade, die dem semantischen Muster der Frage entsprechen, nicht nur dem Text-Match.
|
||||||
|
|
||||||
|
### WP-22 – Content Lifecycle & Meta-Configuration
|
||||||
|
**Status:** ✅ Fertig (v2.7.0)
|
||||||
|
**Ziel:** Professionalisierung der Datenhaltung durch Einführung eines Lebenszyklus und "Docs-as-Code" Konfiguration.
|
||||||
|
**Lösungsansätze:**
|
||||||
|
1. **Status-Logik (Frontmatter):** `stable` vs. `draft` Scoring Modifier.
|
||||||
|
2. **Single Source of Truth (SSOT):** Die Registry nutzt `01_edge_vocabulary.md` als führende Konfiguration.
|
||||||
|
3. **Self-Learning Loop:** Protokollierung unbekannter Kanten in `unknown_edges.jsonl`.
|
||||||
|
|
||||||
|
## 23: Agentic Multi-Stream Reasoning (Mindnet 2025)
|
||||||
|
|
||||||
|
### 1. Zielsetzung & Problemstellung
|
||||||
|
Das bisherige System basiert auf einem globalen Scoring-Modell, bei dem Notizen unterschiedlicher Typen (z. B. `insight` vs. `belief`) in einem einzigen Retrieval-Topf konkurrieren. Dies führt dazu, dass leiser gewichtete, aber fundamentale Identitätsmerkmale oft durch hochgewichtete aktuelle Erkenntnisse verdrängt werden. Ziel dieses Pakets ist die Einführung einer parallelen **Stream-Architektur**, um die Vielschichtigkeit menschlicher Entscheidungsprozesse (Werte + Erfahrung + Absicht) im LLM-Kontext zu garantieren.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 2. Funktionsbeschreibung: Die Streams
|
||||||
|
Die Daten aus der `types.yaml` werden in drei logische Verarbeitungseinheiten unterteilt:
|
||||||
|
|
||||||
|
#### A. Identity Stream (Die Wahrheitsebene)
|
||||||
|
* **Inhalt:** `value`, `belief`, `trait`, `principle`, `need`, `boundary`, `bias`.
|
||||||
|
* **Zweck:** Definition des moralischen Kompasses, der psychologischen Grundbedürfnisse und kognitiven Muster.
|
||||||
|
* **Wirkung:** Liefert das "Warum" hinter jeder Handlung.
|
||||||
|
|
||||||
|
#### B. History Stream (Die Evidenzebene)
|
||||||
|
* **Inhalt:** `experience`, `event`, `source`, `journal`, `person`.
|
||||||
|
* **Zweck:** Bereitstellung empirischer Belege aus der Vergangenheit und sozialer Kontexte.
|
||||||
|
* **Wirkung:** Verankert die Antwort in real erlebten Mustern und Fakten.
|
||||||
|
|
||||||
|
#### C. Action Stream (Die Dynamikebene)
|
||||||
|
* **Inhalt:** `project`, `decision`, `goal`, `task`, `risk`, `motivation`, `habit`, `state`.
|
||||||
|
* **Zweck:** Analyse der aktuellen Richtung, geplanter Vorhaben und des gegenwärtigen Zustands.
|
||||||
|
* **Wirkung:** Liefert den Kontext für die Umsetzung und zukünftige Ziele.
|
||||||
|
|
||||||
|
|
||||||
|
### 3. Technische Wirkungsweise (Solution Sketch)
|
||||||
|
|
||||||
|
#### Schritt 1: Query-Decomposition
|
||||||
|
Ein initialer Klassifizierungs-Agent analysiert die Nutzeranfrage und bestimmt, welcher Stream primär angesprochen werden muss (z. B. "Wie soll ich mich entscheiden?" boostet den Identity Stream).
|
||||||
|
|
||||||
|
#### Schritt 2: Parallel Stream Retrieval
|
||||||
|
Anstelle einer Suche werden drei unabhängige Vektor-Suchen mit Typ-Filtern durchgeführt:
|
||||||
|
* **Search_A (Identity):** Top-5 Ergebnisse aus Identitäts-Notizen.
|
||||||
|
* **Search_B (History):** Top-5 Ergebnisse aus biografischen/externen Notizen.
|
||||||
|
* **Search_C (Action):** Top-5 Ergebnisse aus operativen/strategischen Notizen.
|
||||||
|
|
||||||
|
#### Schritt 3: Agentic Synthesis (The Reasoning)
|
||||||
|
Ein Synthese-Agent (LLM) erhält die aggregierten Ergebnisse in getrennten Sektionen. Die Anweisung lautet:
|
||||||
|
1. **Prüfung:** Steht das aktuelle Vorhaben (Action) im Einklang mit den Werten (Identity)?
|
||||||
|
2. **Abgleich:** Welche vergangenen Erfahrungen (History) stützen oder widersprechen diesem Weg?
|
||||||
|
3. **Korrektur:** Identifiziere mögliche Biases oder Grenzüberschreitungen (Boundary).
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
### 4. Erwartete Ergebnisse
|
||||||
|
* **Höhere Resonanz:** Antworten wirken authentischer, da sie explizit auf das Wertesystem des Nutzers Bezug nehmen.
|
||||||
|
* **Widerspruchs-Erkennung:** Das System kann den Nutzer aktiv warnen, wenn ein Projekt gegen seine `principles` oder `needs` verstößt.
|
||||||
|
* **Robustes Retrieval:** Wichtige Identitäts-Informationen gehen nicht mehr im "Rauschen" von hunderten Journal-Einträgen verloren.
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. Abhängigkeiten & Release-Plan
|
||||||
|
|
||||||
|
```mermaid
|
||||||
|
graph TD
|
||||||
|
WP19(Graph Viz) --> WP19a(Discovery)
|
||||||
|
WP19a --> WP17(Memory)
|
||||||
|
WP15(Smart Edges) --> WP16(Auto-Discovery)
|
||||||
|
WP15 --> WP14(Refactoring)
|
||||||
|
WP03(Import) --> WP18(Health Check)
|
||||||
|
WP03 --> WP13(MCP)
|
||||||
|
WP04 --> WP13(MCP)
|
||||||
|
WP06(Decision Engine) --> WP21(Semantic Routing)
|
||||||
|
WP03(Import Pipeline) --> WP21
|
||||||
|
WP21 --> WP22(Lifecycle & Registry)
|
||||||
|
WP22 --> WP14
|
||||||
|
WP15(Smart Edges) --> WP21
|
||||||
|
WP20(Cloud Hybrid) --> WP15b
|
||||||
|
```
|
||||||
@@ -0,0 +1,318 @@
|
|||||||
|
---
|
||||||
|
doc_type: operations
|
||||||
|
audience: developer, admin
|
||||||
|
status: active
|
||||||
|
version: 1.0
|
||||||
|
context: "Sammlung von Initialisierungs-Prompts für neue Chat-Sessions. Jeder Prompt entspricht dem Projektauftrag für ein spezifisches Workpackage."
|
||||||
|
---
|
||||||
|
|
||||||
|
# Mindnet WP-Handover Prompts
|
||||||
|
|
||||||
|
**Verwendung:**
|
||||||
|
Kopiere den entsprechenden Block in ein **neues** Chat-Fenster, um die KI-Instanz exakt auf den Kontext und die Ziele des Workpackages einzustellen.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## WP-19a: Graph Intelligence & Discovery
|
||||||
|
|
||||||
|
**Status:** 🚀 Startklar
|
||||||
|
**Fokus:** Frontend-Erweiterung, Semantische Suche, Filterung.
|
||||||
|
|
||||||
|
```text
|
||||||
|
Du bist der Lead Developer für "Mindnet", ein lokales RAG-System (Python/FastAPI/Streamlit/Qdrant).
|
||||||
|
Wir starten jetzt **WP-19a: Graph Intelligence & Discovery**.
|
||||||
|
|
||||||
|
**Status Quo (v2.6.0):**
|
||||||
|
- Backend: Async API mit `/query` (Hybrid Search) und `/chat`.
|
||||||
|
- Frontend: Modularisiertes Streamlit (`ui.py`, `ui_graph.py`).
|
||||||
|
- Daten: Qdrant Indizes (`notes`, `chunks`, `edges`) sind gefüllt.
|
||||||
|
|
||||||
|
**Dein Auftrag (WP-19a):**
|
||||||
|
Implementiere "Deep Dive" Werkzeuge im Frontend, um den Graphen nicht nur zu sehen, sondern zu verstehen.
|
||||||
|
1. **Neues UI-Modul:** Erstelle `app/frontend/ui_discovery.py`.
|
||||||
|
2. **Discovery Tab:** Implementiere eine Oberfläche für:
|
||||||
|
- Semantische Suche (ohne Chat-Modus).
|
||||||
|
- Wildcard-Filter ("Zeige alle Notes vom Typ 'decision'").
|
||||||
|
- Pfad-Analyse ("Wie sind Note A und Note B verbunden?").
|
||||||
|
3. **Chunk Inspection:** Baue einen Toggle, der im Graph-Explorer zwischen "Note-View" (grob) und "Chunk-View" (fein) umschaltet.
|
||||||
|
|
||||||
|
**Regeln:**
|
||||||
|
- Nutze `st.session_state` für Persistenz zwischen Re-Renders.
|
||||||
|
- Halte die Business-Logik im Backend (ggf. neue Endpoints in `app/routers/query.py`).
|
||||||
|
- Gib vollständigen, lauffähigen Code aus.
|
||||||
|
|
||||||
|
Bitte bestätige die Übernahme und skizziere die Architektur für `ui_discovery.py`.
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## WP-13: MCP Integration & Agenten-Layer
|
||||||
|
|
||||||
|
**Status:** 🟡 Geplant
|
||||||
|
**Fokus:** Schnittstelle für externe Agenten (Claude Desktop).
|
||||||
|
|
||||||
|
```text
|
||||||
|
Du bist der Lead Developer für "Mindnet" (Python/FastAPI/Qdrant).
|
||||||
|
Wir starten jetzt **WP-13: MCP Integration**.
|
||||||
|
|
||||||
|
**Status Quo (v2.6.0):**
|
||||||
|
- Das System läuft stabil asynchron.
|
||||||
|
- `types.yaml` steuert die Logik.
|
||||||
|
- Es existieren Services für Retrieval und Graph-Access.
|
||||||
|
|
||||||
|
**Dein Auftrag (WP-13):**
|
||||||
|
Implementiere einen MCP-Server (Model Context Protocol), der Mindnet als "Tool" für Claude Desktop verfügbar macht.
|
||||||
|
1. **Server:** Erstelle `app/mcp_server.py` basierend auf dem `mcp`-SDK.
|
||||||
|
2. **Tools:** Implementiere folgende Tools:
|
||||||
|
- `search_notes(query)`: Nutzt unseren Hybriden Retriever.
|
||||||
|
- `read_note(id)`: Liest Fulltext einer Notiz.
|
||||||
|
- `list_connections(id)`: Zeigt Edges an.
|
||||||
|
- `Notes(content)`: (Optional) Nutzt die Ingestion-Pipeline.
|
||||||
|
3. **Integration:** Nutze die bestehenden Services (`Retriever`, `QdrantClient`) wieder – kein redundanter Code!
|
||||||
|
4. **Async:** Achte auf Kompatibilität zwischen MCP und unserem `asyncio` Core.
|
||||||
|
|
||||||
|
**Regeln:**
|
||||||
|
- Halte dich strikt an die Architektur in `mindnet_technical_architecture.md`.
|
||||||
|
- Aktualisiere den `admin_guide.md` mit Anweisungen zur Einbindung in Claude Desktop config.
|
||||||
|
|
||||||
|
Bitte bestätige die Übernahme und zeige einen ersten Entwurf für `app/mcp_server.py`.
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## WP-14: Review & Refactoring
|
||||||
|
|
||||||
|
**Status:** 🟡 Laufend
|
||||||
|
**Fokus:** Code-Qualität, Modularisierung, Technische Schulden.
|
||||||
|
|
||||||
|
```text
|
||||||
|
Du bist der Software-Architekt für "Mindnet".
|
||||||
|
Wir starten **WP-14: Review & Refactoring**.
|
||||||
|
|
||||||
|
**Status Quo (v2.6.0):**
|
||||||
|
- Das System ist funktional mächtig, aber einige Dateien (z.B. `chunker.py`) sind monolithisch geworden.
|
||||||
|
- Dokumentation und Code müssen synchronisiert werden.
|
||||||
|
|
||||||
|
**Dein Auftrag (WP-14):**
|
||||||
|
1. **Refactoring `chunker.py`:** Zerlege den Monolithen in ein sauberes Package `app/core/chunking/`.
|
||||||
|
- `strategies.py`: Enthält `sliding_window` und `by_heading` Logik.
|
||||||
|
- `orchestration.py`: Enthält `assemble_chunks` und Smart-Edge-Flow.
|
||||||
|
- `utils.py`: Helper.
|
||||||
|
2. **Cleanup:** Entferne veraltete / auskommentierte Code-Blöcke im gesamten Projekt.
|
||||||
|
3. **Doc-Sync:** Prüfe, ob alle Parameter in `types.yaml` auch im Code verwendet werden (Dead Config Detection).
|
||||||
|
|
||||||
|
**Regeln:**
|
||||||
|
- Funktionalität darf sich nicht ändern (Regression Tests!).
|
||||||
|
- Imports in `scripts/import_markdown.py` müssen angepasst werden.
|
||||||
|
|
||||||
|
Bitte bestätige und beginne mit der Strukturierung des neuen `chunking` Packages.
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## WP-16: Auto-Discovery & Intelligent Ingestion
|
||||||
|
|
||||||
|
**Status:** 🟡 Geplant
|
||||||
|
**Fokus:** Automatisierung beim Import, "Smarter Text".
|
||||||
|
|
||||||
|
```text
|
||||||
|
Du bist der Lead Developer für "Mindnet".
|
||||||
|
Wir starten **WP-16: Auto-Discovery & Intelligent Ingestion**.
|
||||||
|
|
||||||
|
**Status Quo (v2.6.0):**
|
||||||
|
- Import verlässt sich auf explizite Wikilinks und manuelle Profil-Wahl in `types.yaml`.
|
||||||
|
- Smart Edges filtern nur vorhandene Links.
|
||||||
|
|
||||||
|
**Dein Auftrag (WP-16):**
|
||||||
|
Mache den Import intelligenter, bevor Daten gespeichert werden.
|
||||||
|
1. **Structure Analyzer:** Erweitere den Chunker um eine Vor-Analyse.
|
||||||
|
- Berechne "Heading Density" (Überschriften pro Wort).
|
||||||
|
- Wähle automatisch `structured` (hohe Dichte) oder `sliding` (niedrige Dichte), wenn `profile: auto` gesetzt ist.
|
||||||
|
2. **Smart Link Enricher:** Implementiere einen Service, der im Text nach Keywords sucht, die als Titel anderer Notizen existieren (Exact Match & Fuzzy Match).
|
||||||
|
- Schlage diese als `suggested_edges` vor.
|
||||||
|
3. **Hierarchy Merging:** Generalisiere die Logik, dass leere Überschriften ("Tier 2") automatisch mit dem folgenden Inhalt verschmelzen.
|
||||||
|
|
||||||
|
**Regeln:**
|
||||||
|
- Performance beachten! Der Import darf nicht ewig dauern.
|
||||||
|
- Änderungen am Content nur im RAM, Original-Datei bleibt unangetastet (außer User will Writeback).
|
||||||
|
|
||||||
|
Bitte bestätige und skizziere den Algorithmus für den Structure Analyzer.
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## WP-17: Conversational Memory
|
||||||
|
|
||||||
|
**Status:** 🟡 Geplant
|
||||||
|
**Fokus:** Dialog-Qualität, Kontext.
|
||||||
|
|
||||||
|
```text
|
||||||
|
Du bist der AI-Engineer für "Mindnet".
|
||||||
|
Wir starten **WP-17: Conversational Memory**.
|
||||||
|
|
||||||
|
**Status Quo (v2.6.0):**
|
||||||
|
- Chat ist "stateless". Jede Anfrage wird isoliert betrachtet.
|
||||||
|
- RAG funktioniert, aber Rückfragen ("Was meinst du damit?") scheitern.
|
||||||
|
|
||||||
|
**Dein Auftrag (WP-17):**
|
||||||
|
Implementiere ein Kurzzeitgedächtnis für den Chat.
|
||||||
|
1. **API Update:** Erweitere `ChatRequest` (DTO) um ein Feld `history: List[Message]`.
|
||||||
|
2. **Frontend:** Passe `ui.py` an, um die letzten N Nachrichten mitzusenden.
|
||||||
|
3. **Token Management:** Implementiere eine Logik im `LLMService`, die das Kontext-Fenster (z.B. 4k Token) balanciert:
|
||||||
|
- System Prompt (fest)
|
||||||
|
- RAG Chunks (hoch gewichtet)
|
||||||
|
- Chat History (auffüllen bis Limit)
|
||||||
|
4. **Prompting:** Integriere `{chat_history}` in das Template in `prompts.yaml`.
|
||||||
|
|
||||||
|
**Regeln:**
|
||||||
|
- Nutze effizientes Truncation (älteste Nachrichten zuerst weg).
|
||||||
|
- History darf RAG-Wissen nicht verdrängen (Reserviere min. 60% für RAG).
|
||||||
|
|
||||||
|
Bitte bestätige und zeige das aktualisierte Pydantic-Modell für `ChatRequest`.
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## WP-18: Graph Health & Maintenance
|
||||||
|
|
||||||
|
**Status:** 🟡 Geplant
|
||||||
|
**Fokus:** Datenintegrität, Garbage Collection.
|
||||||
|
|
||||||
|
```text
|
||||||
|
Du bist der DevOps Engineer für "Mindnet".
|
||||||
|
Wir starten **WP-18: Graph Health & Maintenance**.
|
||||||
|
|
||||||
|
**Status Quo (v2.6.0):**
|
||||||
|
- Import ist asynchron. Bei Timeouts kann der DB-Stand vom File-System abweichen (Hash-Mismatch).
|
||||||
|
- Gelöschte Notizen hinterlassen "Dangling Edges".
|
||||||
|
|
||||||
|
**Dein Auftrag (WP-18):**
|
||||||
|
1. **Transactional Ingestion:** Implementiere einen "Two-Phase Commit" für den Import.
|
||||||
|
- Der File-Hash für die Änderungserkennung darf erst aktualisiert werden, wenn der Qdrant-Upsert *bestätigt* erfolgreich war.
|
||||||
|
2. **Integrity Script:** Erstelle `scripts/check_graph_integrity.py`.
|
||||||
|
- Prüfe: Gibt es Edges, deren `target_id` nicht in `notes` existiert?
|
||||||
|
- Aktion: Report oder Auto-Delete.
|
||||||
|
3. **Resolve References:** Erweitere das Skript um Logik, die "Unresolved Targets" (Text-Links) nachträglich in echte UUID-Links wandelt, wenn die Ziel-Notiz später importiert wurde.
|
||||||
|
|
||||||
|
**Regeln:**
|
||||||
|
- Sicherheit geht vor Geschwindigkeit.
|
||||||
|
- Keine Datenlöschung ohne Log-Eintrag.
|
||||||
|
|
||||||
|
Bitte bestätige und skizziere die Logik für den Transactional Hash Update.
|
||||||
|
```
|
||||||
|
|
||||||
|
## WP-21: Semantic Graph Routing
|
||||||
|
|
||||||
|
**Status:** 🟡 Geplant
|
||||||
|
**Fokus:** Graph-Logik, Retrieval-Präzision, User-Experience.
|
||||||
|
|
||||||
|
```text
|
||||||
|
Du bist der Lead Architect für "Mindnet" (v2.7.0).
|
||||||
|
Wir starten **WP-21: Semantic Graph Routing**.
|
||||||
|
|
||||||
|
**Status Quo:**
|
||||||
|
- Edge-Gewichte sind statisch in `retriever.yaml` definiert.
|
||||||
|
- User müssen exakte Edge-Typen (`caused_by`) nutzen; Synonyme werden nicht erkannt.
|
||||||
|
- Der `HybridRouter` (WP-06) erkennt Intents, nutzt diese aber nur für Note-Typen (`inject_types`), nicht für Kanten.
|
||||||
|
|
||||||
|
**Dein Auftrag (WP-21):**
|
||||||
|
Implementiere eine semantische Steuerung für den Graphen, die (A) Schreibfreiheit erlaubt und (B) die Suche kontextabhängig macht.
|
||||||
|
|
||||||
|
**Technische Anforderungen:**
|
||||||
|
|
||||||
|
1. **Canonical Edge Mapping (Ingestion-Layer):**
|
||||||
|
- Erstelle eine neue Config `config/edge_mappings.yaml` (oder erweitere `types.yaml`).
|
||||||
|
- Definiere Mappings: `User-Synonym` -> `System-Canonical` (z.B. `["führt_zu", "resultat"]` -> `caused_by`).
|
||||||
|
- Erweitere `import_markdown.py` / `Chunker`: Mappe beim Einlesen alle Inline/Callout-Kanten auf den Canonical-Typ, *bevor* sie in Qdrant gespeichert werden. (Speichere das Original ggf. als Metadatum).
|
||||||
|
|
||||||
|
2. **Dynamic Boosting (Retrieval-Layer):**
|
||||||
|
- Erweitere die `DecisionEngine` (`app/services/decision_engine.py` und YAML).
|
||||||
|
- Füge `boost_edges` zu den Strategien hinzu (z.B. `strategy: EXPLANATION` -> `boost: {caused_by: 2.0}`).
|
||||||
|
- Passe den `Retriever` an, um diese dynamischen Gewichte im Query-Moment mit den statischen Config-Werten zu verrechnen (Multiplikator).
|
||||||
|
|
||||||
|
**Zielbild:**
|
||||||
|
- User schreibt: `[[rel:wegen Systemfehler]]`.
|
||||||
|
- System speichert: `caused_by` -> `Systemfehler`.
|
||||||
|
- User fragt: "Warum Absturz?".
|
||||||
|
- System erkennt "Warum" -> Boostet `caused_by` -> Findet die Notiz präzise.
|
||||||
|
|
||||||
|
**Regeln:**
|
||||||
|
- Abwärtskompatibilität wahren (alte Kanten müssen weiter funktionieren).
|
||||||
|
- Performance: Das Mapping muss O(1) sein (Hashmap Lookup), kein LLM-Call pro Kante!
|
||||||
|
|
||||||
|
Bitte bestätige die Übernahme, erstelle die `edge_mappings.yaml` Struktur und skizziere die Anpassung im `Retriever`.
|
||||||
|
---
|
||||||
|
|
||||||
|
### Warum diese Lösungsansätze?
|
||||||
|
|
||||||
|
1. **Warum Mapping beim Import (Ingestion) und nicht bei der Suche?**
|
||||||
|
* **Performance:** Es ist viel effizienter, die Daten *einmal* beim Schreiben zu säubern ("Canonical Form"), als bei *jeder* Suche tausende Synonyme abzufragen.
|
||||||
|
* **Konsistenz:** Der Graph in Qdrant bleibt sauber. `caused_by` ist immer `caused_by`, egal ob der User `wegen`, `durch` oder `ursache` geschrieben hat.
|
||||||
|
|
||||||
|
2. **Warum Boosting über die Decision Engine?**
|
||||||
|
* Wir haben den `HybridRouter` (aus WP-06) schon. Er "versteht" bereits, was der User will (`DECISION` vs `EMPATHY`).
|
||||||
|
* Es ist der logisch perfekte Ort, um zu sagen: "Wenn der User im Analyse-Modus ist, sind Fakten-Kanten wichtiger als Gefühls-Kanten."
|
||||||
|
|
||||||
|
Damit hast du das perfekte Paket für den nächsten Entwicklungsschritt geschnürt!
|
||||||
|
|
||||||
|
## WP-22: Content Lifecycle & Meta-Config
|
||||||
|
|
||||||
|
**Status:** 🚀 Startklar
|
||||||
|
**Fokus:** Ingestion-Filter, Scoring-Logik, Registry-Architektur.
|
||||||
|
|
||||||
|
```text
|
||||||
|
Du bist der Lead Architect für "Mindnet" (v2.7).
|
||||||
|
Wir starten ein umfassendes Architektur-Paket: **WP-22: Graph Intelligence & Lifecycle**.
|
||||||
|
|
||||||
|
**Kontext:**
|
||||||
|
Wir professionalisieren die Datenhaltung ("Docs as Code") und machen die Suche kontextsensitiv.
|
||||||
|
Wir haben eine Markdown-Datei (`01_edge_vocabulary.md`), die als Single-Source-of-Truth für Kanten-Typen dient.
|
||||||
|
|
||||||
|
**Dein Auftrag:**
|
||||||
|
Implementiere (A) den Content-Lifecycle, (B) die Edge-Registry und (C) das Semantic Routing.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Teil A: Content Lifecycle (Ingestion Logic)
|
||||||
|
Steuerung über Frontmatter `status`:
|
||||||
|
1. **System-Dateien (No-Index):**
|
||||||
|
* Wenn `status` in `['system', 'template']`: **Hard Skip**. Datei wird nicht vektorisiert.
|
||||||
|
2. **Wissens-Status (Scoring):**
|
||||||
|
* Wenn `status` in `['draft', 'active', 'stable']`: Status wird im Payload gespeichert.
|
||||||
|
* **ToDo:** Erweitere `scoring.py`, damit `stable` Notizen einen Bonus erhalten (`x 1.2`), `drafts` einen Malus (`x 0.5`).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Teil B: Central Edge Registry & Validation
|
||||||
|
1. **Registry Klasse:**
|
||||||
|
* Erstelle `EdgeRegistry` (Singleton).
|
||||||
|
* Liest beim Start `01_User_Manual/01_edge_vocabulary.md` (Regex parsing der Tabelle).
|
||||||
|
* Stellt `canonical_types` und `aliases` bereit.
|
||||||
|
2. **Rückwärtslogik (Learning):**
|
||||||
|
* Prüfe beim Import jede Kante gegen die Registry.
|
||||||
|
* Unbekannte Typen werden **nicht** verworfen, sondern in `data/logs/unknown_edges.jsonl` geloggt (für späteres Review).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Teil C: Semantic Graph Routing (Dynamic Boosting)
|
||||||
|
**Ziel:** Die Bedeutung einer Kante soll sich je nach Frage-Typ ändern ("Warum" vs. "Wie").
|
||||||
|
|
||||||
|
**Architektur-Vorgabe (WICHTIG):**
|
||||||
|
Die Gewichtung findet **Pre-Retrieval** (im Scoring-Algorithmus) statt, **nicht** im LLM-Prompt.
|
||||||
|
|
||||||
|
1. **Decision Engine (`decision_engine.yaml`):**
|
||||||
|
* Füge `boost_edges` zu Strategien hinzu.
|
||||||
|
* *Beispiel:* `EXPLANATION` (Warum-Fragen) -> Boost `caused_by: 2.5`, `derived_from: 2.0`.
|
||||||
|
* *Beispiel:* `ACTION` (Wie-Fragen) -> Boost `next: 3.0`, `depends_on: 2.0`.
|
||||||
|
2. **Scoring-Logik (`scoring.py`):**
|
||||||
|
* Der `Retriever` erhält vom Router die `boost_edges` Map.
|
||||||
|
* Berechne Score: `BaseScore * (1 + ConfigWeight + DynamicBoost)`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
**Deine Aufgaben:**
|
||||||
|
1. Zeige die `EdgeRegistry` Klasse (Parsing Logik).
|
||||||
|
2. Zeige die Integration in `ingestion.py` (Status-Filter & Edge-Validierung).
|
||||||
|
3. Zeige die Erweiterung in `scoring.py` (Status-Gewicht & Dynamic Edge Boosting).
|
||||||
|
|
||||||
|
Bitte bestätige die Übernahme dieses Architektur-Pakets.
|
||||||
@@ -0,0 +1,94 @@
|
|||||||
|
---
|
||||||
|
doc_type: archive
|
||||||
|
audience: historian, architect
|
||||||
|
status: archived
|
||||||
|
context: "Archivierte Details zu abgeschlossenen Workpackages (WP01-WP19). Referenz für historische Design-Entscheidungen."
|
||||||
|
---
|
||||||
|
|
||||||
|
# Legacy Workpackages (Archiv)
|
||||||
|
|
||||||
|
**Quellen:** `Programmplan_V2.2.md`, `Active Roadmap`
|
||||||
|
|
||||||
|
**Status:** Abgeschlossen / Implementiert.
|
||||||
|
Dieses Dokument dient als Referenz für die Entstehungsgeschichte von Mindnet v2.6.
|
||||||
|
|
||||||
|
## Phase A: Fundament (WP01-03)
|
||||||
|
|
||||||
|
### WP-01 – Wissensdesign
|
||||||
|
* **Ziel:** Definition der Datenstruktur.
|
||||||
|
* **Ergebnis:** Entscheidung gegen komplexe Ontologien (RDF/OWL), für pragmatische Typen (`project`, `concept`). Definition der YAML-Frontmatter-Pflichtfelder.
|
||||||
|
* **Artefakt:** `01_knowledge_design.md`.
|
||||||
|
|
||||||
|
### WP-02 – Chunking & Hash-Strategie
|
||||||
|
* **Ziel:** Texte suchbar machen und Änderungen erkennen.
|
||||||
|
* **Ergebnis:** Implementierung des `SlidingWindowChunker`. Einführung von UUIDv5 für deterministische IDs.
|
||||||
|
* **Learning:** Starre Chunking-Grenzen zerschneiden oft den Kontext. Daher Einführung von Overlap (50 Tokens).
|
||||||
|
|
||||||
|
### WP-03 – Import-Pipeline & Edge-System
|
||||||
|
* **Ziel:** Markdown in Vektoren wandeln.
|
||||||
|
* **Ergebnis:** Der "Importer" (`import_markdown.py`). Entscheidung, Kanten (`_edges`) als eigene Collection zu führen statt als Payload in Chunks (für bessere Graphen-Algorithmen wie Centrality).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Phase B: Semantik (WP04)
|
||||||
|
|
||||||
|
### WP-04a – Retriever & Graph-Scoring
|
||||||
|
* **Ziel:** Bessere Suchergebnisse als reines Vektor-Matching.
|
||||||
|
* **Ergebnis:** Die Formel `Score = Semantik + GraphBonus + TypGewicht`.
|
||||||
|
* **Learning:** Reine Vektorsuche reichte nicht, um den Kontext ("Warum ist das wichtig?") zu erfassen. Der "Graph Bonus" war der Durchbruch für assoziatives Finden.
|
||||||
|
|
||||||
|
### WP-04b – Explanation Layer ("Why-Layer")
|
||||||
|
* **Ziel:** Transparenz.
|
||||||
|
* **Ergebnis:** `explain=True` Parameter. Die API liefert menschenlesbare Gründe ("Gefunden, weil Projekt Alpha davon abhängt").
|
||||||
|
|
||||||
|
### WP-04c – Feedback Logging
|
||||||
|
* **Ziel:** Datenbasis für zukünftiges Lernen schaffen.
|
||||||
|
* **Ergebnis:** Das "Data Flywheel". Jede Suche und Bewertung wird in JSONL-Dateien geloggt (`search_history.jsonl`, `feedback.jsonl`).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Phase C: Persönlichkeit (WP05-07)
|
||||||
|
|
||||||
|
### WP-05 – RAG-Chat
|
||||||
|
* **Ziel:** Natürliche Sprache statt Suchergebnisse.
|
||||||
|
* **Ergebnis:** Integration von Ollama (`phi3`).
|
||||||
|
* **Tech:** Prompt-Engineering (`prompts.yaml`) statt Fine-Tuning, um flexibel zu bleiben.
|
||||||
|
|
||||||
|
### WP-06 – Decision Engine
|
||||||
|
* **Ziel:** Strategische Beratung statt nur Fakten.
|
||||||
|
* **Ergebnis:** Der Hybrid Router.
|
||||||
|
* **Konzept:** Unterscheidung von *Fragen* (RAG) und *Handlungen* (Interview). Strategisches Laden von Werten (`type: value`), um Entscheidungen moralisch zu begründen.
|
||||||
|
|
||||||
|
### WP-07 – Interview-Assistent
|
||||||
|
* **Ziel:** Bekämpfung des "Writer's Block".
|
||||||
|
* **Ergebnis:** One-Shot Extraction. Der Chatbot generiert aus einem losen Satz ("Neues Projekt Alpha") einen strukturierten Markdown-Draft.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Phase D: Interaktion (WP10-15)
|
||||||
|
|
||||||
|
### WP-10/10a – Web UI & Draft Editor
|
||||||
|
* **Ziel:** Usability für Nicht-Techniker.
|
||||||
|
* **Ergebnis:** Streamlit App. Ablösung des Terminals.
|
||||||
|
* **Feature:** "Healing Parser", der defektes JSON vom LLM repariert.
|
||||||
|
|
||||||
|
### WP-11 – Backend Intelligence
|
||||||
|
* **Ziel:** Automatisierung der Vernetzung.
|
||||||
|
* **Ergebnis:** AsyncIO Umstellung für Performance. Einführung von `nomic-embed-text` (768d) für präzise Semantik. Matrix-Logik für automatische Kanten-Typisierung.
|
||||||
|
|
||||||
|
### WP-15 – Smart Edge Allocation (Meilenstein)
|
||||||
|
* **Problem:** "Broadcasting". Ein Chunk erbte alle Links der Note, auch irrelevante. Das verwässerte die Suchergebnisse.
|
||||||
|
* **Lösung:** LLM prüft jeden Chunk auf Link-Relevanz.
|
||||||
|
* **Tech:** Einführung von **Traffic Control** (Semaphore), um Import und Chat zu parallelisieren, ohne die Hardware zu überlasten.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Phase E: Visualisierung & Maintenance (WP19)
|
||||||
|
|
||||||
|
### WP-19 – Graph Visualisierung & Modularisierung
|
||||||
|
* **Ziel:** Transparenz über die Datenstruktur schaffen und technische Schulden (Monolith) abbauen.
|
||||||
|
* **Ergebnis:**
|
||||||
|
* **Modularisierung:** Aufsplittung der `ui.py` in Router, Services und Views (`ui_*.py`).
|
||||||
|
* **Graph Explorer:** Einführung von `st-cytoscape` für stabile, nicht-überlappende Layouts (COSE) als Ergänzung zur Legacy-Engine (Agraph).
|
||||||
|
* **Single Source of Truth:** Der Editor lädt Inhalte nun direkt vom Dateisystem statt aus (potenziell veralteten) Vektor-Payloads.
|
||||||
|
* **UX:** Einführung von URL-Persistenz für Layout-Settings und CSS-basiertes Highlighting zur Vermeidung von Re-Renders.
|
||||||
File renamed without changes.
+149
-44
@@ -1,6 +1,6 @@
|
|||||||
# mindnet v2.4 — Programmplan
|
# mindnet v2.4 — Programmplan
|
||||||
**Version:** 2.4.0 (Inkl. WP-11 Backend Intelligence)
|
**Version:** 2.7.0 (Post-WP15: Roadmap Erweiterung für Graph-Health & Visualisierung)
|
||||||
**Stand:** 2025-12-11
|
**Stand:** 2025-12-12
|
||||||
**Status:** Aktiv
|
**Status:** Aktiv
|
||||||
|
|
||||||
---
|
---
|
||||||
@@ -33,6 +33,12 @@
|
|||||||
- [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)
|
||||||
|
- [WP-18 – Graph Health \& Maintenance (NEU, geplant)](#wp-18--graph-health--maintenance-neu-geplant)
|
||||||
|
- [WP-19 – Graph Visualisierung \& Explorer (NEU, geplant)](#wp-19--graph-visualisierung--explorer-neu-geplant)
|
||||||
|
- [WP-20 – Cloud Hybrid Mode (Gemini) (NEU, geplant)](#wp-20--cloud-hybrid-mode-gemini-neu-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)
|
||||||
@@ -191,7 +197,7 @@ Die folgenden Prinzipien steuern alle Workpackages und Entscheidungen:
|
|||||||
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 (Aktiv)
|
Phase D – Agenten, MCP & Interaktion (Aktiv)
|
||||||
Phase E – Review, Refactoring, Dokumentation
|
Phase E – Maintenance, Visualisierung & Scaling (Neu)
|
||||||
|
|
||||||
Alle Workpackages sind einer Phase zugeordnet. WP-01 bis WP-07 und WP-10/10a/11 sind erfolgreich abgeschlossen.
|
Alle Workpackages sind einer Phase zugeordnet. WP-01 bis WP-07 und WP-10/10a/11 sind erfolgreich abgeschlossen.
|
||||||
|
|
||||||
@@ -514,16 +520,133 @@ 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
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### WP-18 – Graph Health & Maintenance (NEU, geplant)
|
||||||
|
|
||||||
|
**Phase:** E
|
||||||
|
**Status:** 🟡 geplant (Prio 2)
|
||||||
|
|
||||||
|
**Ziel:**
|
||||||
|
Sicherstellung der Konsistenz des Wissensgraphen bei Löschungen oder Umbenennungen von Notizen ("Dangling Edges").
|
||||||
|
|
||||||
|
**Architektur-Idee:**
|
||||||
|
- **Health-Check Script:** Ein Cronjob (`scripts/check_graph_integrity.py`), der alle Kanten prüft, ob ihre `target_id` noch in `mindnet_notes` existiert.
|
||||||
|
- **Report:** Ausgabe von "Broken Links" als Liste für den User.
|
||||||
|
- **Auto-Heal (Optional):** Markieren von defekten Kanten als `broken` statt hartem Löschen.
|
||||||
|
|
||||||
|
**Aufwand / Komplexität:**
|
||||||
|
- Aufwand: Niedrig
|
||||||
|
- Komplexität: Mittel
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### WP-19 – Graph Visualisierung & Explorer (NEU, geplant)
|
||||||
|
|
||||||
|
**Phase:** E
|
||||||
|
**Status:** 🟡 geplant (Prio 1)
|
||||||
|
|
||||||
|
**Ziel:**
|
||||||
|
Schaffung von Vertrauen und Transparenz durch Visualisierung der vom "Smart Chunker" erzeugten Verbindungen.
|
||||||
|
|
||||||
|
**Architektur-Idee:**
|
||||||
|
- **Frontend-Erweiterung:** Neuer Tab "🕸️ Graph" in Streamlit.
|
||||||
|
- **Tech-Stack:** Integration von `streamlit-agraph` oder `pyvis`.
|
||||||
|
- **Feature:** Visualisierung der Nachbarschaft einer Notiz (Ego-Graph) oder eines Suchergebnisses.
|
||||||
|
- **Nutzen:** Schnelle Validierung, ob Smart Edges korrekt gesetzt wurden.
|
||||||
|
|
||||||
|
**Aufwand / Komplexität:**
|
||||||
|
- Aufwand: Mittel
|
||||||
|
- Komplexität: Mittel
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### WP-20 – Cloud Hybrid Mode (Gemini) (NEU, geplant)
|
||||||
|
|
||||||
|
**Phase:** E
|
||||||
|
**Status:** ⚪ optional
|
||||||
|
|
||||||
|
**Ziel:**
|
||||||
|
Optionale Beschleunigung ("Turbo-Modus") für Massen-Imports oder komplexe Analysen durch Nutzung externer High-Performance LLMs (Google Gemini 1.5 Flash), unter Beachtung des Datenschutzes.
|
||||||
|
|
||||||
|
**Architektur-Idee:**
|
||||||
|
- **Provider-Switch:** Erweiterung des `LLMService` um einen Provider-Parameter (`ollama` vs. `gemini`).
|
||||||
|
- **Konfiguration:** `types.yaml` oder `.env` erlaubt Umschalten pro Umgebung (z.B. Dev=Cloud, Prod=Local).
|
||||||
|
- **Privacy:** Warnhinweis im UI, wenn Daten die lokale Umgebung verlassen.
|
||||||
|
|
||||||
|
**Aufwand / Komplexität:**
|
||||||
|
- Aufwand: Mittel
|
||||||
|
- Komplexität: Niedrig
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
## 7. Abhängigkeiten (vereinfacht, aktualisiert)
|
## 7. Abhängigkeiten (vereinfacht, aktualisiert)
|
||||||
|
|
||||||
WP01 → WP02 → WP03 → WP04a
|
WP01-03 → WP04-06 (Core)
|
||||||
WP04a → WP04b → WP04c → WP08
|
WP11 → WP15 (Smart Edges)
|
||||||
WP03 → WP05 → WP06 → WP07
|
WP15 → WP19 (Visualisierung - zur Kontrolle)
|
||||||
WP07 → WP10a
|
WP15 → WP16 (Auto-Discovery)
|
||||||
WP03 → WP09
|
WP03 → WP18 (Maintenance)
|
||||||
WP01/WP03 → WP10 → WP11 → WP12
|
WP10 → WP17 (Memory)
|
||||||
WP03/WP04 → WP13
|
WP20 (Cloud) ist unabhängig/optional.
|
||||||
Alles → WP14
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -531,44 +654,26 @@ Aufräumen, dokumentieren, stabilisieren – insbesondere für Onboarding Dritte
|
|||||||
|
|
||||||
| WP | Aufwand | Komplexität |
|
| WP | Aufwand | Komplexität |
|
||||||
|-------|----------------|------------------|
|
|-------|----------------|------------------|
|
||||||
| WP04b | Mittel | Hoch |
|
| WP15 | Mittel | Hoch |
|
||||||
| WP04c | Mittel | Mittel/Hoch |
|
| WP16 | Mittel | Hoch |
|
||||||
| WP05 | Mittel | Mittel |
|
| WP17 | Mittel | Mittel |
|
||||||
| WP06 | Mittel | Hoch |
|
| WP18 | Niedrig | Mittel |
|
||||||
| WP07 | Niedrig/Mittel | Mittel |
|
| WP19 | Mittel | Mittel |
|
||||||
| WP08 | Hoch | Hoch |
|
| WP20 | Mittel | Niedrig |
|
||||||
| WP09 | Mittel | Niedrig/Mittel |
|
|
||||||
| WP10 | Hoch | Hoch |
|
|
||||||
| WP10a | Mittel | Mittel |
|
|
||||||
| WP11 | Hoch | Hoch |
|
|
||||||
| WP12 | Niedrig/Mittel | Mittel |
|
|
||||||
| WP13 | Mittel | Mittel |
|
|
||||||
| WP14 | Mittel | Niedrig/Mittel |
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 9. Programmfortschritt (Ampel, aktualisiert)
|
## 9. Programmfortschritt (Ampel, aktualisiert)
|
||||||
|
|
||||||
| WP | Status |
|
| WP | Status | Titel |
|
||||||
|-------|--------|
|
|-------|--------|-------|
|
||||||
| WP01 | 🟢 |
|
| WP01-14| 🟢 | (Basis-System) |
|
||||||
| WP02 | 🟢 |
|
| WP15 | 🟢 | Smart Edge Allocation |
|
||||||
| WP03 | 🟢 |
|
| WP16 | 🟡 | Auto-Discovery |
|
||||||
| WP04a | 🟢 |
|
| WP17 | 🟡 | Conversational Memory |
|
||||||
| WP04b | 🟢 |
|
| WP18 | 🟡 | Graph Health (Neu) |
|
||||||
| WP04c | 🟢 |
|
| WP19 | 🟡 | Visualization (Neu) |
|
||||||
| WP05 | 🟢 |
|
| WP20 | ⚪ | Cloud Mode (Neu) |
|
||||||
| WP05b | ⚪ |
|
|
||||||
| WP06 | 🟢 |
|
|
||||||
| WP07 | 🟢 |
|
|
||||||
| WP08 | 🟡 |
|
|
||||||
| WP09 | 🟡 |
|
|
||||||
| WP10 | 🟢 |
|
|
||||||
| WP10a | 🟢 |
|
|
||||||
| WP11 | 🟢 |
|
|
||||||
| WP12 | 🟡 |
|
|
||||||
| WP13 | 🟡 |
|
|
||||||
| WP14 | 🟡 |
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
+39
-18
@@ -1,7 +1,7 @@
|
|||||||
# mindnet v2.4 – Knowledge Design Manual
|
# mindnet v2.4 – Knowledge Design Manual
|
||||||
**Datei:** `docs/mindnet_knowledge_design_manual_v2.4.md`
|
**Datei:** `docs/mindnet_knowledge_design_manual_v2.6.md`
|
||||||
**Stand:** 2025-12-11
|
**Stand:** 2025-12-12
|
||||||
**Status:** **FINAL** (Integrierter Stand WP01–WP11)
|
**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,9 @@ 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.4 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.
|
* **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).
|
* **Active Intelligence (WP11):** Das System hilft dir beim Schreiben und Vernetzen (Link-Vorschläge).
|
||||||
|
|
||||||
@@ -69,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.
|
||||||
@@ -80,7 +80,7 @@ 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") und **welche Felder** im Interview abgefragt werden.
|
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
|
||||||
|
|
||||||
@@ -90,10 +90,13 @@ Mindnet unterscheidet verschiedene Wissensarten. Wähle den Typ, der die **Rolle
|
|||||||
| :--- | :--- | :--- | :--- | :--- |
|
| :--- | :--- | :--- | :--- | :--- |
|
||||||
| **`concept`** | Fachbegriffe, Theorien. Zeitloses Wissen. | **FACT** | Titel, Definition, Tags | Ziel für `uses` |
|
| **`concept`** | Fachbegriffe, Theorien. Zeitloses Wissen. | **FACT** | Titel, Definition, Tags | Ziel für `uses` |
|
||||||
| **`project`** | Ein Vorhaben mit Ziel, Dauer und Aufgaben. | **FACT / DECISION** | Ziel, Status, Stakeholder | Quelle für `uses`, `depends_on` |
|
| **`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** | Situation, Erkenntnis, Emotionen | Quelle für `based_on` |
|
| **`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** | Kontext, Entscheidung, Alternativen | Quelle für `depends_on` |
|
| **`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** | Definition, Anti-Beispiel | Ziel für `based_on` |
|
| **`value`** | Ein persönlicher Wert oder ein Prinzip. | **DECISION** | Definition, Anti-Beispiel | Ziel für `based_on` |
|
||||||
|
| **`principle`** | Handlungsleitlinie. | **DECISION** | Regel, Ausnahme | Quelle für `derived_from` |
|
||||||
| **`goal`** | Ein strategisches Ziel (kurz- oder langfristig). | **DECISION** | Zeitrahmen, KPIs, Werte | Ziel für `related_to` |
|
| **`goal`** | Ein strategisches Ziel (kurz- oder langfristig). | **DECISION** | Zeitrahmen, KPIs, Werte | Ziel für `related_to` |
|
||||||
|
| **`risk`** | Ein identifiziertes Risiko oder eine Gefahr. | **DECISION** | Auswirkung, Wahrscheinlichkeit | Quelle für `blocks` |
|
||||||
|
| **`belief`** | Glaubenssatz / Überzeugung. | **EMPATHY** | Ursprung, Mantra | - |
|
||||||
| **`person`** | Eine reale Person (Netzwerk, Autor). | **FACT** | Rolle, Kontext | - |
|
| **`person`** | Eine reale Person (Netzwerk, Autor). | **FACT** | Rolle, Kontext | - |
|
||||||
| **`journal`** | Zeitbezogener Log-Eintrag, Daily Note. | **FACT** | Datum, Tags | - |
|
| **`journal`** | Zeitbezogener Log-Eintrag, Daily Note. | **FACT** | Datum, Tags | - |
|
||||||
| **`source`** | Externe Quelle (Buch, PDF, Artikel). | **FACT** | Autor, URL | - |
|
| **`source`** | Externe Quelle (Buch, PDF, Artikel). | **FACT** | Autor, URL | - |
|
||||||
@@ -104,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.
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -137,9 +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).
|
||||||
* **Neu (v2.4):** `based_on`, `uses`, `derived_from` (werden oft automatisch vorgeschlagen).
|
* **`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.
|
||||||
@@ -150,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.
|
||||||
|
|
||||||
@@ -210,6 +214,23 @@ Seit v2.4 (WP07) kann Mindnet Notizen für dich entwerfen.
|
|||||||
* **Ergebnis:** Du erhältst einen Code-Block mit `status: draft`. Diesen kannst du im Draft-Editor (UI) direkt bearbeiten und herunterladen.
|
* **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.
|
* **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)
|
||||||
@@ -268,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.
|
||||||
@@ -1,8 +1,8 @@
|
|||||||
# Mindnet v2.4 – Overview & Einstieg
|
# Mindnet v2.4 – Overview & Einstieg
|
||||||
**Datei:** `docs/mindnet_overview_v2.4.md`
|
**Datei:** `docs/mindnet_overview_v2.6.md`
|
||||||
**Stand:** 2025-12-11
|
**Stand:** 2025-12-12
|
||||||
**Status:** **FINAL** (Inkl. Async Intelligence & Editor)
|
**Status:** **FINAL** (Inkl. Smart Edges, Traffic Control & Healing UI)
|
||||||
**Version:** 2.4.0
|
**Version:** 2.6.0
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -28,14 +28,14 @@ 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:** Async Import-Pipeline, Chunking, Vektor-Datenbank (Qdrant).
|
* **Technik:** Async Import-Pipeline, Smart Chunking (LLM-gestützte Kantenzuweisung), Vektor-Datenbank (Qdrant).
|
||||||
* **Status:** 🟢 Live (WP01–WP03, WP11).
|
* **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 + Nomic Embeddings), Explanation Engine.
|
* **Technik:** Hybrider Retriever (Graph + Nomic Embeddings), Explanation Engine.
|
||||||
* **Status:** 🟢 Live (WP04, WP11).
|
* **Status:** 🟢 Live (WP04, WP11, WP15).
|
||||||
|
|
||||||
### Ebene 3: Identität & Interaktion (Die Persönlichkeit)
|
### Ebene 3: Identität & Interaktion (Die Persönlichkeit)
|
||||||
* **Funktion:** Interaktion, Bewertung und Co-Creation.
|
* **Funktion:** Interaktion, Bewertung und Co-Creation.
|
||||||
@@ -43,11 +43,11 @@ Mindnet arbeitet auf drei Schichten, die aufeinander aufbauen:
|
|||||||
* "Ich empfehle Lösung X, weil sie unserem Wert 'Datensparsamkeit' entspricht."
|
* "Ich empfehle Lösung X, weil sie unserem Wert 'Datensparsamkeit' entspricht."
|
||||||
* "Ich sehe, du willst ein Projekt starten. Lass uns die Eckdaten erfassen."
|
* "Ich sehe, du willst ein Projekt starten. Lass uns die Eckdaten erfassen."
|
||||||
* **Technik:**
|
* **Technik:**
|
||||||
* **Intent Router:** Erkennt Absichten (Fakt vs. Gefühl vs. Entscheidung vs. Interview).
|
* **Hybrid Router v5:** Erkennt Absichten (Frage vs. Befehl) und unterscheidet Objekte (`types.yaml`) von Handlungen (`decision_engine.yaml`).
|
||||||
* **Strategic Retrieval:** Lädt gezielt Werte oder Erfahrungen nach.
|
* **Traffic Control:** Priorisiert Chat-Anfragen ("Realtime") vor Hintergrund-Jobs ("Background").
|
||||||
* **One-Shot Extraction:** Generiert Entwürfe für neue Notizen.
|
* **One-Shot Extraction:** Generiert Entwürfe für neue Notizen.
|
||||||
* **Active Intelligence:** Schlägt Links während des Schreibens vor.
|
* **Active Intelligence:** Schlägt Links während des Schreibens vor.
|
||||||
* **Status:** 🟢 Live (WP05–WP07, WP10).
|
* **Status:** 🟢 Live (WP05–WP07, WP10, WP15).
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -57,8 +57,9 @@ Der Datenfluss in Mindnet ist zyklisch ("Data Flywheel"):
|
|||||||
|
|
||||||
1. **Input:** Du schreibst Notizen in Obsidian **ODER** lässt sie von Mindnet im Chat entwerfen.
|
1. **Input:** Du schreibst Notizen in Obsidian **ODER** lässt sie von Mindnet im Chat entwerfen.
|
||||||
2. **Intelligence (Live):** Während du schreibst, analysiert Mindnet den Text und schlägt Verknüpfungen vor (Sliding Window Analyse).
|
2. **Intelligence (Live):** Während du schreibst, analysiert Mindnet den Text und schlägt Verknüpfungen vor (Sliding Window Analyse).
|
||||||
3. **Ingest:** Ein asynchrones Python-Skript importiert, zerlegt (Chunking) und vernetzt (Edges) die Daten in Qdrant.
|
3. **Ingest:** Ein asynchrones Python-Skript importiert und zerlegt die Daten.
|
||||||
4. **Intent Recognition:** Der Router analysiert deine Frage: Willst du Fakten, Code, Empathie oder etwas dokumentieren?
|
* **Neu (Smart Edges):** Ein LLM analysiert jeden Textabschnitt und entscheidet, welche Kanten relevant sind.
|
||||||
|
4. **Intent Recognition:** Der Router analysiert deine Eingabe: Ist es eine Frage (RAG) oder ein Befehl (Interview)?
|
||||||
5. **Retrieval / Action:**
|
5. **Retrieval / Action:**
|
||||||
* Bei Fragen: Das System sucht Inhalte passend zum Intent.
|
* Bei Fragen: Das System sucht Inhalte passend zum Intent.
|
||||||
* Bei Interviews: Das System wählt das passende Schema (z.B. Projekt-Vorlage).
|
* Bei Interviews: Das System wählt das passende Schema (z.B. Projekt-Vorlage).
|
||||||
@@ -69,7 +70,8 @@ Der Datenfluss in Mindnet ist zyklisch ("Data Flywheel"):
|
|||||||
* **Backend:** Python 3.10+, FastAPI (Async).
|
* **Backend:** Python 3.10+, FastAPI (Async).
|
||||||
* **Datenbank:** Qdrant (Vektor & Graph, 768 Dim).
|
* **Datenbank:** Qdrant (Vektor & Graph, 768 Dim).
|
||||||
* **KI:** Ollama (Phi-3 Mini für Chat, Nomic für Embeddings) – 100% lokal.
|
* **KI:** Ollama (Phi-3 Mini für Chat, Nomic für Embeddings) – 100% lokal.
|
||||||
* **Frontend:** Streamlit Web-UI (v2.4).
|
* **Traffic Control:** Semaphore-Logik zur Lastverteilung zwischen Chat und Import.
|
||||||
|
* **Frontend:** Streamlit Web-UI (v2.5) mit Healing Parser.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -79,13 +81,13 @@ 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.4.md` |
|
| **...wissen willst, wie man Notizen schreibt.** | `mindnet_knowledge_design_manual_v2.6.md` |
|
||||||
| **...das System installieren oder betreiben musst.** | `mindnet_admin_guide_v2.4.md` |
|
| **...das System installieren oder betreiben musst.** | `mindnet_admin_guide_v2.6.md` |
|
||||||
| **...am Python-Code entwickeln willst.** | `mindnet_developer_guide_v2.4.md` |
|
| **...am Python-Code entwickeln willst.** | `mindnet_developer_guide_v2.6.md` |
|
||||||
| **...die Pipeline (Import -> RAG) verstehen willst.** | `mindnet_pipeline_playbook_v2.4.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.** | `mindnet_appendices_v2.4.md` |
|
| **...den aktuellen Projektstatus suchst.** | `mindnet_appendices_v2.6.md` |
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -99,5 +101,5 @@ Wo findest du was?
|
|||||||
|
|
||||||
## 6. Aktueller Fokus
|
## 6. Aktueller Fokus
|
||||||
|
|
||||||
Wir haben den **Interview-Assistenten (WP07)** und die **Backend Intelligence (WP11)** erfolgreich integriert.
|
Wir haben die **Smart Edge Allocation (WP15)** und die **System-Stabilisierung (Traffic Control)** erfolgreich abgeschlossen.
|
||||||
Das System kann nun aktiv helfen, Wissen zu strukturieren und zu vernetzen. Der Fokus verschiebt sich nun in Richtung **Self-Tuning (WP08)**, um aus dem gesammelten Feedback automatisch zu lernen.
|
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)**.
|
||||||
@@ -1,8 +1,8 @@
|
|||||||
# Mindnet v2.4 – Admin Guide
|
# Mindnet v2.4 – Admin Guide
|
||||||
**Datei:** `docs/mindnet_admin_guide_v2.4.md`
|
**Datei:** `docs/mindnet_admin_guide_v2.6.md`
|
||||||
**Stand:** 2025-12-11
|
**Stand:** 2025-12-12
|
||||||
**Status:** **FINAL** (Inkl. Async Architecture & Nomic Model)
|
**Status:** **FINAL** (Inkl. Traffic Control & Smart Edge Config)
|
||||||
**Quellen:** `Handbuch.md`, `mindnet_developer_guide_v2.4.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 + UI + DB).
|
> Dieses Handbuch richtet sich an **Administratoren**. Es beschreibt Installation, Konfiguration, Backup-Strategien, Monitoring und den sicheren Betrieb der Mindnet-Instanz (API + UI + DB).
|
||||||
|
|
||||||
@@ -55,7 +55,7 @@ Wir nutzen Qdrant als Vektor-Datenbank. Persistenz ist wichtig.
|
|||||||
|
|
||||||
### 2.4 Ollama Setup (LLM & Embeddings)
|
### 2.4 Ollama Setup (LLM & Embeddings)
|
||||||
Mindnet benötigt einen lokalen LLM-Server für Chat UND Embeddings.
|
Mindnet benötigt einen lokalen LLM-Server für Chat UND Embeddings.
|
||||||
**WICHTIG (Update v2.3.10):** Es muss zwingend `nomic-embed-text` installiert sein, sonst startet der Import nicht.
|
**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
|
||||||
@@ -68,7 +68,7 @@ Mindnet benötigt einen lokalen LLM-Server für Chat UND Embeddings.
|
|||||||
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. Achte besonders auf `VECTOR_DIM` und `MINDNET_EMBEDDING_MODEL`.
|
Erstelle eine `.env` Datei im Root-Verzeichnis. Achte besonders auf `VECTOR_DIM` und das neue `MINDNET_LLM_BACKGROUND_LIMIT`.
|
||||||
|
|
||||||
# Server Config
|
# Server Config
|
||||||
UVICORN_HOST=0.0.0.0
|
UVICORN_HOST=0.0.0.0
|
||||||
@@ -87,11 +87,15 @@ Erstelle eine `.env` Datei im Root-Verzeichnis. Achte besonders auf `VECTOR_DIM`
|
|||||||
# AI Modelle (Ollama)
|
# 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_LLM_MODEL="phi3:mini"
|
||||||
MINDNET_EMBEDDING_MODEL="nomic-embed-text" # NEU
|
MINDNET_EMBEDDING_MODEL="nomic-embed-text"
|
||||||
|
|
||||||
# Timeouts (Erhöht für Async/Nomic)
|
# Timeouts (Erhöht für Async/Nomic/Smart Edges)
|
||||||
MINDNET_LLM_TIMEOUT=300.0
|
MINDNET_LLM_TIMEOUT=300.0
|
||||||
MINDNET_API_TIMEOUT=60.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
|
# Configs
|
||||||
MINDNET_PROMPTS_PATH="./config/prompts.yaml"
|
MINDNET_PROMPTS_PATH="./config/prompts.yaml"
|
||||||
@@ -155,12 +159,15 @@ Mindnet benötigt zwei Services pro Umgebung: API (Uvicorn) und UI (Streamlit).
|
|||||||
## 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. Das Skript nutzt nun **AsyncIO** und eine Semaphore, um Ollama nicht zu überlasten.
|
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 ./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 Komponenten laufen.
|
Prüfe regelmäßig, ob alle Komponenten laufen.
|
||||||
|
|
||||||
@@ -176,7 +183,7 @@ Prüfe regelmäßig, ob alle Komponenten laufen.
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 4. Troubleshooting (Update v2.4)
|
## 4. Troubleshooting (Update v2.6)
|
||||||
|
|
||||||
### "Vector dimension error: expected dim: 768, got 384"
|
### "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.
|
* **Ursache:** Du versuchst, in eine alte Qdrant-Collection (mit 384 Dim aus v2.2) neue Embeddings (mit 768 Dim von Nomic) zu schreiben.
|
||||||
@@ -184,15 +191,17 @@ Prüfe regelmäßig, ob alle Komponenten laufen.
|
|||||||
1. `python -m scripts.reset_qdrant --mode wipe --prefix mindnet --yes` (Löscht DB).
|
1. `python -m scripts.reset_qdrant --mode wipe --prefix mindnet --yes` (Löscht DB).
|
||||||
2. `python -m scripts.import_markdown ...` (Baut neu auf).
|
2. `python -m scripts.import_markdown ...` (Baut neu auf).
|
||||||
|
|
||||||
### "500 Internal Server Error" beim Speichern
|
### "500 Internal Server Error" beim Speichern/Chatten
|
||||||
* **Ursache:** Oft Timeout bei Ollama, wenn `nomic-embed-text` noch nicht im RAM geladen ist ("Cold Start").
|
* **Ursache:** Oft Timeout bei Ollama, wenn `nomic-embed-text` noch nicht im RAM geladen ist ("Cold Start") oder der Import die GPU blockiert.
|
||||||
* **Lösung:**
|
* **Lösung:**
|
||||||
1. Sicherstellen, dass Modell existiert: `ollama list`.
|
1. `MINDNET_LLM_TIMEOUT` in `.env` auf `300.0` setzen.
|
||||||
2. API neustarten (re-initialisiert Async Clients).
|
2. `MINDNET_LLM_BACKGROUND_LIMIT` auf `1` reduzieren (falls Hardware schwach).
|
||||||
|
|
||||||
### "NameError: name 'os' is not defined"
|
### Import ist sehr langsam
|
||||||
* **Ursache:** Fehlender Import in Skripten nach Updates.
|
* **Ursache:** Smart Edges sind aktiv (`types.yaml`) und analysieren jeden Chunk.
|
||||||
* **Lösung:** `git pull` (Fix wurde in v2.3.10 deployed).
|
* **Lösung:**
|
||||||
|
* Akzeptieren (für bessere Qualität).
|
||||||
|
* Oder für Massen-Initial-Import in `types.yaml` temporär `enable_smart_edge_allocation: false` setzen.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -215,7 +224,7 @@ Wenn die Datenbank korrupt ist oder Modelle gewechselt werden:
|
|||||||
|
|
||||||
# 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 ./vault --prefix "mindnet" --apply --force
|
python3 -m scripts.import_markdown --vault ./vault --prefix "mindnet" --apply --force
|
||||||
|
|
||||||
---
|
---
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
# Mindnet v2.4 – Appendices & Referenzen
|
# Mindnet v2.4 – Appendices & Referenzen
|
||||||
**Datei:** `docs/mindnet_appendices_v2.4.md`
|
**Datei:** `docs/mindnet_appendices_v2.6.md`
|
||||||
**Stand:** 2025-12-11
|
**Stand:** 2025-12-12
|
||||||
**Status:** **FINAL** (Integrierter Stand WP01–WP11)
|
**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.4).
|
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. |
|
| **principle** | `structured_smart_edges` | 1.00 | **Ja** | Handlungsleitlinien. |
|
||||||
| **belief** | `medium` | 0.90 | `related_to` | Glaubenssätze. |
|
| **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,6 +48,7 @@ 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". |
|
||||||
|
| `blocks` | Inline | Nein | **NEU:** Blockade. "Risiko X blockiert Projekt Y". |
|
||||||
| `derived_from` | Matrix / Default | Nein | Herkunft. "Erkenntnis stammt aus Prinzip X". |
|
| `derived_from` | Matrix / Default | Nein | Herkunft. "Erkenntnis stammt aus Prinzip X". |
|
||||||
| `based_on` | Matrix | Nein | Fundament. "Erfahrung basiert auf Wert Y". |
|
| `based_on` | Matrix | Nein | Fundament. "Erfahrung basiert auf Wert Y". |
|
||||||
| `uses` | Matrix | Nein | Nutzung. "Projekt nutzt Konzept Z". |
|
| `uses` | Matrix | Nein | Nutzung. "Projekt nutzt Konzept Z". |
|
||||||
@@ -60,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
|
||||||
@@ -78,6 +84,7 @@ Diese sind die Felder, die effektiv in Qdrant gespeichert werden.
|
|||||||
"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
|
||||||
}
|
}
|
||||||
@@ -92,7 +99,8 @@ Diese sind die Felder, die effektiv in Qdrant gespeichert werden.
|
|||||||
"scope": "string (keyword)", // Immer 'chunk'
|
"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
|
"note_id": "string (keyword)", // Owner Note ID
|
||||||
|
"provenance": "keyword" // 'explicit', 'rule', 'smart' (NEU)
|
||||||
}
|
}
|
||||||
|
|
||||||
---
|
---
|
||||||
@@ -115,7 +123,8 @@ Diese Variablen steuern das Verhalten der Skripte und Container.
|
|||||||
| `MINDNET_EMBEDDING_MODEL` | `nomic-embed-text` | **NEU:** Name des Vektor-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` | `300.0` | Timeout für Ollama (Erhöht für CPU-Inference). |
|
| `MINDNET_LLM_TIMEOUT` | `300.0` | Timeout für Ollama (Erhöht für CPU-Inference). |
|
||||||
| `MINDNET_API_TIMEOUT` | `60.0` | **NEU:** Frontend Timeout (Streamlit). |
|
| `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_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`). |
|
||||||
@@ -129,16 +138,19 @@ Diese Variablen steuern das Verhalten der Skripte und Container.
|
|||||||
* **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).
|
* **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.
|
* **Matrix Logic:** Regelwerk, das Kanten-Typen basierend auf Quell- und Ziel-Typ bestimmt.
|
||||||
* **Nomic:** Das neue, hochpräzise Embedding-Modell (768 Dim).
|
* **Nomic:** Das neue, hochpräzise Embedding-Modell (768 Dim).
|
||||||
* **One-Shot Extractor:** LLM-Strategie zur sofortigen Generierung von Drafts ohne Rückfragen (WP07).
|
* **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.
|
||||||
* **Resurrection Pattern:** UI-Technik, um Eingaben bei Tab-Wechseln zu erhalten.
|
* **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.4.0)
|
## Anhang F: Workpackage Status (v2.6.0)
|
||||||
|
|
||||||
Aktueller Implementierungsstand der Module.
|
Aktueller Implementierungsstand der Module.
|
||||||
|
|
||||||
@@ -151,9 +163,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 v5, Strategic Retrieval. |
|
||||||
| **WP07** | Interview Assistent | 🟢 Live | **One-Shot Extractor & Schemas aktiv.** |
|
| **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 | 🟢 Live | Web-Interface (Streamlit). |
|
| **WP10** | Chat Interface | 🟢 Live | Web-Interface (Streamlit). |
|
||||||
| **WP10a**| Draft Editor | 🟢 Live | **Interaktives UI für WP07 Drafts.** |
|
| **WP10a**| Draft Editor | 🟢 Live | **Interaktives UI & Healing Parser.** |
|
||||||
| **WP11** | Backend Intelligence | 🟢 Live | **Async Core, Nomic, Matrix.** |
|
| **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. |
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
# Mindnet v2.4 – Entwickler-Workflow
|
# Mindnet v2.4 – Entwickler-Workflow
|
||||||
**Datei:** `docs/DEV_WORKFLOW.md`
|
**Datei:** `docs/DEV_WORKFLOW.md`
|
||||||
**Stand:** 2025-12-11 (Aktualisiert: Inkl. Async Intelligence & Nomic)
|
**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).
|
||||||
|
|
||||||
@@ -35,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/wp11-async-fix`).
|
* 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 Schemas in `decision_engine.yaml` oder Async-Logik in `ingestion.py`).
|
* 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**.
|
||||||
@@ -64,15 +64,27 @@ 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/wp11-async-fix
|
git checkout feature/wp15-traffic-control
|
||||||
git pull
|
git pull
|
||||||
```
|
```
|
||||||
|
|
||||||
4. **Umgebung vorbereiten (WICHTIG für v2.4):**
|
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 # HTTPX usw.
|
pip install -r requirements.txt
|
||||||
# Sicherstellen, dass das neue Embedding-Modell da ist:
|
|
||||||
ollama pull nomic-embed-text
|
ollama pull nomic-embed-text
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -102,18 +114,15 @@ Hier prüfst du, ob dein neuer Code auf dem echten Server läuft.
|
|||||||
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
|
||||||
```
|
```
|
||||||
|
|
||||||
6. **Validieren (Smoke Tests):**
|
6. **Validieren (Smoke Tests v2.6):**
|
||||||
|
|
||||||
* **Browser:** Öffne `http://<IP>:8502` um die UI zu testen (Intent Badge prüfen!).
|
* **Test A: Last-Test (Traffic Control):**
|
||||||
* **CLI:** Führe Testskripte in einem **zweiten Terminal** aus:
|
1. Starte einen Import im Terminal: `python3 -m scripts.import_markdown ...`
|
||||||
|
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 A: Intelligence / Aliases (Neu in WP11)**
|
* **Test B: API Check**
|
||||||
```bash
|
|
||||||
python debug_analysis.py
|
|
||||||
# Erwartung: "✅ ALIAS GEFUNDEN"
|
|
||||||
```
|
|
||||||
|
|
||||||
**Test B: API Check**
|
|
||||||
```bash
|
```bash
|
||||||
curl -X POST "http://localhost:8002/ingest/analyze" -d '{"text": "mindnet", "type": "journal"}'
|
curl -X POST "http://localhost:8002/ingest/analyze" -d '{"text": "mindnet", "type": "journal"}'
|
||||||
```
|
```
|
||||||
@@ -147,6 +156,9 @@ Jetzt bringen wir die Änderung in das Live-System (Port 8001 / 8501).
|
|||||||
pip install -r requirements.txt
|
pip install -r requirements.txt
|
||||||
ollama pull nomic-embed-text
|
ollama pull nomic-embed-text
|
||||||
|
|
||||||
|
# .env prüfen (Traffic Control)
|
||||||
|
# Ggf. MINDNET_LLM_BACKGROUND_LIMIT=2 hinzufügen
|
||||||
|
|
||||||
# Falls sich die Vektor-Dimension geändert hat (v2.4 Upgrade):
|
# Falls sich die Vektor-Dimension geändert hat (v2.4 Upgrade):
|
||||||
# python3 -m scripts.reset_qdrant --mode wipe --prefix "mindnet" --yes
|
# python3 -m scripts.reset_qdrant --mode wipe --prefix "mindnet" --yes
|
||||||
# python3 -m scripts.import_markdown --vault ./vault --prefix "mindnet" --apply --force
|
# python3 -m scripts.import_markdown --vault ./vault --prefix "mindnet" --apply --force
|
||||||
@@ -168,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/wp11-async-fix
|
git branch -d feature/wp15-traffic-control
|
||||||
```
|
```
|
||||||
3. **VS Code:**
|
3. **VS Code:**
|
||||||
* Auf `main` wechseln.
|
* Auf `main` wechseln.
|
||||||
@@ -182,23 +194,26 @@ Damit das Chaos nicht wächst, löschen wir den fertigen Branch.
|
|||||||
| Wo? | Befehl | Was tut es? |
|
| Wo? | Befehl | Was tut es? |
|
||||||
| :--- | :--- | :--- |
|
| :--- | :--- | :--- |
|
||||||
| **Beelink** | `sudo systemctl restart mindnet-dev` | **Neustart Dev-Backend (Port 8002).** |
|
| **Beelink** | `sudo systemctl restart mindnet-dev` | **Neustart Dev-Backend (Port 8002).** |
|
||||||
|
| **Beelink** | `sudo systemctl restart mindnet-ui-dev` | **Neustart Dev-Frontend (Port 8002).** |
|
||||||
| **Beelink** | `journalctl -u mindnet-dev -f` | **Live-Logs Backend.** |
|
| **Beelink** | `journalctl -u mindnet-dev -f` | **Live-Logs Backend.** |
|
||||||
| **Beelink** | `python debug_analysis.py` | **Prüft Aliases & Scores.** |
|
| **Beelink** | `python debug_analysis.py` | **Prüft Aliases & Scores.** |
|
||||||
| **Beelink** | `python -m scripts.reset_qdrant ...` | **Löscht & Repariert DB.** |
|
| **Beelink** | `python3 -m scripts.reset_qdrant --mode wipe --prefix "mindnet_dev" --yes` | **Löscht & Repariert DB.** |
|
||||||
|
| **Beelink** | `python3 -m scripts.import_markdown --vault ./vault_master --prefix "mindnet_dev" --apply --force` | **Löscht & Repariert DB.** |
|
||||||
|
| **Beelink** | `source .venv/bin/activate` | **Aktivieren des virtual environments** |
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 4. Troubleshooting
|
## 4. Troubleshooting
|
||||||
|
|
||||||
**"Vector dimension error: expected 768, got 384"**
|
**"Read timed out" im Frontend**
|
||||||
* **Ursache:** Du hast `nomic-embed-text` (768) aktiviert, aber die DB ist noch alt (384).
|
* **Ursache:** Backend braucht für Smart Edges länger als 60s.
|
||||||
* **Lösung:** `scripts.reset_qdrant` ausführen und neu importieren.
|
* **Lösung:** `MINDNET_API_TIMEOUT=300.0` in `.env` setzen und Services neustarten.
|
||||||
|
|
||||||
**"Read timed out (300s)" / 500 Error beim Interview**
|
**Import ist extrem langsam**
|
||||||
* **Ursache:** Das LLM (Ollama) braucht für den One-Shot Draft länger als das Timeout erlaubt.
|
* **Ursache:** Smart Edges analysieren jeden Chunk mit LLM.
|
||||||
* **Lösung:**
|
* **Lösung:**
|
||||||
1. Erhöhe in `.env` den Wert: `MINDNET_LLM_TIMEOUT=300.0`.
|
* Akzeptieren (Qualität vor Speed).
|
||||||
2. Starte die Server neu.
|
* 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.
|
||||||
+44
-31
@@ -1,7 +1,7 @@
|
|||||||
# Mindnet v2.4 – Developer Guide
|
# Mindnet v2.4 – Developer Guide
|
||||||
**Datei:** `docs/mindnet_developer_guide_v2.4.md`
|
**Datei:** `docs/mindnet_developer_guide_v2.6.md`
|
||||||
**Stand:** 2025-12-11
|
**Stand:** 2025-12-12
|
||||||
**Status:** **FINAL** (Inkl. Async Core, Nomic & Frontend State)
|
**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.
|
||||||
@@ -9,7 +9,7 @@
|
|||||||
|
|
||||||
---
|
---
|
||||||
- [Mindnet v2.4 – Developer Guide](#mindnet-v24--developer-guide)
|
- [Mindnet v2.4 – Developer Guide](#mindnet-v24--developer-guide)
|
||||||
- [1. Projektstruktur (Post-WP10)](#1-projektstruktur-post-wp10)
|
- [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)
|
||||||
@@ -21,6 +21,7 @@
|
|||||||
- [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.4 Das Frontend (`app.frontend.ui`)](#34-das-frontend-appfrontendui)
|
||||||
- [3.5 Embedding Service (`app.services.embeddings_client`)](#35-embedding-service-appservicesembeddings_client)
|
- [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)
|
||||||
@@ -34,15 +35,15 @@
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 1. Projektstruktur (Post-WP10)
|
## 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
|
||||||
│ │ ├── ingestion.py # NEU: Async Ingestion Service (WP11)
|
│ │ ├── ingestion.py # NEU: Async Ingestion Service mit Change Detection
|
||||||
│ │ ├── chunker.py # Text-Zerlegung
|
│ │ ├── 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
|
||||||
@@ -52,21 +53,22 @@ Der Code ist modular in `app` (Logik), `scripts` (CLI) und `config` (Steuerung)
|
|||||||
│ ├── routers/ # FastAPI Endpoints
|
│ ├── routers/ # FastAPI Endpoints
|
||||||
│ │ ├── query.py # Suche
|
│ │ ├── query.py # Suche
|
||||||
│ │ ├── ingest.py # NEU: Save/Analyze (WP11)
|
│ │ ├── ingest.py # NEU: Save/Analyze (WP11)
|
||||||
│ │ ├── chat.py # Hybrid Router & Interview Logic (WP06/WP07)
|
│ │ ├── 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
|
||||||
│ │ ├── embeddings_client.py# NEU: Async Embeddings (HTTPX)
|
│ │ ├── 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)
|
||||||
│ │ └── discovery.py # NEU: Intelligence Logic (WP11)
|
│ │ └── discovery.py # NEU: Intelligence Logic (WP11)
|
||||||
│ ├── frontend/ # NEU (WP10)
|
│ ├── frontend/ # NEU (WP10)
|
||||||
│ │ └── ui.py # Streamlit Application inkl. Draft-Editor
|
│ │ └── 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 & Interview Templates (WP06/07)
|
│ ├── prompts.yaml # LLM Prompts & Interview Templates
|
||||||
│ ├── decision_engine.yaml # Router-Strategien & Schemas (WP06/07)
|
│ ├── 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)
|
||||||
@@ -121,12 +123,13 @@ Erstelle eine `.env` Datei im Root-Verzeichnis.
|
|||||||
MINDNET_LLM_MODEL="phi3:mini"
|
MINDNET_LLM_MODEL="phi3:mini"
|
||||||
MINDNET_EMBEDDING_MODEL="nomic-embed-text" # NEU
|
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_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)
|
# Frontend Settings (WP10)
|
||||||
MINDNET_API_URL="http://localhost:8002"
|
MINDNET_API_URL="http://localhost:8002"
|
||||||
MINDNET_API_TIMEOUT=60.0
|
MINDNET_API_TIMEOUT=300.0 # Erhöht wegen Smart Edge Berechnung
|
||||||
|
|
||||||
# Import-Strategie
|
# Import-Strategie
|
||||||
MINDNET_HASH_COMPARE="Body"
|
MINDNET_HASH_COMPARE="Body"
|
||||||
@@ -154,15 +157,15 @@ Wir entwickeln mit zwei Services. Du kannst sie manuell in zwei Terminals starte
|
|||||||
### 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_async()`.
|
* **Einstieg:** `scripts/import_markdown.py` -> `main_async()`.
|
||||||
* **Async & Semaphore:** Das Skript nutzt nun `asyncio` und eine Semaphore (Limit: 5), um parallele Embeddings zu erzeugen, ohne Ollama zu überlasten.
|
* **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) und Interview-Modus (WP07).
|
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.
|
||||||
* **One-Shot:** Wenn Intent `INTERVIEW` erkannt wird, wird **kein Retrieval** ausgeführt. Stattdessen wird ein Draft generiert.
|
* **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.
|
||||||
@@ -172,14 +175,20 @@ Hier passiert das Scoring.
|
|||||||
### 3.4 Das Frontend (`app.frontend.ui`)
|
### 3.4 Das Frontend (`app.frontend.ui`)
|
||||||
Eine Streamlit-App (WP10).
|
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`.
|
* **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`.
|
||||||
* **Draft Editor:** Enthält einen YAML-Sanitizer (`normalize_meta_and_body`), der sicherstellt, dass LLM-Halluzinationen im Frontmatter nicht das File zerstören.
|
* **Healing Parser:** Die Funktion `parse_markdown_draft` repariert defekte YAML-Frontmatter (fehlendes `---`) automatisch.
|
||||||
* **Logik:** Ruft `/chat` und `/feedback` und `/ingest/analyze` Endpoints der API auf.
|
* **Logik:** Ruft `/chat`, `/feedback` und `/ingest/analyze` Endpoints der API auf.
|
||||||
|
|
||||||
### 3.5 Embedding Service (`app.services.embeddings_client`)
|
### 3.5 Embedding Service (`app.services.embeddings_client`)
|
||||||
**Neu in v2.4:**
|
**Neu in v2.4:**
|
||||||
* Nutzt `httpx.AsyncClient` für non-blocking Calls an Ollama.
|
* 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.
|
* Unterstützt dediziertes Embedding-Modell (`nomic-embed-text`) getrennt vom Chat-Modell.
|
||||||
* Enthält Legacy-Funktion `embed_text` für synchrone Skripte.
|
|
||||||
|
### 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`.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -232,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.
|
||||||
@@ -262,14 +272,17 @@ Konfiguriere `edge_weights`, wenn Kausalität wichtiger ist als Ähnlichkeit.
|
|||||||
|
|
||||||
Wenn Mindnet neue Fragen stellen soll:
|
Wenn Mindnet neue Fragen stellen soll:
|
||||||
|
|
||||||
**1. Schema erweitern (`config/decision_engine.yaml`)**
|
**1. Schema erweitern (`config/types.yaml`)**
|
||||||
Füge das Feld in die Liste ein.
|
Füge das Feld in die Liste ein (Neu: Schemas liegen jetzt hier).
|
||||||
|
|
||||||
project:
|
project:
|
||||||
fields: ["Titel", "Ziel", "Budget"] # <--- Budget neu
|
schema:
|
||||||
|
- "Titel"
|
||||||
|
- "Ziel"
|
||||||
|
- "Budget (Neu)"
|
||||||
|
|
||||||
**2. Keine Code-Änderung nötig**
|
**2. Keine Code-Änderung nötig**
|
||||||
Der `One-Shot Extractor` (Prompt Template) liest diese Liste dynamisch und weist das LLM an, das Budget zu extrahieren oder `[TODO]` zu setzen.
|
Der `One-Shot Extractor` (Prompt Template) liest diese Liste dynamisch.
|
||||||
|
|
||||||
### Fazit
|
### Fazit
|
||||||
* **Vault:** Liefert das Wissen.
|
* **Vault:** Liefert das Wissen.
|
||||||
+86
-48
@@ -1,9 +1,9 @@
|
|||||||
# Mindnet v2.4 – Fachliche Architektur
|
# Mindnet v2.4 – Fachliche Architektur
|
||||||
**Datei:** `docs/mindnet_functional_architecture_v2.4.md`
|
**Datei:** `docs/mindnet_functional_architecture_v2.6.md`
|
||||||
**Stand:** 2025-12-11
|
**Stand:** 2025-12-12
|
||||||
**Status:** **FINAL** (Integrierter Stand WP01–WP11: Async Intelligence)
|
**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 **RAG-Chat** (Decision Engine, Interview-Modus & Persönlichkeit).
|
> 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>
|
||||||
@@ -19,7 +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 Matrix-Logik (Kontextsensitive Kanten) – Neu in v2.4](#24-matrix-logik-kontextsensitive-kanten--neu-in-v24)
|
- [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)
|
||||||
@@ -27,13 +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–WP11)](#6-context-intelligence--intent-router-wp06wp11)
|
- [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 Der Interview-Modus (One-Shot Extraction)](#65-der-interview-modus-one-shot-extraction)
|
- [6.5 Reasoning (Das Gewissen)](#65-reasoning-das-gewissen)
|
||||||
- [6.6 Active Intelligence (Link Suggestions) – Neu in v2.4](#66-active-intelligence-link-suggestions--neu-in-v24)
|
- [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)
|
||||||
@@ -49,7 +52,7 @@
|
|||||||
- [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](#14-beispiel--von-markdown-zu-kanten)
|
- [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.4.0)](#16-workpackage-status-v240)
|
- [16) Workpackage Status (v2.6.0)](#16-workpackage-status-v260)
|
||||||
|
|
||||||
</details>
|
</details>
|
||||||
---
|
---
|
||||||
@@ -63,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 (seit v2.3.10 asynchron) erzeugt diese Artefakte **deterministisch** und **idempotent** (erneute Läufe überschreiben konsistent statt zu duplizieren). Die Import-Schritte sind: *parse → chunk → embed → 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*.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -80,9 +83,9 @@ Die Import-Pipeline (seit v2.3.10 asynchron) erzeugt diese Artefakte **determini
|
|||||||
- 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*.
|
||||||
- **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.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).
|
||||||
- **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.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.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -97,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.
|
||||||
@@ -131,7 +134,19 @@ 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 Matrix-Logik (Kontextsensitive Kanten) – Neu in v2.4
|
### 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").
|
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`:**
|
**Beispiel für `Source Type: experience`:**
|
||||||
@@ -154,7 +169,7 @@ Jede Kante hat mindestens:
|
|||||||
|
|
||||||
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.
|
||||||
|
|
||||||
@@ -168,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`
|
||||||
@@ -220,9 +239,12 @@ 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–WP11)
|
## 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 Partner.
|
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.
|
||||||
|
|
||||||
@@ -230,40 +252,51 @@ Seit WP06 agiert Mindnet nicht mehr statisch, sondern passt seine Suchstrategie
|
|||||||
* **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 (Rat, Fakten oder Datenerfassung) und wechselt den Modus.
|
* **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. **INTERVIEW (WP07):** Wunsch, Wissen zu erfassen ("Neues Projekt anlegen"). → Aktiviert den Draft-Generator.
|
|
||||||
5. **CODING:** Technische Anfragen.
|
|
||||||
|
|
||||||
### 6.3 Strategic Retrieval (Injektion von Werten)
|
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.
|
||||||
|
|
||||||
|
3. **LLM Fallback (Slow Path):**
|
||||||
|
* Wenn beides fehlschlägt, entscheidet das LLM über den Intent.
|
||||||
|
|
||||||
|
### 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.
|
||||||
|
|
||||||
### 6.4 Reasoning (Das Gewissen)
|
### 6.5 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.5 Der Interview-Modus (One-Shot Extraction)
|
### 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**.
|
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).
|
* **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.
|
* **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.
|
||||||
* **Draft-Status:** Fehlende Pflichtfelder werden mit `[TODO]` markiert.
|
* **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.
|
* **UI-Integration:** Das Frontend rendert statt einer Chat-Antwort einen **interaktiven Editor** (WP10), in dem der Entwurf finalisiert werden kann.
|
||||||
|
|
||||||
### 6.6 Active Intelligence (Link Suggestions) – Neu in v2.4
|
### 6.7 Active Intelligence (Link Suggestions)
|
||||||
Im **Draft Editor** (Frontend) unterstützt das System den Autor aktiv.
|
Im **Draft Editor** (Frontend) unterstützt das System den Autor aktiv.
|
||||||
* **Analyse:** Ein "Sliding Window" scannt den Text im Hintergrund (auch lange Entwürfe).
|
* **Analyse:** Ein "Sliding Window" scannt den Text im Hintergrund (auch lange Entwürfe).
|
||||||
* **Erkennung:** Es findet Begriffe ("Mindnet") und semantische Konzepte ("Autofahrt in Italien").
|
* **Erkennung:** Es findet Begriffe ("Mindnet") und semantische Konzepte ("Autofahrt in Italien").
|
||||||
* **Matching:** Es prüft gegen den Index (Aliases und Vektoren).
|
* **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.
|
* **Vorschlag:** Es bietet fertige Markdown-Links an (z.B. `[[rel:related_to ...]]`), die per Klick eingefügt werden.
|
||||||
* **Logik:** Dabei kommt die in 2.4 beschriebene **Matrix-Logik** zum Einsatz, um den korrekten Kanten-Typ vorzuschlagen.
|
* **Logik:** Dabei kommt die in 2.5 beschriebene **Matrix-Logik** zum Einsatz, um den korrekten Kanten-Typ vorzuschlagen.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -301,8 +334,9 @@ Mindnet lernt nicht durch klassisches Training (Fine-Tuning), sondern durch **Ko
|
|||||||
chunk_profile: short # Risiken sind oft kurze Statements
|
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.
|
||||||
@@ -359,12 +393,12 @@ Die Interaktion erfolgt primär über das **Web-Interface (WP10)**.
|
|||||||
## 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.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -413,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.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -425,6 +459,7 @@ 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`.
|
||||||
@@ -435,7 +470,7 @@ Frontmatter-Eigenschaften (Properties) bleiben **minimiert**:
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 16) Workpackage Status (v2.4.0)
|
## 16) Workpackage Status (v2.6.0)
|
||||||
|
|
||||||
Aktueller Implementierungsstand der Module.
|
Aktueller Implementierungsstand der Module.
|
||||||
|
|
||||||
@@ -448,9 +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. |
|
||||||
| **WP07** | Interview Assistent | 🟢 Live | **One-Shot Extractor & Schemas aktiv.** |
|
| **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 | 🟢 Live | Web-Interface (Streamlit). |
|
| **WP10** | Chat Interface | 🟢 Live | Web-Interface (Streamlit). |
|
||||||
| **WP10a**| Draft Editor | 🟢 Live | **Interaktives UI für WP07 Drafts.** |
|
| **WP10a**| Draft Editor | 🟢 Live | **Interaktives UI & Healing Parser.** |
|
||||||
| **WP11** | Backend Intelligence | 🟢 Live | **Async Ingestion, Nomic Embeddings, Matrix Logic.** |
|
| **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. |
|
||||||
+112
-86
@@ -1,21 +1,21 @@
|
|||||||
# Mindnet v2.4 – Technische Architektur
|
# Mindnet v2.6 – Technische Architektur
|
||||||
**Datei:** `docs/mindnet_technical_architecture_v2.4.md`
|
**Datei:** `docs/mindnet_technical_architecture_v2.6.md`
|
||||||
**Stand:** 2025-12-11
|
**Stand:** 2025-12-12
|
||||||
**Status:** **FINAL** (Integrierter Stand WP01–WP11: Async Intelligence)
|
**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, der **RAG-Komponenten (Decision Engine & Hybrid Router)**, des **Interview-Modus** und dem **Frontend (Streamlit)**.
|
> 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.4 – Technische Architektur](#mindnet-v24--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-WP10)](#12-verzeichnisstruktur--komponenten-post-wp10)
|
- [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,22 +27,23 @@
|
|||||||
- [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 (Async)](#41-verarbeitungsschritte-async)
|
- [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 + WP07 Interview)](#6-rag--chat-architektur-wp06-hybrid-router--wp07-interview)
|
- [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: Retrieval vs. Extraction](#64-schritt-3-retrieval-vs-extraction)
|
- [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)
|
||||||
|
- [6.6 Schritt 4: Generation \& Response](#66-schritt-4-generation--response)
|
||||||
- [7. Frontend Architektur (WP10)](#7-frontend-architektur-wp10)
|
- [7. Frontend Architektur (WP10)](#7-frontend-architektur-wp10)
|
||||||
- [7.1 Kommunikation](#71-kommunikation)
|
- [7.1 Kommunikation](#71-kommunikation)
|
||||||
- [7.2 Features \& UI-Logik](#72-features--ui-logik)
|
- [7.2 Features \& UI-Logik](#72-features--ui-logik)
|
||||||
- [7.3 Draft-Editor \& Sanitizer (Neu in WP10a)](#73-draft-editor--sanitizer-neu-in-wp10a)
|
- [7.3 Draft-Editor \& Healing Parser (Neu in WP10a/v2.5)](#73-draft-editor--healing-parser-neu-in-wp10av25)
|
||||||
- [7.4 State Management (Resurrection Pattern)](#74-state-management-resurrection-pattern)
|
- [7.4 State Management (Resurrection Pattern)](#74-state-management-resurrection-pattern)
|
||||||
- [7.5 Deployment Ports](#75-deployment-ports)
|
- [7.5 Deployment Ports](#75-deployment-ports)
|
||||||
- [8. Feedback \& Logging Architektur (WP04c)](#8-feedback--logging-architektur-wp04c)
|
- [8. Feedback \& Logging Architektur (WP04c)](#8-feedback--logging-architektur-wp04c)
|
||||||
@@ -62,57 +63,63 @@
|
|||||||
Mindnet ist ein **lokales RAG-System (Retrieval Augmented Generation)** mit Web-Interface.
|
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. **Backend:** 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.
|
||||||
* **Update v2.3.10:** Der Core arbeitet nun vollständig **asynchron (AsyncIO)**, um Blockaden bei Embedding-Requests zu vermeiden.
|
* **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** und **Intelligence-Features**.
|
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`.
|
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-WP10)
|
### 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 Service (WP11)
|
│ │ ├── 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
|
||||||
│ │ ├── ingest.py # NEU: API für Save & Analyze (WP11)
|
│ │ ├── ingest.py # NEU: API für Save & Analyze (WP11)
|
||||||
│ │ ├── chat.py # Hybrid Router & Interview Logic (WP06/07)
|
│ │ ├── 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 Chat Client
|
│ │ ├── llm_service.py # Ollama Chat Client mit Traffic Control (v2.8.0)
|
||||||
│ │ ├── embeddings_client.py# NEU: Async Embedding Client (HTTPX)
|
│ │ ├── semantic_analyzer.py# NEU: LLM-Filter für Edges (WP15)
|
||||||
│ │ └── feedback_service.py # JSONL Logging (WP04c)
|
│ │ ├── embeddings_client.py# NEU: Async Embeddings (HTTPX)
|
||||||
|
│ │ ├── feedback_service.py # Logging (JSONL Writer)
|
||||||
|
│ │ └── discovery.py # NEU: Intelligence Logic (WP11)
|
||||||
│ ├── frontend/ # NEU (WP10)
|
│ ├── frontend/ # NEU (WP10)
|
||||||
│ └── ui.py # Streamlit Application inkl. Sanitizer
|
│ │ └── ui.py # Streamlit Application inkl. Healing Parser
|
||||||
├── config/
|
│ └── main.py # Entrypoint der API
|
||||||
│ ├── types.yaml # Typ-Definitionen (Import-Zeit)
|
├── config/ # YAML-Konfigurationen (Single Source of Truth)
|
||||||
│ ├── retriever.yaml # Scoring-Gewichte (Laufzeit)
|
│ ├── types.yaml # Import-Regeln & Smart-Edge Config
|
||||||
│ ├── decision_engine.yaml # Strategien & Schemas (WP06/WP07)
|
│ ├── prompts.yaml # LLM Prompts & Interview Templates (WP06/07)
|
||||||
│ └── prompts.yaml # LLM System-Prompts & Templates (WP06)
|
│ ├── 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 (Async)
|
│ ├── 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)
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -140,7 +147,7 @@ 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.3.10:** Vektor-Dimension ist jetzt **768** (für `nomic-embed-text`).
|
* **Update v2.4:** Vektor-Dimension ist jetzt **768** (für `nomic-embed-text`).
|
||||||
* **Schema (Payload):**
|
* **Schema (Payload):**
|
||||||
|
|
||||||
| Feld | Datentyp | Beschreibung |
|
| Feld | Datentyp | Beschreibung |
|
||||||
@@ -171,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` |
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -181,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).
|
||||||
@@ -199,14 +214,14 @@ 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/07:** Steuert den Intent-Router und die Interview-Schemas.
|
**Neu in WP06/07:** Steuert den Intent-Router.
|
||||||
* Definiert Strategien (`DECISION`, `INTERVIEW`, etc.).
|
* Definiert Strategien (`DECISION`, `INTERVIEW`, etc.).
|
||||||
* Definiert `schemas` für den Interview-Modus (Pflichtfelder pro Typ).
|
* **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 inkl. `interview_template` mit One-Shot Logik.
|
* 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 und Embedding-Modell:
|
Erweiterung für LLM-Steuerung und Embedding-Modell:
|
||||||
@@ -215,32 +230,33 @@ Erweiterung für LLM-Steuerung und Embedding-Modell:
|
|||||||
MINDNET_EMBEDDING_MODEL=nomic-embed-text # NEU in v2.3.10
|
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=60.0 # Neu: Timeout für Frontend-API Calls
|
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_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.3.10:** Der Import nutzt `asyncio` und eine **Semaphore**, um Ollama nicht zu überlasten.
|
**Neu in v2.6:** Der Import nutzt `asyncio` und **Traffic Control**, um Ollama nicht zu überlasten.
|
||||||
|
|
||||||
### 4.1 Verarbeitungsschritte (Async)
|
### 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`.
|
||||||
* Bestimmung des `type` via `types.yaml`.
|
4. **Chunking & Smart Edges (WP15):**
|
||||||
3. **Chunking:**
|
* Zerlegung des Textes via `chunker.py`.
|
||||||
* Zerlegung via `chunker.py` basierend auf `chunk_profile`.
|
* Wenn Smart Edges aktiv: Der `SemanticAnalyzer` sendet Chunks an das LLM.
|
||||||
4. **Embedding (Async):**
|
* **Traffic Control:** Der Request nutzt `priority="background"`. Die Semaphore (Limit: 2) drosselt die Parallelität.
|
||||||
* Der `EmbeddingsClient` (`app/services/embeddings_client.py`) sendet Text-Chunks asynchron an Ollama.
|
|
||||||
* Modell: `nomic-embed-text` (768d).
|
|
||||||
* Semaphore: Max. 5 gleichzeitige Files, um OOM (Out-of-Memory) zu verhindern.
|
|
||||||
5. **Kantenableitung (Edge Derivation):**
|
5. **Kantenableitung (Edge Derivation):**
|
||||||
* `derive_edges.py` erzeugt Inline-, Callout- und Default-Edges.
|
* `derive_edges.py` erzeugt Inline-, Callout- und Default-Edges.
|
||||||
6. **Upsert:**
|
6. **Embedding (Async):**
|
||||||
|
* Der `EmbeddingsClient` (`app/services/embeddings_client.py`) sendet Text-Chunks asynchron an Ollama.
|
||||||
|
* Modell: `nomic-embed-text` (768d).
|
||||||
|
7. **Upsert:**
|
||||||
* Schreiben in Qdrant. Nutzung von `--purge-before-upsert`.
|
* Schreiben in Qdrant. Nutzung von `--purge-before-upsert`.
|
||||||
* **Strict Mode:** Der Prozess bricht ab, wenn Embeddings leer sind oder Dimension `0` haben.
|
* **Strict Mode:** Der Prozess bricht ab, wenn Embeddings leer sind oder Dimension `0` haben.
|
||||||
|
|
||||||
@@ -269,49 +285,55 @@ $$
|
|||||||
* **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 + WP07 Interview)
|
## 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`, `INTERVIEW`, `CODING` oder `FACT`.
|
|
||||||
|
|
||||||
### 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:
|
||||||
* **Bei RAG (FACT/DECISION):** `inject_types` für Strategic Retrieval.
|
* **Bei RAG (FACT/DECISION):** `inject_types` für Strategic Retrieval.
|
||||||
* **Bei INTERVIEW (WP07):** `schemas` (Pflichtfelder) basierend auf der erkannten Ziel-Entität (`_detect_target_type`).
|
* **Bei INTERVIEW (WP07):** `schemas` (Pflichtfelder) basierend auf der erkannten Ziel-Entität (`_detect_target_type`).
|
||||||
|
|
||||||
### 6.4 Schritt 3: Retrieval vs. Extraction
|
### 6.5 Schritt 3: Retrieval vs. Extraction
|
||||||
Der Router verzweigt hier:
|
Der Router verzweigt hier:
|
||||||
|
|
||||||
**A) RAG Modus (FACT, DECISION, EMPATHY):**
|
**A) RAG Modus (FACT, DECISION, EMPATHY):**
|
||||||
@@ -324,9 +346,9 @@ Der Router verzweigt hier:
|
|||||||
2. **Schema Injection:** Das Schema für den erkannten Typ (z.B. "Project") wird geladen.
|
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.
|
3. **Prompt Assembly:** Der `interview_template` Prompt wird mit der Schema-Definition ("Ziel", "Status") gefüllt.
|
||||||
|
|
||||||
### 6.5 Schritt 4: Generation & Response
|
### 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 (im Interview-Modus: Markdown Codeblock), Quellenliste und den erkannten `intent`.
|
* **Response:** Rückgabe enthält Antworttext (im Interview-Modus: Markdown Codeblock), Quellenliste und den erkannten `intent`.
|
||||||
|
|
||||||
---
|
---
|
||||||
@@ -337,8 +359,12 @@ Das Frontend ist eine **Streamlit-Anwendung** (`app/frontend/ui.py`), die als se
|
|||||||
|
|
||||||
### 7.1 Kommunikation
|
### 7.1 Kommunikation
|
||||||
* **Backend-URL:** Konfiguriert via `MINDNET_API_URL` (Default: `http://localhost:8002`).
|
* **Backend-URL:** Konfiguriert via `MINDNET_API_URL` (Default: `http://localhost:8002`).
|
||||||
* **Endpoints:** Nutzt `/chat` für Interaktion, `/feedback` für Bewertungen und `/ingest/analyze` für Intelligence.
|
* **Endpoints:**
|
||||||
* **Resilienz:** Das Frontend implementiert eigene Timeouts (`MINDNET_API_TIMEOUT`, Default 300s).
|
* `/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
|
### 7.2 Features & UI-Logik
|
||||||
* **State Management:** Session-State speichert Chat-Verlauf und `query_id`.
|
* **State Management:** Session-State speichert Chat-Verlauf und `query_id`.
|
||||||
@@ -347,16 +373,16 @@ Das Frontend ist eine **Streamlit-Anwendung** (`app/frontend/ui.py`), die als se
|
|||||||
* **Source Expanders:** Zeigt verwendete Chunks inkl. Score und "Why"-Explanation.
|
* **Source Expanders:** Zeigt verwendete Chunks inkl. Score und "Why"-Explanation.
|
||||||
* **Sidebar:** Zeigt Suchhistorie (Log-basiert) und Konfiguration.
|
* **Sidebar:** Zeigt Suchhistorie (Log-basiert) und Konfiguration.
|
||||||
|
|
||||||
### 7.3 Draft-Editor & Sanitizer (Neu in WP10a)
|
### 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**.
|
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.
|
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`):**
|
2. **Sanitization (`normalize_meta_and_body`):**
|
||||||
* Prüft den YAML-Frontmatter auf unerlaubte Felder (Halluzinationen des LLMs).
|
* Prüft den YAML-Frontmatter auf unerlaubte Felder (Halluzinationen des LLMs).
|
||||||
* Verschiebt ungültige Felder (z.B. "Situation") in den Body der Notiz.
|
* Verschiebt ungültige Felder (z.B. "Situation") in den Body der Notiz.
|
||||||
* Stellt sicher, dass das Markdown valide bleibt.
|
|
||||||
3. **Editor Widget:** `st.text_area` erlaubt das Bearbeiten des Inhalts vor dem Speichern.
|
3. **Editor Widget:** `st.text_area` erlaubt das Bearbeiten des Inhalts vor dem Speichern.
|
||||||
4. **Action:** Buttons zum Download oder Kopieren des fertigen Markdowns.
|
4. **Save Action:** Speichert über `/ingest/save` atomar in Vault und DB. Erzeugt intelligente Dateinamen via `slugify`.
|
||||||
|
|
||||||
### 7.4 State Management (Resurrection Pattern)
|
### 7.4 State Management (Resurrection Pattern)
|
||||||
Um Datenverlust bei Tab-Wechseln (Chat <-> Editor) zu verhindern, nutzt `ui.py` ein Persistenz-Muster:
|
Um Datenverlust bei Tab-Wechseln (Chat <-> Editor) zu verhindern, nutzt `ui.py` ein Persistenz-Muster:
|
||||||
@@ -420,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.
|
||||||
+57
-39
@@ -1,7 +1,7 @@
|
|||||||
# mindnet v2.4 – Pipeline Playbook
|
# mindnet v2.4 – Pipeline Playbook
|
||||||
**Datei:** `docs/mindnet_pipeline_playbook_v2.4.md`
|
**Datei:** `docs/mindnet_pipeline_playbook_v2.6.md`
|
||||||
**Stand:** 2025-12-11
|
**Stand:** 2025-12-12
|
||||||
**Status:** **FINAL** (Inkl. Async Ingestion & Active Intelligence)
|
**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.4.md`.
|
**Quellen:** `mindnet_v2_implementation_playbook.md`, `Handbuch.md`, `chunking_strategy.md`, `docs_mindnet_retriever.md`, `mindnet_admin_guide_v2.4.md`.
|
||||||
|
|
||||||
---
|
---
|
||||||
@@ -12,7 +12,7 @@
|
|||||||
- [](#)
|
- [](#)
|
||||||
- [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 (Async)](#21-der-12-schritte-prozess-async)
|
- [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,12 +21,13 @@
|
|||||||
- [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/07)](#52-intent-router-wp0607)
|
- [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)
|
- [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)
|
||||||
@@ -34,7 +35,7 @@
|
|||||||
- [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.4.0)](#16-workpackage-status-v240)
|
- [16. Workpackage Status (v2.6.0)](#16-workpackage-status-v260)
|
||||||
|
|
||||||
</details>
|
</details>
|
||||||
---
|
---
|
||||||
@@ -45,7 +46,7 @@ Dieses Playbook ist das zentrale operative Handbuch für die **mindnet-Pipeline*
|
|||||||
|
|
||||||
**Zielgruppe:** Dev/Ops, Tech-Leads.
|
**Zielgruppe:** Dev/Ops, Tech-Leads.
|
||||||
**Scope:**
|
**Scope:**
|
||||||
* **Ist-Stand (WP01–WP11):** Async Import, Chunking, Edge-Erzeugung, Hybrider Retriever, RAG-Chat (Hybrid Router), Feedback Loop, Frontend, Draft Editor, Active Intelligence.
|
* **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).
|
||||||
|
|
||||||
---
|
---
|
||||||
@@ -54,23 +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 (Async)
|
### 2.1 Der 13-Schritte-Prozess (Async + Smart)
|
||||||
Seit v2.3.10 läuft der Import **asynchron**, um Netzwerk-Blockaden bei der Embedding-Generierung zu vermeiden.
|
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. **Embedding & Upsert (Async):**
|
* **Priority:** Der Request nutzt `priority="background"`.
|
||||||
* Das System nutzt eine **Semaphore** (Limit: 5 Files concurrent), um Ollama nicht zu überlasten.
|
* **Semaphore:** Eine globale Semaphore (Limit: 2, konfigurierbar) verhindert System-Überlastung.
|
||||||
|
* **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).
|
* Generierung der Vektoren via `nomic-embed-text` (768 Dim).
|
||||||
11. **Strict Mode:** Der Prozess bricht sofort ab, wenn ein Embedding leer ist oder die Dimension `0` hat.
|
12. **Strict Mode:** Der Prozess bricht sofort ab, wenn ein Embedding leer ist oder die Dimension `0` hat.
|
||||||
12. **Diagnose:** Automatischer Check der Integrität nach dem Lauf.
|
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.
|
||||||
@@ -102,7 +112,7 @@ Nach einem Import oder Code-Update müssen die API-Prozesse neu gestartet werden
|
|||||||
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 beim Wechsel des Embedding-Modells (z.B. Update auf `nomic-embed-text`).
|
Notwendig bei Änderungen an `types.yaml` (z.B. Smart Edges an/aus) oder beim Wechsel des Embedding-Modells.
|
||||||
|
|
||||||
**WICHTIG:** Vorher das Modell pullen, sonst schlägt der Import fehl!
|
**WICHTIG:** Vorher das Modell pullen, sonst schlägt der Import fehl!
|
||||||
|
|
||||||
@@ -123,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:
|
||||||
@@ -137,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:
|
||||||
@@ -147,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).
|
||||||
@@ -165,25 +182,23 @@ Der Datenfluss endet nicht beim Finden. Er geht weiter bis zur Antwort.
|
|||||||
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/07)
|
### 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.
|
2. **Keyword Scan:** Enthält es Keywords aus `types.yaml` (Objekt, z.B. "Projekt") oder `decision_engine.yaml` (Action, z.B. "erstellen")? -> INTERVIEW Modus.
|
||||||
* `FACT`: Wissen abfragen.
|
3. **LLM Fallback:** Wenn unklar, entscheidet das LLM.
|
||||||
* `DECISION`: Rat suchen.
|
|
||||||
* `EMPATHY`: Trost suchen.
|
|
||||||
* `INTERVIEW`: Wissen eingeben (Neu in WP07).
|
|
||||||
3. **Result:** Auswahl der Strategie und der `inject_types` oder `schemas`.
|
|
||||||
|
|
||||||
### 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)`.
|
||||||
|
|
||||||
### 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`, `interview_template` etc.).
|
* **Prompting:** Template wird basierend auf Intent gewählt (`decision_template`, `interview_template` etc.).
|
||||||
* **One-Shot (WP07):** Im Interview-Modus generiert das LLM direkt einen Markdown-Block ohne Rückfragen.
|
* **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)
|
### 5.5 Active Intelligence Pipeline (Neu in v2.4)
|
||||||
Ein paralleler Datenfluss im Frontend ("Draft Editor") zur Unterstützung des Autors.
|
Ein paralleler Datenfluss im Frontend ("Draft Editor") zur Unterstützung des Autors.
|
||||||
@@ -252,7 +267,7 @@ Wie entwickeln wir die Pipeline weiter?
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 16. Workpackage Status (v2.4.0)
|
## 16. Workpackage Status (v2.6.0)
|
||||||
|
|
||||||
Aktueller Implementierungsstand der Module.
|
Aktueller Implementierungsstand der Module.
|
||||||
|
|
||||||
@@ -271,3 +286,6 @@ Aktueller Implementierungsstand der Module.
|
|||||||
| **WP10** | Chat Interface | 🟢 Live | Web-Interface (Streamlit). |
|
| **WP10** | Chat Interface | 🟢 Live | Web-Interface (Streamlit). |
|
||||||
| **WP10a**| Draft Editor | 🟢 Live | **Interaktives UI für WP07 Drafts.** |
|
| **WP10a**| Draft Editor | 🟢 Live | **Interaktives UI für WP07 Drafts.** |
|
||||||
| **WP11** | Backend Intelligence | 🟢 Live | **Async Ingestion, Nomic Embeddings, Matrix Logic.** |
|
| **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,7 +1,7 @@
|
|||||||
# Mindnet v2.4 – User Guide
|
# Mindnet v2.4 – User Guide
|
||||||
**Datei:** `docs/mindnet_user_guide_v2.4.md`
|
**Datei:** `docs/mindnet_user_guide_v2.6.md`
|
||||||
**Stand:** 2025-12-11
|
**Stand:** 2025-12-12
|
||||||
**Status:** **FINAL** (Inkl. RAG, Web-Interface & Interview-Assistent & Intelligence)
|
**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.**
|
||||||
@@ -18,6 +18,7 @@ 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)
|
||||||
Mindnet passt seinen Charakter dynamisch an deine Frage an:
|
Mindnet passt seinen Charakter dynamisch an deine Frage an:
|
||||||
@@ -52,28 +53,22 @@ Seit Version 2.3.1 bedienst du Mindnet über eine grafische Oberfläche im Brows
|
|||||||
|
|
||||||
## 3. Den Chat steuern (Intents)
|
## 3. Den Chat steuern (Intents)
|
||||||
|
|
||||||
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.
|
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 Modus: Entscheidung ("Der Berater")
|
### 3.1 Frage-Modus (Wissen abrufen)
|
||||||
Wenn du vor einer Wahl stehst, hilft Mindnet dir, konform zu deinen Prinzipien zu bleiben.
|
Sobald du ein Fragezeichen `?` benutzt oder Wörter wie "Wer", "Wie", "Was", "Soll ich" verwendest, sucht Mindnet nach Antworten (**RAG**).
|
||||||
|
|
||||||
* **Auslöser (Keywords):** "Soll ich...", "Was ist deine Meinung?", "Strategie für...", "Vor- und Nachteile".
|
* **Entscheidung ("Soll ich?"):** Mindnet lädt deine **Werte** (`type: value`) und **Ziele** (`type: goal`) in den Kontext und prüft die Fakten dagegen.
|
||||||
* **Was passiert:** 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'."
|
||||||
* **Beispiel-Dialog:**
|
* **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.
|
||||||
* *Du:* "Soll ich Tool X nutzen?"
|
* *Beispiel:* "Ich bin frustriert." -> "Das erinnert mich an Projekt Y, da ging es uns ähnlich..."
|
||||||
* *Mindnet:* "Nein. Tool X speichert Daten in den USA. Das verstößt gegen dein Prinzip 'Privacy First' und dein Ziel 'Digitale Autarkie'."
|
|
||||||
|
|
||||||
### 3.2 Modus: Empathie ("Der Spiegel")
|
### 3.2 Befehls-Modus (Wissen erfassen / Interview)
|
||||||
Wenn du frustriert bist oder reflektieren willst, wechselt Mindnet in den "Ich"-Modus.
|
Wenn du keine Frage stellst, sondern eine Absicht äußerst, wechselt Mindnet in den **Interview-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.
|
|
||||||
|
|
||||||
### 3.3 Modus: Interview ("Der Analyst")
|
|
||||||
Wenn du Wissen festhalten willst, statt zu suchen.
|
|
||||||
|
|
||||||
* **Auslöser:** "Neues Projekt", "Notiz erstellen", "Ich will etwas festhalten", "Neue Entscheidung dokumentieren".
|
* **Auslöser:** "Neues Projekt", "Notiz erstellen", "Ich will etwas festhalten", "Neue Entscheidung dokumentieren".
|
||||||
* **Was passiert:** Siehe Kapitel 6.3.
|
* **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".
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -127,9 +122,10 @@ Mindnet kann dir helfen, Markdown-Notizen zu schreiben.
|
|||||||
2. **Generierung:** Mindnet erkennt den Wunsch (`INTERVIEW`), analysiert den Satz und erstellt **sofort** einen Entwurf.
|
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**.
|
3. **Editor:** Die UI wechselt von der Chat-Blase zu einem **Draft-Editor**.
|
||||||
* Du siehst das generierte Frontmatter (`type: project`, `status: draft`).
|
* 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).
|
* 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**.
|
4. **Finalisierung:** Ergänze die fehlenden Infos direkt im Editor und klicke auf **Download** oder **Kopieren**.
|
||||||
5. **Speichern:** Speichere die Datei in deinen Obsidian Vault. Beim nächsten Import ist sie im System.
|
5. **Speichern:** Klicke auf "💾 Speichern". Die Notiz landet sofort im Vault und im Index.
|
||||||
|
|
||||||
### 6.4 Der Intelligence-Workflow (Neu in v2.4)
|
### 6.4 Der Intelligence-Workflow (Neu in v2.4)
|
||||||
Wenn du Texte im **manuellen Editor** schreibst, unterstützt dich Mindnet aktiv bei der Vernetzung:
|
Wenn du Texte im **manuellen Editor** schreibst, unterstützt dich Mindnet aktiv bei der Vernetzung:
|
||||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
Loaded 100 of 131 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user